@sanity/sdk 3.4.0-rc.0 → 3.5.0-next.20260922182803
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 +4 -4
- package/dist/_exports/_internal.d.ts.map +1 -1
- package/dist/_exports/_internal.js +5 -5
- package/dist/_exports/_internal.js.map +1 -1
- package/dist/_exports/agent.d.ts +1 -1
- package/dist/_exports/agent.js +1 -1
- package/dist/_exports/comlink.d.ts +1 -1
- package/dist/_exports/dashboard.d.ts +2 -2
- package/dist/_exports/dashboard.js +2 -2
- package/dist/{applications-903KQTrD.d.ts → applications-BKrtfXA2.d.ts} +10 -20
- package/dist/applications-BKrtfXA2.d.ts.map +1 -0
- package/dist/{clientStore-QDrJNTM4.js → clientStore-CD-USpIU.js} +11 -15
- package/dist/clientStore-CD-USpIU.js.map +1 -0
- package/dist/{createSanityInstance--Lrldto8.d.ts → createSanityInstance-BQIqyGLX.d.ts} +3 -6
- package/dist/createSanityInstance-BQIqyGLX.d.ts.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +204 -211
- package/dist/index.js.map +1 -1
- package/dist/{topicStore-BJ54_X6H.js → topicStore-CPhGph6z.js} +53 -13
- package/dist/topicStore-CPhGph6z.js.map +1 -0
- package/dist/{topicStore-VQILEI1R.d.ts → topicStore-e_kQ8ZvS.d.ts} +110 -6
- package/dist/topicStore-e_kQ8ZvS.d.ts.map +1 -0
- package/dist/{version-CYqZgJX1.js → version-BKdIDRP1.js} +3 -3
- package/dist/{version-CYqZgJX1.js.map → version-BKdIDRP1.js.map} +1 -1
- package/package.json +6 -6
- package/src/_exports/dashboard.ts +7 -0
- package/src/applications/applicationOrigin.ts +3 -1
- package/src/auth/authStore.test.ts +0 -18
- package/src/auth/authStore.ts +1 -4
- package/src/auth/handleAuthCallback.test.ts +0 -33
- package/src/auth/handleAuthCallback.ts +1 -11
- package/src/auth/logout.test.ts +1 -9
- package/src/auth/logout.ts +1 -18
- package/src/auth/oauth/oauthActions.test.ts +1 -178
- package/src/auth/oauth/oauthActions.ts +46 -111
- package/src/auth/oauth/oauthAuth.test.ts +0 -23
- package/src/auth/oauth/oauthAuth.ts +8 -18
- package/src/config/authConfig.ts +2 -5
- package/src/dashboard/messageBus/bus.test.ts +118 -0
- package/src/dashboard/messageBus/bus.ts +81 -7
- package/src/dashboard/messageBus/topics.test.ts +29 -2
- package/src/dashboard/messageBus/topics.ts +94 -2
- package/src/document/documentConstants.ts +5 -2
- package/src/document/documentStore.test.ts +194 -0
- package/src/document/documentStore.ts +79 -39
- package/src/document/reducers.ts +2 -2
- package/src/installations/installations.ts +4 -0
- package/dist/applications-903KQTrD.d.ts.map +0 -1
- package/dist/clientStore-QDrJNTM4.js.map +0 -1
- package/dist/createSanityInstance--Lrldto8.d.ts.map +0 -1
- package/dist/topicStore-BJ54_X6H.js.map +0 -1
- package/dist/topicStore-VQILEI1R.d.ts.map +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { m as SanityConfig, s as DocumentResource, t as SanityInstance } from "../createSanityInstance
|
|
2
|
-
import { Ai as CacheWriter, Ar as getCommentsOptionsKey, Bi as BoundStoreAction, Et as GetUsersOptions, Fi as MutationResult, G as getQueryKey, Ii as defineFetcher, Li as defineMutation, Mi as FetcherDefinition, Mr as parseCommentsOptionsKey, Ni as FetcherSnapshot, Pi as MutationDefinition, Sr as createLogger, ct as PreviewValue, ji as Fetcher, ki as CacheTag, q as parseQueryKey, r as ApplicationBase, st as PreviewQueryResult } from "../applications-
|
|
3
|
-
import {
|
|
1
|
+
import { m as SanityConfig, s as DocumentResource, t as SanityInstance } from "../createSanityInstance-BQIqyGLX.js";
|
|
2
|
+
import { Ai as CacheWriter, Ar as getCommentsOptionsKey, Bi as BoundStoreAction, Et as GetUsersOptions, Fi as MutationResult, G as getQueryKey, Ii as defineFetcher, Li as defineMutation, Mi as FetcherDefinition, Mr as parseCommentsOptionsKey, Ni as FetcherSnapshot, Pi as MutationDefinition, Sr as createLogger, ct as PreviewValue, ji as Fetcher, ki as CacheTag, q as parseQueryKey, r as ApplicationBase, st as PreviewQueryResult } from "../applications-BKrtfXA2.js";
|
|
3
|
+
import { D as ApplicationStatus, I as MessageBusTopics, O as ApplicationStatusUpdate, S as resetMessageBus, i as resolveTopic, o as InstallMessageBusOptions, r as getTopicState, u as MessageBusConnection, x as installMessageBus } from "../topicStore-e_kQ8ZvS.js";
|
|
4
4
|
import { ClientError, SanityClient } from "@sanity/client";
|
|
5
5
|
import { Observable } from "rxjs";
|
|
6
6
|
import { CurrentUser } from "@sanity/types";
|
|
@@ -11,7 +11,7 @@ import { CurrentUser } from "@sanity/types";
|
|
|
11
11
|
*
|
|
12
12
|
* @internal
|
|
13
13
|
*/
|
|
14
|
-
export declare function getApplicationOrigin(application: ApplicationBase): string | null;
|
|
14
|
+
export declare function getApplicationOrigin(application: Pick<ApplicationBase, 'externalUrl' | 'slug' | 'isSingleton' | 'organizationId'>): string | null;
|
|
15
15
|
/**
|
|
16
16
|
* Returns `true` when the config indicates the SDK is running inside a Studio.
|
|
17
17
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"_internal.d.ts","names":[],"sources":["../../src/applications/applicationOrigin.ts","../../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":";;;;;;;;;;;;;wBAWgB,
|
|
1
|
+
{"version":3,"file":"_internal.d.ts","names":[],"sources":["../../src/applications/applicationOrigin.ts","../../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":";;;;;;;;;;;;;wBAWgB,qBACd,aAAa,KAAK;;;;;;wBC+BJ,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,qBAAA;;;;;;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,7 +1,7 @@
|
|
|
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-
|
|
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-
|
|
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-CD-USpIU.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-BKdIDRP1.js";
|
|
3
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-
|
|
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-CPhGph6z.js";
|
|
5
5
|
import "@sanity/client";
|
|
6
6
|
import { createImageUrlBuilder } from "@sanity/image-url";
|
|
7
7
|
import { createBatchedStore, defineEvent } from "@sanity/telemetry";
|
|
@@ -328,8 +328,8 @@ function initTelemetry(instance, projectId) {
|
|
|
328
328
|
environment
|
|
329
329
|
}), Promise.all([
|
|
330
330
|
Promise.resolve().then(() => telemetryManager_exports),
|
|
331
|
-
import("../clientStore-
|
|
332
|
-
import("../clientStore-
|
|
331
|
+
import("../clientStore-CD-USpIU.js").then((n) => n.t),
|
|
332
|
+
import("../clientStore-CD-USpIU.js").then((n) => n.a)
|
|
333
333
|
]).then(async ([{ createTelemetryManager }, { getClient }, { getTokenState }]) => {
|
|
334
334
|
if (instance.isDisposed()) {
|
|
335
335
|
initInFlight.delete(instance), logger.debug("telemetry skipped: instance disposed before imports resolved");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"_internal.js","names":[],"sources":["../../src/applications/applicationOrigin.ts","../../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":["import {type ApplicationBase} from './applications'\n\ntype SanityGlobal = typeof globalThis & {__SANITY_STAGING__?: boolean}\n\n/**\n * The origin an application is served from, or `null` when it has neither an external URL nor\n * a slug to derive one from. Callers treat `null` as \"nothing to load\" rather than failing the\n * whole list on one bad record.\n *\n * @internal\n */\nexport function getApplicationOrigin(application: ApplicationBase): string | null {\n if (application.externalUrl !== null) return new URL(application.externalUrl).origin\n if (application.slug === null) return null\n\n // Read at runtime, not via a bundler define: a remote is built once and runs in whichever\n // host page loaded it, and the host sets this flag. Mirrors workbench's `getSanityEnv`.\n const staging = (globalThis as SanityGlobal).__SANITY_STAGING__ === true\n if (application.isSingleton) {\n const domain = staging ? 'run.sanity.work' : 'sanity.run'\n return `https://${application.slug}-apps-${application.organizationId}.${domain}`\n }\n\n const domain = staging ? 'studio.sanity.work' : 'sanity.studio'\n return `https://${application.slug}.${domain}`\n}\n","/**\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"],"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C,QAAQ,OAAO,MAAM,CAAC,CAAC,QAAQ,MAAM,MAG7B,EAAE;AACjD"}
|
|
1
|
+
{"version":3,"file":"_internal.js","names":[],"sources":["../../src/applications/applicationOrigin.ts","../../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":["import {type ApplicationBase} from './applications'\n\ntype SanityGlobal = typeof globalThis & {__SANITY_STAGING__?: boolean}\n\n/**\n * The origin an application is served from, or `null` when it has neither an external URL nor\n * a slug to derive one from. Callers treat `null` as \"nothing to load\" rather than failing the\n * whole list on one bad record.\n *\n * @internal\n */\nexport function getApplicationOrigin(\n application: Pick<ApplicationBase, 'externalUrl' | 'slug' | 'isSingleton' | 'organizationId'>,\n): string | null {\n if (application.externalUrl !== null) return new URL(application.externalUrl).origin\n if (application.slug === null) return null\n\n // Read at runtime, not via a bundler define: a remote is built once and runs in whichever\n // host page loaded it, and the host sets this flag. Mirrors workbench's `getSanityEnv`.\n const staging = (globalThis as SanityGlobal).__SANITY_STAGING__ === true\n if (application.isSingleton) {\n const domain = staging ? 'run.sanity.work' : 'sanity.run'\n return `https://${application.slug}-apps-${application.organizationId}.${domain}`\n }\n\n const domain = staging ? 'studio.sanity.work' : 'sanity.studio'\n return `https://${application.slug}.${domain}`\n}\n","/**\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":";;;;;;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AM,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 */
|
package/dist/_exports/agent.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Bi as BoundStoreAction, zi as StateSource } from "../applications-
|
|
1
|
+
import { Bi as BoundStoreAction, zi as StateSource } from "../applications-BKrtfXA2.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
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { B as
|
|
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 };
|
|
1
|
+
import { A as CapabilityRecord, B as RemoteModuleRef, C as ApplicationActivity, E as ApplicationContext, F as LocalApplication, G as TopicResult, H as StateTopic, J as capabilities, K as Topics, L as NavigationLocation, M as DocumentActivity, N as EventTopic, P as EventTopicDef, R as NavigationTarget, T as ApplicationConfigAppType, U as StateTopicDef, V as ReplyOf, W as TopicName, _ 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 DashboardTopics, k as Capability, l as MessageBusClient, m as MessageBusErrorCode, n as TopicError, p as MessageBusError, q as ValueOf, s as MessageBus, t as TopicData, u as MessageBusConnection, v as MessageBusQueryOptions, w as ApplicationConfig, y as MessageBusStateSource, z as PayloadOf } from "../topicStore-e_kQ8ZvS.js";
|
|
2
|
+
export { type ApplicationActivity, type ApplicationConfig, type ApplicationConfigAppType, type ApplicationContext, type Capability, type CapabilityRecord, type ConnectMessageBusOptions, type DashboardTopics, type DocumentActivity, type EventTopic, type EventTopicDef, type LocalApplication, 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, capabilities, connectMessageBus };
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { c as connectMessageBus, s as MessageBusError, t as TopicError } from "../topicStore-
|
|
2
|
-
export { MessageBusError, TopicError, connectMessageBus };
|
|
1
|
+
import { c as connectMessageBus, d as capabilities, s as MessageBusError, t as TopicError } from "../topicStore-CPhGph6z.js";
|
|
2
|
+
export { MessageBusError, TopicError, capabilities, connectMessageBus };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { b as AuthConfig, c as DocumentTypeHandle, d as ProjectHandle, f as ReleaseHandle, i as DatasetHandle, o as DocumentHandle, s as DocumentResource, t as SanityInstance, u as PerspectiveHandle, x as AuthProvider } from "./createSanityInstance
|
|
1
|
+
import { b as AuthConfig, c as DocumentTypeHandle, d as ProjectHandle, f as ReleaseHandle, i as DatasetHandle, o as DocumentHandle, s as DocumentResource, t as SanityInstance, u as PerspectiveHandle, x as AuthProvider } from "./createSanityInstance-BQIqyGLX.js";
|
|
2
2
|
import { ClientConfig, ClientPerspective, DatasetsResponse, ListenEvent, MultipleMutationResult, ReleaseDocument, ReleaseDocument as ReleaseDocument$1, ResponseQueryOptions, SanityClient, SanityDocument, SanityProject } from "@sanity/client";
|
|
3
3
|
import { Observable, Subject } from "rxjs";
|
|
4
4
|
import { CurrentUser, CurrentUser as CurrentUser$1, InsertPatch, Mutation, PatchOperations, Path, PortableTextBlock, Role, SanityDocument as SanityDocument$1, SanityDocument as SanityDocument$3, SanityDocumentLike } from "@sanity/types";
|
|
@@ -531,20 +531,10 @@ interface OrgVerificationResult {
|
|
|
531
531
|
*/
|
|
532
532
|
declare function observeOrganizationVerificationState(instance: SanityInstance, projectIds: string[]): Observable<OrgVerificationResult>;
|
|
533
533
|
/**
|
|
534
|
-
* Handles the auth redirect callback. In OAuth mode this delegates to
|
|
535
|
-
* {@link handleOAuthCallback}; otherwise it exchanges the legacy `sid` for a
|
|
536
|
-
* long-lived token.
|
|
537
|
-
*
|
|
538
534
|
* @public
|
|
539
535
|
*/
|
|
540
536
|
declare const handleAuthCallback: BoundStoreAction<AuthStoreState, [locationHref?: string | undefined], Promise<string | false>>;
|
|
541
537
|
/**
|
|
542
|
-
* Logs the current user out. In OAuth mode this revokes the OAuth tokens
|
|
543
|
-
* instead of calling the legacy `/auth/logout` endpoint; revocation is
|
|
544
|
-
* best-effort, so the OAuth path resolves even if the revoke request fails,
|
|
545
|
-
* whereas the legacy path rejects when `/auth/logout` fails. Local state and
|
|
546
|
-
* storage are cleared in both cases.
|
|
547
|
-
*
|
|
548
538
|
* @public
|
|
549
539
|
*/
|
|
550
540
|
declare const logout: BoundStoreAction<AuthStoreState, [], Promise<void>>;
|
|
@@ -561,14 +551,9 @@ declare const startOAuthAuthorization: BoundStoreAction<AuthStoreState, [], Prom
|
|
|
561
551
|
* responses, exchanges the authorization `code` for tokens, persists them, and
|
|
562
552
|
* transitions to `LOGGED_IN`.
|
|
563
553
|
*
|
|
564
|
-
* Returns the URL for the caller to
|
|
565
|
-
*
|
|
566
|
-
*
|
|
567
|
-
* params. Returns `false` when there was nothing to handle (no code, or an
|
|
568
|
-
* exchange already in progress). A callback that fails validation while a
|
|
569
|
-
* session is already `LOGGED_IN` (e.g. a remount before the params were
|
|
570
|
-
* stripped) is ignored with a warning and still returns the cleaned URL, so a
|
|
571
|
-
* string result does not imply an exchange ran.
|
|
554
|
+
* Returns the callback URL cleaned of OAuth params (for the caller to
|
|
555
|
+
* `history.replaceState`) when a callback was processed, or `false` when there
|
|
556
|
+
* was nothing to handle (no code, or an exchange already in progress).
|
|
572
557
|
*
|
|
573
558
|
* @public
|
|
574
559
|
*/
|
|
@@ -1969,6 +1954,7 @@ interface DocumentStoreState {
|
|
|
1969
1954
|
}
|
|
1970
1955
|
interface DocumentState {
|
|
1971
1956
|
id: string;
|
|
1957
|
+
error?: unknown;
|
|
1972
1958
|
/**
|
|
1973
1959
|
* the "remote" local copy that matches the server. represents the last known
|
|
1974
1960
|
* server state. this gets updated every time we confirm remote patches
|
|
@@ -2499,6 +2485,10 @@ interface InstallationBase {
|
|
|
2499
2485
|
/** Qualified, globally-unique handle of the installed singleton (e.g. `sanity/<name>`). */
|
|
2500
2486
|
reference: string;
|
|
2501
2487
|
slug: string | null;
|
|
2488
|
+
/** Sanitized SVG icon markup, or `null` when the singleton has no icon. */
|
|
2489
|
+
icon: string | null;
|
|
2490
|
+
/** The singleton's publishing organization; the top-level `organizationId` is the installing one. */
|
|
2491
|
+
organizationId: string;
|
|
2502
2492
|
};
|
|
2503
2493
|
}
|
|
2504
2494
|
/**
|
|
@@ -3632,4 +3622,4 @@ interface DeleteApplicationInput {
|
|
|
3632
3622
|
*/
|
|
3633
3623
|
declare const deleteApplication: (instance: SanityInstance, input: DeleteApplicationInput) => Promise<MutationResult<DeletedResult>>;
|
|
3634
3624
|
export { Project as $, createRelease as $n, ClientOptions as $r, FavoriteStatusResponse as $t, stringifyPath$1 as A, CacheWriter as Ai, patchOperations as An, getCommentsOptionsKey as Ar, SanityUser as At, getPerspectiveState as B, BoundStoreAction as Bi, DocumentAction as Bn, createComment as Br, OrganizationMember as Bt, SanityDocument$3 as C, getTokenState as Ci, resolveDocument as Cn, createDatasetHandle as Cr, TransportEvent as Ct, joinPaths as D, AccessResourceType as Di, PermissionDeniedReason as Dn, CommentsOptions as Dr, Membership as Dt, getPathDepth as E, AuthStateType as Ei, DocumentPermissionsResult as En, createProjectHandle as Er, GetUsersOptions as Et, getUsersState as F, MutationResult as Fi, CreateDocumentAction as Fn, CreateCommentOptions as Fr, Organizations as Ft, getQueryKey as G, PublishReleaseAction as Gn, Comment as Gr, InstallationActiveConfig as Gt, getActiveReleasesState as H, EditDocumentOptions as Hn, replyToComment as Hr, organization as Ht, loadMoreUsers as I, defineFetcher as Ii, CreateReleaseAction as In, RemoveCommentOptions as Ir, OrganizationsOptions as It, resolveQuery as J, UnarchiveReleaseAction as Jn, CommentReaction as Jr, InstallationsOptions as Jt, getQueryState as K, ReleaseAction as Kn, CommentLocalState as Kr, InstallationBase as Kt, resolveUser as L, defineMutation as Li, DeleteDocumentAction as Ln, ReplyToCommentOptions as Lr, organizations as Lt, isImportError as M, FetcherDefinition as Mi, JsonMatch as Mn, parseCommentsOptionsKey as Mr, UserProfile as Mt, getCorsErrorProjectId as N, FetcherSnapshot as Ni, Action as Nn, resolveCommentThreads as Nr, UsersGroupState as Nt, jsonMatch$1 as O, checkPermissions as Oi, DocumentSet as On, ResolveCommentsOptions as Or, ResolveUserOptions as Ot, getUserState as P, MutationDefinition as Pi, ArchiveReleaseAction as Pn, resolveComments as Pr, UsersStoreState as Pt, getProjectionState as Q, createDocument as Qn, CommentThread as Qr, FavoriteDocumentContext as Qt, resolveUsers as R, Selector as Ri, DeleteReleaseAction as Rn, SetCommentStatusOptions as Rr, Organization as Rt, Role as S, getLoginUrlState as Si, getPermissionsState as Sn, createLogger as Sr, StateEvent as St, getIndexForKey$1 as T, OAuthTokens as Ti, subscribeDocumentEvents as Tn, createDocumentTypeHandle as Tr, GetUserOptions as Tt, getAllReleasesState as U, EditReleaseAction as Un, setCommentStatus as Ur, Installation as Ut, ReleaseState as V, EditDocumentAction as Vn, removeComment as Vr, OrganizationOptions as Vt, QueryOptions as W, PublishDocumentAction as Wn, updateComment as Wr, InstallationAccess as Wt, projects as X, UnscheduleReleaseAction as Xn, CommentTextSelection as Xr, installation as Xt, ProjectsOptions as Y, UnpublishDocumentAction as Yn, CommentStatus as Yr, InstallationsResponse as Yt, resolveProjection as Z, archiveRelease as Zn, CommentTextSelectionItem as Zr, installations as Zt, applications as _, LoggingInAuthState as _i, TransactionAcceptedEvent as _n, LogContext as _r, PresencePerspectiveOptions as _t, ApplicationInclude as a, refreshOAuthTokens as ai, ApplyDocumentActionsOptions as an, publishDocument as ar, project as at, CurrentUser$1 as b, getDashboardOrganizationId as bi, getDocumentState as bn, Logger as br, ReportPresenceOptions as bt, ApplicationStudioConfig as c, logout as ci, DocumentCreatedEvent as cn, unarchiveRelease as cr, PreviewValue as ct, ApplicationsOptions as d, OrgVerificationResult as di, DocumentEditedEvent as dn, ResolveDocument as dr, getPresence as dt, ClientStoreState as ei, SetFavoriteInput as en, deleteDocument as er, ProjectBase as et, ApplicationsResponse as f, AuthState as fi, DocumentEvent as fn, ResolveProjectionResult as fr, reportPresence as ft, application as g, LoggedOutAuthState as gi, DocumentUnpublishedEvent as gn, InstanceContext as gr, PresenceLocation as gt, UpdateApplicationInput as h, LoggedInAuthState as hi, DocumentTransactionSubmissionResult as hn, configureLogging as hr, DocumentPresenceOptions as ht, ApplicationDeployment as i, handleOAuthCallback as ii, ActionsResult as in, editRelease as ir, ProjectOptions as it, CORE_SDK_VERSION as j, Fetcher as ji, processMutations as jn, getCommentsState as jr, SanityUserResponse as jt, slicePath$1 as k, CacheTag as ki, ProcessMutationsOptions as kn, getCommentThreadsState as kr, ResolveUsersOptions as kt, ApplicationVisibility as l, handleAuthCallback as li, DocumentDeletedEvent as ln, unpublishDocument as lr, ProjectionValuePending as lt, DeletedResult as m, ErrorAuthState as mi, DocumentRemotePatchesEvent as mn, datasets as mr, DocumentPresence as mt, ApplicationAccess as n, getClientState as ni, setFavorite as nn, discardDocument as nr, ProjectMemberRole as nt, ApplicationInterface as o, revokeOAuthTokens as oi, applyDocumentActions as on, publishRelease as or, PreviewMedia as ot, DeleteApplicationInput as p, AuthStoreState as pi, DocumentPublishedEvent as pn, ResolveQueryResult as pr, DisconnectEvent as pt, parseQueryKey as q, ScheduleReleaseAction as qn, CommentMessage as qr, InstallationInclude as qt, ApplicationBase as r, getOAuthTokensState as ri, getReleaseDocumentId as rn, editDocument as rr, ProjectMetadata as rt, ApplicationInterfacePlacementMetadata as s, startOAuthAuthorization as si, ActionErrorEvent as sn, scheduleRelease as sr, PreviewQueryResult as st, Application as t, getClient as ti, favorites as tn, deleteRelease as tr, ProjectMember as tt, ApplicationWorkspace as u, observeOrganizationVerificationState as ui, DocumentDiscardedEvent as un, unscheduleRelease as ur, getDocumentPresence as ut, deleteApplication as v, getAuthState as vi, TransactionRevertedEvent as vn, LogLevel as vr, PresenceSelection as vt, SanityProject$1 as w, setAuthToken as wi, resolvePermissions as wn, createDocumentHandle as wr, UserPresence as wt, ReleaseDocument$1 as x, getIsInDashboardState as xi, getDocumentSyncStatus as xn, LoggerConfig as xr, RollCallEvent as xt, updateApplication as y, getCurrentUserState as yi, DocumentOptions as yn, LogNamespace as yr, PresenceSelectionPoint as yt, defineProjection as z, StateSource as zi, DiscardDocumentAction as zn, UpdateCommentOptions as zr, OrganizationBase as zt };
|
|
3635
|
-
//# sourceMappingURL=applications-
|
|
3625
|
+
//# sourceMappingURL=applications-BKrtfXA2.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"applications-BKrtfXA2.d.ts","names":[],"sources":["../src/store/createStoreState.ts","../src/store/defineStore.ts","../src/store/createActionBinder.ts","../src/store/createStateSourceAction.ts","../src/store/fetcherStore.ts","../src/access/checkPermissions.ts","../src/auth/authStateType.ts","../src/auth/oauth/types.ts","../src/auth/authStore.ts","../src/project/organizationVerification.ts","../src/auth/getOrganizationVerificationState.ts","../src/auth/handleAuthCallback.ts","../src/auth/logout.ts","../src/auth/oauth/oauthActions.ts","../src/client/clientStore.ts","../src/comments/types.ts","../src/comments/commentActions.ts","../src/comments/commentsStore.ts","../src/config/handles.ts","../src/utils/logger.ts","../src/config/loggingConfig.ts","../src/datasets/datasets.ts","../src/typegen/groqCompat.ts","../src/typegen/resolve.ts","../src/document/actions.ts","../src/document/patchOperations.ts","../src/document/processMutations.ts","../src/document/permissions.ts","../src/document/sharedListener.ts","../src/document/documentStore.ts","../src/document/reducers.ts","../src/document/events.ts","../src/document/applyDocumentActions.ts","../src/document/processActions/releaseUtil.ts","../src/favorites/favorites.ts","../src/utils/includeShape.ts","../src/installations/installations.ts","../src/organization/organization.ts","../src/organizations/organizations.ts","../src/users/types.ts","../src/presence/types.ts","../src/presence/presenceStore.ts","../src/projection/types.ts","../src/preview/types.ts","../src/project/project.ts","../src/projection/getProjectionState.ts","../src/projection/resolveProjection.ts","../src/projects/projects.ts","../src/query/queryStore.ts","../src/releases/releasesStore.ts","../src/releases/getPerspectiveState.ts","../src/typegen/defineProjection.ts","../src/users/usersStore.ts","../src/utils/getCorsErrorProjectId.ts","../src/utils/isImportError.ts","../src/version.ts","../src/_exports/index.ts","../src/applications/applications.ts"],"mappings":";;;;;;;;;;;;;UAOiB,WAAW;;;;;;;EAO1B,WAAW;;;;;;;;;;EAWX,MAAM,cAAc,cAAc,QAAQ,YAAY,GAAG,WAAW,QAAQ;;;;;;;;;EAU5E,YAAY,WAAW;;;;;UC7BR,aAAa,QAAQ;;;;;;;EAOpC,UAAU;;;;;;;EAQV,OAAO,WAAW;;;;EAKlB,KAAK;;;;;KCAK,YAAY,QAAQ,2BAA2B,SAAS,mBAClE,SAAS,aAAa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BAAkB,gBAAgB,sBAAsB,SAC3D,qCAEA;EACC,SAAS;KAEV,SAAS,yCAAyC;EAAU;;KAGzD,uBAAuB,gBAAgB,uBAAuB,6BACjE;EAEG,SAAS,kBAAkB;IAC5B,YAAY,SAAS;EAClB,QAAQ,kBAAkB;;KAK5B,2BAA2B,gBAAgB,uBAAuB,6BACrE;EAEG,mBAAmB,sBAAsB;IAC1C,YAAY,SAAS;EAClB,kBAAkB,sBAAsB;;;;;;;;;;;KAYnC,YAAY,gBAAgB,8BAA8B,kBACpE,uBAAuB,WACvB,2BAA2B;;;;;;;UAQZ,oBAAoB,gBAAgB,qBAAqB;EACxE;;EAEA;EACA,UAAU;;EAEV;;EAEA;;;;;;;;UASe,qBAAqB,gBAAgB;EACpD;EACA,MAAM,YAAY;;;;;;;;;cAeP,cAAY,SAAA,SAAA,oBAAA,sBAAA,qBAAA;;;;;;;;;cA2CZ,aAkBX,SAlBsB,uBAAA;EACuB,UAAA;gBAiB7C,YAAA;;;;;;;UAQe;EACf;;;;;;;;KASU,wBAAwB;;;;;;;;KASxB;EAA0B;IAAyB,QAC7D,KAAK;;;;;;;;cAUM,oBAAiB,UAAjB,gBAAiB,OAAA,2BAAA,QAAA,eAAA;;;;;;UA0Bb;EACf;;;;;;;;;cAUW,oBAAiB,UAAjB,gBAAiB,OAAA,2BAAA,QAAA,eAAA"}
|
|
@@ -439,7 +439,7 @@ function getTokenFromStorage(storageArea, storageKey) {
|
|
|
439
439
|
* returns an EMPTY observable.
|
|
440
440
|
*/
|
|
441
441
|
function getStorageEvents() {
|
|
442
|
-
return typeof window
|
|
442
|
+
return typeof window > "u" || typeof window.addEventListener != "function" ? EMPTY : fromEvent(window, "storage");
|
|
443
443
|
}
|
|
444
444
|
/**
|
|
445
445
|
* Returns a default storage instance (localStorage) if available.
|
|
@@ -573,13 +573,9 @@ function initializeDashboardAuth(context, tokenRefresherRunning) {
|
|
|
573
573
|
tokenRefresherStarted: startedRefresher
|
|
574
574
|
};
|
|
575
575
|
}
|
|
576
|
-
/** localStorage (or configured `storageArea`) key for persisted OAuth tokens. */
|
|
577
|
-
const OAUTH_TOKENS_KEY = "__sanity_oauth_tokens";
|
|
578
576
|
/**
|
|
579
577
|
* Parses persisted token JSON back into {@link OAuthTokens}. Returns `null`
|
|
580
|
-
* when the value is missing or malformed
|
|
581
|
-
* not parse to a valid date (an `Invalid Date` would otherwise read as never
|
|
582
|
-
* expiring, since `NaN <= now` is always `false`).
|
|
578
|
+
* when the value is missing or malformed.
|
|
583
579
|
*
|
|
584
580
|
* @internal
|
|
585
581
|
*/
|
|
@@ -588,12 +584,12 @@ function deserializeTokens(raw) {
|
|
|
588
584
|
try {
|
|
589
585
|
let parsed = JSON.parse(raw);
|
|
590
586
|
if (typeof parsed != "object" || !parsed || !("accessToken" in parsed) || typeof parsed.accessToken != "string" || !("expiresAt" in parsed) || typeof parsed.expiresAt != "string") return null;
|
|
591
|
-
let value = parsed
|
|
592
|
-
return
|
|
587
|
+
let value = parsed;
|
|
588
|
+
return {
|
|
593
589
|
accessToken: value.accessToken,
|
|
594
590
|
tokenType: "bearer",
|
|
595
591
|
expiresIn: value.expiresIn,
|
|
596
|
-
expiresAt,
|
|
592
|
+
expiresAt: new Date(value.expiresAt),
|
|
597
593
|
...value.refreshToken !== void 0 && { refreshToken: value.refreshToken }
|
|
598
594
|
};
|
|
599
595
|
} catch {
|
|
@@ -605,15 +601,15 @@ function deserializeTokens(raw) {
|
|
|
605
601
|
*
|
|
606
602
|
* State discovery order:
|
|
607
603
|
* 1. Persisted tokens in `__sanity_oauth_tokens` → `LOGGED_IN`
|
|
608
|
-
* 2. Callback URL (contains `code
|
|
604
|
+
* 2. Callback URL (contains `code`/`state`/`error` and matches `redirectUri`)
|
|
609
605
|
* → `LOGGING_IN`
|
|
610
606
|
* 3. Otherwise → `LOGGED_OUT`
|
|
611
607
|
*
|
|
612
608
|
* @internal
|
|
613
609
|
*/
|
|
614
610
|
function getOauthInitialState(options) {
|
|
615
|
-
let { authConfig, initialLocationHref } = options, storageKey =
|
|
616
|
-
if (
|
|
611
|
+
let { authConfig, initialLocationHref } = options, storageKey = "__sanity_oauth_tokens", storageArea = authConfig.storageArea ?? getDefaultStorage(), redirectUri = authConfig.oauth?.redirectUri, tokens = deserializeTokens(storageArea?.getItem("__sanity_oauth_tokens") ?? null);
|
|
612
|
+
if (tokens) return {
|
|
617
613
|
authState: createLoggedInAuthState(tokens.accessToken, null),
|
|
618
614
|
storageKey,
|
|
619
615
|
storageArea,
|
|
@@ -621,7 +617,7 @@ function getOauthInitialState(options) {
|
|
|
621
617
|
dashboardContext: {},
|
|
622
618
|
oauthTokens: tokens
|
|
623
619
|
};
|
|
624
|
-
let { searchParams } = new URL(initialLocationHref, DEFAULT_BASE), isCallback = searchParams.has("code") || searchParams.has("error");
|
|
620
|
+
let { searchParams } = new URL(initialLocationHref, DEFAULT_BASE), isCallback = searchParams.has("code") || searchParams.has("state") || searchParams.has("error");
|
|
625
621
|
if (redirectUri && isCallback) {
|
|
626
622
|
let loc = new URL(initialLocationHref, DEFAULT_BASE), redirect = new URL(redirectUri, DEFAULT_BASE);
|
|
627
623
|
if (loc.origin === redirect.origin && loc.pathname === redirect.pathname) return {
|
|
@@ -1009,7 +1005,7 @@ const authStore = defineStore({
|
|
|
1009
1005
|
storageKey: result.storageKey,
|
|
1010
1006
|
storageArea: result.storageArea,
|
|
1011
1007
|
authMethod: result.authMethod,
|
|
1012
|
-
oauth:
|
|
1008
|
+
oauth: authConfig.oauth
|
|
1013
1009
|
}
|
|
1014
1010
|
};
|
|
1015
1011
|
},
|
|
@@ -1130,4 +1126,4 @@ const allowedKeys = Object.keys({
|
|
|
1130
1126
|
}), getClientState = bindActionGlobally(clientStore, createStateSourceAction(({ instance }, options) => getClient(instance, options)));
|
|
1131
1127
|
export { __exportAll as A, isStudioConfig as C, getAuthLogger as D, REQUEST_TAG_PREFIX as E, configureLogging as O, AuthStateType as S, DEFAULT_BASE as T, getClientErrorApiDescription as _, authStore_exports as a, getTokenFromLocation as b, getDashboardOrganizationId as c, getTokenState as d, setAuthToken as f, getClientErrorApiBody as g, getCleanedUrl as h, authStore as i, createLogger as k, getIsInDashboardState as l, getAuthCode as m, getClient as n, getAuthState as o, createLoggedInAuthState as p, getClientState as r, getCurrentUserState as s, clientStore_exports as t, getLoginUrlState as u, getClientErrorApiType as v, DEFAULT_API_VERSION$1 as w, isProjectUserNotFoundClientError as x, getDefaultLocation as y };
|
|
1132
1128
|
|
|
1133
|
-
//# sourceMappingURL=clientStore-
|
|
1129
|
+
//# sourceMappingURL=clientStore-CD-USpIU.js.map
|