@sanity/sdk 3.1.0 → 3.2.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.
- package/dist/_exports/_internal.d.ts +52 -21
- package/dist/_exports/_internal.d.ts.map +1 -1
- package/dist/_exports/_internal.js +10 -9
- package/dist/_exports/_internal.js.map +1 -1
- package/dist/_exports/agent.d.ts +7 -7
- package/dist/_exports/agent.d.ts.map +1 -1
- package/dist/_exports/agent.js +1 -1
- package/dist/_exports/comlink.d.ts +9 -9
- package/dist/_exports/comlink.d.ts.map +1 -1
- package/dist/_exports/comlink.js +3 -2
- package/dist/_exports/comlink.js.map +1 -1
- package/dist/_exports/dashboard.d.ts +2 -0
- package/dist/_exports/dashboard.js +2 -0
- package/dist/{authStore-C-OEkGaM.d.ts → authStore-BO2vch3I.d.ts} +516 -63
- package/dist/authStore-BO2vch3I.d.ts.map +1 -0
- package/dist/{clientStore-gUALQ0qW.js → clientStore-BI4D8HhJ.js} +124 -7
- package/dist/clientStore-BI4D8HhJ.js.map +1 -0
- package/dist/{createSanityInstance-DCePpBYW.d.ts → createSanityInstance-BQIqyGLX.d.ts} +16 -1
- package/dist/createSanityInstance-BQIqyGLX.d.ts.map +1 -0
- package/dist/{object-BwynGPRZ.js → createStateSourceAction-DdAhEfnZ.js} +2 -82
- package/dist/createStateSourceAction-DdAhEfnZ.js.map +1 -0
- package/dist/defineProperty-Bho9Ngsi.js +31 -0
- package/dist/{getNodeState-E0hjqFOo.js → getNodeState-B4nG0sjm.js} +3 -2
- package/dist/{getNodeState-E0hjqFOo.js.map → getNodeState-B4nG0sjm.js.map} +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +335 -51
- package/dist/index.js.map +1 -1
- package/dist/object-CxXlSVg7.js +83 -0
- package/dist/object-CxXlSVg7.js.map +1 -0
- package/dist/topicStore-Ct7IFNtY.js +565 -0
- package/dist/topicStore-Ct7IFNtY.js.map +1 -0
- package/dist/topicStore-D0WqhQGF.d.ts +435 -0
- package/dist/topicStore-D0WqhQGF.d.ts.map +1 -0
- package/dist/{version-C90rNWaX.js → version-BcRmCiYi.js} +6 -6
- package/dist/{version-C90rNWaX.js.map → version-BcRmCiYi.js.map} +1 -1
- package/package.json +19 -18
- package/src/_exports/_internal.ts +12 -0
- package/src/_exports/dashboard.ts +36 -0
- package/src/_exports/index.ts +17 -1
- package/src/applications/applications.test-d.ts +28 -4
- package/src/applications/applications.ts +39 -14
- package/src/auth/authMode.test.ts +24 -0
- package/src/auth/authMode.ts +8 -3
- package/src/auth/authStore.ts +12 -0
- package/src/auth/authStrategy.ts +2 -0
- package/src/auth/logout.test.ts +45 -0
- package/src/auth/logout.ts +1 -0
- package/src/auth/oauth/oauthActions.test.ts +457 -0
- package/src/auth/oauth/oauthActions.ts +389 -0
- package/src/auth/oauth/oauthAuth.test.ts +206 -0
- package/src/auth/oauth/oauthAuth.ts +168 -0
- package/src/auth/oauth/pkce.test.ts +44 -0
- package/src/auth/oauth/pkce.ts +60 -0
- package/src/auth/oauth/types.ts +12 -0
- package/src/config/authConfig.ts +18 -0
- package/src/dashboard/messageBus/__fixtures__/test-topics.ts +18 -0
- package/src/dashboard/messageBus/bus.test.ts +1033 -0
- package/src/dashboard/messageBus/bus.ts +1246 -0
- package/src/dashboard/messageBus/store.test.ts +142 -0
- package/src/dashboard/messageBus/store.ts +74 -0
- package/src/dashboard/messageBus/topicStore.test.ts +172 -0
- package/src/dashboard/messageBus/topicStore.ts +184 -0
- package/src/dashboard/messageBus/topics.test.ts +71 -0
- package/src/dashboard/messageBus/topics.ts +260 -0
- package/src/document/actions.ts +3 -3
- package/src/document/applyDocumentActions.ts +3 -3
- package/src/document/documentStore.ts +12 -12
- package/src/document/processMutations.ts +58 -22
- package/src/installations/installations.test-d.ts +3 -3
- package/src/installations/installations.ts +2 -19
- package/src/projection/getProjectionState.ts +2 -2
- package/src/projection/resolveProjection.ts +2 -2
- package/src/query/queryStore.ts +3 -3
- package/src/typegen/defineProjection.test.ts +17 -0
- package/src/typegen/defineProjection.ts +19 -0
- package/src/typegen/groqCompat.ts +122 -0
- package/src/typegen/resolve.ts +37 -0
- package/src/utils/createGroqSearchFilter.test.ts +8 -0
- package/src/utils/createGroqSearchFilter.ts +6 -3
- package/dist/authStore-C-OEkGaM.d.ts.map +0 -1
- package/dist/clientStore-gUALQ0qW.js.map +0 -1
- package/dist/createSanityInstance-DCePpBYW.d.ts.map +0 -1
- package/dist/object-BwynGPRZ.js.map +0 -1
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { m as SanityConfig, s as DocumentResource, t as SanityInstance } from "../createSanityInstance-
|
|
2
|
-
import {
|
|
1
|
+
import { m as SanityConfig, s as DocumentResource, t as SanityInstance } from "../createSanityInstance-BQIqyGLX.js";
|
|
2
|
+
import { Ai as CacheWriter, Bi as BoundStoreAction, Er as parseCommentsOptionsKey, Fi as MutationResult, Ii as defineFetcher, Li as defineMutation, Mi as FetcherDefinition, Ni as FetcherSnapshot, Pi as MutationDefinition, V as parseQueryKey, bt as GetUsersOptions, gr as createLogger, ji as Fetcher, ki as CacheTag, nt as PreviewValue, tt as PreviewQueryResult, wr as getCommentsOptionsKey, z as getQueryKey } from "../authStore-BO2vch3I.js";
|
|
3
|
+
import { S as resetMessageBus, i as resolveTopic, o as InstallMessageBusOptions, r as getTopicState, u as MessageBusConnection, x as installMessageBus } from "../topicStore-D0WqhQGF.js";
|
|
3
4
|
import { ClientError, SanityClient } from "@sanity/client";
|
|
4
5
|
import { Observable } from "rxjs";
|
|
5
6
|
import { CurrentUser } from "@sanity/types";
|
|
@@ -8,7 +9,7 @@ import { CurrentUser } from "@sanity/types";
|
|
|
8
9
|
*
|
|
9
10
|
* @internal
|
|
10
11
|
*/
|
|
11
|
-
declare function isStudioConfig(config: SanityConfig): boolean;
|
|
12
|
+
export declare function isStudioConfig(config: SanityConfig): boolean;
|
|
12
13
|
/** @internal */
|
|
13
14
|
type ApiErrorBody = {
|
|
14
15
|
error?: {
|
|
@@ -20,20 +21,50 @@ type ApiErrorBody = {
|
|
|
20
21
|
message?: string;
|
|
21
22
|
};
|
|
22
23
|
/** @internal Extracts the structured API error body from a ClientError, if present. */
|
|
23
|
-
declare function getClientErrorApiBody(error: ClientError): ApiErrorBody | undefined;
|
|
24
|
+
export declare function getClientErrorApiBody(error: ClientError): ApiErrorBody | undefined;
|
|
24
25
|
/** @internal Returns the error type string from an API error body, if available. */
|
|
25
|
-
declare function getClientErrorApiType(error: ClientError): string | undefined;
|
|
26
|
+
export declare function getClientErrorApiType(error: ClientError): string | undefined;
|
|
26
27
|
/** @internal Returns the error description string from an API error body, if available. */
|
|
27
|
-
declare function getClientErrorApiDescription(error: ClientError): string | undefined;
|
|
28
|
+
export declare function getClientErrorApiDescription(error: ClientError): string | undefined;
|
|
28
29
|
/** @internal True if the error represents a projectUserNotFoundError. */
|
|
29
|
-
declare function isProjectUserNotFoundClientError(error: ClientError): boolean;
|
|
30
|
+
export declare function isProjectUserNotFoundClientError(error: ClientError): boolean;
|
|
31
|
+
interface DashboardMessageBusState {
|
|
32
|
+
connection?: MessageBusConnection;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Returns the message bus connection for this instance, connecting on first call.
|
|
36
|
+
*
|
|
37
|
+
* @remarks
|
|
38
|
+
* One connection is made per {@link SanityInstance}, carrying that window's
|
|
39
|
+
* module identity. The first caller wins; later callers get the cached
|
|
40
|
+
* connection. When no host bus is installed it returns `undefined` without
|
|
41
|
+
* caching, so a later call retries once a host installs the bus.
|
|
42
|
+
* @internal
|
|
43
|
+
*/
|
|
44
|
+
export declare const getDashboardMessageBus: BoundStoreAction<DashboardMessageBusState, [moduleId?: string | undefined], MessageBusConnection | undefined>;
|
|
45
|
+
/**
|
|
46
|
+
* Returns the instance's message bus connection, or throws when no dashboard host has
|
|
47
|
+
* installed a bus. `action` names what the caller was about to do, e.g. `read topic "x"`.
|
|
48
|
+
* @internal
|
|
49
|
+
*/
|
|
50
|
+
export declare function requireDashboardMessageBus(instance: SanityInstance, action: string): MessageBusConnection;
|
|
51
|
+
/**
|
|
52
|
+
* Returns whether a dashboard host has installed a message bus.
|
|
53
|
+
*
|
|
54
|
+
* @remarks
|
|
55
|
+
* Answers "does a host own this session", not "has this instance connected yet". Callers
|
|
56
|
+
* such as the login redirect run before {@link getDashboardMessageBus} has been called for
|
|
57
|
+
* the instance, so this must not depend on the connection state.
|
|
58
|
+
* @internal
|
|
59
|
+
*/
|
|
60
|
+
export declare function isDashboardEnvironment(): boolean;
|
|
30
61
|
/**
|
|
31
62
|
* Generates a GROQ projection for preview data without requiring a schema.
|
|
32
63
|
* Uses common field names to make educated guesses about which fields to use.
|
|
33
64
|
*
|
|
34
65
|
* @internal
|
|
35
66
|
*/
|
|
36
|
-
declare const PREVIEW_PROJECTION: string;
|
|
67
|
+
export declare const PREVIEW_PROJECTION: string;
|
|
37
68
|
/**
|
|
38
69
|
* Transforms a projection result (with titleCandidates, subtitleCandidates, media)
|
|
39
70
|
* into a PreviewValue (with title, subtitle, media).
|
|
@@ -43,7 +74,7 @@ declare const PREVIEW_PROJECTION: string;
|
|
|
43
74
|
* @param resource - Data resource for the preview
|
|
44
75
|
* @internal
|
|
45
76
|
*/
|
|
46
|
-
declare function transformProjectionToPreview(instance: SanityInstance, projectionResult: PreviewQueryResult, resource?: DocumentResource): PreviewValue;
|
|
77
|
+
export declare function transformProjectionToPreview(instance: SanityInstance, projectionResult: PreviewQueryResult, resource?: DocumentResource): PreviewValue;
|
|
47
78
|
/**
|
|
48
79
|
* Manages telemetry for a single SDK instance.
|
|
49
80
|
*
|
|
@@ -105,14 +136,14 @@ interface TelemetryManager {
|
|
|
105
136
|
*
|
|
106
137
|
* @internal
|
|
107
138
|
*/
|
|
108
|
-
declare function initTelemetry(instance: SanityInstance, projectId: string): void;
|
|
139
|
+
export declare function initTelemetry(instance: SanityInstance, projectId: string): void;
|
|
109
140
|
/**
|
|
110
141
|
* Retrieves the telemetry manager for an instance, if one exists.
|
|
111
142
|
* Returns undefined when telemetry is disabled or not yet initialized.
|
|
112
143
|
*
|
|
113
144
|
* @internal
|
|
114
145
|
*/
|
|
115
|
-
declare function getTelemetryManager(instance: SanityInstance): TelemetryManager | undefined;
|
|
146
|
+
export declare function getTelemetryManager(instance: SanityInstance): TelemetryManager | undefined;
|
|
116
147
|
/**
|
|
117
148
|
* Record a hook name for an instance. If the telemetry manager is
|
|
118
149
|
* already initialized the event is logged immediately. Otherwise
|
|
@@ -120,11 +151,11 @@ declare function getTelemetryManager(instance: SanityInstance): TelemetryManager
|
|
|
120
151
|
*
|
|
121
152
|
* @internal
|
|
122
153
|
*/
|
|
123
|
-
declare function trackHookMounted(instance: SanityInstance, hookName: string): void;
|
|
154
|
+
export declare function trackHookMounted(instance: SanityInstance, hookName: string): void;
|
|
124
155
|
/** @internal */
|
|
125
|
-
declare const getUsersKey: (instance: SanityInstance, { resourceType, organizationId, batchSize, projectId, userId }?: GetUsersOptions) => string;
|
|
156
|
+
export declare const getUsersKey: (instance: SanityInstance, { resourceType, organizationId, batchSize, projectId, userId }?: GetUsersOptions) => string;
|
|
126
157
|
/** @internal */
|
|
127
|
-
declare const parseUsersKey: (key: string) => {
|
|
158
|
+
export declare const parseUsersKey: (key: string) => {
|
|
128
159
|
batchSize: number;
|
|
129
160
|
resourceType?: "organization" | "project";
|
|
130
161
|
projectId?: string;
|
|
@@ -136,7 +167,7 @@ declare const parseUsersKey: (key: string) => {
|
|
|
136
167
|
* from a raw search query string.
|
|
137
168
|
*
|
|
138
169
|
* It applies wildcard ('*') logic to the last eligible token and escapes
|
|
139
|
-
* double quotes within the search term.
|
|
170
|
+
* backslashes and double quotes within the search term.
|
|
140
171
|
*
|
|
141
172
|
* If the input query is empty or only whitespace, it returns an empty string.
|
|
142
173
|
*
|
|
@@ -144,7 +175,7 @@ declare const parseUsersKey: (key: string) => {
|
|
|
144
175
|
* @returns The GROQ search filter string, or an empty string.
|
|
145
176
|
* @internal
|
|
146
177
|
*/
|
|
147
|
-
declare function createGroqSearchFilter(query: string): string;
|
|
178
|
+
export declare function createGroqSearchFilter(query: string): string;
|
|
148
179
|
/**
|
|
149
180
|
* Generates a random ID of the given length from the alphabet `[a-zA-Z0-9]`, the same shape
|
|
150
181
|
* `@sanity/client` and Sanity Studio use for short IDs such as release IDs.
|
|
@@ -155,7 +186,7 @@ declare function createGroqSearchFilter(query: string): string;
|
|
|
155
186
|
*
|
|
156
187
|
* @internal
|
|
157
188
|
*/
|
|
158
|
-
declare function randomId(length?: number): string;
|
|
189
|
+
export declare function randomId(length?: number): string;
|
|
159
190
|
/**
|
|
160
191
|
* Generates a random v4 UUID.
|
|
161
192
|
*
|
|
@@ -166,13 +197,13 @@ declare function randomId(length?: number): string;
|
|
|
166
197
|
*
|
|
167
198
|
* @internal
|
|
168
199
|
*/
|
|
169
|
-
declare function randomUuid(): string;
|
|
200
|
+
export declare function randomUuid(): string;
|
|
170
201
|
/**
|
|
171
202
|
* Creates a shallow copy containing only the provided properties.
|
|
172
203
|
*
|
|
173
204
|
* @internal
|
|
174
205
|
*/
|
|
175
|
-
declare function pickProperties<T extends object, K extends keyof T>(value: T, keys: readonly K[]): Pick<T, K>;
|
|
206
|
+
export declare function pickProperties<T extends object, K extends keyof T>(value: T, keys: readonly K[]): Pick<T, K>;
|
|
176
207
|
/**
|
|
177
208
|
* Compares values deeply across the plain object, array, map, and set shapes used by the SDK.
|
|
178
209
|
* This helper is intended for acyclic SDK data structures and does not guard against circular
|
|
@@ -180,6 +211,6 @@ declare function pickProperties<T extends object, K extends keyof T>(value: T, k
|
|
|
180
211
|
*
|
|
181
212
|
* @internal
|
|
182
213
|
*/
|
|
183
|
-
declare function isDeepEqual<T>(left: T, right: T): boolean;
|
|
184
|
-
export { type ApiErrorBody, type CacheTag, type CacheWriter, type Fetcher, type FetcherDefinition, type FetcherSnapshot, type MutationDefinition, type MutationResult,
|
|
214
|
+
export declare function isDeepEqual<T>(left: T, right: T): boolean;
|
|
215
|
+
export { type ApiErrorBody, type CacheTag, type CacheWriter, type Fetcher, type FetcherDefinition, type FetcherSnapshot, type InstallMessageBusOptions, type MutationDefinition, type MutationResult, createLogger, defineFetcher, defineMutation, getCommentsOptionsKey, getQueryKey, getTopicState, installMessageBus, parseCommentsOptionsKey, parseQueryKey, resetMessageBus, resolveTopic };
|
|
185
216
|
//# sourceMappingURL=_internal.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"_internal.d.ts","names":[],"sources":["../../src/auth/authMode.ts","../../src/auth/utils.ts","../../src/preview/previewConstants.ts","../../src/preview/previewProjectionUtils.ts","../../src/telemetry/telemetryManager.ts","../../src/telemetry/initTelemetry.ts","../../src/users/reducers.ts","../../src/utils/createGroqSearchFilter.ts","../../src/utils/ids.ts","../../src/utils/object.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"_internal.d.ts","names":[],"sources":["../../src/auth/authMode.ts","../../src/auth/utils.ts","../../src/dashboard/messageBus/store.ts","../../src/preview/previewConstants.ts","../../src/preview/previewProjectionUtils.ts","../../src/telemetry/telemetryManager.ts","../../src/telemetry/initTelemetry.ts","../../src/users/reducers.ts","../../src/utils/createGroqSearchFilter.ts","../../src/utils/ids.ts","../../src/utils/object.ts"],"mappings":";;;;;;;;;;;wBA2CgB,eAAe,QAAQ;;KCqI3B;EACV;IAAS;IAAe;;EACxB;EACA;EACA;;;wBAIc,sBAAsB,OAAO,cAAc;;wBAM3C,sBAAsB,OAAO;;wBAM7B,6BAA6B,OAAO;;wBAMpC,iCAAiC,OAAO;UCrM9C;EACR,aAAa;;;;;;;;;;;;qBA2BF,wBAAsB,iBAAA,2BAAA,gCAAA;;;;;;wBAkBnB,2BACd,UAAU,gBACV,iBACC;;;;;;;;;;wBAiBa;;;;;;;qBCjDH;;;;;;;;;;wBCiDG,6BACd,UAAU,gBACV,kBAAkB,oBAClB,WAAW,mBACV;;;;;;;;;;;;UC3Cc;;;;;;;EAOf,gBAAgB;;EAGhB,kBAAkB;IAAO;IAAmB;IAAqB;;;EAGjE,iBAAiB;;EAGjB,SAAS,mBAAmB;;EAG5B;;EAGA;;WAGS,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;wBCXN,cAAc,UAAU,gBAAgB;;;;;;;wBAoIxC,oBAAoB,UAAU,iBAAiB;;;;;;;;wBAW/C,iBAAiB,UAAU,gBAAgB;;qBCvL9C,cACX,UAAU,kBACV,cAAA,gBAAA,WAAA,WAAA,WAMG;;qBAWQ,gBACX;EAEA;EACA;EACA;EACA;EACA;;;;;;;;;;;;;;;wBCYc,uBAAuB;;;;;;;;;;;wBChCvB,SAAS;;;;;;;;;;;wBAsBT;;;;;;wBCIA,eAAe,kBAAkB,gBAAgB,GAC/D,OAAO,GACP,eAAe,MACd,KAAK,GAAG;;;;;;;;wBA2DK,YAAY,GAAG,MAAM,GAAG,OAAO"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { i as
|
|
3
|
-
import {
|
|
1
|
+
import { A as __exportAll, C as isStudioConfig, _ as getClientErrorApiDescription, g as getClientErrorApiBody, k as createLogger, n as getClient, v as getClientErrorApiType, x as isProjectUserNotFoundClientError } from "../clientStore-BI4D8HhJ.js";
|
|
2
|
+
import { G as defineMutation, K as randomId, S as getCommentsOptionsKey, W as defineFetcher, d as getUsersKey, i as parseQueryKey, n as getQueryKey, p as parseUsersKey, q as randomUuid, t as CORE_SDK_VERSION, w as parseCommentsOptionsKey } from "../version-BcRmCiYi.js";
|
|
3
|
+
import { i as pickProperties, n as isObject, t as isDeepEqual } from "../object-CxXlSVg7.js";
|
|
4
|
+
import { a as isDashboardEnvironment, i as getDashboardMessageBus, l as installMessageBus, n as getTopicState, o as requireDashboardMessageBus, r as resolveTopic, u as resetMessageBus } from "../topicStore-Ct7IFNtY.js";
|
|
4
5
|
import "@sanity/client";
|
|
5
6
|
import { createImageUrlBuilder } from "@sanity/image-url";
|
|
6
7
|
import { createBatchedStore, defineEvent } from "@sanity/telemetry";
|
|
@@ -309,8 +310,8 @@ function initTelemetry(instance, projectId) {
|
|
|
309
310
|
environment
|
|
310
311
|
}), Promise.all([
|
|
311
312
|
Promise.resolve().then(() => telemetryManager_exports),
|
|
312
|
-
import("../clientStore-
|
|
313
|
-
import("../clientStore-
|
|
313
|
+
import("../clientStore-BI4D8HhJ.js").then((n) => n.t),
|
|
314
|
+
import("../clientStore-BI4D8HhJ.js").then((n) => n.a)
|
|
314
315
|
]).then(async ([{ createTelemetryManager }, { getClient }, { getTokenState }]) => {
|
|
315
316
|
if (instance.isDisposed()) {
|
|
316
317
|
initInFlight.delete(instance), logger.debug("telemetry skipped: instance disposed before imports resolved");
|
|
@@ -325,7 +326,7 @@ function initTelemetry(instance, projectId) {
|
|
|
325
326
|
let cleanup = { unsubscribe: () => {} }, unsub = instance.onDispose(() => {
|
|
326
327
|
cleanup.unsubscribe(), resolve(!1);
|
|
327
328
|
}), received = !1, sub = getTokenState(instance).observable.subscribe((t) => {
|
|
328
|
-
received
|
|
329
|
+
!received && t && (received = !0, logger.debug("auth token received"), unsub(), resolve(!0), cleanup.unsubscribe());
|
|
329
330
|
});
|
|
330
331
|
cleanup.unsubscribe = () => sub.unsubscribe(), received && cleanup.unsubscribe();
|
|
331
332
|
}) || instance.isDisposed())) {
|
|
@@ -431,7 +432,7 @@ function isExactMatchToken(token) {
|
|
|
431
432
|
* from a raw search query string.
|
|
432
433
|
*
|
|
433
434
|
* It applies wildcard ('*') logic to the last eligible token and escapes
|
|
434
|
-
* double quotes within the search term.
|
|
435
|
+
* backslashes and double quotes within the search term.
|
|
435
436
|
*
|
|
436
437
|
* If the input query is empty or only whitespace, it returns an empty string.
|
|
437
438
|
*
|
|
@@ -443,8 +444,8 @@ function createGroqSearchFilter(query) {
|
|
|
443
444
|
let trimmedQuery = query.trim();
|
|
444
445
|
if (!trimmedQuery) return "";
|
|
445
446
|
let tokens = trimmedQuery.match(TOKEN_REGEX) ?? [], reversedIndex = [...tokens].reverse().findIndex((token) => !isNegationToken(token) && !isExactMatchToken(token)), finalIncrementalTokenIndex = reversedIndex === -1 ? -1 : tokens.length - 1 - reversedIndex, finalIncrementalToken = tokens[finalIncrementalTokenIndex], processedTokens = [...tokens];
|
|
446
|
-
return finalIncrementalToken !== void 0 && !isPrefixToken(finalIncrementalToken) && processedTokens.splice(finalIncrementalTokenIndex, 1, `${finalIncrementalToken}*`), `[@] match text::query("${processedTokens.join(" ").replace(/"/g, "\\\"")}")`;
|
|
447
|
+
return finalIncrementalToken !== void 0 && !isPrefixToken(finalIncrementalToken) && processedTokens.splice(finalIncrementalTokenIndex, 1, `${finalIncrementalToken}*`), `[@] match text::query("${processedTokens.join(" ").replace(/\\/g, "\\\\").replace(/"/g, "\\\"")}")`;
|
|
447
448
|
}
|
|
448
|
-
export { PREVIEW_PROJECTION, createGroqSearchFilter, defineFetcher, defineMutation, getClientErrorApiBody, getClientErrorApiDescription, getClientErrorApiType, getCommentsOptionsKey, getQueryKey, getTelemetryManager, getUsersKey, initTelemetry, isDeepEqual, isProjectUserNotFoundClientError, isStudioConfig, parseCommentsOptionsKey, parseQueryKey, parseUsersKey, pickProperties, randomId, randomUuid, trackHookMounted, transformProjectionToPreview };
|
|
449
|
+
export { PREVIEW_PROJECTION, createGroqSearchFilter, createLogger, defineFetcher, defineMutation, getClientErrorApiBody, getClientErrorApiDescription, getClientErrorApiType, getCommentsOptionsKey, getDashboardMessageBus, getQueryKey, getTelemetryManager, getTopicState, getUsersKey, initTelemetry, installMessageBus, isDashboardEnvironment, isDeepEqual, isProjectUserNotFoundClientError, isStudioConfig, parseCommentsOptionsKey, parseQueryKey, parseUsersKey, pickProperties, randomId, randomUuid, requireDashboardMessageBus, resetMessageBus, resolveTopic, trackHookMounted, transformProjectionToPreview };
|
|
449
450
|
|
|
450
451
|
//# sourceMappingURL=_internal.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"_internal.js","names":[],"sources":["../../src/preview/previewConstants.ts","../../src/preview/previewProjectionUtils.ts","../../src/telemetry/environment.ts","../../src/telemetry/events.ts","../../src/telemetry/telemetryManager.ts","../../src/telemetry/initTelemetry.ts","../../src/utils/createGroqSearchFilter.ts"],"sourcesContent":["/**\n * The fields to check for a title.\n * The order of the items in the array defines the priority.\n *\n * @internal\n */\nexport const TITLE_CANDIDATES = ['title', 'name', 'label', 'heading', 'header', 'caption']\n\n/**\n * The fields to check for a subtitle.\n * The order of the items in the array defines the priority.\n *\n * @internal\n */\nexport const SUBTITLE_CANDIDATES = ['description', 'subtitle', ...TITLE_CANDIDATES]\n\n/**\n * Generates a GROQ projection for preview data without requiring a schema.\n * Uses common field names to make educated guesses about which fields to use.\n *\n * @internal\n */\nexport const PREVIEW_PROJECTION = `{\n // Get all potential title fields\n \"titleCandidates\": {\n ${TITLE_CANDIDATES.map((field) => `\"${field}\": ${field}`).join(',\\n ')}\n },\n // Get all potential subtitle fields\n \"subtitleCandidates\": {\n ${SUBTITLE_CANDIDATES.map((field) => `\"${field}\": ${field}`).join(',\\n ')}\n },\n \"media\": coalesce(\n select(\n defined(asset) => {\"type\": \"image-asset\", \"_ref\": asset._ref},\n defined(image.asset) => {\"type\": \"image-asset\", \"_ref\": image.asset._ref},\n defined(mainImage.asset) => {\"type\": \"image-asset\", \"_ref\": mainImage.asset._ref},\n null\n )\n ),\n _type,\n _id,\n _updatedAt\n}`\n","import {type SanityClient} from '@sanity/client'\nimport {createImageUrlBuilder} from '@sanity/image-url'\n\nimport {getClient} from '../client/clientStore'\nimport {type DocumentResource} from '../config/sanityConfig'\nimport {type SanityInstance} from '../store/createSanityInstance'\nimport {isObject} from '../utils/object'\nimport {SUBTITLE_CANDIDATES, TITLE_CANDIDATES} from './previewConstants'\nimport {type PreviewQueryResult, type PreviewValue} from './types'\n\nconst API_VERSION = 'v2025-05-06'\n\n/**\n * Checks if the provided value has `_ref` property that is a string and starts with `image-`\n */\nfunction hasImageRef<T>(value: unknown): value is T & {_ref: string} {\n return isObject(value) && '_ref' in value && typeof (value as {_ref: unknown})._ref === 'string'\n}\n\n/**\n * Normalizes a media asset to a preview value.\n * Adds a url to a media asset reference using `@sanity/image-url`.\n *\n * @internal\n */\nexport function normalizeMedia(media: unknown, client: SanityClient): PreviewValue['media'] {\n if (!media) return null\n if (!hasImageRef(media)) return null\n\n const builder = createImageUrlBuilder(client)\n const url = builder.image({_ref: media._ref}).url()\n\n return {\n type: 'image-asset',\n _ref: media._ref,\n url,\n }\n}\n\n/**\n * Finds a single field value from a set of candidates based on a priority list of field names.\n * Returns the first non-empty string value found from the candidates matching the priority list order.\n *\n * @internal\n */\nfunction findFirstDefined(\n fieldsToSearch: string[],\n candidates: Record<string, unknown>,\n exclude?: unknown,\n): string | undefined {\n if (!candidates) return undefined\n\n for (const field of fieldsToSearch) {\n const value = candidates[field]\n if (typeof value === 'string' && value.trim() !== '' && value !== exclude) {\n return value\n }\n }\n\n return undefined\n}\n\n/**\n * Transforms a projection result (with titleCandidates, subtitleCandidates, media)\n * into a PreviewValue (with title, subtitle, media).\n *\n * @param projectionResult - The raw projection result from GROQ\n * @param instance - The Sanity instance to use for client configuration\n * @param resource - Data resource for the preview\n * @internal\n */\nexport function transformProjectionToPreview(\n instance: SanityInstance,\n projectionResult: PreviewQueryResult,\n resource?: DocumentResource,\n): PreviewValue {\n const title = findFirstDefined(TITLE_CANDIDATES, projectionResult.titleCandidates)\n const subtitle = findFirstDefined(SUBTITLE_CANDIDATES, projectionResult.subtitleCandidates, title)\n\n // Get a client for the resource (if provided) or use the instance config\n const client = getClient(instance, {\n apiVersion: API_VERSION,\n resource,\n })\n\n return {\n title: String(title || `${projectionResult._type}: ${projectionResult._id}`),\n subtitle: subtitle || undefined,\n media: normalizeMedia(projectionResult.media, client),\n ...(projectionResult._status && {_status: projectionResult._status}),\n }\n}\n","/**\n * Telemetry environment classification.\n *\n * - `'development'` — the SDK is running on the local developer's machine\n * (`localhost` / `127.0.0.1` in the browser, or `NODE_ENV=development`\n * in Node). These are the original dev-only telemetry sessions.\n *\n * - `'production'` — the SDK is running on a production Sanity-controlled\n * domain (Studio deployments on `*.sanity.studio`, the dashboard on\n * `*.sanity.io`) where end users are authenticated Sanity users with\n * Populus consent records. Production telemetry is gated to this\n * allowlist; SDK apps deployed to customer-controlled domains do not\n * emit telemetry. Staging (`*.sanity.work`) and preview\n * (`*.sanity.dev`) hosts are deliberately excluded.\n *\n * @internal\n */\nexport type TelemetryEnvironment = 'development' | 'production'\n\n/**\n * Hostname suffixes that count as Sanity-controlled for the purposes of\n * production telemetry. A user reaching one of these hosts in the\n * browser is authenticated against Sanity and has a Populus consent\n * record, so we apply the same telemetry rules as the Studio's\n * `telemetry-sink`.\n *\n * The leading `.` is required: it ensures suffix matches hit a real\n * subdomain boundary, so apex matches (`sanity.io`, `sanity.studio`)\n * and lookalikes (`evilsanity.studio`) are excluded. Only production\n * hosts are listed; staging (`*.sanity.work`) and preview\n * (`*.sanity.dev`) hosts are excluded by omission.\n *\n * @internal\n */\nconst SANITY_CONTROLLED_HOST_SUFFIXES = ['.sanity.studio', '.sanity.io'] as const\n\nfunction getBrowserHostname(win: Window): string | null {\n const hostname = win.location?.hostname\n return typeof hostname === 'string' && hostname.length > 0 ? hostname.toLowerCase() : null\n}\n\nfunction isLocalHostname(hostname: string): boolean {\n return hostname === 'localhost' || hostname === '127.0.0.1'\n}\n\nfunction isSanityControlledHostname(hostname: string): boolean {\n return SANITY_CONTROLLED_HOST_SUFFIXES.some((suffix) => hostname.endsWith(suffix))\n}\n\n/**\n * Returns the telemetry environment for the current runtime, or `null`\n * when telemetry should not run at all.\n *\n * Browser:\n * - `localhost` / `127.0.0.1` → `'development'`\n * - host matches the Sanity-controlled allowlist → `'production'`\n * - anything else (customer domains, unknown contexts) → `null`\n *\n * Node (scripts, SSR, tests):\n * - `NODE_ENV=development` → `'development'`\n * - otherwise → `null`. Production-side server runtimes don't carry the\n * browser-authenticated user/consent assumption, so we don't enable\n * them under the production gate.\n *\n * Bracket-notation `process.env['NODE_ENV']` is used to avoid bundler\n * dead-code replacement.\n *\n * @internal\n */\nexport function getTelemetryEnvironment(): TelemetryEnvironment | null {\n if (typeof window !== 'undefined') {\n const hostname = getBrowserHostname(window)\n if (!hostname) return null\n if (isLocalHostname(hostname)) return 'development'\n if (isSanityControlledHostname(hostname)) return 'production'\n return null\n }\n\n if (typeof process !== 'undefined' && process.env?.['NODE_ENV'] === 'development') {\n return 'development'\n }\n return null\n}\n\n/**\n * Convenience predicate for \"telemetry can run in this environment\".\n *\n * @internal\n */\nexport function isTelemetryEnabled(): boolean {\n return getTelemetryEnvironment() !== null\n}\n","import {defineEvent} from '@sanity/telemetry'\n\n/** @internal */\nexport const SDKSessionStarted = defineEvent<{\n version: string\n projectId: string\n perspective: string\n authMethod: string\n}>({\n name: 'SDK Session Started',\n version: 1,\n description: 'SDK instance created (environment is recorded in the event context)',\n})\n\n/** @internal */\nexport const SDKHookMounted = defineEvent<{\n hookName: string\n}>({\n name: 'SDK Hook Mounted',\n version: 1,\n description: 'An SDK hook was mounted for the first time in this session',\n})\n\n/** @internal */\nexport const SDKSessionEnded = defineEvent<{\n durationSeconds: number\n hooksUsed: string[]\n}>({\n name: 'SDK Session Ended',\n version: 1,\n description: 'SDK instance disposed (environment is recorded in the event context)',\n})\n\n/** @internal */\nexport const SDKError = defineEvent<{\n errorType: string\n hookName: string\n}>({\n name: 'SDK Error',\n version: 1,\n description: 'Runtime error caught in the SDK',\n})\n","import {type SanityClient} from '@sanity/client'\nimport {\n type ConsentStatus,\n createBatchedStore,\n type SessionId,\n type TelemetryEvent,\n type TelemetryLogger,\n type TelemetryStore,\n} from '@sanity/telemetry'\n\nimport {createLogger} from '../utils/logger'\nimport {CORE_SDK_VERSION} from '../version'\nimport {type TelemetryEnvironment} from './environment'\nimport {SDKError, SDKHookMounted, SDKSessionEnded, SDKSessionStarted} from './events'\n\nconst FLUSH_INTERVAL_MS = 30_000\nconst CONSENT_TAG = 'telemetry-consent.sdk'\nconst BATCH_TAG = 'telemetry.batch'\n\nconst log = createLogger('telemetry')\n\n/**\n * Manages telemetry for a single SDK instance.\n *\n * Wraps `@sanity/telemetry`'s batched store with SDK-specific concerns:\n * consent caching, session lifecycle events, and hook usage tracking.\n * The `environment` is captured at construction time and recorded in\n * the event context so downstream pipelines can distinguish dev and\n * production sessions.\n *\n * @internal\n */\nexport interface TelemetryManager {\n /**\n * Eagerly resolve and cache the user's consent status.\n * Returns true only when the user has explicitly opted in (`granted`).\n * Call this before logging any events to avoid buffering events that\n * will be dropped on the first flush.\n */\n checkConsent(): Promise<boolean>\n\n /** Log a \"SDK Session Started\" event */\n logSessionStarted(data: {projectId: string; perspective: string; authMethod: string}): void\n\n /** Log a \"SDK Hook Mounted\" event (deduplicated per hook name) */\n logHookFirstUsed(hookName: string): void\n\n /** Log a \"SDK Error\" event */\n logError(errorType: string, hookName: string): void\n\n /** Log a \"SDK Session Ended\" event and tear down the store */\n endSession(): void\n\n /** Tear down the store without logging a session-end event */\n dispose(): void\n\n /** The set of hook names used during this session */\n readonly hooksUsed: ReadonlySet<string>\n}\n\ninterface TelemetryManagerOptions {\n sessionId: string\n getClient: () => SanityClient\n projectId: string\n environment: TelemetryEnvironment\n}\n\n/**\n * Creates a telemetry manager for a single SDK instance session.\n *\n * The manager initializes a `createBatchedStore` from `@sanity/telemetry`,\n * caches the consent check for the lifetime of the session, and provides\n * typed methods for each SDK telemetry event.\n *\n * @internal\n */\nexport function createTelemetryManager(options: TelemetryManagerOptions): TelemetryManager {\n const {sessionId, getClient, projectId, environment} = options\n const startedAt = Date.now()\n const emittedHooks = new Set<string>()\n\n let cachedConsent: {status: ConsentStatus} | null = null\n\n const resolveConsent = async (): Promise<{status: ConsentStatus}> => {\n if (cachedConsent) return cachedConsent\n try {\n const client = getClient()\n const result = await client.request<{status: ConsentStatus}>({\n url: '/intake/telemetry-status',\n tag: CONSENT_TAG,\n })\n cachedConsent = result\n } catch {\n cachedConsent = {status: 'undetermined'}\n }\n return cachedConsent\n }\n\n const enrichBatch = (batch: TelemetryEvent[]) =>\n batch.map((event) => {\n // Trace events (`trace.start` / `trace.log` / `trace.error` /\n // `trace.complete`) arrive with their own caller-provided `context`.\n // Log / userProperties events don't. Narrow via `in` so `event`\n // stays typed as `TelemetryEvent`, then merge so we don't drop the\n // trace context. SDK-owned fields below win on conflict.\n const existing =\n 'context' in event ? (event.context as Record<string, unknown> | undefined) : undefined\n return {\n ...event,\n context: {\n ...existing,\n version: CORE_SDK_VERSION,\n environment,\n origin: typeof window !== 'undefined' ? window.location.origin : 'node',\n },\n }\n })\n\n const sendEvents = async (batch: TelemetryEvent[]): Promise<unknown> => {\n const client = getClient()\n log.debug('sending event batch', {batchSize: batch.length, environment})\n return client.request({\n url: '/intake/batch',\n method: 'POST',\n body: {projectId, batch: enrichBatch(batch)},\n tag: BATCH_TAG,\n })\n }\n\n const store: TelemetryStore<Record<string, unknown>> = createBatchedStore(\n sessionId as SessionId,\n {\n flushInterval: FLUSH_INTERVAL_MS,\n resolveConsent,\n sendEvents,\n },\n )\n\n const logger: TelemetryLogger<Record<string, unknown>> = store.logger\n\n return {\n async checkConsent() {\n const {status} = await resolveConsent()\n return status === 'granted'\n },\n\n logSessionStarted(data) {\n log.debug('event: SDK Session Started', {\n projectId: data.projectId,\n perspective: data.perspective,\n authMethod: data.authMethod,\n version: CORE_SDK_VERSION,\n environment,\n })\n logger.log(SDKSessionStarted, {\n version: CORE_SDK_VERSION,\n ...data,\n })\n },\n\n logHookFirstUsed(hookName: string) {\n if (emittedHooks.has(hookName)) return\n emittedHooks.add(hookName)\n log.debug('event: SDK Hook Mounted', {hookName})\n logger.log(SDKHookMounted, {hookName})\n },\n\n logError(errorType: string, hookName: string) {\n log.debug('event: SDK Error', {errorType, hookName})\n logger.log(SDKError, {errorType, hookName})\n },\n\n endSession() {\n const durationSeconds = Math.round((Date.now() - startedAt) / 1000)\n log.debug('event: SDK Session Ended', {\n durationSeconds,\n hooksUsed: [...emittedHooks],\n environment,\n })\n logger.log(SDKSessionEnded, {\n durationSeconds,\n hooksUsed: [...emittedHooks],\n })\n\n store.flush().catch(() => {\n // Best-effort flush on dispose; swallow errors\n })\n store.end()\n },\n\n dispose() {\n store.end()\n },\n\n get hooksUsed(): ReadonlySet<string> {\n return emittedHooks\n },\n }\n}\n","import {type SanityInstance} from '../store/createSanityInstance'\nimport {createLogger} from '../utils/logger'\nimport {getTelemetryEnvironment} from './environment'\nimport {type TelemetryManager} from './telemetryManager'\n\nconst DEFAULT_TELEMETRY_API_VERSION = '2024-11-12'\n\nconst logger = createLogger('telemetry')\n\n/**\n * Per-instance map of active telemetry managers. Allows the React\n * package (and other consumers) to look up the manager for a given\n * instance and log hook usage / errors without importing the full\n * telemetry module themselves.\n *\n * @internal\n */\nconst telemetryManagers = new WeakMap<SanityInstance, TelemetryManager>()\nconst pendingHooks = new WeakMap<SanityInstance, Set<string>>()\nconst initInFlight = new WeakSet<SanityInstance>()\n\n/**\n * Initializes telemetry for a SDK instance if the runtime environment\n * qualifies. The environment is resolved by `getTelemetryEnvironment()`:\n *\n * - `'development'` — local dev servers (`localhost` / `127.0.0.1`, or\n * Node with `NODE_ENV=development`). This is the original opt-in\n * surface.\n * - `'production'` — apps deployed to Sanity-controlled domains\n * (e.g. `*.sanity.studio`, the dashboard). End users are\n * authenticated Sanity users with Populus consent records, so we\n * apply the same consent gate as the Studio's `telemetry-sink`.\n *\n * Apps on customer-controlled domains return `null` and skip telemetry\n * entirely.\n *\n * `telemetryManager` and `clientStore` are dynamically imported so the\n * telemetry code path stays out of production bundles for apps that\n * don't qualify. Only the lightweight environment check runs at boot.\n *\n * The `projectId` must be passed explicitly because the resource\n * configuration is typically set by the React layer after the\n * instance has already been created.\n *\n * @internal\n */\nexport function initTelemetry(instance: SanityInstance, projectId: string): void {\n const environment = getTelemetryEnvironment()\n if (!environment) {\n logger.trace('initTelemetry skipped: environment not eligible', {internal: true})\n return\n }\n if (!projectId) {\n logger.trace('initTelemetry skipped: no projectId', {internal: true})\n return\n }\n if (telemetryManagers.has(instance) || initInFlight.has(instance)) {\n return\n }\n initInFlight.add(instance)\n\n logger.debug('initializing telemetry', {projectId, environment})\n\n Promise.all([\n import('./telemetryManager'),\n import('../client/clientStore'),\n import('../auth/authStore'),\n ])\n .then(async ([{createTelemetryManager}, {getClient}, {getTokenState}]) => {\n if (instance.isDisposed()) {\n initInFlight.delete(instance)\n logger.debug('telemetry skipped: instance disposed before imports resolved')\n return\n }\n\n // Wait for the auth store to resolve a token. The client needs a\n // Bearer token for the consent check and batch POSTs. If the token\n // is already available (e.g. static token config), this resolves\n // immediately. For OAuth/localStorage discovery it waits for the\n // first emission. For unauthenticated apps the promise never\n // resolves, which is fine since telemetry requires auth anyway.\n const token = getTokenState(instance).getCurrent()\n logger.trace('auth token check', {tokenPresent: !!token, internal: true})\n\n if (!token) {\n logger.debug('waiting for auth token')\n const hasToken = await new Promise<boolean>((resolve) => {\n if (instance.isDisposed()) return resolve(false)\n const cleanup = {unsubscribe: () => {}}\n const unsub = instance.onDispose(() => {\n cleanup.unsubscribe()\n resolve(false)\n })\n // The token observable is a `shareReplay({bufferSize: 1, refCount: true})`\n // (see `createStateSourceAction`), so it can deliver a buffered value\n // synchronously while we're still inside `.subscribe(cb)`. At that\n // moment `sub` is in the TDZ, so the callback can't reach it. We\n // gate on a `received` flag and let the post-subscribe block do the\n // unsubscribe in the sync-emission case.\n let received = false\n const sub = getTokenState(instance).observable.subscribe((t) => {\n if (received || !t) return\n received = true\n logger.debug('auth token received')\n unsub()\n resolve(true)\n cleanup.unsubscribe()\n })\n cleanup.unsubscribe = () => sub.unsubscribe()\n if (received) cleanup.unsubscribe()\n })\n if (!hasToken || instance.isDisposed()) {\n initInFlight.delete(instance)\n logger.debug('telemetry skipped: no token resolved or instance disposed')\n return\n }\n }\n\n const manager = createTelemetryManager({\n sessionId: instance.instanceId,\n getClient: () => getClient(instance, {apiVersion: DEFAULT_TELEMETRY_API_VERSION}),\n projectId,\n environment,\n })\n\n const consented = await manager.checkConsent()\n logger.debug('consent check complete', {consented})\n if (!consented || instance.isDisposed()) {\n initInFlight.delete(instance)\n manager.dispose()\n return\n }\n\n initInFlight.delete(instance)\n telemetryManagers.set(instance, manager)\n\n const buffered = pendingHooks.get(instance)\n if (buffered) {\n logger.debug('flushing buffered hooks', {hooks: Array.from(buffered)})\n for (const hookName of buffered) {\n manager.logHookFirstUsed(hookName)\n }\n pendingHooks.delete(instance)\n }\n\n const config = instance.config\n const perspective = typeof config.perspective === 'string' ? config.perspective : 'published'\n const authMethod = config.auth?.token\n ? 'token'\n : config.studio?.auth?.token\n ? 'studio'\n : 'default'\n\n logger.info('telemetry session started', {projectId, perspective, authMethod, environment})\n manager.logSessionStarted({\n projectId,\n perspective,\n authMethod,\n })\n\n instance.onDispose(() => {\n manager.endSession()\n telemetryManagers.delete(instance)\n logger.debug('telemetry session ended')\n })\n })\n .catch((err) => {\n initInFlight.delete(instance)\n logger.warn('telemetry init failed', {error: err})\n })\n}\n\n/**\n * Retrieves the telemetry manager for an instance, if one exists.\n * Returns undefined when telemetry is disabled or not yet initialized.\n *\n * @internal\n */\nexport function getTelemetryManager(instance: SanityInstance): TelemetryManager | undefined {\n return telemetryManagers.get(instance)\n}\n\n/**\n * Record a hook name for an instance. If the telemetry manager is\n * already initialized the event is logged immediately. Otherwise\n * the name is buffered and flushed when init completes.\n *\n * @internal\n */\nexport function trackHookMounted(instance: SanityInstance, hookName: string): void {\n if (!getTelemetryEnvironment()) return\n\n const manager = findManager(instance)\n if (manager) {\n logger.trace('hook mounted (logged)', {hookName, internal: true})\n manager.logHookFirstUsed(hookName)\n return\n }\n\n const root = getRootInstance(instance)\n let hooks = pendingHooks.get(root)\n if (!hooks) {\n hooks = new Set()\n pendingHooks.set(root, hooks)\n }\n if (!hooks.has(hookName)) {\n logger.trace('hook mounted (buffered)', {hookName, internal: true})\n }\n hooks.add(hookName)\n}\n\nfunction findManager(instance: SanityInstance): TelemetryManager | undefined {\n return telemetryManagers.get(instance)\n}\n\nfunction getRootInstance(instance: SanityInstance): SanityInstance {\n return instance\n}\n","const WILDCARD_TOKEN = '*'\nconst NEGATION_TOKEN = '-'\n// This regex handles simple cases including quoted phrases.\n// More complex query syntaxes might need a more robust parser.\nconst TOKEN_REGEX = /(?:[^\\s\"]+|\"[^\"]*\")+/g\n\n/**\n * @internal\n * Checks if a token starts with the negation character.\n */\nfunction isNegationToken(token: string | undefined): boolean {\n return typeof token !== 'undefined' && token.trim().startsWith(NEGATION_TOKEN)\n}\n\n/**\n * @internal\n * Checks if a token ends with the wildcard character.\n */\nfunction isPrefixToken(token: string | undefined): boolean {\n return typeof token !== 'undefined' && token.trim().endsWith(WILDCARD_TOKEN)\n}\n\n/**\n * @internal\n * Checks if a token is enclosed in double quotes.\n */\nfunction isExactMatchToken(token: string | undefined): boolean {\n // Ensure the token exists, has at least 2 characters, and starts/ends with \"\n return !!token && token.length >= 2 && token.startsWith('\"') && token.endsWith('\"')\n}\n\n/**\n * Creates a GROQ search filter string (`[@] match text::query(\"...\")`)\n * from a raw search query string.\n *\n * It applies wildcard ('*') logic to the last eligible token and escapes\n * double quotes within the search term.\n *\n * If the input query is empty or only whitespace, it returns an empty string.\n *\n * @param query - The raw input search string.\n * @returns The GROQ search filter string, or an empty string.\n * @internal\n */\nexport function createGroqSearchFilter(query: string): string {\n // Trim leading/trailing whitespace from the overall query first\n const trimmedQuery = query.trim()\n if (!trimmedQuery) {\n return '' // Return empty if query is empty or just whitespace\n }\n\n // Extract tokens using the regex\n const tokens = trimmedQuery.match(TOKEN_REGEX) ?? []\n\n // Find the index of the last token eligible for wildcard appending\n const reversedTokens = [...tokens].reverse()\n const reversedIndex = reversedTokens.findIndex(\n (token: string) => !isNegationToken(token) && !isExactMatchToken(token),\n )\n const finalIncrementalTokenIndex = reversedIndex === -1 ? -1 : tokens.length - 1 - reversedIndex\n\n // Get the actual token based on the found index\n const finalIncrementalToken = tokens[finalIncrementalTokenIndex]\n\n const processedTokens = [...tokens]\n // If a suitable token was found and it doesn't already end with a wildcard,\n // apply the wildcard.\n if (finalIncrementalToken !== undefined && !isPrefixToken(finalIncrementalToken)) {\n // Replace the identified token with its wildcarded version\n processedTokens.splice(\n finalIncrementalTokenIndex,\n 1,\n `${finalIncrementalToken}${WILDCARD_TOKEN}`,\n )\n }\n\n // Join the tokens back into a space-separated string\n const wildcardSearch = processedTokens.join(' ')\n\n // Escape double quotes within the final search term for the GROQ query\n const escapedSearch = wildcardSearch.replace(/\"/g, '\\\\\"')\n\n // Construct the final GROQ filter clause\n return `[@] match text::query(\"${escapedSearch}\")`\n}\n"],"mappings":";;;;;;;;;;;;AAMA,MAAa,mBAAmB;CAAC;CAAS;CAAQ;CAAS;CAAW;CAAU;AAAS,GAQ5E,sBAAsB;CAAC;CAAe;CAAY,GAAG;AAAgB,GAQrE,qBAAqB;;;MAG5B,iBAAiB,KAAK,UAAU,IAAI,MAAM,KAAK,OAAO,CAAC,CAAC,KAAK,WAAW,EAAE;;;;MAI1E,oBAAoB,KAAK,UAAU,IAAI,MAAM,KAAK,OAAO,CAAC,CAAC,KAAK,WAAW,EAAE;;;;;;;;;;;;;;;;;ACdnF,SAAS,YAAe,OAA6C;CACnE,OAAO,SAAS,KAAK,KAAK,UAAU,SAAS,OAAQ,MAA0B,QAAS;AAC1F;;;;;;;AAQA,SAAgB,eAAe,OAAgB,QAA6C;CAE1F,IADI,CAAC,SACD,CAAC,YAAY,KAAK,GAAG,OAAO;CAGhC,IAAM,MADU,sBAAsB,MACpB,CAAC,CAAC,MAAM,EAAC,MAAM,MAAM,KAAI,CAAC,CAAC,CAAC,IAAI;CAElD,OAAO;EACL,MAAM;EACN,MAAM,MAAM;EACZ;CACF;AACF;;;;;;;AAQA,SAAS,iBACP,gBACA,YACA,SACoB;CACf,gBAEL,KAAK,IAAM,SAAS,gBAAgB;EAClC,IAAM,QAAQ,WAAW;EACzB,IAAI,OAAO,SAAU,YAAY,MAAM,KAAK,MAAM,MAAM,UAAU,SAChE,OAAO;CAEX;AAGF;;;;;;;;;;AAWA,SAAgB,6BACd,UACA,kBACA,UACc;C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_internal.js","names":[],"sources":["../../src/preview/previewConstants.ts","../../src/preview/previewProjectionUtils.ts","../../src/telemetry/environment.ts","../../src/telemetry/events.ts","../../src/telemetry/telemetryManager.ts","../../src/telemetry/initTelemetry.ts","../../src/utils/createGroqSearchFilter.ts"],"sourcesContent":["/**\n * The fields to check for a title.\n * The order of the items in the array defines the priority.\n *\n * @internal\n */\nexport const TITLE_CANDIDATES = ['title', 'name', 'label', 'heading', 'header', 'caption']\n\n/**\n * The fields to check for a subtitle.\n * The order of the items in the array defines the priority.\n *\n * @internal\n */\nexport const SUBTITLE_CANDIDATES = ['description', 'subtitle', ...TITLE_CANDIDATES]\n\n/**\n * Generates a GROQ projection for preview data without requiring a schema.\n * Uses common field names to make educated guesses about which fields to use.\n *\n * @internal\n */\nexport const PREVIEW_PROJECTION = `{\n // Get all potential title fields\n \"titleCandidates\": {\n ${TITLE_CANDIDATES.map((field) => `\"${field}\": ${field}`).join(',\\n ')}\n },\n // Get all potential subtitle fields\n \"subtitleCandidates\": {\n ${SUBTITLE_CANDIDATES.map((field) => `\"${field}\": ${field}`).join(',\\n ')}\n },\n \"media\": coalesce(\n select(\n defined(asset) => {\"type\": \"image-asset\", \"_ref\": asset._ref},\n defined(image.asset) => {\"type\": \"image-asset\", \"_ref\": image.asset._ref},\n defined(mainImage.asset) => {\"type\": \"image-asset\", \"_ref\": mainImage.asset._ref},\n null\n )\n ),\n _type,\n _id,\n _updatedAt\n}`\n","import {type SanityClient} from '@sanity/client'\nimport {createImageUrlBuilder} from '@sanity/image-url'\n\nimport {getClient} from '../client/clientStore'\nimport {type DocumentResource} from '../config/sanityConfig'\nimport {type SanityInstance} from '../store/createSanityInstance'\nimport {isObject} from '../utils/object'\nimport {SUBTITLE_CANDIDATES, TITLE_CANDIDATES} from './previewConstants'\nimport {type PreviewQueryResult, type PreviewValue} from './types'\n\nconst API_VERSION = 'v2025-05-06'\n\n/**\n * Checks if the provided value has `_ref` property that is a string and starts with `image-`\n */\nfunction hasImageRef<T>(value: unknown): value is T & {_ref: string} {\n return isObject(value) && '_ref' in value && typeof (value as {_ref: unknown})._ref === 'string'\n}\n\n/**\n * Normalizes a media asset to a preview value.\n * Adds a url to a media asset reference using `@sanity/image-url`.\n *\n * @internal\n */\nexport function normalizeMedia(media: unknown, client: SanityClient): PreviewValue['media'] {\n if (!media) return null\n if (!hasImageRef(media)) return null\n\n const builder = createImageUrlBuilder(client)\n const url = builder.image({_ref: media._ref}).url()\n\n return {\n type: 'image-asset',\n _ref: media._ref,\n url,\n }\n}\n\n/**\n * Finds a single field value from a set of candidates based on a priority list of field names.\n * Returns the first non-empty string value found from the candidates matching the priority list order.\n *\n * @internal\n */\nfunction findFirstDefined(\n fieldsToSearch: string[],\n candidates: Record<string, unknown>,\n exclude?: unknown,\n): string | undefined {\n if (!candidates) return undefined\n\n for (const field of fieldsToSearch) {\n const value = candidates[field]\n if (typeof value === 'string' && value.trim() !== '' && value !== exclude) {\n return value\n }\n }\n\n return undefined\n}\n\n/**\n * Transforms a projection result (with titleCandidates, subtitleCandidates, media)\n * into a PreviewValue (with title, subtitle, media).\n *\n * @param projectionResult - The raw projection result from GROQ\n * @param instance - The Sanity instance to use for client configuration\n * @param resource - Data resource for the preview\n * @internal\n */\nexport function transformProjectionToPreview(\n instance: SanityInstance,\n projectionResult: PreviewQueryResult,\n resource?: DocumentResource,\n): PreviewValue {\n const title = findFirstDefined(TITLE_CANDIDATES, projectionResult.titleCandidates)\n const subtitle = findFirstDefined(SUBTITLE_CANDIDATES, projectionResult.subtitleCandidates, title)\n\n // Get a client for the resource (if provided) or use the instance config\n const client = getClient(instance, {\n apiVersion: API_VERSION,\n resource,\n })\n\n return {\n title: String(title || `${projectionResult._type}: ${projectionResult._id}`),\n subtitle: subtitle || undefined,\n media: normalizeMedia(projectionResult.media, client),\n ...(projectionResult._status && {_status: projectionResult._status}),\n }\n}\n","/**\n * Telemetry environment classification.\n *\n * - `'development'` — the SDK is running on the local developer's machine\n * (`localhost` / `127.0.0.1` in the browser, or `NODE_ENV=development`\n * in Node). These are the original dev-only telemetry sessions.\n *\n * - `'production'` — the SDK is running on a production Sanity-controlled\n * domain (Studio deployments on `*.sanity.studio`, the dashboard on\n * `*.sanity.io`) where end users are authenticated Sanity users with\n * Populus consent records. Production telemetry is gated to this\n * allowlist; SDK apps deployed to customer-controlled domains do not\n * emit telemetry. Staging (`*.sanity.work`) and preview\n * (`*.sanity.dev`) hosts are deliberately excluded.\n *\n * @internal\n */\nexport type TelemetryEnvironment = 'development' | 'production'\n\n/**\n * Hostname suffixes that count as Sanity-controlled for the purposes of\n * production telemetry. A user reaching one of these hosts in the\n * browser is authenticated against Sanity and has a Populus consent\n * record, so we apply the same telemetry rules as the Studio's\n * `telemetry-sink`.\n *\n * The leading `.` is required: it ensures suffix matches hit a real\n * subdomain boundary, so apex matches (`sanity.io`, `sanity.studio`)\n * and lookalikes (`evilsanity.studio`) are excluded. Only production\n * hosts are listed; staging (`*.sanity.work`) and preview\n * (`*.sanity.dev`) hosts are excluded by omission.\n *\n * @internal\n */\nconst SANITY_CONTROLLED_HOST_SUFFIXES = ['.sanity.studio', '.sanity.io'] as const\n\nfunction getBrowserHostname(win: Window): string | null {\n const hostname = win.location?.hostname\n return typeof hostname === 'string' && hostname.length > 0 ? hostname.toLowerCase() : null\n}\n\nfunction isLocalHostname(hostname: string): boolean {\n return hostname === 'localhost' || hostname === '127.0.0.1'\n}\n\nfunction isSanityControlledHostname(hostname: string): boolean {\n return SANITY_CONTROLLED_HOST_SUFFIXES.some((suffix) => hostname.endsWith(suffix))\n}\n\n/**\n * Returns the telemetry environment for the current runtime, or `null`\n * when telemetry should not run at all.\n *\n * Browser:\n * - `localhost` / `127.0.0.1` → `'development'`\n * - host matches the Sanity-controlled allowlist → `'production'`\n * - anything else (customer domains, unknown contexts) → `null`\n *\n * Node (scripts, SSR, tests):\n * - `NODE_ENV=development` → `'development'`\n * - otherwise → `null`. Production-side server runtimes don't carry the\n * browser-authenticated user/consent assumption, so we don't enable\n * them under the production gate.\n *\n * Bracket-notation `process.env['NODE_ENV']` is used to avoid bundler\n * dead-code replacement.\n *\n * @internal\n */\nexport function getTelemetryEnvironment(): TelemetryEnvironment | null {\n if (typeof window !== 'undefined') {\n const hostname = getBrowserHostname(window)\n if (!hostname) return null\n if (isLocalHostname(hostname)) return 'development'\n if (isSanityControlledHostname(hostname)) return 'production'\n return null\n }\n\n if (typeof process !== 'undefined' && process.env?.['NODE_ENV'] === 'development') {\n return 'development'\n }\n return null\n}\n\n/**\n * Convenience predicate for \"telemetry can run in this environment\".\n *\n * @internal\n */\nexport function isTelemetryEnabled(): boolean {\n return getTelemetryEnvironment() !== null\n}\n","import {defineEvent} from '@sanity/telemetry'\n\n/** @internal */\nexport const SDKSessionStarted = defineEvent<{\n version: string\n projectId: string\n perspective: string\n authMethod: string\n}>({\n name: 'SDK Session Started',\n version: 1,\n description: 'SDK instance created (environment is recorded in the event context)',\n})\n\n/** @internal */\nexport const SDKHookMounted = defineEvent<{\n hookName: string\n}>({\n name: 'SDK Hook Mounted',\n version: 1,\n description: 'An SDK hook was mounted for the first time in this session',\n})\n\n/** @internal */\nexport const SDKSessionEnded = defineEvent<{\n durationSeconds: number\n hooksUsed: string[]\n}>({\n name: 'SDK Session Ended',\n version: 1,\n description: 'SDK instance disposed (environment is recorded in the event context)',\n})\n\n/** @internal */\nexport const SDKError = defineEvent<{\n errorType: string\n hookName: string\n}>({\n name: 'SDK Error',\n version: 1,\n description: 'Runtime error caught in the SDK',\n})\n","import {type SanityClient} from '@sanity/client'\nimport {\n type ConsentStatus,\n createBatchedStore,\n type SessionId,\n type TelemetryEvent,\n type TelemetryLogger,\n type TelemetryStore,\n} from '@sanity/telemetry'\n\nimport {createLogger} from '../utils/logger'\nimport {CORE_SDK_VERSION} from '../version'\nimport {type TelemetryEnvironment} from './environment'\nimport {SDKError, SDKHookMounted, SDKSessionEnded, SDKSessionStarted} from './events'\n\nconst FLUSH_INTERVAL_MS = 30_000\nconst CONSENT_TAG = 'telemetry-consent.sdk'\nconst BATCH_TAG = 'telemetry.batch'\n\nconst log = createLogger('telemetry')\n\n/**\n * Manages telemetry for a single SDK instance.\n *\n * Wraps `@sanity/telemetry`'s batched store with SDK-specific concerns:\n * consent caching, session lifecycle events, and hook usage tracking.\n * The `environment` is captured at construction time and recorded in\n * the event context so downstream pipelines can distinguish dev and\n * production sessions.\n *\n * @internal\n */\nexport interface TelemetryManager {\n /**\n * Eagerly resolve and cache the user's consent status.\n * Returns true only when the user has explicitly opted in (`granted`).\n * Call this before logging any events to avoid buffering events that\n * will be dropped on the first flush.\n */\n checkConsent(): Promise<boolean>\n\n /** Log a \"SDK Session Started\" event */\n logSessionStarted(data: {projectId: string; perspective: string; authMethod: string}): void\n\n /** Log a \"SDK Hook Mounted\" event (deduplicated per hook name) */\n logHookFirstUsed(hookName: string): void\n\n /** Log a \"SDK Error\" event */\n logError(errorType: string, hookName: string): void\n\n /** Log a \"SDK Session Ended\" event and tear down the store */\n endSession(): void\n\n /** Tear down the store without logging a session-end event */\n dispose(): void\n\n /** The set of hook names used during this session */\n readonly hooksUsed: ReadonlySet<string>\n}\n\ninterface TelemetryManagerOptions {\n sessionId: string\n getClient: () => SanityClient\n projectId: string\n environment: TelemetryEnvironment\n}\n\n/**\n * Creates a telemetry manager for a single SDK instance session.\n *\n * The manager initializes a `createBatchedStore` from `@sanity/telemetry`,\n * caches the consent check for the lifetime of the session, and provides\n * typed methods for each SDK telemetry event.\n *\n * @internal\n */\nexport function createTelemetryManager(options: TelemetryManagerOptions): TelemetryManager {\n const {sessionId, getClient, projectId, environment} = options\n const startedAt = Date.now()\n const emittedHooks = new Set<string>()\n\n let cachedConsent: {status: ConsentStatus} | null = null\n\n const resolveConsent = async (): Promise<{status: ConsentStatus}> => {\n if (cachedConsent) return cachedConsent\n try {\n const client = getClient()\n const result = await client.request<{status: ConsentStatus}>({\n url: '/intake/telemetry-status',\n tag: CONSENT_TAG,\n })\n cachedConsent = result\n } catch {\n cachedConsent = {status: 'undetermined'}\n }\n return cachedConsent\n }\n\n const enrichBatch = (batch: TelemetryEvent[]) =>\n batch.map((event) => {\n // Trace events (`trace.start` / `trace.log` / `trace.error` /\n // `trace.complete`) arrive with their own caller-provided `context`.\n // Log / userProperties events don't. Narrow via `in` so `event`\n // stays typed as `TelemetryEvent`, then merge so we don't drop the\n // trace context. SDK-owned fields below win on conflict.\n const existing =\n 'context' in event ? (event.context as Record<string, unknown> | undefined) : undefined\n return {\n ...event,\n context: {\n ...existing,\n version: CORE_SDK_VERSION,\n environment,\n origin: typeof window !== 'undefined' ? window.location.origin : 'node',\n },\n }\n })\n\n const sendEvents = async (batch: TelemetryEvent[]): Promise<unknown> => {\n const client = getClient()\n log.debug('sending event batch', {batchSize: batch.length, environment})\n return client.request({\n url: '/intake/batch',\n method: 'POST',\n body: {projectId, batch: enrichBatch(batch)},\n tag: BATCH_TAG,\n })\n }\n\n const store: TelemetryStore<Record<string, unknown>> = createBatchedStore(\n sessionId as SessionId,\n {\n flushInterval: FLUSH_INTERVAL_MS,\n resolveConsent,\n sendEvents,\n },\n )\n\n const logger: TelemetryLogger<Record<string, unknown>> = store.logger\n\n return {\n async checkConsent() {\n const {status} = await resolveConsent()\n return status === 'granted'\n },\n\n logSessionStarted(data) {\n log.debug('event: SDK Session Started', {\n projectId: data.projectId,\n perspective: data.perspective,\n authMethod: data.authMethod,\n version: CORE_SDK_VERSION,\n environment,\n })\n logger.log(SDKSessionStarted, {\n version: CORE_SDK_VERSION,\n ...data,\n })\n },\n\n logHookFirstUsed(hookName: string) {\n if (emittedHooks.has(hookName)) return\n emittedHooks.add(hookName)\n log.debug('event: SDK Hook Mounted', {hookName})\n logger.log(SDKHookMounted, {hookName})\n },\n\n logError(errorType: string, hookName: string) {\n log.debug('event: SDK Error', {errorType, hookName})\n logger.log(SDKError, {errorType, hookName})\n },\n\n endSession() {\n const durationSeconds = Math.round((Date.now() - startedAt) / 1000)\n log.debug('event: SDK Session Ended', {\n durationSeconds,\n hooksUsed: [...emittedHooks],\n environment,\n })\n logger.log(SDKSessionEnded, {\n durationSeconds,\n hooksUsed: [...emittedHooks],\n })\n\n store.flush().catch(() => {\n // Best-effort flush on dispose; swallow errors\n })\n store.end()\n },\n\n dispose() {\n store.end()\n },\n\n get hooksUsed(): ReadonlySet<string> {\n return emittedHooks\n },\n }\n}\n","import {type SanityInstance} from '../store/createSanityInstance'\nimport {createLogger} from '../utils/logger'\nimport {getTelemetryEnvironment} from './environment'\nimport {type TelemetryManager} from './telemetryManager'\n\nconst DEFAULT_TELEMETRY_API_VERSION = '2024-11-12'\n\nconst logger = createLogger('telemetry')\n\n/**\n * Per-instance map of active telemetry managers. Allows the React\n * package (and other consumers) to look up the manager for a given\n * instance and log hook usage / errors without importing the full\n * telemetry module themselves.\n *\n * @internal\n */\nconst telemetryManagers = new WeakMap<SanityInstance, TelemetryManager>()\nconst pendingHooks = new WeakMap<SanityInstance, Set<string>>()\nconst initInFlight = new WeakSet<SanityInstance>()\n\n/**\n * Initializes telemetry for a SDK instance if the runtime environment\n * qualifies. The environment is resolved by `getTelemetryEnvironment()`:\n *\n * - `'development'` — local dev servers (`localhost` / `127.0.0.1`, or\n * Node with `NODE_ENV=development`). This is the original opt-in\n * surface.\n * - `'production'` — apps deployed to Sanity-controlled domains\n * (e.g. `*.sanity.studio`, the dashboard). End users are\n * authenticated Sanity users with Populus consent records, so we\n * apply the same consent gate as the Studio's `telemetry-sink`.\n *\n * Apps on customer-controlled domains return `null` and skip telemetry\n * entirely.\n *\n * `telemetryManager` and `clientStore` are dynamically imported so the\n * telemetry code path stays out of production bundles for apps that\n * don't qualify. Only the lightweight environment check runs at boot.\n *\n * The `projectId` must be passed explicitly because the resource\n * configuration is typically set by the React layer after the\n * instance has already been created.\n *\n * @internal\n */\nexport function initTelemetry(instance: SanityInstance, projectId: string): void {\n const environment = getTelemetryEnvironment()\n if (!environment) {\n logger.trace('initTelemetry skipped: environment not eligible', {internal: true})\n return\n }\n if (!projectId) {\n logger.trace('initTelemetry skipped: no projectId', {internal: true})\n return\n }\n if (telemetryManagers.has(instance) || initInFlight.has(instance)) {\n return\n }\n initInFlight.add(instance)\n\n logger.debug('initializing telemetry', {projectId, environment})\n\n Promise.all([\n import('./telemetryManager'),\n import('../client/clientStore'),\n import('../auth/authStore'),\n ])\n .then(async ([{createTelemetryManager}, {getClient}, {getTokenState}]) => {\n if (instance.isDisposed()) {\n initInFlight.delete(instance)\n logger.debug('telemetry skipped: instance disposed before imports resolved')\n return\n }\n\n // Wait for the auth store to resolve a token. The client needs a\n // Bearer token for the consent check and batch POSTs. If the token\n // is already available (e.g. static token config), this resolves\n // immediately. For OAuth/localStorage discovery it waits for the\n // first emission. For unauthenticated apps the promise never\n // resolves, which is fine since telemetry requires auth anyway.\n const token = getTokenState(instance).getCurrent()\n logger.trace('auth token check', {tokenPresent: !!token, internal: true})\n\n if (!token) {\n logger.debug('waiting for auth token')\n const hasToken = await new Promise<boolean>((resolve) => {\n if (instance.isDisposed()) return resolve(false)\n const cleanup = {unsubscribe: () => {}}\n const unsub = instance.onDispose(() => {\n cleanup.unsubscribe()\n resolve(false)\n })\n // The token observable is a `shareReplay({bufferSize: 1, refCount: true})`\n // (see `createStateSourceAction`), so it can deliver a buffered value\n // synchronously while we're still inside `.subscribe(cb)`. At that\n // moment `sub` is in the TDZ, so the callback can't reach it. We\n // gate on a `received` flag and let the post-subscribe block do the\n // unsubscribe in the sync-emission case.\n let received = false\n const sub = getTokenState(instance).observable.subscribe((t) => {\n if (received || !t) return\n received = true\n logger.debug('auth token received')\n unsub()\n resolve(true)\n cleanup.unsubscribe()\n })\n cleanup.unsubscribe = () => sub.unsubscribe()\n if (received) cleanup.unsubscribe()\n })\n if (!hasToken || instance.isDisposed()) {\n initInFlight.delete(instance)\n logger.debug('telemetry skipped: no token resolved or instance disposed')\n return\n }\n }\n\n const manager = createTelemetryManager({\n sessionId: instance.instanceId,\n getClient: () => getClient(instance, {apiVersion: DEFAULT_TELEMETRY_API_VERSION}),\n projectId,\n environment,\n })\n\n const consented = await manager.checkConsent()\n logger.debug('consent check complete', {consented})\n if (!consented || instance.isDisposed()) {\n initInFlight.delete(instance)\n manager.dispose()\n return\n }\n\n initInFlight.delete(instance)\n telemetryManagers.set(instance, manager)\n\n const buffered = pendingHooks.get(instance)\n if (buffered) {\n logger.debug('flushing buffered hooks', {hooks: Array.from(buffered)})\n for (const hookName of buffered) {\n manager.logHookFirstUsed(hookName)\n }\n pendingHooks.delete(instance)\n }\n\n const config = instance.config\n const perspective = typeof config.perspective === 'string' ? config.perspective : 'published'\n const authMethod = config.auth?.token\n ? 'token'\n : config.studio?.auth?.token\n ? 'studio'\n : 'default'\n\n logger.info('telemetry session started', {projectId, perspective, authMethod, environment})\n manager.logSessionStarted({\n projectId,\n perspective,\n authMethod,\n })\n\n instance.onDispose(() => {\n manager.endSession()\n telemetryManagers.delete(instance)\n logger.debug('telemetry session ended')\n })\n })\n .catch((err) => {\n initInFlight.delete(instance)\n logger.warn('telemetry init failed', {error: err})\n })\n}\n\n/**\n * Retrieves the telemetry manager for an instance, if one exists.\n * Returns undefined when telemetry is disabled or not yet initialized.\n *\n * @internal\n */\nexport function getTelemetryManager(instance: SanityInstance): TelemetryManager | undefined {\n return telemetryManagers.get(instance)\n}\n\n/**\n * Record a hook name for an instance. If the telemetry manager is\n * already initialized the event is logged immediately. Otherwise\n * the name is buffered and flushed when init completes.\n *\n * @internal\n */\nexport function trackHookMounted(instance: SanityInstance, hookName: string): void {\n if (!getTelemetryEnvironment()) return\n\n const manager = findManager(instance)\n if (manager) {\n logger.trace('hook mounted (logged)', {hookName, internal: true})\n manager.logHookFirstUsed(hookName)\n return\n }\n\n const root = getRootInstance(instance)\n let hooks = pendingHooks.get(root)\n if (!hooks) {\n hooks = new Set()\n pendingHooks.set(root, hooks)\n }\n if (!hooks.has(hookName)) {\n logger.trace('hook mounted (buffered)', {hookName, internal: true})\n }\n hooks.add(hookName)\n}\n\nfunction findManager(instance: SanityInstance): TelemetryManager | undefined {\n return telemetryManagers.get(instance)\n}\n\nfunction getRootInstance(instance: SanityInstance): SanityInstance {\n return instance\n}\n","const WILDCARD_TOKEN = '*'\nconst NEGATION_TOKEN = '-'\n// This regex handles simple cases including quoted phrases.\n// More complex query syntaxes might need a more robust parser.\nconst TOKEN_REGEX = /(?:[^\\s\"]+|\"[^\"]*\")+/g\n\n/**\n * @internal\n * Checks if a token starts with the negation character.\n */\nfunction isNegationToken(token: string | undefined): boolean {\n return typeof token !== 'undefined' && token.trim().startsWith(NEGATION_TOKEN)\n}\n\n/**\n * @internal\n * Checks if a token ends with the wildcard character.\n */\nfunction isPrefixToken(token: string | undefined): boolean {\n return typeof token !== 'undefined' && token.trim().endsWith(WILDCARD_TOKEN)\n}\n\n/**\n * @internal\n * Checks if a token is enclosed in double quotes.\n */\nfunction isExactMatchToken(token: string | undefined): boolean {\n // Ensure the token exists, has at least 2 characters, and starts/ends with \"\n return !!token && token.length >= 2 && token.startsWith('\"') && token.endsWith('\"')\n}\n\n/**\n * Creates a GROQ search filter string (`[@] match text::query(\"...\")`)\n * from a raw search query string.\n *\n * It applies wildcard ('*') logic to the last eligible token and escapes\n * backslashes and double quotes within the search term.\n *\n * If the input query is empty or only whitespace, it returns an empty string.\n *\n * @param query - The raw input search string.\n * @returns The GROQ search filter string, or an empty string.\n * @internal\n */\nexport function createGroqSearchFilter(query: string): string {\n // Trim leading/trailing whitespace from the overall query first\n const trimmedQuery = query.trim()\n if (!trimmedQuery) {\n return '' // Return empty if query is empty or just whitespace\n }\n\n // Extract tokens using the regex\n const tokens = trimmedQuery.match(TOKEN_REGEX) ?? []\n\n // Find the index of the last token eligible for wildcard appending\n const reversedTokens = [...tokens].reverse()\n const reversedIndex = reversedTokens.findIndex(\n (token: string) => !isNegationToken(token) && !isExactMatchToken(token),\n )\n const finalIncrementalTokenIndex = reversedIndex === -1 ? -1 : tokens.length - 1 - reversedIndex\n\n // Get the actual token based on the found index\n const finalIncrementalToken = tokens[finalIncrementalTokenIndex]\n\n const processedTokens = [...tokens]\n // If a suitable token was found and it doesn't already end with a wildcard,\n // apply the wildcard.\n if (finalIncrementalToken !== undefined && !isPrefixToken(finalIncrementalToken)) {\n // Replace the identified token with its wildcarded version\n processedTokens.splice(\n finalIncrementalTokenIndex,\n 1,\n `${finalIncrementalToken}${WILDCARD_TOKEN}`,\n )\n }\n\n // Join the tokens back into a space-separated string\n const wildcardSearch = processedTokens.join(' ')\n\n // Escape backslashes and double quotes within the final search term for the\n // GROQ query. Backslashes go first, so the escapes added for quotes are not\n // themselves escaped. Without this a trailing backslash would escape the\n // closing quote and let the input break out of the string literal.\n const escapedSearch = wildcardSearch.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')\n\n // Construct the final GROQ filter clause\n return `[@] match text::query(\"${escapedSearch}\")`\n}\n"],"mappings":";;;;;;;;;;;;;AAMA,MAAa,mBAAmB;CAAC;CAAS;CAAQ;CAAS;CAAW;CAAU;AAAS,GAQ5E,sBAAsB;CAAC;CAAe;CAAY,GAAG;AAAgB,GAQrE,qBAAqB;;;MAG5B,iBAAiB,KAAK,UAAU,IAAI,MAAM,KAAK,OAAO,CAAC,CAAC,KAAK,WAAW,EAAE;;;;MAI1E,oBAAoB,KAAK,UAAU,IAAI,MAAM,KAAK,OAAO,CAAC,CAAC,KAAK,WAAW,EAAE;;;;;;;;;;;;;;;;;ACdnF,SAAS,YAAe,OAA6C;CACnE,OAAO,SAAS,KAAK,KAAK,UAAU,SAAS,OAAQ,MAA0B,QAAS;AAC1F;;;;;;;AAQA,SAAgB,eAAe,OAAgB,QAA6C;CAE1F,IADI,CAAC,SACD,CAAC,YAAY,KAAK,GAAG,OAAO;CAGhC,IAAM,MADU,sBAAsB,MACpB,CAAC,CAAC,MAAM,EAAC,MAAM,MAAM,KAAI,CAAC,CAAC,CAAC,IAAI;CAElD,OAAO;EACL,MAAM;EACN,MAAM,MAAM;EACZ;CACF;AACF;;;;;;;AAQA,SAAS,iBACP,gBACA,YACA,SACoB;CACf,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A0B,KAAA,KAAa,CAAC,cAAc,qBAAqB,KAE7E,gBAAgB,OACd,4BACA,GACA,GAAG,wBACL,GAaK,0BATgB,gBAAgB,KAAK,GAMT,CAAC,CAAC,QAAQ,OAAO,MAAM,CAAC,CAAC,QAAQ,MAAM,MAG7B,EAAE;AACjD"}
|
package/dist/_exports/agent.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { s as DocumentResource, t as SanityInstance } from "../createSanityInstance-
|
|
1
|
+
import { s as DocumentResource, t as SanityInstance } from "../createSanityInstance-BQIqyGLX.js";
|
|
2
2
|
import { SanityClient } from "@sanity/client";
|
|
3
3
|
import { Observable } from "rxjs";
|
|
4
4
|
/** @alpha */
|
|
@@ -28,7 +28,7 @@ type AgentPatchResult = Awaited<ReturnType<SanityClient['agent']['action']['patc
|
|
|
28
28
|
* @returns An Observable emitting the result of the agent generate action.
|
|
29
29
|
* @alpha
|
|
30
30
|
*/
|
|
31
|
-
declare function agentGenerate(instance: SanityInstance, options: AgentGenerateOptions, resource?: DocumentResource): AgentGenerateResult;
|
|
31
|
+
export declare function agentGenerate(instance: SanityInstance, options: AgentGenerateOptions, resource?: DocumentResource): AgentGenerateResult;
|
|
32
32
|
/**
|
|
33
33
|
* Transforms a document using the agent.
|
|
34
34
|
* @param instance - The Sanity instance.
|
|
@@ -36,7 +36,7 @@ declare function agentGenerate(instance: SanityInstance, options: AgentGenerateO
|
|
|
36
36
|
* @returns An Observable emitting the result of the agent transform action.
|
|
37
37
|
* @alpha
|
|
38
38
|
*/
|
|
39
|
-
declare function agentTransform(instance: SanityInstance, options: AgentTransformOptions, resource?: DocumentResource): AgentTransformResult;
|
|
39
|
+
export declare function agentTransform(instance: SanityInstance, options: AgentTransformOptions, resource?: DocumentResource): AgentTransformResult;
|
|
40
40
|
/**
|
|
41
41
|
* Translates a document using the agent.
|
|
42
42
|
* @param instance - The Sanity instance.
|
|
@@ -44,7 +44,7 @@ declare function agentTransform(instance: SanityInstance, options: AgentTransfor
|
|
|
44
44
|
* @returns An Observable emitting the result of the agent translate action.
|
|
45
45
|
* @alpha
|
|
46
46
|
*/
|
|
47
|
-
declare function agentTranslate(instance: SanityInstance, options: AgentTranslateOptions, resource?: DocumentResource): AgentTranslateResult;
|
|
47
|
+
export declare function agentTranslate(instance: SanityInstance, options: AgentTranslateOptions, resource?: DocumentResource): AgentTranslateResult;
|
|
48
48
|
/**
|
|
49
49
|
* Prompts the agent using the same instruction template format as the other actions, but returns text or json instead of acting on a document.
|
|
50
50
|
* @param instance - The Sanity instance.
|
|
@@ -52,7 +52,7 @@ declare function agentTranslate(instance: SanityInstance, options: AgentTranslat
|
|
|
52
52
|
* @returns An Observable emitting the result of the agent prompt action.
|
|
53
53
|
* @alpha
|
|
54
54
|
*/
|
|
55
|
-
declare function agentPrompt(instance: SanityInstance, options: AgentPromptOptions, resource?: DocumentResource): Observable<AgentPromptResult>;
|
|
55
|
+
export declare function agentPrompt(instance: SanityInstance, options: AgentPromptOptions, resource?: DocumentResource): Observable<AgentPromptResult>;
|
|
56
56
|
/**
|
|
57
57
|
* Patches a document using the agent.
|
|
58
58
|
* @param instance - The Sanity instance.
|
|
@@ -60,6 +60,6 @@ declare function agentPrompt(instance: SanityInstance, options: AgentPromptOptio
|
|
|
60
60
|
* @returns An Observable emitting the result of the agent patch action.
|
|
61
61
|
* @alpha
|
|
62
62
|
*/
|
|
63
|
-
declare function agentPatch(instance: SanityInstance, options: AgentPatchOptions, resource?: DocumentResource): Observable<AgentPatchResult>;
|
|
64
|
-
export {
|
|
63
|
+
export declare function agentPatch(instance: SanityInstance, options: AgentPatchOptions, resource?: DocumentResource): Observable<AgentPatchResult>;
|
|
64
|
+
export type { AgentGenerateOptions, AgentGenerateResult, AgentPatchOptions, AgentPatchResult, AgentPromptOptions, AgentPromptResult, AgentTransformOptions, AgentTransformResult, AgentTranslateOptions, AgentTranslateResult };
|
|
65
65
|
//# sourceMappingURL=agent.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.d.ts","names":[],"sources":["../../src/agent/agentActions.ts"],"mappings":";;;;KAUY,uBAAuB,WACjC;;KAIU,wBAAwB,WAClC;;KAIU,wBAAwB,WAClC;;KAIU,qBAAqB,WAAW;;KAGhC,oBAAoB,WAAW;;KAG/B,sBAAsB,QAChC,WAAW;;KAID,uBAAuB,QACjC,WAAW;;KAID,uBAAuB,QACjC,WAAW;;KAID,oBAAoB,QAAQ,WAAW;;KAGvC,mBAAmB,QAAQ,WAAW;;;;;;;;
|
|
1
|
+
{"version":3,"file":"agent.d.ts","names":[],"sources":["../../src/agent/agentActions.ts"],"mappings":";;;;KAUY,uBAAuB,WACjC;;KAIU,wBAAwB,WAClC;;KAIU,wBAAwB,WAClC;;KAIU,qBAAqB,WAAW;;KAGhC,oBAAoB,WAAW;;KAG/B,sBAAsB,QAChC,WAAW;;KAID,uBAAuB,QACjC,WAAW;;KAID,uBAAuB,QACjC,WAAW;;KAID,oBAAoB,QAAQ,WAAW;;KAGvC,mBAAmB,QAAQ,WAAW;;;;;;;;wBASlC,cACd,UAAU,gBACV,SAAS,sBACT,WAAW,mBACV;;;;;;;;wBAaa,eACd,UAAU,gBACV,SAAS,uBACT,WAAW,mBACV;;;;;;;;wBAaa,eACd,UAAU,gBACV,SAAS,uBACT,WAAW,mBACV;;;;;;;;wBAaa,YACd,UAAU,gBACV,SAAS,oBACT,WAAW,mBACV,WAAW;;;;;;;;wBAaE,WACd,UAAU,gBACV,SAAS,mBACT,WAAW,mBACV,WAAW"}
|
package/dist/_exports/agent.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { Bi as BoundStoreAction, zi as StateSource } from "../authStore-BO2vch3I.js";
|
|
2
2
|
import { ChannelInput, ChannelInstance, Controller, Message, Node, NodeInput, Status } from "@sanity/comlink";
|
|
3
3
|
/**
|
|
4
4
|
* Message sent from a containing app to an iframe
|
|
@@ -51,24 +51,24 @@ interface ComlinkControllerState {
|
|
|
51
51
|
* Calls the destroy method on the controller and resets the controller state.
|
|
52
52
|
* @public
|
|
53
53
|
*/
|
|
54
|
-
declare const destroyController: BoundStoreAction<ComlinkControllerState, [], void>;
|
|
54
|
+
export declare const destroyController: BoundStoreAction<ComlinkControllerState, [], void>;
|
|
55
55
|
/**
|
|
56
56
|
* Retrieve or create a channel to be used for communication between
|
|
57
57
|
* an application and the controller.
|
|
58
58
|
* @public
|
|
59
59
|
*/
|
|
60
|
-
declare const getOrCreateChannel: BoundStoreAction<ComlinkControllerState, [options: ChannelInput], ChannelInstance<import("@sanity/comlink").Message, import("@sanity/comlink").Message>>;
|
|
60
|
+
export declare const getOrCreateChannel: BoundStoreAction<ComlinkControllerState, [options: ChannelInput], ChannelInstance<import("@sanity/comlink").Message, import("@sanity/comlink").Message>>;
|
|
61
61
|
/**
|
|
62
62
|
* Initializes or fetches a controller to handle communication
|
|
63
63
|
* between an application and iframes.
|
|
64
64
|
* @public
|
|
65
65
|
*/
|
|
66
|
-
declare const getOrCreateController: BoundStoreAction<ComlinkControllerState, [targetOrigin: string], Controller>;
|
|
66
|
+
export declare const getOrCreateController: BoundStoreAction<ComlinkControllerState, [targetOrigin: string], Controller>;
|
|
67
67
|
/**
|
|
68
68
|
* Signals to the store that the consumer has stopped using the channel
|
|
69
69
|
* @public
|
|
70
70
|
*/
|
|
71
|
-
declare const releaseChannel: BoundStoreAction<ComlinkControllerState, [name: string], void>;
|
|
71
|
+
export declare const releaseChannel: BoundStoreAction<ComlinkControllerState, [name: string], void>;
|
|
72
72
|
/**
|
|
73
73
|
* Individual node with its relevant options
|
|
74
74
|
* @public
|
|
@@ -91,14 +91,14 @@ interface ComlinkNodeState {
|
|
|
91
91
|
* Signals to the store that the consumer has stopped using the node
|
|
92
92
|
* @public
|
|
93
93
|
*/
|
|
94
|
-
declare const releaseNode: BoundStoreAction<ComlinkNodeState, [name: string], void>;
|
|
94
|
+
export declare const releaseNode: BoundStoreAction<ComlinkNodeState, [name: string], void>;
|
|
95
95
|
/**
|
|
96
96
|
* Retrieve or create a node to be used for communication between
|
|
97
97
|
* an application and the controller -- specifically, a node should
|
|
98
98
|
* be created within a frame / window to communicate with the controller.
|
|
99
99
|
* @public
|
|
100
100
|
*/
|
|
101
|
-
declare const getOrCreateNode: BoundStoreAction<ComlinkNodeState, [options: NodeInput], Node<import("@sanity/comlink").Message, import("@sanity/comlink").Message>>;
|
|
101
|
+
export declare const getOrCreateNode: BoundStoreAction<ComlinkNodeState, [options: NodeInput], Node<import("@sanity/comlink").Message, import("@sanity/comlink").Message>>;
|
|
102
102
|
/**
|
|
103
103
|
* @public
|
|
104
104
|
*/
|
|
@@ -113,6 +113,6 @@ interface NodeState {
|
|
|
113
113
|
* @returns A subscribable state source for the node
|
|
114
114
|
* @public
|
|
115
115
|
*/
|
|
116
|
-
declare const getNodeState: BoundStoreAction<ComlinkNodeState, [NodeInput], StateSource<NodeState | undefined>>;
|
|
117
|
-
export {
|
|
116
|
+
export declare const getNodeState: BoundStoreAction<ComlinkNodeState, [NodeInput], StateSource<NodeState | undefined>>;
|
|
117
|
+
export type { ComlinkControllerState, ComlinkNodeState, FrameMessage, NewTokenResponseMessage, NodeState, RequestNewTokenMessage, WindowMessage };
|
|
118
118
|
//# sourceMappingURL=comlink.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"comlink.d.ts","names":[],"sources":["../../src/comlink/types.ts","../../src/comlink/controller/comlinkControllerStore.ts","../../src/comlink/node/comlinkNodeStore.ts","../../src/comlink/node/getNodeState.ts"],"mappings":";;;;;;KAMY,eAAe;;;;;KAMf,gBAAgB;;;;;KAMhB;EACV;EACA;;;;;;KAOU;EACV;EACA;IAAU;IAAsB;;;;;;;UCfjB;EACf,SAAS,gBAAgB,cAAc;EAEvC,SAAS;EAET;;;;;;UAOe;EACf,YAAY;EACZ;EACA,UAAU,YAAY;;;;;;
|
|
1
|
+
{"version":3,"file":"comlink.d.ts","names":[],"sources":["../../src/comlink/types.ts","../../src/comlink/controller/comlinkControllerStore.ts","../../src/comlink/node/comlinkNodeStore.ts","../../src/comlink/node/getNodeState.ts"],"mappings":";;;;;;KAMY,eAAe;;;;;KAMf,gBAAgB;;;;;KAMhB;EACV;EACA;;;;;;KAOU;EACV;EACA;IAAU;IAAsB;;;;;;;UCfjB;EACf,SAAS,gBAAgB,cAAc;EAEvC,SAAS;EAET;;;;;;UAOe;EACf,YAAY;EACZ;EACA,UAAU,YAAY;;;;;;qBAyBX,mBAAiB,iBAAA;;;;;;qBAUjB,oBAAkB,iBAAA,yBAAA,SAAA,eAAA,0CAAA,mCAAA;;;;;;qBAUlB,uBAAqB,iBAAA,yBAAA,uBAAA;;;;;qBASrB,gBAAc,iBAAA,yBAAA;;;;;UCvEV;EACf,MAAM,KAAK,eAAe;EAE1B,SAAS;EAET,QAAQ;EACR;;;;;;UAOe;EACf,OAAO,YAAY;EAEnB,eAAe,YAAY;;;;;;qBAuBhB,aAAW,iBAAA,mBAAA;;;;;;;qBAQX,iBAAe,iBAAA,mBAAA,SAAA,YAAA,+BAAA,mCAAA;;;;UCvCX;EACf,MAAM,KAAK,eAAe;EAC1B,QAAQ;;;;;;;;;qBAaG,cAAY,iBAAA,mBAAA,YAAA,YAAA"}
|
package/dist/_exports/comlink.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { i as bindActionGlobally, o as defineStore } from "../createStateSourceAction-DdAhEfnZ.js";
|
|
2
|
+
import { t as isDeepEqual } from "../object-CxXlSVg7.js";
|
|
3
|
+
import { n as getOrCreateNode, r as releaseNode, t as getNodeState } from "../getNodeState-B4nG0sjm.js";
|
|
3
4
|
import { createController } from "@sanity/comlink";
|
|
4
5
|
/**
|
|
5
6
|
* Calls the destroy method on the controller and resets the controller state.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"comlink.js","names":["destroyController","getOrCreateChannel","getOrCreateController","releaseChannel","unboundDestroyController","unboundGetOrCreateChannel","unboundGetOrCreateController","unboundReleaseChannel"],"sources":["../../src/comlink/controller/actions/destroyController.ts","../../src/comlink/controller/actions/getOrCreateChannel.ts","../../src/comlink/controller/actions/getOrCreateController.ts","../../src/comlink/controller/actions/releaseChannel.ts","../../src/comlink/controller/comlinkControllerStore.ts"],"sourcesContent":["import {type StoreContext} from '../../../store/defineStore'\nimport {type ComlinkControllerState} from '../comlinkControllerStore'\n\n/**\n * Calls the destroy method on the controller and resets the controller state.\n * @public\n */\nexport const destroyController = ({state}: StoreContext<ComlinkControllerState>): void => {\n const {controller} = state.get()\n\n if (controller) {\n controller.destroy()\n state.set('destroyController', {\n controller: null,\n channels: new Map(),\n })\n }\n}\n","import {type ChannelInput, type ChannelInstance} from '@sanity/comlink'\n\nimport {type StoreContext} from '../../../store/defineStore'\nimport {isDeepEqual} from '../../../utils/object'\nimport {type FrameMessage, type WindowMessage} from '../../types'\nimport {type ComlinkControllerState} from '../comlinkControllerStore'\n\n/**\n * Retrieve or create a channel to be used for communication between\n * an application and the controller.\n * @public\n */\nexport const getOrCreateChannel = (\n {state}: StoreContext<ComlinkControllerState>,\n options: ChannelInput,\n): ChannelInstance<FrameMessage, WindowMessage> => {\n const controller = state.get().controller\n\n if (!controller) {\n throw new Error('Controller must be initialized before using or creating channels')\n }\n\n const channels = state.get().channels\n const existing = channels.get(options.name)\n\n // limit channels to one per name\n if (existing) {\n if (!isDeepEqual(existing.options, options)) {\n throw new Error(`Channel \"${options.name}\" already exists with different options`)\n }\n\n state.set('incrementChannelRefCount', {\n channels: new Map(channels).set(options.name, {\n ...existing,\n refCount: existing.refCount + 1,\n }),\n })\n existing.channel.start()\n return existing.channel\n }\n\n const channel = controller.createChannel(options)\n channel.start()\n state.set('createChannel', {\n channels: new Map(channels).set(options.name, {\n channel,\n options,\n refCount: 1,\n }),\n })\n\n return channel\n}\n","import {type Controller, createController} from '@sanity/comlink'\n\nimport {type StoreContext} from '../../../store/defineStore'\nimport {type ComlinkControllerState} from '../comlinkControllerStore'\nimport {destroyController} from './destroyController'\n\n/**\n * Initializes or fetches a controller to handle communication\n * between an application and iframes.\n * @public\n */\nexport const getOrCreateController = (\n {state, instance}: StoreContext<ComlinkControllerState>,\n targetOrigin: string,\n): Controller => {\n const {controller, controllerOrigin} = state.get()\n if (controller && controllerOrigin === targetOrigin) {\n return controller\n }\n\n // if the target origin has changed, we'll create a new controller,\n // but need to clean up first\n if (controller) {\n destroyController({state, instance, key: undefined})\n }\n\n const newController = createController({targetOrigin})\n state.set('initializeController', {\n controllerOrigin: targetOrigin,\n controller: newController,\n })\n\n return newController\n}\n","import {type StoreContext} from '../../../store/defineStore'\nimport {type ComlinkControllerState} from '../comlinkControllerStore'\n\n/**\n * Signals to the store that the consumer has stopped using the channel\n * @public\n */\nexport const releaseChannel = (\n {state}: StoreContext<ComlinkControllerState>,\n name: string,\n): void => {\n const channels = state.get().channels\n const channelEntry = channels.get(name)\n\n if (channelEntry) {\n const newRefCount = channelEntry.refCount === 0 ? 0 : channelEntry.refCount - 1\n\n if (newRefCount === 0) {\n channelEntry.channel.stop()\n channels.delete(name)\n state.set('releaseChannel', {channels: new Map(channels)})\n } else {\n state.set('releaseChannel', {\n channels: new Map(channels).set(name, {\n ...channelEntry,\n refCount: newRefCount,\n }),\n })\n }\n }\n}\n","import {type ChannelInput, type ChannelInstance, type Controller} from '@sanity/comlink'\n\nimport {bindActionGlobally} from '../../store/createActionBinder'\nimport {defineStore} from '../../store/defineStore'\nimport {type FrameMessage, type WindowMessage} from '../types'\nimport {destroyController as unboundDestroyController} from './actions/destroyController'\nimport {getOrCreateChannel as unboundGetOrCreateChannel} from './actions/getOrCreateChannel'\nimport {getOrCreateController as unboundGetOrCreateController} from './actions/getOrCreateController'\nimport {releaseChannel as unboundReleaseChannel} from './actions/releaseChannel'\n\n/**\n * Individual channel with its relevant options\n * @public\n */\nexport interface ChannelEntry {\n channel: ChannelInstance<FrameMessage, WindowMessage>\n // we store options to ensure that channels remain as unique / consistent as possible\n options: ChannelInput\n // we store refCount to ensure channels remain open only as long as they are in use\n refCount: number\n}\n\n/**\n * Internal state tracking comlink connections\n * @public\n */\nexport interface ComlinkControllerState {\n controller: Controller | null\n controllerOrigin: string | null\n channels: Map<string, ChannelEntry>\n}\n\nexport const comlinkControllerStore = defineStore<ComlinkControllerState>({\n name: 'connectionStore',\n getInitialState: () => {\n const initialState = {\n controller: null,\n controllerOrigin: null,\n channels: new Map(),\n }\n return initialState\n },\n initialize({instance}) {\n return () => {\n // destroying controller also destroys channels\n destroyController(instance)\n }\n },\n})\n\n/**\n * Calls the destroy method on the controller and resets the controller state.\n * @public\n */\nexport const destroyController = bindActionGlobally(\n comlinkControllerStore,\n unboundDestroyController,\n)\n\n/**\n * Retrieve or create a channel to be used for communication between\n * an application and the controller.\n * @public\n */\nexport const getOrCreateChannel = bindActionGlobally(\n comlinkControllerStore,\n unboundGetOrCreateChannel,\n)\n\n/**\n * Initializes or fetches a controller to handle communication\n * between an application and iframes.\n * @public\n */\nexport const getOrCreateController = bindActionGlobally(\n comlinkControllerStore,\n unboundGetOrCreateController,\n)\n\n/**\n * Signals to the store that the consumer has stopped using the channel\n * @public\n */\nexport const releaseChannel = bindActionGlobally(comlinkControllerStore, unboundReleaseChannel)\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"comlink.js","names":["destroyController","getOrCreateChannel","getOrCreateController","releaseChannel","unboundDestroyController","unboundGetOrCreateChannel","unboundGetOrCreateController","unboundReleaseChannel"],"sources":["../../src/comlink/controller/actions/destroyController.ts","../../src/comlink/controller/actions/getOrCreateChannel.ts","../../src/comlink/controller/actions/getOrCreateController.ts","../../src/comlink/controller/actions/releaseChannel.ts","../../src/comlink/controller/comlinkControllerStore.ts"],"sourcesContent":["import {type StoreContext} from '../../../store/defineStore'\nimport {type ComlinkControllerState} from '../comlinkControllerStore'\n\n/**\n * Calls the destroy method on the controller and resets the controller state.\n * @public\n */\nexport const destroyController = ({state}: StoreContext<ComlinkControllerState>): void => {\n const {controller} = state.get()\n\n if (controller) {\n controller.destroy()\n state.set('destroyController', {\n controller: null,\n channels: new Map(),\n })\n }\n}\n","import {type ChannelInput, type ChannelInstance} from '@sanity/comlink'\n\nimport {type StoreContext} from '../../../store/defineStore'\nimport {isDeepEqual} from '../../../utils/object'\nimport {type FrameMessage, type WindowMessage} from '../../types'\nimport {type ComlinkControllerState} from '../comlinkControllerStore'\n\n/**\n * Retrieve or create a channel to be used for communication between\n * an application and the controller.\n * @public\n */\nexport const getOrCreateChannel = (\n {state}: StoreContext<ComlinkControllerState>,\n options: ChannelInput,\n): ChannelInstance<FrameMessage, WindowMessage> => {\n const controller = state.get().controller\n\n if (!controller) {\n throw new Error('Controller must be initialized before using or creating channels')\n }\n\n const channels = state.get().channels\n const existing = channels.get(options.name)\n\n // limit channels to one per name\n if (existing) {\n if (!isDeepEqual(existing.options, options)) {\n throw new Error(`Channel \"${options.name}\" already exists with different options`)\n }\n\n state.set('incrementChannelRefCount', {\n channels: new Map(channels).set(options.name, {\n ...existing,\n refCount: existing.refCount + 1,\n }),\n })\n existing.channel.start()\n return existing.channel\n }\n\n const channel = controller.createChannel(options)\n channel.start()\n state.set('createChannel', {\n channels: new Map(channels).set(options.name, {\n channel,\n options,\n refCount: 1,\n }),\n })\n\n return channel\n}\n","import {type Controller, createController} from '@sanity/comlink'\n\nimport {type StoreContext} from '../../../store/defineStore'\nimport {type ComlinkControllerState} from '../comlinkControllerStore'\nimport {destroyController} from './destroyController'\n\n/**\n * Initializes or fetches a controller to handle communication\n * between an application and iframes.\n * @public\n */\nexport const getOrCreateController = (\n {state, instance}: StoreContext<ComlinkControllerState>,\n targetOrigin: string,\n): Controller => {\n const {controller, controllerOrigin} = state.get()\n if (controller && controllerOrigin === targetOrigin) {\n return controller\n }\n\n // if the target origin has changed, we'll create a new controller,\n // but need to clean up first\n if (controller) {\n destroyController({state, instance, key: undefined})\n }\n\n const newController = createController({targetOrigin})\n state.set('initializeController', {\n controllerOrigin: targetOrigin,\n controller: newController,\n })\n\n return newController\n}\n","import {type StoreContext} from '../../../store/defineStore'\nimport {type ComlinkControllerState} from '../comlinkControllerStore'\n\n/**\n * Signals to the store that the consumer has stopped using the channel\n * @public\n */\nexport const releaseChannel = (\n {state}: StoreContext<ComlinkControllerState>,\n name: string,\n): void => {\n const channels = state.get().channels\n const channelEntry = channels.get(name)\n\n if (channelEntry) {\n const newRefCount = channelEntry.refCount === 0 ? 0 : channelEntry.refCount - 1\n\n if (newRefCount === 0) {\n channelEntry.channel.stop()\n channels.delete(name)\n state.set('releaseChannel', {channels: new Map(channels)})\n } else {\n state.set('releaseChannel', {\n channels: new Map(channels).set(name, {\n ...channelEntry,\n refCount: newRefCount,\n }),\n })\n }\n }\n}\n","import {type ChannelInput, type ChannelInstance, type Controller} from '@sanity/comlink'\n\nimport {bindActionGlobally} from '../../store/createActionBinder'\nimport {defineStore} from '../../store/defineStore'\nimport {type FrameMessage, type WindowMessage} from '../types'\nimport {destroyController as unboundDestroyController} from './actions/destroyController'\nimport {getOrCreateChannel as unboundGetOrCreateChannel} from './actions/getOrCreateChannel'\nimport {getOrCreateController as unboundGetOrCreateController} from './actions/getOrCreateController'\nimport {releaseChannel as unboundReleaseChannel} from './actions/releaseChannel'\n\n/**\n * Individual channel with its relevant options\n * @public\n */\nexport interface ChannelEntry {\n channel: ChannelInstance<FrameMessage, WindowMessage>\n // we store options to ensure that channels remain as unique / consistent as possible\n options: ChannelInput\n // we store refCount to ensure channels remain open only as long as they are in use\n refCount: number\n}\n\n/**\n * Internal state tracking comlink connections\n * @public\n */\nexport interface ComlinkControllerState {\n controller: Controller | null\n controllerOrigin: string | null\n channels: Map<string, ChannelEntry>\n}\n\nexport const comlinkControllerStore = defineStore<ComlinkControllerState>({\n name: 'connectionStore',\n getInitialState: () => {\n const initialState = {\n controller: null,\n controllerOrigin: null,\n channels: new Map(),\n }\n return initialState\n },\n initialize({instance}) {\n return () => {\n // destroying controller also destroys channels\n destroyController(instance)\n }\n },\n})\n\n/**\n * Calls the destroy method on the controller and resets the controller state.\n * @public\n */\nexport const destroyController = bindActionGlobally(\n comlinkControllerStore,\n unboundDestroyController,\n)\n\n/**\n * Retrieve or create a channel to be used for communication between\n * an application and the controller.\n * @public\n */\nexport const getOrCreateChannel = bindActionGlobally(\n comlinkControllerStore,\n unboundGetOrCreateChannel,\n)\n\n/**\n * Initializes or fetches a controller to handle communication\n * between an application and iframes.\n * @public\n */\nexport const getOrCreateController = bindActionGlobally(\n comlinkControllerStore,\n unboundGetOrCreateController,\n)\n\n/**\n * Signals to the store that the consumer has stopped using the channel\n * @public\n */\nexport const releaseChannel = bindActionGlobally(comlinkControllerStore, unboundReleaseChannel)\n"],"mappings":";;;;;;;;AAOA,MAAaA,uBAAqB,EAAC,YAAuD;CACxF,IAAM,EAAC,eAAc,MAAM,IAAI;CAE/B,AAAI,eACF,WAAW,QAAQ,GACnB,MAAM,IAAI,qBAAqB;EAC7B,YAAY;EACZ,0BAAU,IAAI,IAAI;CACpB,CAAC;AAEL,GCLaC,wBACX,EAAC,SACD,YACiD;CACjD,IAAM,aAAa,MAAM,IAAI,CAAC,CAAC;CAE/B,IAAI,CAAC,YACH,MAAU,MAAM,kEAAkE;CAGpF,IAAM,WAAW,MAAM,IAAI,CAAC,CAAC,UACvB,WAAW,SAAS,IAAI,QAAQ,IAAI;CAG1C,IAAI,UAAU;EACZ,IAAI,CAAC,YAAY,SAAS,SAAS,OAAO,GACxC,MAAU,MAAM,YAAY,QAAQ,KAAK,wCAAwC;EAUnF,OAPA,MAAM,IAAI,4BAA4B,EACpC,UAAU,IAAI,IAAI,QAAQ,CAAC,CAAC,IAAI,QAAQ,MAAM;GAC5C,GAAG;GACH,UAAU,SAAS,WAAW;EAChC,CAAC,EACH,CAAC,GACD,SAAS,QAAQ,MAAM,GAChB,SAAS;CAClB;CAEA,IAAM,UAAU,WAAW,cAAc,OAAO;CAUhD,OATA,QAAQ,MAAM,GACd,MAAM,IAAI,iBAAiB,EACzB,UAAU,IAAI,IAAI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|
1
|
+
import { A as PayloadOf, C as ApplicationConfig, D as EventTopicDef, E as EventTopic, F as TopicName, I as TopicResult, L as Topics, M as ReplyOf, N as StateTopic, O as NavigationLocation, P as StateTopicDef, R as ValueOf, T as DashboardTopics, _ as MessageBusMeta, a as ConnectMessageBusOptions, b as connectMessageBus, c as MessageBusAbortOptions, d as MessageBusEmitOptions, f as MessageBusEmitResult, g as MessageBusMessage, h as MessageBusHost, j as RemoteModuleRef, k as NavigationTarget, l as MessageBusClient, m as MessageBusErrorCode, n as TopicError, p as MessageBusError, s as MessageBus, t as TopicData, u as MessageBusConnection, v as MessageBusQueryOptions, w as ApplicationConfigAppType, y as MessageBusStateSource } from "../topicStore-D0WqhQGF.js";
|
|
2
|
+
export { type ApplicationConfig, type ApplicationConfigAppType, type ConnectMessageBusOptions, type DashboardTopics, type EventTopic, type EventTopicDef, type MessageBus, type MessageBusAbortOptions, type MessageBusClient, type MessageBusConnection, type MessageBusEmitOptions, type MessageBusEmitResult, MessageBusError, type MessageBusErrorCode, type MessageBusHost, type MessageBusMessage, type MessageBusMeta, type MessageBusQueryOptions, type MessageBusStateSource, type NavigationLocation, type NavigationTarget, type PayloadOf, type RemoteModuleRef, type ReplyOf, type StateTopic, type StateTopicDef, type TopicData, TopicError, type TopicName, type TopicResult, type Topics, type ValueOf, connectMessageBus };
|