@sanity/embeddings-index-ui 3.0.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs DELETED
@@ -1,2353 +0,0 @@
1
- import { AddIcon, ErrorOutlineIcon, TrashIcon, EllipsisVerticalIcon, UndoIcon, EarthGlobeIcon, LinkIcon } from "@sanity/icons";
2
- import { useClient, useProjectId, useSchema, DefaultPreview, useDocumentPreviewStore, getPreviewStateObservable, SanityDefaultPreview, getPreviewValueWithFallback, typed, definePlugin, unset, setIfMissing, set, isObjectInputProps } from "sanity";
3
- import { jsx, jsxs, Fragment } from "react/jsx-runtime";
4
- import { Card, Text, Stack, Label, Box, TextInput, TextArea, Dialog, Button, Spinner, Autocomplete, Flex, Heading, MenuButton, Menu, MenuItem } from "@sanity/ui";
5
- import React, { useMemo, createContext, useState, useEffect, useContext, useCallback, useId, useRef, useSyncExternalStore, forwardRef } from "react";
6
- import { useIntentLink, useRouter } from "sanity/router";
7
- import { useDocumentPane } from "sanity/desk";
8
- function queryIndex(queryConfig, client) {
9
- const { query, indexName, maxResults, filter } = queryConfig, projectId = client.config().projectId, dataset = client.config().dataset, queryString = query?.trim();
10
- return client.request({
11
- method: "POST",
12
- url: `/embeddings-index/query/${dataset}/${indexName}?projectId=${projectId}`,
13
- body: {
14
- query: queryString,
15
- maxResults,
16
- filter
17
- }
18
- });
19
- }
20
- function getIndexes(client) {
21
- const projectId = client.config().projectId, dataset = client.config().dataset;
22
- return client.request({
23
- method: "GET",
24
- url: `/embeddings-index/${dataset}?projectId=${projectId}`
25
- });
26
- }
27
- function deleteIndex(indexName, client) {
28
- const projectId = client.config().projectId, dataset = client.config().dataset;
29
- return client.request({
30
- method: "DELETE",
31
- url: `/embeddings-index/${dataset}/${indexName}?projectId=${projectId}`
32
- });
33
- }
34
- function useApiClient() {
35
- const client = useClient({ apiVersion: "vX" });
36
- return useMemo(() => {
37
- const customHost = localStorage.getItem("embeddings-index-host");
38
- return customHost ? client.withConfig({
39
- apiHost: customHost,
40
- useProjectHostname: !1,
41
- withCredentials: !1
42
- }) : client;
43
- }, [client]);
44
- }
45
- const FeatureEnabledContext = createContext("loading");
46
- function useIsFeatureEnabled() {
47
- const client = useApiClient(), [status, setStatus] = useState("loading");
48
- return useEffect(() => {
49
- client.request({
50
- method: "GET",
51
- url: "/embeddings-index/status"
52
- }).then((response) => {
53
- setStatus(response.enabled ? "enabled" : "disabled");
54
- }).catch((err) => {
55
- console.error(err), setStatus("error");
56
- });
57
- }, [client]), status;
58
- }
59
- function FeatureEnabledProvider(props) {
60
- const status = useIsFeatureEnabled();
61
- return /* @__PURE__ */ jsx(FeatureEnabledContext.Provider, { value: status, children: props.children });
62
- }
63
- function useIsFeatureEnabledContext() {
64
- return useContext(FeatureEnabledContext);
65
- }
66
- function FeatureDisabledNotice(props) {
67
- const projectId = useProjectId();
68
- return /* @__PURE__ */ jsx(Card, { tone: "primary", border: !0, padding: 4, children: /* @__PURE__ */ jsxs(Text, { size: 1, children: [
69
- "\u{1F48E} Unlock semantic search with the Embeddings Index API \u2014 available on Team, Business, and Enterprise plans.",
70
- " ",
71
- /* @__PURE__ */ jsx("a", { href: `https://www.sanity.io/manage/project/${projectId}/plan${props.urlSuffix ?? ""}`, children: "Upgrade now \u2192" })
72
- ] }) });
73
- }
74
- function FeatureError() {
75
- return /* @__PURE__ */ jsx(Card, { padding: 4, border: !0, tone: "critical", children: "An error occurred. See console for details." });
76
- }
77
- function isType(schemaType, typeName) {
78
- return schemaType.name === typeName ? !0 : schemaType.type ? isType(schemaType.type, typeName) : !1;
79
- }
80
- const defaultProjection = "{...}";
81
- function useDefaultIndex(schema, dataset) {
82
- const defaultFilter = useMemo(
83
- () => `_type in [${schema.getTypeNames().map((n) => schema.get(n)).filter(
84
- (schemaType) => !!(schemaType && isType(schemaType, "document"))
85
- ).filter(
86
- (documentType) => !documentType.name.startsWith("sanity.") && !documentType.name.startsWith("assist.") && documentType.name !== "document"
87
- ).map((documentType) => `"${documentType.name}"`).join(`,
88
- `)}]`,
89
- [schema]
90
- );
91
- return useMemo(
92
- () => ({
93
- dataset,
94
- projection: defaultProjection,
95
- filter: defaultFilter
96
- }),
97
- [defaultFilter, dataset]
98
- );
99
- }
100
- function IndexFormInput(props) {
101
- const { label, description, index, prop, onChange, readOnly, placeholder, type } = props, handleChange = useCallback(
102
- (propValue) => onChange((current) => ({ ...current, [prop]: propValue })),
103
- [onChange, prop]
104
- );
105
- return /* @__PURE__ */ jsx(
106
- FormInput,
107
- {
108
- label,
109
- description,
110
- onChange: handleChange,
111
- value: index[prop] ?? "",
112
- readOnly,
113
- placeholder,
114
- type
115
- }
116
- );
117
- }
118
- function FormInput(props) {
119
- const { label, description, onChange, value, readOnly, placeholder, type = "text" } = props, id = useId(), handleChange = useCallback(
120
- (e) => onChange(e.currentTarget.value),
121
- [onChange]
122
- );
123
- return /* @__PURE__ */ jsxs(Stack, { space: 3, children: [
124
- /* @__PURE__ */ jsx(Label, { muted: !0, htmlFor: id, children: /* @__PURE__ */ jsx("label", { htmlFor: id, children: label }) }),
125
- description && /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(Text, { size: 1, muted: !0, children: description }) }),
126
- type === "text" ? /* @__PURE__ */ jsx(
127
- TextInput,
128
- {
129
- id,
130
- value,
131
- onChange: handleChange,
132
- readOnly,
133
- placeholder
134
- }
135
- ) : /* @__PURE__ */ jsx(
136
- TextArea,
137
- {
138
- id,
139
- value,
140
- rows: 3,
141
- onChange: handleChange,
142
- readOnly,
143
- placeholder,
144
- style: { resize: "vertical" }
145
- }
146
- )
147
- ] });
148
- }
149
- function EditIndexDialog(props) {
150
- const { open, onClose, onSubmit } = props, id = useId(), ref = useRef(null);
151
- useEffect(() => {
152
- open && setTimeout(() => ref.current?.querySelector("input")?.focus());
153
- }, [ref, open]);
154
- const handleSubmit = useCallback(
155
- (index) => {
156
- onSubmit(index), onClose();
157
- },
158
- [onSubmit, onClose]
159
- );
160
- return open ? /* @__PURE__ */ jsx(Dialog, { id, width: 1, ref, onClose, header: "Create embeddings index", children: /* @__PURE__ */ jsx(Stack, { padding: 4, space: 5, children: /* @__PURE__ */ jsx(IndexEditor, { readOnly: !1, onSubmit: handleSubmit }) }) }) : null;
161
- }
162
- function IndexEditor(props) {
163
- const { readOnly, index: selectedIndex, onSubmit } = props, client = useApiClient(), schema = useSchema(), defaultIndex = useDefaultIndex(schema, client.config().dataset ?? ""), [errors, setErrors] = useState(), [loading, setLoading] = useState(), [index, setIndex] = useState(() => ({
164
- ...defaultIndex,
165
- ...selectedIndex
166
- }));
167
- useEffect(() => setIndex(selectedIndex ?? { ...defaultIndex }), [selectedIndex, defaultIndex]);
168
- const handleSubmit = useCallback(
169
- (e) => {
170
- if (e.preventDefault(), readOnly)
171
- return;
172
- const validationErrors = [];
173
- if (index.indexName ? index.indexName.match(/^[a-zA-Z0-9-_]+$/g) || validationErrors.push("Index name can only contain the letters a-z, numbers - and _") : validationErrors.push("Index name is required"), index.dataset || validationErrors.push("Dataset is required"), index.filter || validationErrors.push("Filter is required"), index.projection || validationErrors.push("Projection is required"), validationErrors.length) {
174
- setErrors(validationErrors);
175
- return;
176
- }
177
- const { projectId } = client.config();
178
- setLoading(!0), client.request({
179
- method: "POST",
180
- url: `/embeddings-index/${index.dataset}?projectId=${projectId}`,
181
- body: {
182
- indexName: index.indexName,
183
- projection: index.projection,
184
- filter: index.filter
185
- }
186
- }).then((response) => {
187
- onSubmit && onSubmit(response.index);
188
- }).catch((err) => {
189
- console.error(err), setErrors([err.message]);
190
- }).finally(() => {
191
- setLoading(!1);
192
- });
193
- },
194
- [index, readOnly, onSubmit, client]
195
- );
196
- return /* @__PURE__ */ jsx("form", { onSubmit: handleSubmit, children: /* @__PURE__ */ jsxs(Stack, { space: 4, children: [
197
- errors?.length ? /* @__PURE__ */ jsx(Card, { tone: "critical", border: !0, padding: 2, children: /* @__PURE__ */ jsx(Text, { children: /* @__PURE__ */ jsx("ul", { style: { marginLeft: -10 }, children: errors?.map((error, i) => /* @__PURE__ */ jsx("li", { children: error }, `${error}-${i}`)) }) }) }) : null,
198
- /* @__PURE__ */ jsx(
199
- IndexFormInput,
200
- {
201
- label: "Index name",
202
- placeholder: "Name of index without spaces...",
203
- index,
204
- prop: "indexName",
205
- onChange: setIndex,
206
- readOnly
207
- }
208
- ),
209
- /* @__PURE__ */ jsx(IndexFormInput, { label: "Dataset", index, prop: "dataset", onChange: setIndex, readOnly: !0 }),
210
- /* @__PURE__ */ jsx(
211
- IndexFormInput,
212
- {
213
- label: "Filter",
214
- description: "Must be a valid GROQ filter",
215
- placeholder: defaultIndex.filter,
216
- index,
217
- prop: "filter",
218
- onChange: setIndex,
219
- readOnly,
220
- type: "textarea"
221
- }
222
- ),
223
- /* @__PURE__ */ jsx(
224
- IndexFormInput,
225
- {
226
- label: "Projection",
227
- description: "Must be a valid GROQ projection, starting { and ending with }",
228
- placeholder: defaultIndex.projection,
229
- index,
230
- prop: "projection",
231
- onChange: setIndex,
232
- readOnly,
233
- type: "textarea"
234
- }
235
- ),
236
- onSubmit && /* @__PURE__ */ jsx(
237
- Button,
238
- {
239
- type: "submit",
240
- text: "Create index",
241
- icon: loading ? /* @__PURE__ */ jsx(Box, { style: { marginTop: 5 }, children: /* @__PURE__ */ jsx(Spinner, {}) }) : AddIcon,
242
- disabled: readOnly || loading,
243
- tone: "primary"
244
- }
245
- )
246
- ] }) });
247
- }
248
- /**
249
- * Copyright (c) Meta Platforms, Inc. and affiliates.
250
- *
251
- * This source code is licensed under the MIT license found in the
252
- * LICENSE file in the root directory of this source tree.
253
- *
254
- * @lightSyntaxTransform
255
- * @noflow
256
- * @nolint
257
- * @preventMunge
258
- * @preserve-invariant-messages
259
- */
260
- var dist, hasRequiredDist;
261
- function requireDist() {
262
- if (hasRequiredDist) return dist;
263
- hasRequiredDist = 1;
264
- var __create = Object.create, __defProp = Object.defineProperty, __getOwnPropDesc = Object.getOwnPropertyDescriptor, __getOwnPropNames = Object.getOwnPropertyNames, __getProtoOf = Object.getPrototypeOf, __hasOwnProp = Object.prototype.hasOwnProperty, __export = (target, all) => {
265
- for (var name in all)
266
- __defProp(target, name, { get: all[name], enumerable: !0 });
267
- }, __copyProps = (to, from2, except, desc) => {
268
- if (from2 && typeof from2 == "object" || typeof from2 == "function")
269
- for (let key of __getOwnPropNames(from2))
270
- !__hasOwnProp.call(to, key) && key !== except && __defProp(to, key, { get: () => from2[key], enumerable: !(desc = __getOwnPropDesc(from2, key)) || desc.enumerable });
271
- return to;
272
- }, __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
273
- // If the importer is in node compatibility mode or this is not an ESM
274
- // file that has been converted to a CommonJS file using a Babel-
275
- // compatible transform (i.e. "__esModule" has not been set), then set
276
- // "default" to the CommonJS "module.exports" for node compatibility.
277
- !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: !0 }) : target,
278
- mod
279
- )), __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: !0 }), mod), index_exports = {};
280
- __export(index_exports, {
281
- $dispatcherGuard: () => $dispatcherGuard,
282
- $makeReadOnly: () => $makeReadOnly,
283
- $reset: () => $reset,
284
- $structuralCheck: () => $structuralCheck,
285
- c: () => c,
286
- clearRenderCounterRegistry: () => clearRenderCounterRegistry,
287
- renderCounterRegistry: () => renderCounterRegistry,
288
- useRenderCounter: () => useRenderCounter
289
- }), dist = __toCommonJS(index_exports);
290
- var React$1 = __toESM(React), { useRef: useRef2, useEffect: useEffect2, isValidElement } = React$1, _a, ReactSecretInternals = (
291
- //@ts-ignore
292
- (_a = React$1.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE) != null ? _a : React$1.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED
293
- ), $empty = Symbol.for("react.memo_cache_sentinel"), _a2, c = (
294
- // @ts-expect-error
295
- typeof ((_a2 = React$1.__COMPILER_RUNTIME) == null ? void 0 : _a2.c) == "function" ? (
296
- // @ts-expect-error
297
- React$1.__COMPILER_RUNTIME.c
298
- ) : function(size) {
299
- return React$1.useMemo(() => {
300
- const $ = new Array(size);
301
- for (let ii = 0; ii < size; ii++)
302
- $[ii] = $empty;
303
- return $[$empty] = !0, $;
304
- }, []);
305
- }
306
- ), LazyGuardDispatcher = {};
307
- [
308
- "readContext",
309
- "useCallback",
310
- "useContext",
311
- "useEffect",
312
- "useImperativeHandle",
313
- "useInsertionEffect",
314
- "useLayoutEffect",
315
- "useMemo",
316
- "useReducer",
317
- "useRef",
318
- "useState",
319
- "useDebugValue",
320
- "useDeferredValue",
321
- "useTransition",
322
- "useMutableSource",
323
- "useSyncExternalStore",
324
- "useId",
325
- "unstable_isNewReconciler",
326
- "getCacheSignal",
327
- "getCacheForType",
328
- "useCacheRefresh"
329
- ].forEach((name) => {
330
- LazyGuardDispatcher[name] = () => {
331
- throw new Error(
332
- `[React] Unexpected React hook call (${name}) from a React compiled function. Check that all hooks are called directly and named according to convention ('use[A-Z]') `
333
- );
334
- };
335
- });
336
- var originalDispatcher = null;
337
- LazyGuardDispatcher.useMemoCache = (count) => {
338
- if (originalDispatcher == null)
339
- throw new Error(
340
- "React Compiler internal invariant violation: unexpected null dispatcher"
341
- );
342
- return originalDispatcher.useMemoCache(count);
343
- };
344
- function setCurrent(newDispatcher) {
345
- return ReactSecretInternals.ReactCurrentDispatcher.current = newDispatcher, ReactSecretInternals.ReactCurrentDispatcher.current;
346
- }
347
- var guardFrames = [];
348
- function $dispatcherGuard(kind) {
349
- const curr = ReactSecretInternals.ReactCurrentDispatcher.current;
350
- if (kind === 0) {
351
- if (guardFrames.push(curr), guardFrames.length === 1 && (originalDispatcher = curr), curr === LazyGuardDispatcher)
352
- throw new Error(
353
- "[React] Unexpected call to custom hook or component from a React compiled function. Check that (1) all hooks are called directly and named according to convention ('use[A-Z]') and (2) components are returned as JSX instead of being directly invoked."
354
- );
355
- setCurrent(LazyGuardDispatcher);
356
- } else if (kind === 1) {
357
- const lastFrame = guardFrames.pop();
358
- if (lastFrame == null)
359
- throw new Error(
360
- "React Compiler internal error: unexpected null in guard stack"
361
- );
362
- guardFrames.length === 0 && (originalDispatcher = null), setCurrent(lastFrame);
363
- } else if (kind === 2)
364
- guardFrames.push(curr), setCurrent(originalDispatcher);
365
- else if (kind === 3) {
366
- const lastFrame = guardFrames.pop();
367
- if (lastFrame == null)
368
- throw new Error(
369
- "React Compiler internal error: unexpected null in guard stack"
370
- );
371
- setCurrent(lastFrame);
372
- } else
373
- throw new Error("React Compiler internal error: unreachable block" + kind);
374
- }
375
- function $reset($) {
376
- for (let ii = 0; ii < $.length; ii++)
377
- $[ii] = $empty;
378
- }
379
- function $makeReadOnly() {
380
- throw new Error("TODO: implement $makeReadOnly in react-compiler-runtime");
381
- }
382
- var renderCounterRegistry = /* @__PURE__ */ new Map();
383
- function clearRenderCounterRegistry() {
384
- for (const counters of renderCounterRegistry.values())
385
- counters.forEach((counter) => {
386
- counter.count = 0;
387
- });
388
- }
389
- function registerRenderCounter(name, val) {
390
- let counters = renderCounterRegistry.get(name);
391
- counters == null && (counters = /* @__PURE__ */ new Set(), renderCounterRegistry.set(name, counters)), counters.add(val);
392
- }
393
- function removeRenderCounter(name, val) {
394
- const counters = renderCounterRegistry.get(name);
395
- counters?.delete(val);
396
- }
397
- function useRenderCounter(name) {
398
- const val = useRef2(null);
399
- val.current != null && (val.current.count += 1), useEffect2(() => {
400
- if (val.current == null) {
401
- const counter = { count: 0 };
402
- registerRenderCounter(name, counter), val.current = counter;
403
- }
404
- return () => {
405
- val.current !== null && removeRenderCounter(name, val.current);
406
- };
407
- });
408
- }
409
- var seenErrors = /* @__PURE__ */ new Set();
410
- function $structuralCheck(oldValue, newValue, variableName, fnName, kind, loc) {
411
- function error(l, r, path, depth) {
412
- const str = `${fnName}:${loc} [${kind}] ${variableName}${path} changed from ${l} to ${r} at depth ${depth}`;
413
- seenErrors.has(str) || (seenErrors.add(str), console.error(str));
414
- }
415
- const depthLimit = 2;
416
- function recur(oldValue2, newValue2, path, depth) {
417
- if (!(depth > depthLimit)) {
418
- if (oldValue2 === newValue2)
419
- return;
420
- if (typeof oldValue2 != typeof newValue2)
421
- error(`type ${typeof oldValue2}`, `type ${typeof newValue2}`, path, depth);
422
- else if (typeof oldValue2 == "object") {
423
- const oldArray = Array.isArray(oldValue2), newArray = Array.isArray(newValue2);
424
- if (oldValue2 === null && newValue2 !== null)
425
- error("null", `type ${typeof newValue2}`, path, depth);
426
- else if (newValue2 === null)
427
- error(`type ${typeof oldValue2}`, "null", path, depth);
428
- else if (oldValue2 instanceof Map)
429
- if (!(newValue2 instanceof Map))
430
- error("Map instance", "other value", path, depth);
431
- else if (oldValue2.size !== newValue2.size)
432
- error(
433
- `Map instance with size ${oldValue2.size}`,
434
- `Map instance with size ${newValue2.size}`,
435
- path,
436
- depth
437
- );
438
- else
439
- for (const [k, v] of oldValue2)
440
- newValue2.has(k) ? recur(v, newValue2.get(k), `${path}.get(${k})`, depth + 1) : error(
441
- `Map instance with key ${k}`,
442
- `Map instance without key ${k}`,
443
- path,
444
- depth
445
- );
446
- else if (newValue2 instanceof Map)
447
- error("other value", "Map instance", path, depth);
448
- else if (oldValue2 instanceof Set)
449
- if (!(newValue2 instanceof Set))
450
- error("Set instance", "other value", path, depth);
451
- else if (oldValue2.size !== newValue2.size)
452
- error(
453
- `Set instance with size ${oldValue2.size}`,
454
- `Set instance with size ${newValue2.size}`,
455
- path,
456
- depth
457
- );
458
- else
459
- for (const v of newValue2)
460
- oldValue2.has(v) || error(
461
- `Set instance without element ${v}`,
462
- `Set instance with element ${v}`,
463
- path,
464
- depth
465
- );
466
- else if (newValue2 instanceof Set)
467
- error("other value", "Set instance", path, depth);
468
- else if (oldArray || newArray)
469
- if (oldArray !== newArray)
470
- error(
471
- `type ${oldArray ? "array" : "object"}`,
472
- `type ${newArray ? "array" : "object"}`,
473
- path,
474
- depth
475
- );
476
- else if (oldValue2.length !== newValue2.length)
477
- error(
478
- `array with length ${oldValue2.length}`,
479
- `array with length ${newValue2.length}`,
480
- path,
481
- depth
482
- );
483
- else
484
- for (let ii = 0; ii < oldValue2.length; ii++)
485
- recur(oldValue2[ii], newValue2[ii], `${path}[${ii}]`, depth + 1);
486
- else if (isValidElement(oldValue2) || isValidElement(newValue2))
487
- isValidElement(oldValue2) !== isValidElement(newValue2) ? error(
488
- `type ${isValidElement(oldValue2) ? "React element" : "object"}`,
489
- `type ${isValidElement(newValue2) ? "React element" : "object"}`,
490
- path,
491
- depth
492
- ) : oldValue2.type !== newValue2.type ? error(
493
- `React element of type ${oldValue2.type}`,
494
- `React element of type ${newValue2.type}`,
495
- path,
496
- depth
497
- ) : recur(
498
- oldValue2.props,
499
- newValue2.props,
500
- `[props of ${path}]`,
501
- depth + 1
502
- );
503
- else {
504
- for (const key in newValue2)
505
- key in oldValue2 || error(
506
- `object without key ${key}`,
507
- `object with key ${key}`,
508
- path,
509
- depth
510
- );
511
- for (const key in oldValue2)
512
- key in newValue2 ? recur(oldValue2[key], newValue2[key], `${path}.${key}`, depth + 1) : error(
513
- `object with key ${key}`,
514
- `object without key ${key}`,
515
- path,
516
- depth
517
- );
518
- }
519
- } else {
520
- if (typeof oldValue2 == "function")
521
- return;
522
- isNaN(oldValue2) || isNaN(newValue2) ? isNaN(oldValue2) !== isNaN(newValue2) && error(
523
- `${isNaN(oldValue2) ? "NaN" : "non-NaN value"}`,
524
- `${isNaN(newValue2) ? "NaN" : "non-NaN value"}`,
525
- path,
526
- depth
527
- ) : oldValue2 !== newValue2 && error(oldValue2, newValue2, path, depth);
528
- }
529
- }
530
- }
531
- recur(oldValue, newValue, "", 0);
532
- }
533
- return dist;
534
- }
535
- var distExports = requireDist(), extendStatics = function(d, b) {
536
- return extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
537
- d2.__proto__ = b2;
538
- } || function(d2, b2) {
539
- for (var p in b2) Object.prototype.hasOwnProperty.call(b2, p) && (d2[p] = b2[p]);
540
- }, extendStatics(d, b);
541
- };
542
- function __extends(d, b) {
543
- if (typeof b != "function" && b !== null)
544
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
545
- extendStatics(d, b);
546
- function __() {
547
- this.constructor = d;
548
- }
549
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
550
- }
551
- function __awaiter(thisArg, _arguments, P, generator) {
552
- function adopt(value) {
553
- return value instanceof P ? value : new P(function(resolve) {
554
- resolve(value);
555
- });
556
- }
557
- return new (P || (P = Promise))(function(resolve, reject) {
558
- function fulfilled(value) {
559
- try {
560
- step(generator.next(value));
561
- } catch (e) {
562
- reject(e);
563
- }
564
- }
565
- function rejected(value) {
566
- try {
567
- step(generator.throw(value));
568
- } catch (e) {
569
- reject(e);
570
- }
571
- }
572
- function step(result) {
573
- result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
574
- }
575
- step((generator = generator.apply(thisArg, _arguments || [])).next());
576
- });
577
- }
578
- function __generator(thisArg, body) {
579
- var _ = { label: 0, sent: function() {
580
- if (t[0] & 1) throw t[1];
581
- return t[1];
582
- }, trys: [], ops: [] }, f, y, t, g;
583
- return g = { next: verb(0), throw: verb(1), return: verb(2) }, typeof Symbol == "function" && (g[Symbol.iterator] = function() {
584
- return this;
585
- }), g;
586
- function verb(n) {
587
- return function(v) {
588
- return step([n, v]);
589
- };
590
- }
591
- function step(op) {
592
- if (f) throw new TypeError("Generator is already executing.");
593
- for (; g && (g = 0, op[0] && (_ = 0)), _; ) try {
594
- if (f = 1, y && (t = op[0] & 2 ? y.return : op[0] ? y.throw || ((t = y.return) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
595
- switch (y = 0, t && (op = [op[0] & 2, t.value]), op[0]) {
596
- case 0:
597
- case 1:
598
- t = op;
599
- break;
600
- case 4:
601
- return _.label++, { value: op[1], done: !1 };
602
- case 5:
603
- _.label++, y = op[1], op = [0];
604
- continue;
605
- case 7:
606
- op = _.ops.pop(), _.trys.pop();
607
- continue;
608
- default:
609
- if (t = _.trys, !(t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
610
- _ = 0;
611
- continue;
612
- }
613
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
614
- _.label = op[1];
615
- break;
616
- }
617
- if (op[0] === 6 && _.label < t[1]) {
618
- _.label = t[1], t = op;
619
- break;
620
- }
621
- if (t && _.label < t[2]) {
622
- _.label = t[2], _.ops.push(op);
623
- break;
624
- }
625
- t[2] && _.ops.pop(), _.trys.pop();
626
- continue;
627
- }
628
- op = body.call(thisArg, _);
629
- } catch (e) {
630
- op = [6, e], y = 0;
631
- } finally {
632
- f = t = 0;
633
- }
634
- if (op[0] & 5) throw op[1];
635
- return { value: op[0] ? op[1] : void 0, done: !0 };
636
- }
637
- }
638
- function __values(o) {
639
- var s = typeof Symbol == "function" && Symbol.iterator, m = s && o[s], i = 0;
640
- if (m) return m.call(o);
641
- if (o && typeof o.length == "number") return {
642
- next: function() {
643
- return o && i >= o.length && (o = void 0), { value: o && o[i++], done: !o };
644
- }
645
- };
646
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
647
- }
648
- function __read(o, n) {
649
- var m = typeof Symbol == "function" && o[Symbol.iterator];
650
- if (!m) return o;
651
- var i = m.call(o), r, ar = [], e;
652
- try {
653
- for (; (n === void 0 || n-- > 0) && !(r = i.next()).done; ) ar.push(r.value);
654
- } catch (error) {
655
- e = { error };
656
- } finally {
657
- try {
658
- r && !r.done && (m = i.return) && m.call(i);
659
- } finally {
660
- if (e) throw e.error;
661
- }
662
- }
663
- return ar;
664
- }
665
- function __spreadArray(to, from2, pack) {
666
- if (pack || arguments.length === 2) for (var i = 0, l = from2.length, ar; i < l; i++)
667
- (ar || !(i in from2)) && (ar || (ar = Array.prototype.slice.call(from2, 0, i)), ar[i] = from2[i]);
668
- return to.concat(ar || Array.prototype.slice.call(from2));
669
- }
670
- function __await(v) {
671
- return this instanceof __await ? (this.v = v, this) : new __await(v);
672
- }
673
- function __asyncGenerator(thisArg, _arguments, generator) {
674
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
675
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
676
- return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
677
- return this;
678
- }, i;
679
- function verb(n) {
680
- g[n] && (i[n] = function(v) {
681
- return new Promise(function(a, b) {
682
- q.push([n, v, a, b]) > 1 || resume(n, v);
683
- });
684
- });
685
- }
686
- function resume(n, v) {
687
- try {
688
- step(g[n](v));
689
- } catch (e) {
690
- settle(q[0][3], e);
691
- }
692
- }
693
- function step(r) {
694
- r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
695
- }
696
- function fulfill(value) {
697
- resume("next", value);
698
- }
699
- function reject(value) {
700
- resume("throw", value);
701
- }
702
- function settle(f, v) {
703
- f(v), q.shift(), q.length && resume(q[0][0], q[0][1]);
704
- }
705
- }
706
- function __asyncValues(o) {
707
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
708
- var m = o[Symbol.asyncIterator], i;
709
- return m ? m.call(o) : (o = typeof __values == "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
710
- return this;
711
- }, i);
712
- function verb(n) {
713
- i[n] = o[n] && function(v) {
714
- return new Promise(function(resolve, reject) {
715
- v = o[n](v), settle(resolve, reject, v.done, v.value);
716
- });
717
- };
718
- }
719
- function settle(resolve, reject, d, v) {
720
- Promise.resolve(v).then(function(v2) {
721
- resolve({ value: v2, done: d });
722
- }, reject);
723
- }
724
- }
725
- function isFunction(value) {
726
- return typeof value == "function";
727
- }
728
- function createErrorClass(createImpl) {
729
- var _super = function(instance) {
730
- Error.call(instance), instance.stack = new Error().stack;
731
- }, ctorFunc = createImpl(_super);
732
- return ctorFunc.prototype = Object.create(Error.prototype), ctorFunc.prototype.constructor = ctorFunc, ctorFunc;
733
- }
734
- var UnsubscriptionError = createErrorClass(function(_super) {
735
- return function(errors) {
736
- _super(this), this.message = errors ? errors.length + ` errors occurred during unsubscription:
737
- ` + errors.map(function(err, i) {
738
- return i + 1 + ") " + err.toString();
739
- }).join(`
740
- `) : "", this.name = "UnsubscriptionError", this.errors = errors;
741
- };
742
- });
743
- function arrRemove(arr, item) {
744
- if (arr) {
745
- var index = arr.indexOf(item);
746
- 0 <= index && arr.splice(index, 1);
747
- }
748
- }
749
- var Subscription = function() {
750
- function Subscription2(initialTeardown) {
751
- this.initialTeardown = initialTeardown, this.closed = !1, this._parentage = null, this._finalizers = null;
752
- }
753
- return Subscription2.prototype.unsubscribe = function() {
754
- var e_1, _a, e_2, _b, errors;
755
- if (!this.closed) {
756
- this.closed = !0;
757
- var _parentage = this._parentage;
758
- if (_parentage)
759
- if (this._parentage = null, Array.isArray(_parentage))
760
- try {
761
- for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
762
- var parent_1 = _parentage_1_1.value;
763
- parent_1.remove(this);
764
- }
765
- } catch (e_1_1) {
766
- e_1 = { error: e_1_1 };
767
- } finally {
768
- try {
769
- _parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return) && _a.call(_parentage_1);
770
- } finally {
771
- if (e_1) throw e_1.error;
772
- }
773
- }
774
- else
775
- _parentage.remove(this);
776
- var initialFinalizer = this.initialTeardown;
777
- if (isFunction(initialFinalizer))
778
- try {
779
- initialFinalizer();
780
- } catch (e) {
781
- errors = e instanceof UnsubscriptionError ? e.errors : [e];
782
- }
783
- var _finalizers = this._finalizers;
784
- if (_finalizers) {
785
- this._finalizers = null;
786
- try {
787
- for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
788
- var finalizer = _finalizers_1_1.value;
789
- try {
790
- execFinalizer(finalizer);
791
- } catch (err) {
792
- errors = errors ?? [], err instanceof UnsubscriptionError ? errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors)) : errors.push(err);
793
- }
794
- }
795
- } catch (e_2_1) {
796
- e_2 = { error: e_2_1 };
797
- } finally {
798
- try {
799
- _finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return) && _b.call(_finalizers_1);
800
- } finally {
801
- if (e_2) throw e_2.error;
802
- }
803
- }
804
- }
805
- if (errors)
806
- throw new UnsubscriptionError(errors);
807
- }
808
- }, Subscription2.prototype.add = function(teardown) {
809
- var _a;
810
- if (teardown && teardown !== this)
811
- if (this.closed)
812
- execFinalizer(teardown);
813
- else {
814
- if (teardown instanceof Subscription2) {
815
- if (teardown.closed || teardown._hasParent(this))
816
- return;
817
- teardown._addParent(this);
818
- }
819
- (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
820
- }
821
- }, Subscription2.prototype._hasParent = function(parent) {
822
- var _parentage = this._parentage;
823
- return _parentage === parent || Array.isArray(_parentage) && _parentage.includes(parent);
824
- }, Subscription2.prototype._addParent = function(parent) {
825
- var _parentage = this._parentage;
826
- this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
827
- }, Subscription2.prototype._removeParent = function(parent) {
828
- var _parentage = this._parentage;
829
- _parentage === parent ? this._parentage = null : Array.isArray(_parentage) && arrRemove(_parentage, parent);
830
- }, Subscription2.prototype.remove = function(teardown) {
831
- var _finalizers = this._finalizers;
832
- _finalizers && arrRemove(_finalizers, teardown), teardown instanceof Subscription2 && teardown._removeParent(this);
833
- }, Subscription2.EMPTY = function() {
834
- var empty = new Subscription2();
835
- return empty.closed = !0, empty;
836
- }(), Subscription2;
837
- }(), EMPTY_SUBSCRIPTION = Subscription.EMPTY;
838
- function isSubscription(value) {
839
- return value instanceof Subscription || value && "closed" in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe);
840
- }
841
- function execFinalizer(finalizer) {
842
- isFunction(finalizer) ? finalizer() : finalizer.unsubscribe();
843
- }
844
- var config = {
845
- Promise: void 0
846
- }, timeoutProvider = {
847
- setTimeout: function(handler, timeout) {
848
- for (var args = [], _i = 2; _i < arguments.length; _i++)
849
- args[_i - 2] = arguments[_i];
850
- return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
851
- },
852
- clearTimeout: function(handle) {
853
- return clearTimeout(handle);
854
- },
855
- delegate: void 0
856
- };
857
- function reportUnhandledError(err) {
858
- timeoutProvider.setTimeout(function() {
859
- throw err;
860
- });
861
- }
862
- function noop() {
863
- }
864
- function errorContext(cb) {
865
- cb();
866
- }
867
- var Subscriber = function(_super) {
868
- __extends(Subscriber2, _super);
869
- function Subscriber2(destination) {
870
- var _this = _super.call(this) || this;
871
- return _this.isStopped = !1, destination ? (_this.destination = destination, isSubscription(destination) && destination.add(_this)) : _this.destination = EMPTY_OBSERVER, _this;
872
- }
873
- return Subscriber2.create = function(next, error, complete) {
874
- return new SafeSubscriber(next, error, complete);
875
- }, Subscriber2.prototype.next = function(value) {
876
- this.isStopped || this._next(value);
877
- }, Subscriber2.prototype.error = function(err) {
878
- this.isStopped || (this.isStopped = !0, this._error(err));
879
- }, Subscriber2.prototype.complete = function() {
880
- this.isStopped || (this.isStopped = !0, this._complete());
881
- }, Subscriber2.prototype.unsubscribe = function() {
882
- this.closed || (this.isStopped = !0, _super.prototype.unsubscribe.call(this), this.destination = null);
883
- }, Subscriber2.prototype._next = function(value) {
884
- this.destination.next(value);
885
- }, Subscriber2.prototype._error = function(err) {
886
- try {
887
- this.destination.error(err);
888
- } finally {
889
- this.unsubscribe();
890
- }
891
- }, Subscriber2.prototype._complete = function() {
892
- try {
893
- this.destination.complete();
894
- } finally {
895
- this.unsubscribe();
896
- }
897
- }, Subscriber2;
898
- }(Subscription), ConsumerObserver = function() {
899
- function ConsumerObserver2(partialObserver) {
900
- this.partialObserver = partialObserver;
901
- }
902
- return ConsumerObserver2.prototype.next = function(value) {
903
- var partialObserver = this.partialObserver;
904
- if (partialObserver.next)
905
- try {
906
- partialObserver.next(value);
907
- } catch (error) {
908
- handleUnhandledError(error);
909
- }
910
- }, ConsumerObserver2.prototype.error = function(err) {
911
- var partialObserver = this.partialObserver;
912
- if (partialObserver.error)
913
- try {
914
- partialObserver.error(err);
915
- } catch (error) {
916
- handleUnhandledError(error);
917
- }
918
- else
919
- handleUnhandledError(err);
920
- }, ConsumerObserver2.prototype.complete = function() {
921
- var partialObserver = this.partialObserver;
922
- if (partialObserver.complete)
923
- try {
924
- partialObserver.complete();
925
- } catch (error) {
926
- handleUnhandledError(error);
927
- }
928
- }, ConsumerObserver2;
929
- }(), SafeSubscriber = function(_super) {
930
- __extends(SafeSubscriber2, _super);
931
- function SafeSubscriber2(observerOrNext, error, complete) {
932
- var _this = _super.call(this) || this, partialObserver;
933
- return isFunction(observerOrNext) || !observerOrNext ? partialObserver = {
934
- next: observerOrNext ?? void 0,
935
- error: error ?? void 0,
936
- complete: complete ?? void 0
937
- } : partialObserver = observerOrNext, _this.destination = new ConsumerObserver(partialObserver), _this;
938
- }
939
- return SafeSubscriber2;
940
- }(Subscriber);
941
- function handleUnhandledError(error) {
942
- reportUnhandledError(error);
943
- }
944
- function defaultErrorHandler(err) {
945
- throw err;
946
- }
947
- var EMPTY_OBSERVER = {
948
- closed: !0,
949
- next: noop,
950
- error: defaultErrorHandler,
951
- complete: noop
952
- }, observable = function() {
953
- return typeof Symbol == "function" && Symbol.observable || "@@observable";
954
- }();
955
- function identity(x) {
956
- return x;
957
- }
958
- function pipeFromArray(fns) {
959
- return fns.length === 0 ? identity : fns.length === 1 ? fns[0] : function(input) {
960
- return fns.reduce(function(prev, fn) {
961
- return fn(prev);
962
- }, input);
963
- };
964
- }
965
- var Observable = function() {
966
- function Observable2(subscribe) {
967
- subscribe && (this._subscribe = subscribe);
968
- }
969
- return Observable2.prototype.lift = function(operator) {
970
- var observable2 = new Observable2();
971
- return observable2.source = this, observable2.operator = operator, observable2;
972
- }, Observable2.prototype.subscribe = function(observerOrNext, error, complete) {
973
- var _this = this, subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
974
- return errorContext(function() {
975
- var _a = _this, operator = _a.operator, source = _a.source;
976
- subscriber.add(operator ? operator.call(subscriber, source) : source ? _this._subscribe(subscriber) : _this._trySubscribe(subscriber));
977
- }), subscriber;
978
- }, Observable2.prototype._trySubscribe = function(sink) {
979
- try {
980
- return this._subscribe(sink);
981
- } catch (err) {
982
- sink.error(err);
983
- }
984
- }, Observable2.prototype.forEach = function(next, promiseCtor) {
985
- var _this = this;
986
- return promiseCtor = getPromiseCtor(promiseCtor), new promiseCtor(function(resolve, reject) {
987
- var subscriber = new SafeSubscriber({
988
- next: function(value) {
989
- try {
990
- next(value);
991
- } catch (err) {
992
- reject(err), subscriber.unsubscribe();
993
- }
994
- },
995
- error: reject,
996
- complete: resolve
997
- });
998
- _this.subscribe(subscriber);
999
- });
1000
- }, Observable2.prototype._subscribe = function(subscriber) {
1001
- var _a;
1002
- return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
1003
- }, Observable2.prototype[observable] = function() {
1004
- return this;
1005
- }, Observable2.prototype.pipe = function() {
1006
- for (var operations = [], _i = 0; _i < arguments.length; _i++)
1007
- operations[_i] = arguments[_i];
1008
- return pipeFromArray(operations)(this);
1009
- }, Observable2.prototype.toPromise = function(promiseCtor) {
1010
- var _this = this;
1011
- return promiseCtor = getPromiseCtor(promiseCtor), new promiseCtor(function(resolve, reject) {
1012
- var value;
1013
- _this.subscribe(function(x) {
1014
- return value = x;
1015
- }, function(err) {
1016
- return reject(err);
1017
- }, function() {
1018
- return resolve(value);
1019
- });
1020
- });
1021
- }, Observable2.create = function(subscribe) {
1022
- return new Observable2(subscribe);
1023
- }, Observable2;
1024
- }();
1025
- function getPromiseCtor(promiseCtor) {
1026
- var _a;
1027
- return (_a = promiseCtor ?? config.Promise) !== null && _a !== void 0 ? _a : Promise;
1028
- }
1029
- function isObserver(value) {
1030
- return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
1031
- }
1032
- function isSubscriber(value) {
1033
- return value && value instanceof Subscriber || isObserver(value) && isSubscription(value);
1034
- }
1035
- function hasLift(source) {
1036
- return isFunction(source?.lift);
1037
- }
1038
- function operate(init) {
1039
- return function(source) {
1040
- if (hasLift(source))
1041
- return source.lift(function(liftedSource) {
1042
- try {
1043
- return init(liftedSource, this);
1044
- } catch (err) {
1045
- this.error(err);
1046
- }
1047
- });
1048
- throw new TypeError("Unable to lift unknown Observable type");
1049
- };
1050
- }
1051
- function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
1052
- return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
1053
- }
1054
- var OperatorSubscriber = function(_super) {
1055
- __extends(OperatorSubscriber2, _super);
1056
- function OperatorSubscriber2(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
1057
- var _this = _super.call(this, destination) || this;
1058
- return _this.onFinalize = onFinalize, _this.shouldUnsubscribe = shouldUnsubscribe, _this._next = onNext ? function(value) {
1059
- try {
1060
- onNext(value);
1061
- } catch (err) {
1062
- destination.error(err);
1063
- }
1064
- } : _super.prototype._next, _this._error = onError ? function(err) {
1065
- try {
1066
- onError(err);
1067
- } catch (err2) {
1068
- destination.error(err2);
1069
- } finally {
1070
- this.unsubscribe();
1071
- }
1072
- } : _super.prototype._error, _this._complete = onComplete ? function() {
1073
- try {
1074
- onComplete();
1075
- } catch (err) {
1076
- destination.error(err);
1077
- } finally {
1078
- this.unsubscribe();
1079
- }
1080
- } : _super.prototype._complete, _this;
1081
- }
1082
- return OperatorSubscriber2.prototype.unsubscribe = function() {
1083
- var _a;
1084
- if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
1085
- var closed_1 = this.closed;
1086
- _super.prototype.unsubscribe.call(this), !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 || _a.call(this));
1087
- }
1088
- }, OperatorSubscriber2;
1089
- }(Subscriber), ObjectUnsubscribedError = createErrorClass(function(_super) {
1090
- return function() {
1091
- _super(this), this.name = "ObjectUnsubscribedError", this.message = "object unsubscribed";
1092
- };
1093
- }), Subject = function(_super) {
1094
- __extends(Subject2, _super);
1095
- function Subject2() {
1096
- var _this = _super.call(this) || this;
1097
- return _this.closed = !1, _this.currentObservers = null, _this.observers = [], _this.isStopped = !1, _this.hasError = !1, _this.thrownError = null, _this;
1098
- }
1099
- return Subject2.prototype.lift = function(operator) {
1100
- var subject = new AnonymousSubject(this, this);
1101
- return subject.operator = operator, subject;
1102
- }, Subject2.prototype._throwIfClosed = function() {
1103
- if (this.closed)
1104
- throw new ObjectUnsubscribedError();
1105
- }, Subject2.prototype.next = function(value) {
1106
- var _this = this;
1107
- errorContext(function() {
1108
- var e_1, _a;
1109
- if (_this._throwIfClosed(), !_this.isStopped) {
1110
- _this.currentObservers || (_this.currentObservers = Array.from(_this.observers));
1111
- try {
1112
- for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) {
1113
- var observer = _c.value;
1114
- observer.next(value);
1115
- }
1116
- } catch (e_1_1) {
1117
- e_1 = { error: e_1_1 };
1118
- } finally {
1119
- try {
1120
- _c && !_c.done && (_a = _b.return) && _a.call(_b);
1121
- } finally {
1122
- if (e_1) throw e_1.error;
1123
- }
1124
- }
1125
- }
1126
- });
1127
- }, Subject2.prototype.error = function(err) {
1128
- var _this = this;
1129
- errorContext(function() {
1130
- if (_this._throwIfClosed(), !_this.isStopped) {
1131
- _this.hasError = _this.isStopped = !0, _this.thrownError = err;
1132
- for (var observers = _this.observers; observers.length; )
1133
- observers.shift().error(err);
1134
- }
1135
- });
1136
- }, Subject2.prototype.complete = function() {
1137
- var _this = this;
1138
- errorContext(function() {
1139
- if (_this._throwIfClosed(), !_this.isStopped) {
1140
- _this.isStopped = !0;
1141
- for (var observers = _this.observers; observers.length; )
1142
- observers.shift().complete();
1143
- }
1144
- });
1145
- }, Subject2.prototype.unsubscribe = function() {
1146
- this.isStopped = this.closed = !0, this.observers = this.currentObservers = null;
1147
- }, Object.defineProperty(Subject2.prototype, "observed", {
1148
- get: function() {
1149
- var _a;
1150
- return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;
1151
- },
1152
- enumerable: !1,
1153
- configurable: !0
1154
- }), Subject2.prototype._trySubscribe = function(subscriber) {
1155
- return this._throwIfClosed(), _super.prototype._trySubscribe.call(this, subscriber);
1156
- }, Subject2.prototype._subscribe = function(subscriber) {
1157
- return this._throwIfClosed(), this._checkFinalizedStatuses(subscriber), this._innerSubscribe(subscriber);
1158
- }, Subject2.prototype._innerSubscribe = function(subscriber) {
1159
- var _this = this, _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers;
1160
- return hasError || isStopped ? EMPTY_SUBSCRIPTION : (this.currentObservers = null, observers.push(subscriber), new Subscription(function() {
1161
- _this.currentObservers = null, arrRemove(observers, subscriber);
1162
- }));
1163
- }, Subject2.prototype._checkFinalizedStatuses = function(subscriber) {
1164
- var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped;
1165
- hasError ? subscriber.error(thrownError) : isStopped && subscriber.complete();
1166
- }, Subject2.prototype.asObservable = function() {
1167
- var observable2 = new Observable();
1168
- return observable2.source = this, observable2;
1169
- }, Subject2.create = function(destination, source) {
1170
- return new AnonymousSubject(destination, source);
1171
- }, Subject2;
1172
- }(Observable), AnonymousSubject = function(_super) {
1173
- __extends(AnonymousSubject2, _super);
1174
- function AnonymousSubject2(destination, source) {
1175
- var _this = _super.call(this) || this;
1176
- return _this.destination = destination, _this.source = source, _this;
1177
- }
1178
- return AnonymousSubject2.prototype.next = function(value) {
1179
- var _a, _b;
1180
- (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 || _b.call(_a, value);
1181
- }, AnonymousSubject2.prototype.error = function(err) {
1182
- var _a, _b;
1183
- (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 || _b.call(_a, err);
1184
- }, AnonymousSubject2.prototype.complete = function() {
1185
- var _a, _b;
1186
- (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 || _b.call(_a);
1187
- }, AnonymousSubject2.prototype._subscribe = function(subscriber) {
1188
- var _a, _b;
1189
- return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION;
1190
- }, AnonymousSubject2;
1191
- }(Subject), dateTimestampProvider = {
1192
- now: function() {
1193
- return Date.now();
1194
- }
1195
- }, Action = function(_super) {
1196
- __extends(Action2, _super);
1197
- function Action2(scheduler, work) {
1198
- return _super.call(this) || this;
1199
- }
1200
- return Action2.prototype.schedule = function(state, delay) {
1201
- return this;
1202
- }, Action2;
1203
- }(Subscription), intervalProvider = {
1204
- setInterval: function(handler, timeout) {
1205
- for (var args = [], _i = 2; _i < arguments.length; _i++)
1206
- args[_i - 2] = arguments[_i];
1207
- return setInterval.apply(void 0, __spreadArray([handler, timeout], __read(args)));
1208
- },
1209
- clearInterval: function(handle) {
1210
- return clearInterval(handle);
1211
- },
1212
- delegate: void 0
1213
- }, AsyncAction = function(_super) {
1214
- __extends(AsyncAction2, _super);
1215
- function AsyncAction2(scheduler, work) {
1216
- var _this = _super.call(this, scheduler, work) || this;
1217
- return _this.scheduler = scheduler, _this.work = work, _this.pending = !1, _this;
1218
- }
1219
- return AsyncAction2.prototype.schedule = function(state, delay) {
1220
- var _a;
1221
- if (delay === void 0 && (delay = 0), this.closed)
1222
- return this;
1223
- this.state = state;
1224
- var id = this.id, scheduler = this.scheduler;
1225
- return id != null && (this.id = this.recycleAsyncId(scheduler, id, delay)), this.pending = !0, this.delay = delay, this.id = (_a = this.id) !== null && _a !== void 0 ? _a : this.requestAsyncId(scheduler, this.id, delay), this;
1226
- }, AsyncAction2.prototype.requestAsyncId = function(scheduler, _id, delay) {
1227
- return delay === void 0 && (delay = 0), intervalProvider.setInterval(scheduler.flush.bind(scheduler, this), delay);
1228
- }, AsyncAction2.prototype.recycleAsyncId = function(_scheduler, id, delay) {
1229
- if (delay === void 0 && (delay = 0), delay != null && this.delay === delay && this.pending === !1)
1230
- return id;
1231
- id != null && intervalProvider.clearInterval(id);
1232
- }, AsyncAction2.prototype.execute = function(state, delay) {
1233
- if (this.closed)
1234
- return new Error("executing a cancelled action");
1235
- this.pending = !1;
1236
- var error = this._execute(state, delay);
1237
- if (error)
1238
- return error;
1239
- this.pending === !1 && this.id != null && (this.id = this.recycleAsyncId(this.scheduler, this.id, null));
1240
- }, AsyncAction2.prototype._execute = function(state, _delay) {
1241
- var errored = !1, errorValue;
1242
- try {
1243
- this.work(state);
1244
- } catch (e) {
1245
- errored = !0, errorValue = e || new Error("Scheduled action threw falsy error");
1246
- }
1247
- if (errored)
1248
- return this.unsubscribe(), errorValue;
1249
- }, AsyncAction2.prototype.unsubscribe = function() {
1250
- if (!this.closed) {
1251
- var _a = this, id = _a.id, scheduler = _a.scheduler, actions = scheduler.actions;
1252
- this.work = this.state = this.scheduler = null, this.pending = !1, arrRemove(actions, this), id != null && (this.id = this.recycleAsyncId(scheduler, id, null)), this.delay = null, _super.prototype.unsubscribe.call(this);
1253
- }
1254
- }, AsyncAction2;
1255
- }(Action), nextHandle = 1, resolved, activeHandles = {};
1256
- function findAndClearHandle(handle) {
1257
- return handle in activeHandles ? (delete activeHandles[handle], !0) : !1;
1258
- }
1259
- var Immediate = {
1260
- setImmediate: function(cb) {
1261
- var handle = nextHandle++;
1262
- return activeHandles[handle] = !0, resolved || (resolved = Promise.resolve()), resolved.then(function() {
1263
- return findAndClearHandle(handle) && cb();
1264
- }), handle;
1265
- },
1266
- clearImmediate: function(handle) {
1267
- findAndClearHandle(handle);
1268
- }
1269
- }, setImmediate = Immediate.setImmediate, clearImmediate = Immediate.clearImmediate, immediateProvider = {
1270
- setImmediate: function() {
1271
- for (var args = [], _i = 0; _i < arguments.length; _i++)
1272
- args[_i] = arguments[_i];
1273
- var delegate = immediateProvider.delegate;
1274
- return (delegate?.setImmediate || setImmediate).apply(void 0, __spreadArray([], __read(args)));
1275
- },
1276
- clearImmediate: function(handle) {
1277
- return clearImmediate(handle);
1278
- },
1279
- delegate: void 0
1280
- }, AsapAction = function(_super) {
1281
- __extends(AsapAction2, _super);
1282
- function AsapAction2(scheduler, work) {
1283
- var _this = _super.call(this, scheduler, work) || this;
1284
- return _this.scheduler = scheduler, _this.work = work, _this;
1285
- }
1286
- return AsapAction2.prototype.requestAsyncId = function(scheduler, id, delay) {
1287
- return delay === void 0 && (delay = 0), delay !== null && delay > 0 ? _super.prototype.requestAsyncId.call(this, scheduler, id, delay) : (scheduler.actions.push(this), scheduler._scheduled || (scheduler._scheduled = immediateProvider.setImmediate(scheduler.flush.bind(scheduler, void 0))));
1288
- }, AsapAction2.prototype.recycleAsyncId = function(scheduler, id, delay) {
1289
- var _a;
1290
- if (delay === void 0 && (delay = 0), delay != null ? delay > 0 : this.delay > 0)
1291
- return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay);
1292
- var actions = scheduler.actions;
1293
- id != null && ((_a = actions[actions.length - 1]) === null || _a === void 0 ? void 0 : _a.id) !== id && (immediateProvider.clearImmediate(id), scheduler._scheduled === id && (scheduler._scheduled = void 0));
1294
- }, AsapAction2;
1295
- }(AsyncAction), Scheduler = function() {
1296
- function Scheduler2(schedulerActionCtor, now) {
1297
- now === void 0 && (now = Scheduler2.now), this.schedulerActionCtor = schedulerActionCtor, this.now = now;
1298
- }
1299
- return Scheduler2.prototype.schedule = function(work, delay, state) {
1300
- return delay === void 0 && (delay = 0), new this.schedulerActionCtor(this, work).schedule(state, delay);
1301
- }, Scheduler2.now = dateTimestampProvider.now, Scheduler2;
1302
- }(), AsyncScheduler = function(_super) {
1303
- __extends(AsyncScheduler2, _super);
1304
- function AsyncScheduler2(SchedulerAction, now) {
1305
- now === void 0 && (now = Scheduler.now);
1306
- var _this = _super.call(this, SchedulerAction, now) || this;
1307
- return _this.actions = [], _this._active = !1, _this;
1308
- }
1309
- return AsyncScheduler2.prototype.flush = function(action) {
1310
- var actions = this.actions;
1311
- if (this._active) {
1312
- actions.push(action);
1313
- return;
1314
- }
1315
- var error;
1316
- this._active = !0;
1317
- do
1318
- if (error = action.execute(action.state, action.delay))
1319
- break;
1320
- while (action = actions.shift());
1321
- if (this._active = !1, error) {
1322
- for (; action = actions.shift(); )
1323
- action.unsubscribe();
1324
- throw error;
1325
- }
1326
- }, AsyncScheduler2;
1327
- }(Scheduler), AsapScheduler = function(_super) {
1328
- __extends(AsapScheduler2, _super);
1329
- function AsapScheduler2() {
1330
- return _super !== null && _super.apply(this, arguments) || this;
1331
- }
1332
- return AsapScheduler2.prototype.flush = function(action) {
1333
- this._active = !0;
1334
- var flushId = this._scheduled;
1335
- this._scheduled = void 0;
1336
- var actions = this.actions, error;
1337
- action = action || actions.shift();
1338
- do
1339
- if (error = action.execute(action.state, action.delay))
1340
- break;
1341
- while ((action = actions[0]) && action.id === flushId && actions.shift());
1342
- if (this._active = !1, error) {
1343
- for (; (action = actions[0]) && action.id === flushId && actions.shift(); )
1344
- action.unsubscribe();
1345
- throw error;
1346
- }
1347
- }, AsapScheduler2;
1348
- }(AsyncScheduler), asapScheduler = new AsapScheduler(AsapAction), asyncScheduler = new AsyncScheduler(AsyncAction), async = asyncScheduler;
1349
- function isScheduler(value) {
1350
- return value && isFunction(value.schedule);
1351
- }
1352
- function last(arr) {
1353
- return arr[arr.length - 1];
1354
- }
1355
- function popScheduler(args) {
1356
- return isScheduler(last(args)) ? args.pop() : void 0;
1357
- }
1358
- var isArrayLike = function(x) {
1359
- return x && typeof x.length == "number" && typeof x != "function";
1360
- };
1361
- function isPromise(value) {
1362
- return isFunction(value?.then);
1363
- }
1364
- function isInteropObservable(input) {
1365
- return isFunction(input[observable]);
1366
- }
1367
- function isAsyncIterable(obj) {
1368
- return Symbol.asyncIterator && isFunction(obj?.[Symbol.asyncIterator]);
1369
- }
1370
- function createInvalidObservableTypeError(input) {
1371
- return new TypeError("You provided " + (input !== null && typeof input == "object" ? "an invalid object" : "'" + input + "'") + " where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.");
1372
- }
1373
- function getSymbolIterator() {
1374
- return typeof Symbol != "function" || !Symbol.iterator ? "@@iterator" : Symbol.iterator;
1375
- }
1376
- var iterator = getSymbolIterator();
1377
- function isIterable(input) {
1378
- return isFunction(input?.[iterator]);
1379
- }
1380
- function readableStreamLikeToAsyncGenerator(readableStream) {
1381
- return __asyncGenerator(this, arguments, function() {
1382
- var reader, _a, value, done;
1383
- return __generator(this, function(_b) {
1384
- switch (_b.label) {
1385
- case 0:
1386
- reader = readableStream.getReader(), _b.label = 1;
1387
- case 1:
1388
- _b.trys.push([1, , 9, 10]), _b.label = 2;
1389
- case 2:
1390
- return [4, __await(reader.read())];
1391
- case 3:
1392
- return _a = _b.sent(), value = _a.value, done = _a.done, done ? [4, __await(void 0)] : [3, 5];
1393
- case 4:
1394
- return [2, _b.sent()];
1395
- case 5:
1396
- return [4, __await(value)];
1397
- case 6:
1398
- return [4, _b.sent()];
1399
- case 7:
1400
- return _b.sent(), [3, 2];
1401
- case 8:
1402
- return [3, 10];
1403
- case 9:
1404
- return reader.releaseLock(), [7];
1405
- case 10:
1406
- return [2];
1407
- }
1408
- });
1409
- });
1410
- }
1411
- function isReadableStreamLike(obj) {
1412
- return isFunction(obj?.getReader);
1413
- }
1414
- function innerFrom(input) {
1415
- if (input instanceof Observable)
1416
- return input;
1417
- if (input != null) {
1418
- if (isInteropObservable(input))
1419
- return fromInteropObservable(input);
1420
- if (isArrayLike(input))
1421
- return fromArrayLike(input);
1422
- if (isPromise(input))
1423
- return fromPromise(input);
1424
- if (isAsyncIterable(input))
1425
- return fromAsyncIterable(input);
1426
- if (isIterable(input))
1427
- return fromIterable(input);
1428
- if (isReadableStreamLike(input))
1429
- return fromReadableStreamLike(input);
1430
- }
1431
- throw createInvalidObservableTypeError(input);
1432
- }
1433
- function fromInteropObservable(obj) {
1434
- return new Observable(function(subscriber) {
1435
- var obs = obj[observable]();
1436
- if (isFunction(obs.subscribe))
1437
- return obs.subscribe(subscriber);
1438
- throw new TypeError("Provided object does not correctly implement Symbol.observable");
1439
- });
1440
- }
1441
- function fromArrayLike(array) {
1442
- return new Observable(function(subscriber) {
1443
- for (var i = 0; i < array.length && !subscriber.closed; i++)
1444
- subscriber.next(array[i]);
1445
- subscriber.complete();
1446
- });
1447
- }
1448
- function fromPromise(promise) {
1449
- return new Observable(function(subscriber) {
1450
- promise.then(function(value) {
1451
- subscriber.closed || (subscriber.next(value), subscriber.complete());
1452
- }, function(err) {
1453
- return subscriber.error(err);
1454
- }).then(null, reportUnhandledError);
1455
- });
1456
- }
1457
- function fromIterable(iterable) {
1458
- return new Observable(function(subscriber) {
1459
- var e_1, _a;
1460
- try {
1461
- for (var iterable_1 = __values(iterable), iterable_1_1 = iterable_1.next(); !iterable_1_1.done; iterable_1_1 = iterable_1.next()) {
1462
- var value = iterable_1_1.value;
1463
- if (subscriber.next(value), subscriber.closed)
1464
- return;
1465
- }
1466
- } catch (e_1_1) {
1467
- e_1 = { error: e_1_1 };
1468
- } finally {
1469
- try {
1470
- iterable_1_1 && !iterable_1_1.done && (_a = iterable_1.return) && _a.call(iterable_1);
1471
- } finally {
1472
- if (e_1) throw e_1.error;
1473
- }
1474
- }
1475
- subscriber.complete();
1476
- });
1477
- }
1478
- function fromAsyncIterable(asyncIterable) {
1479
- return new Observable(function(subscriber) {
1480
- process(asyncIterable, subscriber).catch(function(err) {
1481
- return subscriber.error(err);
1482
- });
1483
- });
1484
- }
1485
- function fromReadableStreamLike(readableStream) {
1486
- return fromAsyncIterable(readableStreamLikeToAsyncGenerator(readableStream));
1487
- }
1488
- function process(asyncIterable, subscriber) {
1489
- var asyncIterable_1, asyncIterable_1_1, e_2, _a;
1490
- return __awaiter(this, void 0, void 0, function() {
1491
- var value, e_2_1;
1492
- return __generator(this, function(_b) {
1493
- switch (_b.label) {
1494
- case 0:
1495
- _b.trys.push([0, 5, 6, 11]), asyncIterable_1 = __asyncValues(asyncIterable), _b.label = 1;
1496
- case 1:
1497
- return [4, asyncIterable_1.next()];
1498
- case 2:
1499
- if (asyncIterable_1_1 = _b.sent(), !!asyncIterable_1_1.done) return [3, 4];
1500
- if (value = asyncIterable_1_1.value, subscriber.next(value), subscriber.closed)
1501
- return [2];
1502
- _b.label = 3;
1503
- case 3:
1504
- return [3, 1];
1505
- case 4:
1506
- return [3, 11];
1507
- case 5:
1508
- return e_2_1 = _b.sent(), e_2 = { error: e_2_1 }, [3, 11];
1509
- case 6:
1510
- return _b.trys.push([6, , 9, 10]), asyncIterable_1_1 && !asyncIterable_1_1.done && (_a = asyncIterable_1.return) ? [4, _a.call(asyncIterable_1)] : [3, 8];
1511
- case 7:
1512
- _b.sent(), _b.label = 8;
1513
- case 8:
1514
- return [3, 10];
1515
- case 9:
1516
- if (e_2) throw e_2.error;
1517
- return [7];
1518
- case 10:
1519
- return [7];
1520
- case 11:
1521
- return subscriber.complete(), [2];
1522
- }
1523
- });
1524
- });
1525
- }
1526
- function executeSchedule(parentSubscription, scheduler, work, delay, repeat) {
1527
- delay === void 0 && (delay = 0), repeat === void 0 && (repeat = !1);
1528
- var scheduleSubscription = scheduler.schedule(function() {
1529
- work(), repeat ? parentSubscription.add(this.schedule(null, delay)) : this.unsubscribe();
1530
- }, delay);
1531
- if (parentSubscription.add(scheduleSubscription), !repeat)
1532
- return scheduleSubscription;
1533
- }
1534
- function observeOn(scheduler, delay) {
1535
- return delay === void 0 && (delay = 0), operate(function(source, subscriber) {
1536
- source.subscribe(createOperatorSubscriber(subscriber, function(value) {
1537
- return executeSchedule(subscriber, scheduler, function() {
1538
- return subscriber.next(value);
1539
- }, delay);
1540
- }, function() {
1541
- return executeSchedule(subscriber, scheduler, function() {
1542
- return subscriber.complete();
1543
- }, delay);
1544
- }, function(err) {
1545
- return executeSchedule(subscriber, scheduler, function() {
1546
- return subscriber.error(err);
1547
- }, delay);
1548
- }));
1549
- });
1550
- }
1551
- function subscribeOn(scheduler, delay) {
1552
- return delay === void 0 && (delay = 0), operate(function(source, subscriber) {
1553
- subscriber.add(scheduler.schedule(function() {
1554
- return source.subscribe(subscriber);
1555
- }, delay));
1556
- });
1557
- }
1558
- function scheduleObservable(input, scheduler) {
1559
- return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));
1560
- }
1561
- function schedulePromise(input, scheduler) {
1562
- return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));
1563
- }
1564
- function scheduleArray(input, scheduler) {
1565
- return new Observable(function(subscriber) {
1566
- var i = 0;
1567
- return scheduler.schedule(function() {
1568
- i === input.length ? subscriber.complete() : (subscriber.next(input[i++]), subscriber.closed || this.schedule());
1569
- });
1570
- });
1571
- }
1572
- function scheduleIterable(input, scheduler) {
1573
- return new Observable(function(subscriber) {
1574
- var iterator$1;
1575
- return executeSchedule(subscriber, scheduler, function() {
1576
- iterator$1 = input[iterator](), executeSchedule(subscriber, scheduler, function() {
1577
- var _a, value, done;
1578
- try {
1579
- _a = iterator$1.next(), value = _a.value, done = _a.done;
1580
- } catch (err) {
1581
- subscriber.error(err);
1582
- return;
1583
- }
1584
- done ? subscriber.complete() : subscriber.next(value);
1585
- }, 0, !0);
1586
- }), function() {
1587
- return isFunction(iterator$1?.return) && iterator$1.return();
1588
- };
1589
- });
1590
- }
1591
- function scheduleAsyncIterable(input, scheduler) {
1592
- if (!input)
1593
- throw new Error("Iterable cannot be null");
1594
- return new Observable(function(subscriber) {
1595
- executeSchedule(subscriber, scheduler, function() {
1596
- var iterator2 = input[Symbol.asyncIterator]();
1597
- executeSchedule(subscriber, scheduler, function() {
1598
- iterator2.next().then(function(result) {
1599
- result.done ? subscriber.complete() : subscriber.next(result.value);
1600
- });
1601
- }, 0, !0);
1602
- });
1603
- });
1604
- }
1605
- function scheduleReadableStreamLike(input, scheduler) {
1606
- return scheduleAsyncIterable(readableStreamLikeToAsyncGenerator(input), scheduler);
1607
- }
1608
- function scheduled(input, scheduler) {
1609
- if (input != null) {
1610
- if (isInteropObservable(input))
1611
- return scheduleObservable(input, scheduler);
1612
- if (isArrayLike(input))
1613
- return scheduleArray(input, scheduler);
1614
- if (isPromise(input))
1615
- return schedulePromise(input, scheduler);
1616
- if (isAsyncIterable(input))
1617
- return scheduleAsyncIterable(input, scheduler);
1618
- if (isIterable(input))
1619
- return scheduleIterable(input, scheduler);
1620
- if (isReadableStreamLike(input))
1621
- return scheduleReadableStreamLike(input, scheduler);
1622
- }
1623
- throw createInvalidObservableTypeError(input);
1624
- }
1625
- function from(input, scheduler) {
1626
- return scheduler ? scheduled(input, scheduler) : innerFrom(input);
1627
- }
1628
- function of() {
1629
- for (var args = [], _i = 0; _i < arguments.length; _i++)
1630
- args[_i] = arguments[_i];
1631
- var scheduler = popScheduler(args);
1632
- return from(args, scheduler);
1633
- }
1634
- function isValidDate(value) {
1635
- return value instanceof Date && !isNaN(value);
1636
- }
1637
- function map(project, thisArg) {
1638
- return operate(function(source, subscriber) {
1639
- var index = 0;
1640
- source.subscribe(createOperatorSubscriber(subscriber, function(value) {
1641
- subscriber.next(project.call(thisArg, value, index++));
1642
- }));
1643
- });
1644
- }
1645
- function timer(dueTime, intervalOrScheduler, scheduler) {
1646
- scheduler === void 0 && (scheduler = async);
1647
- var intervalDuration = -1;
1648
- return intervalOrScheduler != null && (isScheduler(intervalOrScheduler) ? scheduler = intervalOrScheduler : intervalDuration = intervalOrScheduler), new Observable(function(subscriber) {
1649
- var due = isValidDate(dueTime) ? +dueTime - scheduler.now() : dueTime;
1650
- due < 0 && (due = 0);
1651
- var n = 0;
1652
- return scheduler.schedule(function() {
1653
- subscriber.closed || (subscriber.next(n++), 0 <= intervalDuration ? this.schedule(void 0, intervalDuration) : subscriber.complete());
1654
- }, due);
1655
- });
1656
- }
1657
- function catchError(selector) {
1658
- return operate(function(source, subscriber) {
1659
- var innerSub = null, syncUnsub = !1, handledResult;
1660
- innerSub = source.subscribe(createOperatorSubscriber(subscriber, void 0, void 0, function(err) {
1661
- handledResult = innerFrom(selector(err, catchError(selector)(source))), innerSub ? (innerSub.unsubscribe(), innerSub = null, handledResult.subscribe(subscriber)) : syncUnsub = !0;
1662
- })), syncUnsub && (innerSub.unsubscribe(), innerSub = null, handledResult.subscribe(subscriber));
1663
- });
1664
- }
1665
- function finalize(callback) {
1666
- return operate(function(source, subscriber) {
1667
- try {
1668
- source.subscribe(subscriber);
1669
- } finally {
1670
- subscriber.add(callback);
1671
- }
1672
- });
1673
- }
1674
- function share(options) {
1675
- options === void 0 && (options = {});
1676
- var _a = options.connector, connector = _a === void 0 ? function() {
1677
- return new Subject();
1678
- } : _a, _b = options.resetOnError, resetOnError = _b === void 0 ? !0 : _b, _c = options.resetOnComplete, resetOnComplete = _c === void 0 ? !0 : _c, _d = options.resetOnRefCountZero, resetOnRefCountZero = _d === void 0 ? !0 : _d;
1679
- return function(wrapperSource) {
1680
- var connection, resetConnection, subject, refCount = 0, hasCompleted = !1, hasErrored = !1, cancelReset = function() {
1681
- resetConnection?.unsubscribe(), resetConnection = void 0;
1682
- }, reset = function() {
1683
- cancelReset(), connection = subject = void 0, hasCompleted = hasErrored = !1;
1684
- }, resetAndUnsubscribe = function() {
1685
- var conn = connection;
1686
- reset(), conn?.unsubscribe();
1687
- };
1688
- return operate(function(source, subscriber) {
1689
- refCount++, !hasErrored && !hasCompleted && cancelReset();
1690
- var dest = subject = subject ?? connector();
1691
- subscriber.add(function() {
1692
- refCount--, refCount === 0 && !hasErrored && !hasCompleted && (resetConnection = handleReset(resetAndUnsubscribe, resetOnRefCountZero));
1693
- }), dest.subscribe(subscriber), !connection && refCount > 0 && (connection = new SafeSubscriber({
1694
- next: function(value) {
1695
- return dest.next(value);
1696
- },
1697
- error: function(err) {
1698
- hasErrored = !0, cancelReset(), resetConnection = handleReset(reset, resetOnError, err), dest.error(err);
1699
- },
1700
- complete: function() {
1701
- hasCompleted = !0, cancelReset(), resetConnection = handleReset(reset, resetOnComplete), dest.complete();
1702
- }
1703
- }), innerFrom(source).subscribe(connection));
1704
- })(wrapperSource);
1705
- };
1706
- }
1707
- function handleReset(reset, on) {
1708
- for (var args = [], _i = 2; _i < arguments.length; _i++)
1709
- args[_i - 2] = arguments[_i];
1710
- if (on === !0) {
1711
- reset();
1712
- return;
1713
- }
1714
- if (on !== !1) {
1715
- var onSubscriber = new SafeSubscriber({
1716
- next: function() {
1717
- onSubscriber.unsubscribe(), reset();
1718
- }
1719
- });
1720
- return innerFrom(on.apply(void 0, __spreadArray([], __read(args)))).subscribe(onSubscriber);
1721
- }
1722
- }
1723
- function tap(observerOrNext, error, complete) {
1724
- var tapObserver = isFunction(observerOrNext) || error || complete ? { next: observerOrNext, error, complete } : observerOrNext;
1725
- return tapObserver ? operate(function(source, subscriber) {
1726
- var _a;
1727
- (_a = tapObserver.subscribe) === null || _a === void 0 || _a.call(tapObserver);
1728
- var isUnsub = !0;
1729
- source.subscribe(createOperatorSubscriber(subscriber, function(value) {
1730
- var _a2;
1731
- (_a2 = tapObserver.next) === null || _a2 === void 0 || _a2.call(tapObserver, value), subscriber.next(value);
1732
- }, function() {
1733
- var _a2;
1734
- isUnsub = !1, (_a2 = tapObserver.complete) === null || _a2 === void 0 || _a2.call(tapObserver), subscriber.complete();
1735
- }, function(err) {
1736
- var _a2;
1737
- isUnsub = !1, (_a2 = tapObserver.error) === null || _a2 === void 0 || _a2.call(tapObserver, err), subscriber.error(err);
1738
- }, function() {
1739
- var _a2, _b;
1740
- isUnsub && ((_a2 = tapObserver.unsubscribe) === null || _a2 === void 0 || _a2.call(tapObserver)), (_b = tapObserver.finalize) === null || _b === void 0 || _b.call(tapObserver);
1741
- }));
1742
- }) : identity;
1743
- }
1744
- function getValue(value) {
1745
- return typeof value == "function" ? value() : value;
1746
- }
1747
- const cache = /* @__PURE__ */ new WeakMap();
1748
- function useObservable(observable2, initialValue) {
1749
- const $ = distExports.c(9);
1750
- let t0;
1751
- if (!cache.has(observable2)) {
1752
- const state = {
1753
- didEmit: !1
1754
- }, entry = {
1755
- state,
1756
- observable: observable2.pipe(map(_temp$1), catchError(_temp2), tap((t12) => {
1757
- const {
1758
- snapshot,
1759
- error: error_0
1760
- } = t12;
1761
- state.didEmit = !0, state.snapshot = snapshot, state.error = error_0;
1762
- }), map(_temp3), finalize(() => cache.delete(observable2)), share({
1763
- resetOnRefCountZero: _temp4
1764
- })),
1765
- getSnapshot: (initialValue_0) => {
1766
- if (state.error)
1767
- throw state.error;
1768
- return state.didEmit ? state.snapshot : getValue(initialValue_0);
1769
- }
1770
- };
1771
- entry.observable.subscribe().unsubscribe(), cache.set(observable2, entry);
1772
- }
1773
- let t1;
1774
- $[0] !== observable2 ? (t1 = cache.get(observable2), $[0] = observable2, $[1] = t1) : t1 = $[1], t0 = t1;
1775
- const instance = t0;
1776
- let t2;
1777
- $[2] !== instance.observable ? (t2 = (onStoreChange) => {
1778
- const subscription_0 = instance.observable.subscribe(onStoreChange);
1779
- return () => {
1780
- subscription_0.unsubscribe();
1781
- };
1782
- }, $[2] = instance.observable, $[3] = t2) : t2 = $[3];
1783
- const subscribe = t2;
1784
- let t3;
1785
- $[4] !== initialValue || $[5] !== instance ? (t3 = () => instance.getSnapshot(initialValue), $[4] = initialValue, $[5] = instance, $[6] = t3) : t3 = $[6];
1786
- let t4;
1787
- return $[7] !== initialValue ? (t4 = typeof initialValue > "u" ? void 0 : () => getValue(initialValue), $[7] = initialValue, $[8] = t4) : t4 = $[8], useSyncExternalStore(subscribe, t3, t4);
1788
- }
1789
- function _temp4() {
1790
- return timer(0, asapScheduler);
1791
- }
1792
- function _temp3(value_0) {
1793
- }
1794
- function _temp2(error) {
1795
- return of({
1796
- snapshot: void 0,
1797
- error
1798
- });
1799
- }
1800
- function _temp$1(value) {
1801
- return {
1802
- snapshot: value,
1803
- error: void 0
1804
- };
1805
- }
1806
- function DocumentPreview({
1807
- documentId,
1808
- style,
1809
- schemaTypeName,
1810
- ...buttonProps
1811
- }) {
1812
- const schema = useSchema(), schemaType = schemaTypeName ? schema.get(schemaTypeName) : void 0;
1813
- return schemaTypeName ? schemaType ? /* @__PURE__ */ jsx(
1814
- DocumentPreviewInner,
1815
- {
1816
- documentId,
1817
- schemaTypeName,
1818
- schemaType,
1819
- style,
1820
- ...buttonProps
1821
- }
1822
- ) : /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsx(
1823
- DefaultPreview,
1824
- {
1825
- withShadow: !1,
1826
- withBorder: !1,
1827
- media: () => /* @__PURE__ */ jsx(ErrorOutlineIcon, {}),
1828
- title: /* @__PURE__ */ jsxs(Fragment, { children: [
1829
- "Unknown type ",
1830
- /* @__PURE__ */ jsx("code", { children: schemaTypeName ?? "N/A" }),
1831
- " for ",
1832
- documentId
1833
- ] })
1834
- }
1835
- ) }) : /* @__PURE__ */ jsx(Card, { style: { minHeight: "36px" }, children: /* @__PURE__ */ jsx(
1836
- DefaultPreview,
1837
- {
1838
- withShadow: !1,
1839
- withBorder: !1,
1840
- title: "Loading...",
1841
- schemaType,
1842
- isPlaceholder: !0
1843
- }
1844
- ) });
1845
- }
1846
- function DocumentPreviewInner({
1847
- documentId,
1848
- schemaType,
1849
- style,
1850
- button
1851
- }) {
1852
- const documentPreviewStore = useDocumentPreviewStore(), previewStateObservable = useMemo(
1853
- () => getPreviewStateObservable(documentPreviewStore, schemaType, documentId),
1854
- [documentId, documentPreviewStore, schemaType]
1855
- ), {
1856
- snapshot,
1857
- original,
1858
- isLoading: previewIsLoading
1859
- } = useObservable(previewStateObservable, {
1860
- snapshot: null,
1861
- isLoading: !0,
1862
- original: null
1863
- }), sanityDocument = useMemo(() => ({
1864
- _id: documentId,
1865
- _type: schemaType?.name
1866
- }), [documentId, schemaType?.name]), { onClick: onIntentClick, href } = useIntentLink({
1867
- intent: "edit",
1868
- params: {
1869
- id: documentId,
1870
- type: schemaType?.name
1871
- }
1872
- }), preview = /* @__PURE__ */ jsx(
1873
- SanityDefaultPreview,
1874
- {
1875
- ...getPreviewValueWithFallback({
1876
- snapshot,
1877
- original,
1878
- fallback: sanityDocument
1879
- }),
1880
- isPlaceholder: previewIsLoading ?? !0,
1881
- layout: "default",
1882
- icon: schemaType?.icon
1883
- }
1884
- );
1885
- return button ? /* @__PURE__ */ jsx(
1886
- Button,
1887
- {
1888
- as: "a",
1889
- href,
1890
- onClick: onIntentClick,
1891
- mode: "ghost",
1892
- style: { width: "100%", ...style },
1893
- children: preview
1894
- }
1895
- ) : /* @__PURE__ */ jsx(Box, { style: { width: "100%" }, children: preview });
1896
- }
1897
- const NO_RESULTS_VALUE = "", NO_OPTIONS = [], NO_FILTER = () => !0, SemanticSearchAutocomplete = forwardRef(function(props, ref) {
1898
- const {
1899
- indexConfig,
1900
- filterResult,
1901
- getEmptySearchValue,
1902
- readOnly,
1903
- onFocus,
1904
- onBlur,
1905
- onSelect,
1906
- typeFilter
1907
- } = props, id = useId(), [query, setQuery] = useState(""), queryRef = useRef(query), debouncedQuery = useDebouncedValue(query, 300), prevDebouncedQuery = useRef(debouncedQuery), [searching, setSearching] = useState(!1), [options, setOptions] = useState(NO_OPTIONS), client = useApiClient(), runIndexQuery = useCallback(
1908
- (queryString) => {
1909
- setSearching(!0);
1910
- const indexName = indexConfig?.indexName, maxResults = indexConfig?.maxResults;
1911
- if (!indexName)
1912
- throw new Error("Reference option embeddingsIndex.indexName is required, but was missing");
1913
- queryIndex(
1914
- {
1915
- query: queryString.trim().length ? queryString : getEmptySearchValue() ?? "",
1916
- indexName,
1917
- maxResults,
1918
- filter: {
1919
- type: typeFilter
1920
- }
1921
- },
1922
- client
1923
- ).then((result) => {
1924
- if (queryRef.current === queryString) {
1925
- setSearching(!1), setOptions([]), setOptions([]);
1926
- const resultOptions = result.filter((hit) => filterResult ? filterResult(hit) : !0).map((r) => typed({ result: r, value: r.value.documentId }));
1927
- resultOptions.length ? setOptions(resultOptions) : setOptions([{ value: NO_RESULTS_VALUE }]);
1928
- }
1929
- }).catch((e) => {
1930
- throw queryRef.current === queryString && setSearching(!1), e;
1931
- });
1932
- },
1933
- [client, indexConfig, getEmptySearchValue, filterResult, typeFilter]
1934
- );
1935
- useEffect(() => {
1936
- prevDebouncedQuery.current !== debouncedQuery && runIndexQuery(debouncedQuery), prevDebouncedQuery.current = debouncedQuery;
1937
- }, [debouncedQuery, runIndexQuery]);
1938
- const openButtonConfig = useMemo(
1939
- () => ({ onClick: () => runIndexQuery(queryRef.current) }),
1940
- [runIndexQuery, queryRef]
1941
- ), handleQueryChange = useCallback(
1942
- (newValue) => {
1943
- const newQuery = newValue ?? "";
1944
- queryRef.current = newQuery, setQuery(newQuery);
1945
- },
1946
- [setQuery]
1947
- ), handleChange = useCallback(
1948
- (value) => {
1949
- if (value === NO_RESULTS_VALUE) {
1950
- setOptions(NO_OPTIONS);
1951
- return;
1952
- }
1953
- const option = options.filter((r) => "result" in r).find((r) => r.result.value.documentId === value);
1954
- option && onSelect && onSelect(option.result);
1955
- },
1956
- [onSelect, options]
1957
- );
1958
- return /* @__PURE__ */ jsx(
1959
- Autocomplete,
1960
- {
1961
- id,
1962
- ref,
1963
- "data-testid": "semantic-autocomplete",
1964
- placeholder: "Type to search...",
1965
- openButton: openButtonConfig,
1966
- onFocus,
1967
- onChange: handleChange,
1968
- loading: searching,
1969
- onBlur,
1970
- readOnly,
1971
- filterOption: NO_FILTER,
1972
- onQueryChange: handleQueryChange,
1973
- options,
1974
- renderOption: AutocompleteOption
1975
- }
1976
- );
1977
- });
1978
- function AutocompleteOption(props) {
1979
- if ("result" in props) {
1980
- const value = props.result.value;
1981
- return /* @__PURE__ */ jsx(Button, { mode: "bleed", padding: 1, style: { width: "100%" }, children: /* @__PURE__ */ jsxs(Flex, { gap: 2, align: "center", children: [
1982
- /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsx(DocumentPreview, { documentId: value.documentId, schemaTypeName: value.type }) }),
1983
- /* @__PURE__ */ jsx(Box, { padding: 2, children: /* @__PURE__ */ jsxs(Text, { size: 1, muted: !0, title: "Relevance", children: [
1984
- Math.floor(props.result.score * 100),
1985
- "%"
1986
- ] }) })
1987
- ] }) });
1988
- }
1989
- return /* @__PURE__ */ jsx(Button, { mode: "bleed", padding: 1, style: { width: "100%" }, disabled: !0, children: /* @__PURE__ */ jsx(Flex, { gap: 2, align: "center", children: "No results." }) });
1990
- }
1991
- function useDebouncedValue(value, ms) {
1992
- const [debouncedValue, setDebouncedValue] = useState(value);
1993
- return useEffect(() => {
1994
- const timeoutId = setTimeout(() => {
1995
- setDebouncedValue(value);
1996
- }, ms);
1997
- return () => clearTimeout(timeoutId);
1998
- }, [value, ms]), debouncedValue;
1999
- }
2000
- function QueryIndex(props) {
2001
- const { indexName } = props, getEmpty = useCallback(() => "anything", []), indexConfig = useMemo(
2002
- () => ({ indexName, maxResults: 8 }),
2003
- [indexName]
2004
- ), { resolveIntentLink, navigateUrl } = useRouter(), onSelect = useCallback(
2005
- (hit) => {
2006
- navigateUrl({
2007
- path: resolveIntentLink("edit", { id: hit.value.documentId, type: hit.value.type })
2008
- });
2009
- },
2010
- [resolveIntentLink, navigateUrl]
2011
- );
2012
- return /* @__PURE__ */ jsx(
2013
- SemanticSearchAutocomplete,
2014
- {
2015
- getEmptySearchValue: getEmpty,
2016
- indexConfig,
2017
- onSelect
2018
- }
2019
- );
2020
- }
2021
- function IndexInfo({ selectedIndex, onDeleteIndex }) {
2022
- const handleDelete = useCallback(
2023
- () => onDeleteIndex(selectedIndex),
2024
- [selectedIndex, onDeleteIndex]
2025
- );
2026
- return /* @__PURE__ */ jsxs(Stack, { space: 4, flex: 1, children: [
2027
- /* @__PURE__ */ jsxs(Flex, { align: "center", flex: 1, gap: 2, children: [
2028
- /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsxs(Heading, { children: [
2029
- "Index: ",
2030
- selectedIndex?.indexName ?? "Untitled"
2031
- ] }) }),
2032
- /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(
2033
- MenuButton,
2034
- {
2035
- button: /* @__PURE__ */ jsx(
2036
- Button,
2037
- {
2038
- title: "Open index actions",
2039
- icon: EllipsisVerticalIcon,
2040
- padding: 2,
2041
- mode: "ghost"
2042
- }
2043
- ),
2044
- id: `button-${selectedIndex.indexName}`,
2045
- menu: /* @__PURE__ */ jsx(Menu, { children: /* @__PURE__ */ jsx(
2046
- MenuItem,
2047
- {
2048
- text: "Delete index",
2049
- icon: TrashIcon,
2050
- tone: "critical",
2051
- onClick: handleDelete
2052
- }
2053
- ) }),
2054
- popover: { placement: "right" }
2055
- }
2056
- ) })
2057
- ] }),
2058
- /* @__PURE__ */ jsxs(Flex, { gap: 6, children: [
2059
- /* @__PURE__ */ jsxs(Stack, { space: 4, flex: 1, style: { maxWidth: 600 }, children: [
2060
- /* @__PURE__ */ jsx(Box, { children: /* @__PURE__ */ jsx(IndexEditor, { index: selectedIndex, readOnly: !0 }) }),
2061
- /* @__PURE__ */ jsx(IndexStatus, { selectedIndex })
2062
- ] }),
2063
- /* @__PURE__ */ jsxs(Stack, { space: 3, flex: 1, children: [
2064
- /* @__PURE__ */ jsx(Label, { muted: !0, children: "Query index" }),
2065
- /* @__PURE__ */ jsx(QueryIndex, { indexName: selectedIndex.indexName }, selectedIndex.indexName)
2066
- ] })
2067
- ] })
2068
- ] });
2069
- }
2070
- function IndexStatus({ selectedIndex }) {
2071
- return /* @__PURE__ */ jsxs(Stack, { space: 4, flex: 1, children: [
2072
- /* @__PURE__ */ jsxs(Flex, { gap: 2, align: "center", children: [
2073
- /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsx(Label, { size: 1, muted: !0, children: "Status" }) }),
2074
- /* @__PURE__ */ jsx(Stack, { space: 2, children: /* @__PURE__ */ jsx(Text, { children: selectedIndex.status }) })
2075
- ] }),
2076
- /* @__PURE__ */ jsxs(Flex, { gap: 5, align: "center", children: [
2077
- /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsx(Label, { size: 1, muted: !0, children: "Indexing progress" }) }),
2078
- /* @__PURE__ */ jsx(Stack, { space: 2, children: /* @__PURE__ */ jsxs(Text, { children: [
2079
- selectedIndex.startDocumentCount - selectedIndex.remainingDocumentCount,
2080
- " /",
2081
- " ",
2082
- selectedIndex.startDocumentCount
2083
- ] }) })
2084
- ] }),
2085
- /* @__PURE__ */ jsxs(Flex, { gap: 5, align: "center", children: [
2086
- /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsx(Label, { size: 1, muted: !0, children: "Failed documents" }) }),
2087
- /* @__PURE__ */ jsx(Stack, { space: 2, children: /* @__PURE__ */ jsx(Text, { children: selectedIndex.failedDocumentCount }) })
2088
- ] })
2089
- ] });
2090
- }
2091
- function IndexList(props) {
2092
- const { loading, selectedIndex, indexes, onIndexSelected } = props;
2093
- return /* @__PURE__ */ jsx(Card, { tone: "default", style: { opacity: loading ? 0.5 : 1 }, children: /* @__PURE__ */ jsxs(Stack, { space: 2, children: [
2094
- /* @__PURE__ */ jsx(Card, { borderBottom: !0, flex: 1, paddingBottom: 2, padding: 3, children: /* @__PURE__ */ jsxs(Flex, { children: [
2095
- /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsx(Label, { muted: !0, children: "Index name" }) }),
2096
- /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsx(Label, { muted: !0, children: "Dataset" }) }),
2097
- /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsx(Label, { muted: !0, children: "Status" }) }),
2098
- /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsx(Label, { muted: !0, children: "Progress" }) })
2099
- ] }) }),
2100
- indexes.length ? /* @__PURE__ */ jsx(Stack, { space: 2, style: { maxHeight: 200, overflow: "auto" }, children: indexes.map((index) => /* @__PURE__ */ jsx(
2101
- IndexRow,
2102
- {
2103
- selectedIndex,
2104
- index,
2105
- onIndexSelected
2106
- },
2107
- index.indexName
2108
- )) }) : /* @__PURE__ */ jsx(Text, { muted: !0, children: "No indexes found." })
2109
- ] }) });
2110
- }
2111
- function IndexRow(props) {
2112
- const { selectedIndex, index, onIndexSelected } = props, onSelect = useCallback(() => onIndexSelected(index), [onIndexSelected, index]);
2113
- return /* @__PURE__ */ jsx(
2114
- Button,
2115
- {
2116
- tone: selectedIndex?.indexName === index.indexName ? "primary" : "default",
2117
- mode: selectedIndex?.indexName === index.indexName ? "default" : "ghost",
2118
- onClick: onSelect,
2119
- padding: 3,
2120
- children: /* @__PURE__ */ jsxs(Flex, { children: [
2121
- /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsx("strong", { children: index.indexName }) }),
2122
- /* @__PURE__ */ jsx(Box, { flex: 1, children: index.dataset }),
2123
- /* @__PURE__ */ jsx(Box, { flex: 1, children: index.status }),
2124
- /* @__PURE__ */ jsxs(Box, { flex: 1, children: [
2125
- index.startDocumentCount ? Math.floor(
2126
- (index.startDocumentCount - index.remainingDocumentCount) / index.startDocumentCount * 100
2127
- ) : "?",
2128
- "%"
2129
- ] })
2130
- ] })
2131
- },
2132
- index.indexName
2133
- );
2134
- }
2135
- function EmbeddingsIndexTool() {
2136
- const featureState = useIsFeatureEnabled();
2137
- return /* @__PURE__ */ jsx(Card, { flex: 1, children: /* @__PURE__ */ jsxs(Flex, { justify: "center", flex: 1, children: [
2138
- featureState === "error" ? /* @__PURE__ */ jsx(Box, { padding: 4, children: /* @__PURE__ */ jsx(FeatureError, {}) }) : null,
2139
- featureState === "disabled" ? /* @__PURE__ */ jsx(Box, { padding: 4, children: /* @__PURE__ */ jsx(FeatureDisabledNotice, { urlSuffix: "?ref=embeddings-tab" }) }) : null,
2140
- featureState === "loading" ? /* @__PURE__ */ jsx(Box, { padding: 6, children: /* @__PURE__ */ jsx(Spinner, { size: 4 }) }) : null,
2141
- featureState === "enabled" ? /* @__PURE__ */ jsx(Card, { flex: 1, style: { maxWidth: 1200 }, padding: 5, children: /* @__PURE__ */ jsx(Indexes, {}) }) : null
2142
- ] }) });
2143
- }
2144
- const NO_INDEXES = [];
2145
- function Indexes() {
2146
- const client = useApiClient(), [indexes, setIndexes] = useState(NO_INDEXES), [loading, setLoading] = useState(!1), [error, setError] = useState(!1), [createIndexOpen, setCreateIndexOpen] = useState(!1), [selectedIndex, setSelectedIndex] = useState(void 0), onCreateIndexClose = useCallback(() => setCreateIndexOpen(!1), []);
2147
- useEffect(() => {
2148
- setSelectedIndex(indexes.find((i) => i.indexName === selectedIndex?.indexName));
2149
- }, [indexes, selectedIndex]);
2150
- const updateIndexes = useCallback(() => {
2151
- setLoading(!0), setError(!1), getIndexes(client).then((response) => {
2152
- setLoading(!1), setIndexes(response);
2153
- }).catch((e) => {
2154
- console.error(e), setError(!0);
2155
- }).finally(() => {
2156
- setLoading(!1);
2157
- });
2158
- }, [client]), deleteNamedIndex = useCallback(
2159
- (index) => {
2160
- confirm(`Are you sure you want to delete ${index.indexName} for dataset ${index.dataset}?`) && (setLoading(!0), setError(!1), deleteIndex(index.indexName, client).then(() => {
2161
- setTimeout(() => updateIndexes());
2162
- }).catch((e) => {
2163
- console.error(e), setError(!0);
2164
- }).finally(() => {
2165
- setLoading(!1);
2166
- }));
2167
- },
2168
- [client, updateIndexes]
2169
- ), onSelectIndex = useCallback(
2170
- (index) => {
2171
- setSelectedIndex(index), updateIndexes();
2172
- },
2173
- [setSelectedIndex, updateIndexes]
2174
- );
2175
- useEffect(() => {
2176
- updateIndexes();
2177
- }, [updateIndexes]);
2178
- const openCreate = useCallback(() => setCreateIndexOpen(!0), []), onSubmit = useCallback(
2179
- (index) => {
2180
- setIndexes((current) => [...current, index]), setSelectedIndex(index), updateIndexes();
2181
- },
2182
- [updateIndexes]
2183
- );
2184
- return /* @__PURE__ */ jsxs(Stack, { space: 4, children: [
2185
- /* @__PURE__ */ jsxs(Flex, { gap: 2, align: "center", style: { height: 30 }, children: [
2186
- /* @__PURE__ */ jsx(Box, { flex: 1, children: /* @__PURE__ */ jsx(Heading, { size: 1, children: "Embeddings indexes" }) }),
2187
- /* @__PURE__ */ jsx(Box, { style: { justifySelf: "flex-end" }, children: /* @__PURE__ */ jsx(
2188
- Button,
2189
- {
2190
- icon: AddIcon,
2191
- text: "New index",
2192
- tone: "default",
2193
- mode: "ghost",
2194
- onClick: openCreate
2195
- }
2196
- ) }),
2197
- /* @__PURE__ */ jsx(
2198
- Button,
2199
- {
2200
- size: 1,
2201
- icon: loading ? /* @__PURE__ */ jsx(Spinner, {}) : UndoIcon,
2202
- title: "Refresh index list",
2203
- tone: "default",
2204
- mode: "bleed",
2205
- onClick: updateIndexes,
2206
- disabled: loading
2207
- }
2208
- )
2209
- ] }),
2210
- error ? /* @__PURE__ */ jsx(Card, { tone: "critical", padding: 2, border: !0, children: "An error occurred. See console for details." }) : null,
2211
- /* @__PURE__ */ jsx(
2212
- IndexList,
2213
- {
2214
- loading,
2215
- indexes,
2216
- selectedIndex,
2217
- onIndexSelected: onSelectIndex
2218
- }
2219
- ),
2220
- selectedIndex && /* @__PURE__ */ jsx(IndexInfo, { selectedIndex, onDeleteIndex: deleteNamedIndex }),
2221
- /* @__PURE__ */ jsx(EditIndexDialog, { open: createIndexOpen, onClose: onCreateIndexClose, onSubmit })
2222
- ] });
2223
- }
2224
- const embeddingsIndexTool = {
2225
- name: "embeddings-index",
2226
- title: "Embeddings",
2227
- icon: EarthGlobeIcon,
2228
- component: EmbeddingsIndexTool
2229
- }, embeddingsIndexDashboard = definePlugin({
2230
- name: "@sanity/embeddings-index-dashboard",
2231
- tools: [embeddingsIndexTool]
2232
- });
2233
- function publicId(id) {
2234
- return id.replace("drafts.", "");
2235
- }
2236
- function useEmeddingsConfig(embeddingsIndexConfig, defaultConfig) {
2237
- return useMemo(() => {
2238
- if (embeddingsIndexConfig === !0 || !embeddingsIndexConfig) {
2239
- if (!defaultConfig?.indexName)
2240
- throw new Error(
2241
- "Default embeddingsIndex config is missing. When options.embeddingsIndex: true, embeddingsIndexReferenceInput plugin config is required."
2242
- );
2243
- return defaultConfig;
2244
- }
2245
- const finalConfig = {
2246
- ...defaultConfig,
2247
- ...embeddingsIndexConfig
2248
- };
2249
- if (!finalConfig?.indexName)
2250
- throw new Error(
2251
- "indexName is missing. Either set it in options.embeddingsIndex or configure defaults using plugin config."
2252
- );
2253
- return finalConfig;
2254
- }, [defaultConfig, embeddingsIndexConfig]);
2255
- }
2256
- function SemanticSearchReferenceInput(props) {
2257
- const embeddingsIndexConfig = props.schemaType?.options?.embeddingsIndex, config2 = useEmeddingsConfig(embeddingsIndexConfig, props.defaultConfig), defaultEnabled = config2.searchMode === "embeddings", featureState = useIsFeatureEnabledContext(), [semantic, setSemantic] = useState(defaultEnabled), toggleSemantic = useCallback(() => setSemantic((current) => !current), []);
2258
- return /* @__PURE__ */ jsxs(Flex, { gap: 2, flex: 1, style: { width: "100%" }, children: [
2259
- semantic && featureState == "loading" ? /* @__PURE__ */ jsx(Box, { padding: 2, children: /* @__PURE__ */ jsx(Spinner, {}) }) : null,
2260
- semantic && featureState == "disabled" ? /* @__PURE__ */ jsx(FeatureDisabledNotice, { urlSuffix: "?ref=embeddings-ref" }) : null,
2261
- semantic && featureState === "error" ? /* @__PURE__ */ jsx(Box, { padding: 4, children: /* @__PURE__ */ jsx(FeatureError, {}) }) : null,
2262
- /* @__PURE__ */ jsx(Box, { flex: 1, style: { maxHeight: 36, overflow: "hidden" }, children: semantic && featureState == "enabled" ? /* @__PURE__ */ jsx(SemanticSearchInput, { ...props, indexConfig: config2 }) : props.renderDefault(props) }),
2263
- /* @__PURE__ */ jsx(
2264
- Button,
2265
- {
2266
- icon: semantic ? EarthGlobeIcon : LinkIcon,
2267
- onClick: toggleSemantic,
2268
- mode: "bleed",
2269
- title: semantic ? "Switch to standard reference search" : "Switch to semantic reference search"
2270
- }
2271
- )
2272
- ] });
2273
- }
2274
- function SemanticSearchInput(props) {
2275
- const { indexConfig, onPathFocus, onChange, readOnly, schemaType, value } = props, { value: currentDocument } = useDocumentPane(), docRef = useRef(currentDocument), autocompleteRef = useRef(null);
2276
- useEffect(() => {
2277
- docRef.current = currentDocument;
2278
- }, [currentDocument]), useEffect(() => {
2279
- value?._ref && autocompleteRef.current?.focus();
2280
- }, []);
2281
- const handleFocus = useCallback(() => onPathFocus(["_ref"]), [onPathFocus]), handleBlur = useCallback(() => onPathFocus([]), [onPathFocus]), handleChange = useCallback(
2282
- (result) => {
2283
- if (!result) {
2284
- onChange(unset()), onPathFocus([]);
2285
- return;
2286
- }
2287
- const patches = [
2288
- setIfMissing({}),
2289
- set(schemaType.name, ["_type"]),
2290
- set(publicId(result.value.documentId), ["_ref"]),
2291
- unset(["_weak"]),
2292
- unset(["_strengthenOnPublish"])
2293
- ];
2294
- onChange(patches), onPathFocus([]);
2295
- },
2296
- [onChange, onPathFocus, schemaType.name]
2297
- ), filterResult = useCallback(
2298
- (r) => r.value.documentId !== publicId(docRef.current._id),
2299
- [docRef]
2300
- ), getEmptySearchValue = useCallback(() => JSON.stringify(docRef.current), [docRef]), typeFilter = useMemo(
2301
- () => schemaType.to.map((refType) => refType.name),
2302
- [schemaType]
2303
- );
2304
- return /* @__PURE__ */ jsx(
2305
- SemanticSearchAutocomplete,
2306
- {
2307
- ref: autocompleteRef,
2308
- typeFilter,
2309
- indexConfig,
2310
- onSelect: handleChange,
2311
- onFocus: handleFocus,
2312
- onBlur: handleBlur,
2313
- getEmptySearchValue,
2314
- filterResult,
2315
- readOnly
2316
- }
2317
- );
2318
- }
2319
- const embeddingsIndexReferenceInput = definePlugin(
2320
- (defaultConfig) => {
2321
- const config2 = typeof defaultConfig == "object" ? defaultConfig : void 0;
2322
- return {
2323
- name: "@sanity/embeddings-index-reference-input",
2324
- studio: {
2325
- components: {
2326
- layout: (props) => /* @__PURE__ */ jsx(FeatureEnabledProvider, { children: props.renderDefault(props) })
2327
- }
2328
- },
2329
- form: {
2330
- components: {
2331
- input: (props) => {
2332
- const embeddingsIndexConfig = props.schemaType?.options?.embeddingsIndex;
2333
- return isObjectInputProps(props) && isType(props.schemaType, "reference") && (embeddingsIndexConfig === !0 || embeddingsIndexConfig?.indexName) ? /* @__PURE__ */ jsx(
2334
- SemanticSearchReferenceInput,
2335
- {
2336
- ...props,
2337
- defaultConfig: config2
2338
- }
2339
- ) : props.renderDefault(props);
2340
- }
2341
- }
2342
- }
2343
- };
2344
- }
2345
- );
2346
- export {
2347
- deleteIndex,
2348
- embeddingsIndexDashboard,
2349
- embeddingsIndexReferenceInput,
2350
- getIndexes,
2351
- queryIndex
2352
- };
2353
- //# sourceMappingURL=index.mjs.map