@sanity/schema 6.5.0-next.18 → 6.5.0-next.20

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.
@@ -1,6 +1,7 @@
1
1
  import { a as SchemaValidationResult, i as ProblemPathTypeSegment, l as Schema$1, n as ProblemPathPropertySegment, o as TypeWithProblems, r as ProblemPathSegment, s as _FIXME_, t as ProblemPath } from "./_chunks-dts/typedefs.js";
2
2
  import { SetSynchronization, SynchronizationRequest, SynchronizationResult } from "@sanity/descriptors";
3
3
  import { SanityDocumentLike, Schema, SchemaType, SchemaTypeDefinition, SchemaValidationProblem, SchemaValidationProblemGroup } from "@sanity/types";
4
+ import { RequestOptions } from "get-it";
4
5
  import { ComponentType, ReactNode } from "react";
5
6
  import { SchemaType as SchemaType$1 } from "groq-js";
6
7
  /** The scheduler is capable of executing work in different ways. */
@@ -36,6 +37,154 @@ type SchemaSynchronizationResult = SynchronizationResult;
36
37
  * @returns The next request, or `null` if it's been fully synchronized.
37
38
  */
38
39
  declare function processSchemaSynchronization(sync: SetSynchronization<RegistryType>, response: SchemaSynchronizationResult | null): SchemaSynchronizationRequest | null;
40
+ /**
41
+ * Headers applied to each request.
42
+ *
43
+ * @internal
44
+ */
45
+ type RequestHeaders = Record<string, string>;
46
+ /**
47
+ * Request shape the client passes to the transport. Aliases get-it's
48
+ * `RequestOptions` so the bundled requester and any caller-injected one share a
49
+ * single contract; the client itself only ever sets `url`, `method`, `body`,
50
+ * and `headers`.
51
+ *
52
+ * @internal
53
+ */
54
+ type DescriptorRequestOptions = RequestOptions;
55
+ /**
56
+ * The transport seam. The client calls this for every request; the return value
57
+ * is the parsed response body. Any requester with the shape
58
+ * `<B>(options): Promise<B>` — such as a configured `get-it` instance — is
59
+ * structurally assignable, so callers can bring their own transport.
60
+ *
61
+ * @internal
62
+ */
63
+ type DescriptorRequester = <T>(options: DescriptorRequestOptions) => Promise<T>;
64
+ /**
65
+ * A completed phase of an upload, passed to `onPhaseComplete`.
66
+ *
67
+ * @internal
68
+ */
69
+ interface UploadSchemaPhase {
70
+ /**
71
+ * - `convert` — schema → descriptor set. Awaited but CPU-bound; the shared
72
+ * converter's `WeakMap` cache makes this ~0s on a repeat upload of the same
73
+ * compiled `Schema` instance.
74
+ * - `claim` — the claim request (permanent or temporary).
75
+ * - `synchronize` — one synchronize iteration (see `iteration`).
76
+ * - `commit` — the commit request that pins a permanent claim. Emitted by
77
+ * the `commit()` thunk returned from `prepareSchemaUpload`, or inline by
78
+ * `uploadSchema`. Never emitted for a temporary claim.
79
+ * - `total` — the whole `uploadSchema` call; emitted last, on success
80
+ * only. `prepareSchemaUpload` does not emit `total` (a standalone caller can
81
+ * time the awaited promise itself).
82
+ */
83
+ phase: 'convert' | 'claim' | 'synchronize' | 'commit' | 'total';
84
+ /** Elapsed wall-clock time for this phase, in seconds. */
85
+ durationSeconds: number;
86
+ /** Zero-based iteration index. Present only for `phase: 'synchronize'`. */
87
+ iteration?: number;
88
+ }
89
+ interface BaseUploadSchemaOptions {
90
+ /** Context key the server uses to scope/optimize synchronization, e.g. `studio:<appId>`. */
91
+ contextKey: string;
92
+ /** Headers applied to every request. */
93
+ headers?: RequestHeaders;
94
+ /** Convenience auth applied as `Authorization: Bearer <token>` on every request. */
95
+ token?: string;
96
+ /** Descriptor API version path segment. Default 'v2025-06-01'. */
97
+ apiVersion?: string;
98
+ /** Max synchronize iterations before throwing. Default 5. */
99
+ maxSyncIterations?: number;
100
+ /**
101
+ * Optional observability hook. Invoked once per phase as it completes, with
102
+ * the elapsed wall-clock time for that phase.
103
+ *
104
+ * Fire-and-forget: the return value is ignored and any error it throws is
105
+ * swallowed, so instrumentation can never break or slow an upload.
106
+ */
107
+ onPhaseComplete?: (event: UploadSchemaPhase) => void;
108
+ }
109
+ /**
110
+ * Transport — provide exactly one of `baseUrl` or `requester`. The mutually
111
+ * exclusive shape makes "both" and "neither" a compile-time error.
112
+ */
113
+ type TransportOptions = {
114
+ /** Base URL for the bundled get-it transport. */baseUrl: string;
115
+ requester?: never;
116
+ } | {
117
+ /** Bring-your-own transport. Use instead of `baseUrl` to control auth, retries, etc. */requester: DescriptorRequester;
118
+ baseUrl?: never;
119
+ };
120
+ /**
121
+ * Options for {@link prepareSchemaUpload}.
122
+ *
123
+ * @internal
124
+ */
125
+ type PrepareSchemaUploadOptions = BaseUploadSchemaOptions & TransportOptions & {
126
+ /**
127
+ * Claim lifecycle for the uploaded descriptor — chosen here because the kind
128
+ * of claim is fixed in the `/claim` request and cannot be changed later:
129
+ *
130
+ * - `'permanent'` — claim with `permanent: true`. The response carries a
131
+ * `commitId` and the descriptor is **not** retained until committed. The
132
+ * returned `PreparedSchemaUpload` includes a `commit()` thunk to finalize
133
+ * it (e.g. after a dependent write succeeds). Never calling `commit()`
134
+ * leaves the claim to expire — nothing is pinned.
135
+ * - `'temporary'` — claim with `permanent: false`. The response carries
136
+ * `expiresAt`; there is nothing to commit, so no `commit()` thunk is
137
+ * returned. The descriptor is retained only until the claim expires (or
138
+ * until pinned by a referencing permanent descriptor — e.g. a manifest
139
+ * that lists it).
140
+ */
141
+ claim: 'temporary' | 'permanent';
142
+ };
143
+ /**
144
+ * Options for {@link uploadSchema}.
145
+ *
146
+ * @internal
147
+ */
148
+ type UploadSchemaOptions = BaseUploadSchemaOptions & TransportOptions;
149
+ /**
150
+ * Result of {@link prepareSchemaUpload}: the synchronized descriptor id and,
151
+ * for a permanent claim, a `commit()` thunk to pin it later.
152
+ *
153
+ * @internal
154
+ */
155
+ interface PreparedSchemaUpload {
156
+ /** Content-addressed descriptor id of the synchronized schema. */
157
+ descriptorId: string;
158
+ /**
159
+ * Present only for `claim: 'permanent'`. Finalizes the permanent claim by
160
+ * committing it. Safe to skip: not calling it leaves the claim to expire.
161
+ */
162
+ commit?: () => Promise<void>;
163
+ }
164
+ /**
165
+ * Convert a Sanity schema to a descriptor set, claim its id, and synchronize
166
+ * until complete — but do **not** commit. For a permanent claim, the returned
167
+ * `commit()` thunk finalizes the claim when the caller is ready (e.g. after a
168
+ * dependent write succeeds); for a temporary claim no thunk is returned. This is
169
+ * the building block `uploadSchema` is built on, exposed for callers that need
170
+ * to control the claim/commit lifecycle.
171
+ *
172
+ * @internal
173
+ */
174
+ declare function prepareSchemaUpload(schema: Schema, options: PrepareSchemaUploadOptions): Promise<PreparedSchemaUpload>;
175
+ /**
176
+ * Convert a Sanity schema to a descriptor set and upload it permanently:
177
+ * permanently claim the id, run the synchronization loop until complete, then
178
+ * commit the claim to pin the descriptor. Returns the content-addressed
179
+ * descriptor id.
180
+ *
181
+ * A convenience over {@link prepareSchemaUpload} — it prepares a permanent claim
182
+ * and commits it inline. Callers that need a temporary claim, or that need to
183
+ * commit in a later step, should use `prepareSchemaUpload` directly.
184
+ *
185
+ * @internal
186
+ */
187
+ declare function uploadSchema(schema: Schema, options: UploadSchemaOptions): Promise<string>;
39
188
  declare const isActionEnabled: (schemaType: SchemaType, action: string) => boolean;
40
189
  declare const DEFAULT_MAX_FIELD_DEPTH = 5;
41
190
  declare function resolveSearchConfigForBaseFieldPaths(type: any, maxDepth?: number): any;
@@ -481,4 +630,4 @@ declare class ValidationError extends Error {
481
630
  problems: SchemaValidationProblemGroup[];
482
631
  constructor(problems: SchemaValidationProblemGroup[]);
483
632
  }
484
- export { ALL_FIELDS_GROUP_NAME, type CreateManifest, type CreateWorkspaceManifest, DEFAULT_MAX_FIELD_DEPTH, type DefaultWorkspaceSchemaId, DescriptorConverter, type _FIXME_ as FIXME, type IconResolver, type ManifestSchemaType, type ManifestWorkspaceFile, type ParsedWorkspaceSchemaId, type SchemaValidationResult as Problem, type SchemaValidationResult as ValidationResult, type ProblemPath, type ProblemPathPropertySegment, type ProblemPathSegment, type ProblemPathTypeSegment, SchemaSynchronizationRequest, SchemaSynchronizationResult, type StoredWorkspaceSchema, type TypeWithProblems, ValidationError, type WorkspaceSchemaId, builtinTypes, createSchemaFromManifestTypes, createStoredWorkspaceSchemaPayload, extractCreateWorkspaceManifest, extractManifestSchemaTypes, extractSchema, getWorkspaceSchemaId, groupProblems, isActionEnabled, parseWorkspaceSchemaId, processSchemaSynchronization, resolveSearchConfig, resolveSearchConfigForBaseFieldPaths, validForNamesChars, validForNamesPattern, validateMediaLibraryAssetAspect, validateSchema };
633
+ export { ALL_FIELDS_GROUP_NAME, type CreateManifest, type CreateWorkspaceManifest, DEFAULT_MAX_FIELD_DEPTH, type DefaultWorkspaceSchemaId, DescriptorConverter, type DescriptorRequester, type _FIXME_ as FIXME, type IconResolver, type ManifestSchemaType, type ManifestWorkspaceFile, type ParsedWorkspaceSchemaId, type PrepareSchemaUploadOptions, type PreparedSchemaUpload, type SchemaValidationResult as Problem, type SchemaValidationResult as ValidationResult, type ProblemPath, type ProblemPathPropertySegment, type ProblemPathSegment, type ProblemPathTypeSegment, SchemaSynchronizationRequest, SchemaSynchronizationResult, type StoredWorkspaceSchema, type TypeWithProblems, type UploadSchemaOptions, type UploadSchemaPhase, ValidationError, type WorkspaceSchemaId, builtinTypes, createSchemaFromManifestTypes, createStoredWorkspaceSchemaPayload, extractCreateWorkspaceManifest, extractManifestSchemaTypes, extractSchema, getWorkspaceSchemaId, groupProblems, isActionEnabled, parseWorkspaceSchemaId, prepareSchemaUpload, processSchemaSynchronization, resolveSearchConfig, resolveSearchConfigForBaseFieldPaths, uploadSchema, validForNamesChars, validForNamesPattern, validateMediaLibraryAssetAspect, validateSchema };
package/lib/_internal.js CHANGED
@@ -4,6 +4,8 @@ import isEqual from "lodash-es/isEqual.js";
4
4
  import isObject from "lodash-es/isObject.js";
5
5
  import { OWN_PROPS_NAME, Rule, Schema } from "./_chunks-es/Schema.js";
6
6
  import { ALL_FIELDS_GROUP_NAME, DEFAULT_MAX_FIELD_DEPTH, resolveSearchConfig, resolveSearchConfigForBaseFieldPaths } from "./_chunks-es/Schema.js";
7
+ import { getIt } from "get-it";
8
+ import { base, jsonResponse, jsonRequest, httpErrors, retry, promise } from "get-it/middleware";
7
9
  import "@sanity/generate-help-url";
8
10
  import difference from "lodash-es/difference.js";
9
11
  import cloneDeep from "lodash-es/cloneDeep.js";
@@ -596,6 +598,101 @@ function isLessCanonicalName(a, b) {
596
598
  function processSchemaSynchronization(sync, response) {
597
599
  return processSetSynchronization(sync, response);
598
600
  }
601
+ function defaultShouldRetry(err) {
602
+ const statusCode = err?.response?.statusCode;
603
+ return statusCode === 429 || typeof statusCode == "number" && statusCode >= 500;
604
+ }
605
+ function createGetItRequester(options) {
606
+ const requester = getIt([
607
+ base(options.baseUrl),
608
+ jsonResponse(),
609
+ jsonRequest(),
610
+ httpErrors(),
611
+ retry({ shouldRetry: defaultShouldRetry }),
612
+ promise({ onlyBody: !0 })
613
+ ]);
614
+ return (opts) => requester(opts);
615
+ }
616
+ const DEFAULT_API_VERSION = "v2025-06-01", DEFAULT_MAX_SYNC_ITERATIONS = 5, sharedConverter = new DescriptorConverter();
617
+ function mergeHeaders(token, headers) {
618
+ const hasAuthHeader = headers ? Object.keys(headers).some((key) => key.toLowerCase() === "authorization") : !1;
619
+ return {
620
+ ...token && !hasAuthHeader ? { Authorization: `Bearer ${token}` } : {},
621
+ ...headers
622
+ };
623
+ }
624
+ function resolveRequester(options) {
625
+ if (options.requester !== void 0 && options.baseUrl !== void 0)
626
+ throw new Error("uploadSchema: provide either `requester` or `baseUrl`, not both");
627
+ if (options.requester !== void 0)
628
+ return options.requester;
629
+ if (options.baseUrl !== void 0)
630
+ return createGetItRequester({ baseUrl: options.baseUrl });
631
+ throw new Error("uploadSchema: one of `requester` or `baseUrl` is required");
632
+ }
633
+ function makeEmit(onPhaseComplete) {
634
+ return function(phase, startedAt, iteration) {
635
+ if (!onPhaseComplete) return;
636
+ const event = {
637
+ phase,
638
+ durationSeconds: (performance.now() - startedAt) / 1e3
639
+ };
640
+ iteration !== void 0 && (event.iteration = iteration);
641
+ try {
642
+ onPhaseComplete(event);
643
+ } catch {
644
+ }
645
+ };
646
+ }
647
+ async function prepareSchemaUpload(schema, options) {
648
+ const requester = resolveRequester(options), apiVersion = options.apiVersion ?? DEFAULT_API_VERSION, maxSyncIterations = options.maxSyncIterations ?? DEFAULT_MAX_SYNC_ITERATIONS;
649
+ if (!Number.isInteger(maxSyncIterations) || maxSyncIterations < 0)
650
+ throw new Error("uploadSchema: `maxSyncIterations` must be a non-negative integer");
651
+ const { contextKey } = options, permanent = options.claim === "permanent", headers = mergeHeaders(options.token, options.headers);
652
+ function request(opts) {
653
+ return requester({ ...opts, headers });
654
+ }
655
+ function url(path) {
656
+ return `/${apiVersion}/descriptors/${path}`;
657
+ }
658
+ const emit = makeEmit(options.onPhaseComplete), startedConvert = performance.now(), sync = await sharedConverter.get(schema), descriptorId = sync.set.id;
659
+ emit("convert", startedConvert);
660
+ const startedClaim = performance.now(), claimResponse = await request({
661
+ url: url("claim"),
662
+ method: "POST",
663
+ body: { descriptorId, contextKey, permanent }
664
+ });
665
+ emit("claim", startedClaim);
666
+ let commitId;
667
+ if (permanent && (commitId = claimResponse.commitId, !commitId))
668
+ throw new Error("uploadSchema: claim response is missing `commitId` for the permanent claim");
669
+ let syncResult = claimResponse.synchronization;
670
+ for (let i = 0; i <= maxSyncIterations; i++) {
671
+ const syncRequest = processSchemaSynchronization(sync, syncResult);
672
+ if (syncRequest === null)
673
+ return { descriptorId, commit: permanent ? async () => {
674
+ const startedCommit = performance.now();
675
+ await request({
676
+ url: url("commit"),
677
+ method: "POST",
678
+ body: { contextKey, id: commitId }
679
+ }), emit("commit", startedCommit);
680
+ } : void 0 };
681
+ if (i === maxSyncIterations)
682
+ break;
683
+ const startedSync = performance.now();
684
+ syncResult = await request({
685
+ url: url("synchronize"),
686
+ method: "POST",
687
+ body: syncRequest
688
+ }), emit("synchronize", startedSync, i);
689
+ }
690
+ throw new Error(`Schema synchronization didn't succeed in ${maxSyncIterations} iterations`);
691
+ }
692
+ async function uploadSchema(schema, options) {
693
+ const startedTotal = performance.now(), emit = makeEmit(options.onPhaseComplete), { descriptorId, commit } = await prepareSchemaUpload(schema, { ...options, claim: "permanent" });
694
+ return await commit(), emit("total", startedTotal), descriptorId;
695
+ }
599
696
  const ACTIONS_FLAG = "__experimental_actions", DEFAULT_ACTIONS = ["create", "update", "delete", "publish"], VALID_ACTIONS = DEFAULT_ACTIONS, readActions = (schemaType) => ACTIONS_FLAG in schemaType ? schemaType[ACTIONS_FLAG] : DEFAULT_ACTIONS, validateActions = (typeName, actions) => {
600
697
  if (!Array.isArray(actions))
601
698
  throw new Error(
@@ -2840,28 +2937,28 @@ const documentDefaultFields = (typeName) => ({
2840
2937
  function extractSchema(schemaDef, extractOptions = {}) {
2841
2938
  const inlineFields = /* @__PURE__ */ new Set(), documentTypes = /* @__PURE__ */ new Map(), schema = [], hoistedRefMap = /* @__PURE__ */ new Map(), { sortedSchemaTypeNames, repeated } = sortByDependencies(schemaDef);
2842
2939
  repeated.forEach((key, objectField) => {
2843
- const base = convertSchemaType(objectField.type);
2844
- if (base !== null) {
2845
- if (base.type === "inline") {
2940
+ const base2 = convertSchemaType(objectField.type);
2941
+ if (base2 !== null) {
2942
+ if (base2.type === "inline") {
2846
2943
  repeated.delete(objectField);
2847
2944
  return;
2848
2945
  }
2849
- if (base.type === "unknown") {
2946
+ if (base2.type === "unknown") {
2850
2947
  repeated.delete(objectField);
2851
2948
  return;
2852
2949
  }
2853
2950
  schema.push({
2854
2951
  type: "type",
2855
2952
  name: key,
2856
- value: base
2953
+ value: base2
2857
2954
  });
2858
2955
  }
2859
2956
  }), sortedSchemaTypeNames.forEach((typeName) => {
2860
2957
  const schemaType = schemaDef.get(typeName);
2861
2958
  if (schemaType === void 0)
2862
2959
  return;
2863
- const base = convertBaseType(schemaType);
2864
- base !== null && (base.type === "type" && inlineFields.add(schemaType), base.type === "document" && documentTypes.set(typeName, base), schema.push(base));
2960
+ const base2 = convertBaseType(schemaType);
2961
+ base2 !== null && (base2.type === "type" && inlineFields.add(schemaType), base2.type === "document" && documentTypes.set(typeName, base2), schema.push(base2));
2865
2962
  });
2866
2963
  function reserveRefName(refName) {
2867
2964
  const name = hoistedRefMap.get(refName);
@@ -3416,9 +3513,11 @@ export {
3416
3513
  groupProblems,
3417
3514
  isActionEnabled,
3418
3515
  parseWorkspaceSchemaId,
3516
+ prepareSchemaUpload,
3419
3517
  processSchemaSynchronization,
3420
3518
  resolveSearchConfig,
3421
3519
  resolveSearchConfigForBaseFieldPaths,
3520
+ uploadSchema,
3422
3521
  validForNamesChars,
3423
3522
  validForNamesPattern,
3424
3523
  validateMediaLibraryAssetAspect,