@sanity/sdk 2.2.0 → 2.3.1

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.js CHANGED
@@ -1,4 +1,4 @@
1
- import { createClient } from "@sanity/client";
1
+ import { createClient, CorsOriginError } from "@sanity/client";
2
2
  import { Observable, share, map, distinctUntilChanged, skip, filter, exhaustMap, from, timer, switchMap, takeWhile, firstValueFrom, fromEvent, EMPTY, defer, asapScheduler, combineLatest, of, concatMap, withLatestFrom, concat, throwError, first as first$1, Subject, takeUntil, partition, merge, shareReplay, tap as tap$1, catchError as catchError$1, startWith as startWith$1, pairwise as pairwise$1, groupBy as groupBy$1, mergeMap as mergeMap$1, throttle, race, NEVER, Subscription, retry, debounceTime as debounceTime$1 } from "rxjs";
3
3
  import { devtools } from "zustand/middleware";
4
4
  import { createStore } from "zustand/vanilla";
@@ -10,6 +10,7 @@ import { SanityEncoder } from "@sanity/mutate";
10
10
  import { getPublishedId as getPublishedId$1 } from "@sanity/client/csm";
11
11
  import { jsonMatch, stringifyPath, slicePath, getIndexForKey } from "@sanity/json-match";
12
12
  import { getIndexForKey as getIndexForKey2, getPathDepth, joinPaths, jsonMatch as jsonMatch2, slicePath as slicePath2, stringifyPath as stringifyPath2 } from "@sanity/json-match";
13
+ import { evaluateSync, parse } from "groq-js";
13
14
  import { diffValue } from "@sanity/diff-patch";
14
15
  import { applyPatches, parsePatch } from "@sanity/diff-match-patch";
15
16
  import { isKeySegment, isKeyedObject } from "@sanity/types";
@@ -379,8 +380,14 @@ function getDefaultLocation() {
379
380
  }
380
381
  }
381
382
  function getCleanedUrl(locationUrl) {
382
- const loc = new URL(locationUrl);
383
- return loc.hash = "", loc.searchParams.delete("sid"), loc.searchParams.delete("url"), loc.toString();
383
+ const loc = new URL(locationUrl), rawHash = loc.hash.startsWith("#") ? loc.hash.slice(1) : loc.hash;
384
+ if (rawHash && rawHash.includes("=")) {
385
+ const hashParams = new URLSearchParams(rawHash);
386
+ hashParams.delete("token"), hashParams.delete("withSid");
387
+ const nextHash = hashParams.toString();
388
+ loc.hash = nextHash ? `#${nextHash}` : "";
389
+ }
390
+ return loc.searchParams.delete("sid"), loc.searchParams.delete("url"), loc.toString();
384
391
  }
385
392
  async function checkForCookieAuth(projectId, clientFactory) {
386
393
  if (!projectId) return !1;
@@ -397,31 +404,34 @@ async function checkForCookieAuth(projectId, clientFactory) {
397
404
  return !1;
398
405
  }
399
406
  }
400
- function getStudioTokenFromLocalStorage(storageArea, projectId) {
401
- if (!storageArea || !projectId) return null;
402
- const studioStorageKey = `__studio_auth_token_${projectId}`;
403
- return getTokenFromStorage(storageArea, studioStorageKey) || null;
407
+ function getStudioTokenFromLocalStorage(storageArea, storageKey) {
408
+ return !storageArea || !storageKey ? null : getTokenFromStorage(storageArea, storageKey) || null;
404
409
  }
405
410
  const subscribeToStateAndFetchCurrentUser = ({
406
- state
411
+ state,
412
+ instance
407
413
  }) => {
408
- const { clientFactory, apiHost } = state.get().options;
414
+ const { clientFactory, apiHost } = state.get().options, useProjectHostname = !!instance.config.studioMode?.enabled, projectId = instance.config.projectId;
409
415
  return state.observable.pipe(
410
- map(({ authState }) => authState),
416
+ map(({ authState, options }) => ({ authState, authMethod: options.authMethod })),
411
417
  filter(
412
- (authState) => authState.type === AuthStateType.LOGGED_IN && !authState.currentUser
418
+ (value) => value.authState.type === AuthStateType.LOGGED_IN && !value.authState.currentUser
413
419
  ),
414
- map((authState) => authState.token),
415
- distinctUntilChanged()
420
+ map((value) => ({ token: value.authState.token, authMethod: value.authMethod })),
421
+ distinctUntilChanged(
422
+ (prev, curr) => prev.token === curr.token && prev.authMethod === curr.authMethod
423
+ )
416
424
  ).pipe(
417
425
  map(
418
- (token) => clientFactory({
426
+ ({ token, authMethod }) => clientFactory({
419
427
  apiVersion: DEFAULT_API_VERSION$1,
420
428
  requestTagPrefix: REQUEST_TAG_PREFIX,
421
- token,
429
+ token: authMethod === "cookie" ? void 0 : token,
422
430
  ignoreBrowserTokenWarning: !0,
423
- useProjectHostname: !1,
431
+ useProjectHostname,
424
432
  useCdn: !1,
433
+ ...authMethod === "cookie" ? { withCredentials: !0 } : {},
434
+ ...useProjectHostname && projectId ? { projectId } : {},
425
435
  ...apiHost && { apiHost }
426
436
  })
427
437
  ),
@@ -444,7 +454,7 @@ const subscribeToStateAndFetchCurrentUser = ({
444
454
  const { storageArea, storageKey } = state.get().options;
445
455
  return defer(getStorageEvents).pipe(
446
456
  filter(
447
- (e3) => e3.storageArea === storageArea && e3.key === storageKey
457
+ (e) => e.storageArea === storageArea && e.key === storageKey
448
458
  ),
449
459
  map(() => getTokenFromStorage(storageArea, storageKey)),
450
460
  distinctUntilChanged()
@@ -466,8 +476,8 @@ const authStore = {
466
476
  clientFactory = createClient,
467
477
  initialLocationHref = getDefaultLocation()
468
478
  } = instance.config.auth ?? {};
469
- let storageArea = instance.config.auth?.storageArea;
470
- const storageKey = "__sanity_auth_token";
479
+ let storageArea = instance.config.auth?.storageArea, storageKey = "__sanity_auth_token";
480
+ const studioModeEnabled = instance.config.studioMode?.enabled;
471
481
  let loginDomain = "https://www.sanity.io";
472
482
  try {
473
483
  apiHost && new URL(apiHost).hostname.endsWith(".sanity.work") && (loginDomain = "https://www.sanity.work");
@@ -485,13 +495,15 @@ const authStore = {
485
495
  } catch (err) {
486
496
  console.error("Failed to parse dashboard context from initial location:", err);
487
497
  }
488
- isInDashboard || (storageArea = storageArea ?? getDefaultStorage());
498
+ (!isInDashboard || studioModeEnabled) && (storageArea = storageArea ?? getDefaultStorage());
489
499
  let token, authMethod;
490
- instance.config.studioMode?.enabled ? (token = getStudioTokenFromLocalStorage(storageArea, instance.config.projectId), token ? authMethod = "localstorage" : checkForCookieAuth(instance.config.projectId, clientFactory).then((isCookieAuthEnabled) => {
491
- isCookieAuthEnabled && (authMethod = "cookie");
492
- })) : (token = getTokenFromStorage(storageArea, storageKey), token && (authMethod = "localstorage"));
500
+ if (studioModeEnabled) {
501
+ const studioStorageKey = `__studio_auth_token_${instance.config.projectId ?? ""}`;
502
+ storageKey = studioStorageKey, token = getStudioTokenFromLocalStorage(storageArea, studioStorageKey), token && (authMethod = "localstorage");
503
+ } else
504
+ token = getTokenFromStorage(storageArea, storageKey), token && (authMethod = "localstorage");
493
505
  let authState;
494
- return providedToken ? authState = { type: AuthStateType.LOGGED_IN, token: providedToken, currentUser: null } : getAuthCode(callbackUrl, initialLocationHref) || getTokenFromLocation(initialLocationHref) ? authState = { type: AuthStateType.LOGGING_IN, isExchangingToken: !1 } : token && !isInDashboard ? authState = { type: AuthStateType.LOGGED_IN, token, currentUser: null } : authState = { type: AuthStateType.LOGGED_OUT, isDestroyingSession: !1 }, {
506
+ return providedToken ? authState = { type: AuthStateType.LOGGED_IN, token: providedToken, currentUser: null } : token && studioModeEnabled ? authState = { type: AuthStateType.LOGGED_IN, token: token ?? "", currentUser: null } : getAuthCode(callbackUrl, initialLocationHref) || getTokenFromLocation(initialLocationHref) ? authState = { type: AuthStateType.LOGGING_IN, isExchangingToken: !1 } : token && !isInDashboard && !studioModeEnabled ? authState = { type: AuthStateType.LOGGED_IN, token, currentUser: null } : authState = { type: AuthStateType.LOGGED_OUT, isDestroyingSession: !1 }, {
495
507
  authState,
496
508
  dashboardContext,
497
509
  options: {
@@ -510,7 +522,21 @@ const authStore = {
510
522
  },
511
523
  initialize(context) {
512
524
  const subscriptions = [];
513
- return subscriptions.push(subscribeToStateAndFetchCurrentUser(context)), context.state.get().options?.storageArea && subscriptions.push(subscribeToStorageEventsAndSetToken(context)), tokenRefresherRunning || (tokenRefresherRunning = !0, subscriptions.push(refreshStampedToken(context))), () => {
525
+ subscriptions.push(subscribeToStateAndFetchCurrentUser(context)), context.state.get().options?.storageArea && subscriptions.push(subscribeToStorageEventsAndSetToken(context));
526
+ try {
527
+ const { instance, state } = context, studioModeEnabled = !!instance.config.studioMode?.enabled, token = state.get().authState?.type === AuthStateType.LOGGED_IN ? state.get().authState.token : null;
528
+ if (studioModeEnabled && !token) {
529
+ const projectId = instance.config.projectId, clientFactory = state.get().options.clientFactory;
530
+ checkForCookieAuth(projectId, clientFactory).then((isCookieAuthEnabled) => {
531
+ isCookieAuthEnabled && state.set("enableCookieAuth", (prev) => ({
532
+ options: { ...prev.options, authMethod: "cookie" },
533
+ authState: prev.authState.type === AuthStateType.LOGGED_IN ? prev.authState : { type: AuthStateType.LOGGED_IN, token: "", currentUser: null }
534
+ }));
535
+ });
536
+ }
537
+ } catch {
538
+ }
539
+ return tokenRefresherRunning || (tokenRefresherRunning = !0, subscriptions.push(refreshStampedToken(context))), () => {
514
540
  for (const subscription of subscriptions)
515
541
  subscription.unsubscribe();
516
542
  };
@@ -651,8 +677,8 @@ function createFetcherStore({
651
677
  state
652
678
  }) => state.observable.pipe(
653
679
  // Map the state to an array of [serialized, entry] pairs.
654
- switchMap$1((s2) => {
655
- const entries = Object.entries(s2.stateByParams);
680
+ switchMap$1((s) => {
681
+ const entries = Object.entries(s.stateByParams);
656
682
  return entries.length > 0 ? from(entries) : EMPTY;
657
683
  }),
658
684
  // Group by the serialized key.
@@ -760,7 +786,7 @@ function createFetcherStore({
760
786
  })
761
787
  ), resolveState = bindActionGlobally(
762
788
  store,
763
- ({ instance }, ...params) => firstValueFrom(getState(instance, ...params).observable.pipe(first((i2) => i2 !== void 0)))
789
+ ({ instance }, ...params) => firstValueFrom(getState(instance, ...params).observable.pipe(first((i) => i !== void 0)))
764
790
  );
765
791
  return { getState, resolveState };
766
792
  }
@@ -1067,8 +1093,8 @@ function deleteDocument(doc) {
1067
1093
  };
1068
1094
  }
1069
1095
  function convertSanityMutatePatch(sanityPatchMutation) {
1070
- return SanityEncoder.encode(sanityPatchMutation).map((i2) => {
1071
- const copy = { ...i2.patch };
1096
+ return SanityEncoder.encode(sanityPatchMutation).map((i) => {
1097
+ const copy = { ...i.patch };
1072
1098
  return "id" in copy && delete copy.id, copy;
1073
1099
  });
1074
1100
  }
@@ -1230,8 +1256,8 @@ function dec(input, pathExpressionValues) {
1230
1256
  }
1231
1257
  function diffMatchPatch(input, pathExpressionValues) {
1232
1258
  const result = Object.entries(pathExpressionValues).flatMap(
1233
- ([pathExpression, dmp]) => Array.from(jsonMatch(input, pathExpression)).map((m2) => ({ ...m2, dmp }))
1234
- ).filter((i2) => i2.value !== void 0).map(({ path, value, dmp }) => {
1259
+ ([pathExpression, dmp]) => Array.from(jsonMatch(input, pathExpression)).map((m) => ({ ...m, dmp }))
1260
+ ).filter((i) => i.value !== void 0).map(({ path, value, dmp }) => {
1235
1261
  if (typeof value != "string")
1236
1262
  throw new Error(
1237
1263
  `Can't diff-match-patch \`${JSON.stringify(value)}\` at path \`${stringifyPath(path)}\`, because it is not a string`
@@ -1274,7 +1300,7 @@ function setDeep(input, path, value) {
1274
1300
  if (Array.isArray(input)) {
1275
1301
  let index;
1276
1302
  return isKeySegment(currentSegment) ? index = getIndexForKey(input, currentSegment._key) ?? input.length : typeof currentSegment == "number" && (index = currentSegment < 0 ? input.length + currentSegment : currentSegment), index === void 0 ? input : index in input ? input.map(
1277
- (nestedInput, i2) => i2 === index ? setDeep(nestedInput, restOfPath, value) : nestedInput
1303
+ (nestedInput, i) => i === index ? setDeep(nestedInput, restOfPath, value) : nestedInput
1278
1304
  ) : [
1279
1305
  ...input,
1280
1306
  ...Array.from({ length: index - input.length }).fill(null),
@@ -1468,7 +1494,7 @@ function sortListenerEvents(options) {
1468
1494
  let baseRevision = state.base.revision, progress = !0;
1469
1495
  for (; progress; ) {
1470
1496
  progress = !1;
1471
- const idx = buffer.findIndex((e3) => e3.previousRev === baseRevision);
1497
+ const idx = buffer.findIndex((e) => e.previousRev === baseRevision);
1472
1498
  if (idx !== -1) {
1473
1499
  const [next] = buffer.splice(idx, 1);
1474
1500
  emitEvents.push(next), baseRevision = next.transition === "disappear" ? void 0 : next.resultRev, progress = !0;
@@ -1513,13 +1539,13 @@ function sortListenerEvents(options) {
1513
1539
  const listen$1 = ({ state }, documentId) => {
1514
1540
  const { sharedListener, fetchDocument } = state.get();
1515
1541
  return sharedListener.events.pipe(
1516
- concatMap((e3) => e3.type === "welcome" ? fetchDocument(documentId).pipe(
1542
+ concatMap((e) => e.type === "welcome" ? fetchDocument(documentId).pipe(
1517
1543
  map((document2) => ({ type: "sync", document: document2 }))
1518
- ) : e3.type === "mutation" && e3.documentId === documentId ? of(e3) : EMPTY),
1544
+ ) : e.type === "mutation" && e.documentId === documentId ? of(e) : EMPTY),
1519
1545
  sortListenerEvents(),
1520
1546
  withLatestFrom(
1521
1547
  state.observable.pipe(
1522
- map((s2) => s2.documentStates[documentId]),
1548
+ map((s) => s.documentStates[documentId]),
1523
1549
  filter(Boolean),
1524
1550
  distinctUntilChanged()
1525
1551
  )
@@ -1552,1665 +1578,6 @@ const listen$1 = ({ state }, documentId) => {
1552
1578
  })
1553
1579
  );
1554
1580
  };
1555
- class e {
1556
- pattern;
1557
- patternRe;
1558
- constructor(e3) {
1559
- this.pattern = e3, this.patternRe = function(e4) {
1560
- const t2 = [];
1561
- for (const r2 of e4.split(".")) r2 === "*" ? t2.push("[^.]+") : r2 === "**" ? t2.push(".*") : t2.push(r2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
1562
- return new RegExp(`^${t2.join(".")}$`);
1563
- }(e3);
1564
- }
1565
- matches(e3) {
1566
- return this.patternRe.test(e3);
1567
- }
1568
- toJSON() {
1569
- return this.pattern;
1570
- }
1571
- }
1572
- class t {
1573
- type = "stream";
1574
- generator;
1575
- ticker;
1576
- isDone;
1577
- data;
1578
- constructor(e3) {
1579
- this.generator = e3, this.ticker = null, this.isDone = !1, this.data = [];
1580
- }
1581
- isArray() {
1582
- return !0;
1583
- }
1584
- async get() {
1585
- const e3 = [];
1586
- for await (const t2 of this) e3.push(await t2.get());
1587
- return e3;
1588
- }
1589
- async first(e3 = () => !0) {
1590
- for await (const t2 of this) if (e3(t2)) return t2;
1591
- }
1592
- async reduce(e3, t2) {
1593
- let r2 = t2;
1594
- for await (const t3 of this) r2 = await e3(r2, t3);
1595
- return r2;
1596
- }
1597
- async *[Symbol.asyncIterator]() {
1598
- let e3 = 0;
1599
- for (; ; ) {
1600
- for (; e3 < this.data.length; e3++) yield this.data[e3];
1601
- if (this.isDone) return;
1602
- await this._nextTick();
1603
- }
1604
- }
1605
- _nextTick() {
1606
- if (this.ticker) return this.ticker;
1607
- let e3;
1608
- const t2 = () => {
1609
- this.ticker = new Promise((t3) => {
1610
- e3 = t3;
1611
- });
1612
- }, r2 = () => {
1613
- e3(), t2();
1614
- };
1615
- return t2(), (async () => {
1616
- for await (const e4 of this.generator()) this.data.push(e4), r2();
1617
- this.isDone = !0, r2();
1618
- })(), this.ticker;
1619
- }
1620
- }
1621
- const r = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|([-+]\d{2}:\d{2}))$/;
1622
- function n(e3, t2) {
1623
- let r2 = e3.toString();
1624
- for (; r2.length < t2; ) r2 = `0${r2}`;
1625
- return r2;
1626
- }
1627
- class o {
1628
- data;
1629
- type;
1630
- constructor(e3, t2) {
1631
- this.data = e3, this.type = t2;
1632
- }
1633
- isArray() {
1634
- return this.type === "array";
1635
- }
1636
- get() {
1637
- return this.data;
1638
- }
1639
- first(e3 = () => !0) {
1640
- if (!this.isArray()) throw new Error("`first` can only be called on array `StaticValue`s");
1641
- const t2 = this.get();
1642
- for (const r2 of t2) {
1643
- const t3 = f(r2, "sync");
1644
- if (e3(t3)) return t3;
1645
- }
1646
- }
1647
- reduce(e3, t2) {
1648
- if (!this.isArray()) throw new Error("`reduce` can only be called on array `StaticValue`s");
1649
- const r2 = this.get();
1650
- let n2 = t2;
1651
- for (const t3 of r2)
1652
- n2 = e3(n2, f(t3, "sync"));
1653
- return n2;
1654
- }
1655
- [Symbol.asyncIterator]() {
1656
- if (Array.isArray(this.data)) return function* (e3) {
1657
- for (const t2 of e3) yield f(t2, "async");
1658
- }(this.data);
1659
- throw new Error(`Cannot iterate over: ${this.type}`);
1660
- }
1661
- }
1662
- const i = new o(null, "null"), s = new o(!0, "boolean"), a = new o(!1, "boolean");
1663
- class c {
1664
- date;
1665
- constructor(e3) {
1666
- this.date = e3;
1667
- }
1668
- static parseToValue(e3) {
1669
- const t2 = function(e4) {
1670
- return r.test(e4) ? new Date(e4) : null;
1671
- }(e3);
1672
- return t2 ? new o(new c(t2), "datetime") : i;
1673
- }
1674
- equals(e3) {
1675
- return this.date.getTime() == e3.date.getTime();
1676
- }
1677
- add(e3) {
1678
- const t2 = new Date(this.date.getTime());
1679
- return t2.setTime(t2.getTime() + 1e3 * e3), new c(t2);
1680
- }
1681
- difference(e3) {
1682
- return (this.date.getTime() - e3.date.getTime()) / 1e3;
1683
- }
1684
- compareTo(e3) {
1685
- return this.date.getTime() - e3.date.getTime();
1686
- }
1687
- toString() {
1688
- return function(e3) {
1689
- const t2 = n(e3.getUTCFullYear(), 4), r2 = n(e3.getUTCMonth() + 1, 2), o2 = n(e3.getUTCDate(), 2), i2 = n(e3.getUTCHours(), 2), s2 = n(e3.getUTCMinutes(), 2), a2 = n(e3.getUTCSeconds(), 2);
1690
- let c2 = "";
1691
- const u2 = e3.getMilliseconds();
1692
- return u2 != 0 && (c2 = `.${n(u2, 3)}`), `${t2}-${r2}-${o2}T${i2}:${s2}:${a2}${c2}Z`;
1693
- }(this.date);
1694
- }
1695
- toJSON() {
1696
- return this.toString();
1697
- }
1698
- }
1699
- function u(e3) {
1700
- return Number.isFinite(e3) ? new o(e3, "number") : i;
1701
- }
1702
- function p(e3) {
1703
- return new o(e3, "string");
1704
- }
1705
- function l(e3) {
1706
- return new o(e3, "datetime");
1707
- }
1708
- function f(e3, r2) {
1709
- return (n2 = e3) && typeof n2.next == "function" && r2 !== "sync" ? new t(async function* () {
1710
- for await (const t2 of e3) yield f(t2, "async");
1711
- }) : e3 == null ? i : new o(e3, y(e3));
1712
- var n2;
1713
- }
1714
- function y(t2) {
1715
- return t2 === null || typeof t2 > "u" ? "null" : Array.isArray(t2) ? "array" : t2 instanceof e ? "path" : t2 instanceof c ? "datetime" : typeof t2;
1716
- }
1717
- const d = (e3) => typeof e3 == "object" && !!e3 && "then" in e3 && typeof e3.then == "function";
1718
- function h(e3) {
1719
- const t2 = e3(), r2 = t2.next();
1720
- if (r2.done) return r2.value;
1721
- function n2(e4) {
1722
- const r3 = t2.next(e4);
1723
- if (r3.done) return r3.value;
1724
- const o3 = r3.value;
1725
- return o3 && d(o3) ? o3.then(n2) : n2(o3);
1726
- }
1727
- const o2 = r2.value;
1728
- return o2 && d(o2) ? o2.then(n2) : n2(o2);
1729
- }
1730
- function m(e3, t2) {
1731
- return e3.type === "string" && t2.type === "string" || e3.type === "boolean" && t2.type === "boolean" || e3.type === "null" && t2.type === "null" || e3.type === "number" && t2.type === "number" ? e3.data === t2.data : e3.type === "datetime" && t2.type === "datetime" && e3.data.equals(t2.data);
1732
- }
1733
- const b = /([^!@#$%^&*(),\\/?";:{}|[\]+<>\s-])+/g, g = /([^!@#$%^&(),\\/?";:{}|[\]+<>\s-])+/g, w = /(\b\.+|\.+\b)/g;
1734
- function k(e3) {
1735
- return e3.replace(w, "").match(b) || [];
1736
- }
1737
- function v(e3) {
1738
- return x(e3).map((e4) => (t2) => t2.some((t3) => e4.test(t3)));
1739
- }
1740
- function x(e3) {
1741
- return (e3.replace(w, "").match(g) || []).map((e4) => new RegExp(`^${e4.slice(0, 1024).replace(/\*/g, ".*")}$`, "i"));
1742
- }
1743
- const _ = { datetime: 1, number: 2, string: 3, boolean: 4 };
1744
- function A(e3, t2) {
1745
- const r2 = y(e3);
1746
- if (r2 !== y(t2)) return null;
1747
- switch (r2) {
1748
- case "number":
1749
- case "boolean":
1750
- return e3 - t2;
1751
- case "string":
1752
- return e3 < t2 ? -1 : e3 > t2 ? 1 : 0;
1753
- case "datetime":
1754
- return e3.compareTo(t2);
1755
- default:
1756
- return null;
1757
- }
1758
- }
1759
- function E(e3, t2) {
1760
- const r2 = y(e3), n2 = y(t2), o2 = _[r2] || 100, i2 = _[n2] || 100;
1761
- if (o2 !== i2) return o2 - i2;
1762
- let s2 = A(e3, t2);
1763
- return s2 === null && (s2 = 0), s2;
1764
- }
1765
- const j = { "==": function(e3, t2) {
1766
- return m(e3, t2) ? s : a;
1767
- }, "!=": function(e3, t2) {
1768
- return m(e3, t2) ? a : s;
1769
- }, ">": function(e3, t2) {
1770
- if (e3.type === "stream" || t2.type === "stream") return i;
1771
- const r2 = A(e3.data, t2.data);
1772
- return r2 === null ? i : r2 > 0 ? s : a;
1773
- }, ">=": function(e3, t2) {
1774
- if (e3.type === "stream" || t2.type === "stream") return i;
1775
- const r2 = A(e3.data, t2.data);
1776
- return r2 === null ? i : r2 >= 0 ? s : a;
1777
- }, "<": function(e3, t2) {
1778
- if (e3.type === "stream" || t2.type === "stream") return i;
1779
- const r2 = A(e3.data, t2.data);
1780
- return r2 === null ? i : r2 < 0 ? s : a;
1781
- }, "<=": function(e3, t2) {
1782
- if (e3.type === "stream" || t2.type === "stream") return i;
1783
- const r2 = A(e3.data, t2.data);
1784
- return r2 === null ? i : r2 <= 0 ? s : a;
1785
- }, in: function(e3, t2) {
1786
- return h(function* () {
1787
- return t2.type === "path" ? e3.type !== "string" ? i : t2.data.matches(e3.data) ? s : a : t2.isArray() ? (yield t2.first((t3) => m(e3, t3))) ? s : a : i;
1788
- });
1789
- }, match: function(e3, t2) {
1790
- return h(function* () {
1791
- const r2 = yield e3.get(), n2 = yield t2.get();
1792
- let o2, i2 = [];
1793
- return Array.isArray(r2) ? i2 = r2.filter((e4) => typeof e4 == "string") : typeof r2 == "string" && (i2 = [r2]), Array.isArray(n2) ? o2 = n2.filter((e4) => typeof e4 == "string") : typeof n2 == "string" && (o2 = [n2]), o2?.length && function(e4, t3) {
1794
- return e4.length !== 0 && t3.length !== 0 && t3.every((t4) => t4(e4));
1795
- }(i2.flatMap(k), o2.flatMap(v)) ? s : a;
1796
- });
1797
- }, "+": function(e3, r2, n2) {
1798
- return e3.type === "datetime" && r2.type === "number" ? l(e3.data.add(r2.data)) : e3.type === "number" && r2.type === "number" ? u(e3.data + r2.data) : e3.type === "string" && r2.type === "string" ? p(e3.data + r2.data) : e3.type === "object" && r2.type === "object" ? f({ ...e3.data, ...r2.data }, n2) : e3.type === "array" && r2.type === "array" ? f(e3.data.concat(r2.data), n2) : e3.isArray() && r2.isArray() ? n2 === "sync" ? h(function* () {
1799
- const t2 = [...yield e3.get(), ...yield r2.get()];
1800
- return new o(t2, "array");
1801
- }) : new t(async function* () {
1802
- for await (const t2 of e3) yield t2;
1803
- for await (const e4 of r2) yield e4;
1804
- }) : i;
1805
- }, "-": function(e3, t2) {
1806
- return e3.type === "datetime" && t2.type === "number" ? l(e3.data.add(-t2.data)) : e3.type === "datetime" && t2.type === "datetime" ? u(e3.data.difference(t2.data)) : e3.type === "number" && t2.type === "number" ? u(e3.data - t2.data) : i;
1807
- }, "*": S((e3, t2) => e3 * t2), "/": S((e3, t2) => e3 / t2), "%": S((e3, t2) => e3 % t2), "**": S((e3, t2) => Math.pow(e3, t2)) };
1808
- function S(e3) {
1809
- return function(t2, r2) {
1810
- return t2.type === "number" && r2.type === "number" ? u(e3(t2.data, r2.data)) : i;
1811
- };
1812
- }
1813
- let O = class e2 {
1814
- params;
1815
- source;
1816
- value;
1817
- parent;
1818
- context;
1819
- isHidden = !1;
1820
- constructor(e3, t2, r2, n2, o2) {
1821
- this.params = e3, this.source = t2, this.value = r2, this.context = n2, this.parent = o2;
1822
- }
1823
- createNested(t2) {
1824
- return this.isHidden ? new e2(this.params, this.source, t2, this.context, this.parent) : new e2(this.params, this.source, t2, this.context, this);
1825
- }
1826
- createHidden(e3) {
1827
- const t2 = this.createNested(e3);
1828
- return t2.isHidden = !0, t2;
1829
- }
1830
- };
1831
- function I(e3, t2, r2) {
1832
- return (0, $[e3.type])(e3, t2, r2);
1833
- }
1834
- const $ = { This: (e3, t2) => t2.value, Selector() {
1835
- throw new Error("Selectors can not be evaluated");
1836
- }, Everything: (e3, t2) => t2.source, Parameter: ({ name: e3 }, t2, r2) => f(t2.params[e3], r2), Context({ key: e3 }, t2) {
1837
- if (e3 === "before" || e3 === "after") return t2.context[e3] || i;
1838
- throw new Error(`unknown context key: ${e3}`);
1839
- }, Parent({ n: e3 }, t2) {
1840
- let r2 = t2;
1841
- for (let t3 = 0; t3 < e3; t3++) {
1842
- if (!r2.parent) return i;
1843
- r2 = r2.parent;
1844
- }
1845
- return r2.value;
1846
- }, OpCall: ({ op: e3, left: t2, right: r2 }, n2, o2) => h(function* () {
1847
- const i2 = j[e3];
1848
- if (!i2) throw new Error(`Unknown operator: ${e3}`);
1849
- const s2 = yield I(t2, n2, o2), a2 = yield I(r2, n2, o2);
1850
- return yield i2(s2, a2, o2);
1851
- }), Select: ({ alternatives: e3, fallback: t2 }, r2, n2) => h(function* () {
1852
- for (const t3 of e3) {
1853
- const e4 = yield I(t3.condition, r2, n2);
1854
- if (e4.type === "boolean" && e4.data === !0) return yield I(t3.value, r2, n2);
1855
- }
1856
- return t2 ? yield I(t2, r2, n2) : i;
1857
- }), InRange: ({ base: e3, left: t2, right: r2, isInclusive: n2 }, o2, c2) => h(function* () {
1858
- const u2 = yield I(e3, o2, c2), p2 = yield I(t2, o2, c2), l2 = yield I(r2, o2, c2), f2 = A(yield u2.get(), yield p2.get());
1859
- if (f2 === null) return i;
1860
- const y2 = A(yield u2.get(), yield l2.get());
1861
- return y2 === null ? i : n2 ? f2 >= 0 && y2 <= 0 ? s : a : f2 >= 0 && y2 < 0 ? s : a;
1862
- }), Filter: ({ base: e3, expr: r2 }, n2, s2) => h(function* () {
1863
- const a2 = yield I(e3, n2, s2);
1864
- if (!a2.isArray()) return i;
1865
- if (s2 === "sync") {
1866
- const e4 = yield a2.get(), t2 = [];
1867
- for (const o2 of e4) {
1868
- const e5 = f(o2, s2), i2 = n2.createNested(e5), a3 = yield I(r2, i2, s2);
1869
- a3.type === "boolean" && a3.data === !0 && t2.push(o2);
1870
- }
1871
- return new o(t2, "array");
1872
- }
1873
- return new t(async function* () {
1874
- for await (const e4 of a2) {
1875
- const t2 = n2.createNested(e4), o2 = await I(r2, t2, s2);
1876
- o2.type === "boolean" && o2.data === !0 && (yield e4);
1877
- }
1878
- });
1879
- }), Projection: ({ base: e3, expr: t2 }, r2, n2) => h(function* () {
1880
- const o2 = yield I(e3, r2, n2);
1881
- if (o2.type !== "object") return i;
1882
- const s2 = r2.createNested(o2);
1883
- return yield I(t2, s2, n2);
1884
- }), FuncCall: ({ func: e3, args: t2 }, r2, n2) => e3(t2, r2, n2), PipeFuncCall: ({ func: e3, base: t2, args: r2 }, n2, o2) => h(function* () {
1885
- const i2 = yield I(t2, n2, o2);
1886
- return yield e3(i2, r2, n2, o2);
1887
- }), AccessAttribute: ({ base: e3, name: t2 }, r2, n2) => h(function* () {
1888
- let o2 = r2.value;
1889
- return e3 && (o2 = yield I(e3, r2, n2)), o2.type === "object" && o2.data.hasOwnProperty(t2) ? f(o2.data[t2], n2) : i;
1890
- }), AccessElement: ({ base: e3, index: t2 }, r2, n2) => h(function* () {
1891
- const o2 = yield I(e3, r2, n2);
1892
- if (!o2.isArray()) return i;
1893
- const s2 = yield o2.get();
1894
- return f(s2[t2 < 0 ? t2 + s2.length : t2], n2);
1895
- }), Slice: ({ base: e3, left: t2, right: r2, isInclusive: n2 }, o2, s2) => h(function* () {
1896
- const a2 = yield I(e3, o2, s2);
1897
- if (!a2.isArray()) return i;
1898
- const c2 = yield a2.get();
1899
- let u2 = t2, p2 = r2;
1900
- return u2 < 0 && (u2 = c2.length + u2), p2 < 0 && (p2 = c2.length + p2), n2 && p2++, u2 < 0 && (u2 = 0), p2 < 0 && (p2 = 0), f(c2.slice(u2, p2), s2);
1901
- }), Deref: ({ base: e3 }, t2, r2) => h(function* () {
1902
- const n2 = yield I(e3, t2, r2);
1903
- if (!t2.source.isArray() || n2.type !== "object") return i;
1904
- const o2 = n2.data._ref;
1905
- return typeof o2 != "string" ? i : t2.context.dereference ? f(yield t2.context.dereference({ _ref: o2 }), r2) : (yield t2.source.first((e4) => e4.type === "object" && o2 == e4.data._id)) || i;
1906
- }), Value: ({ value: e3 }, t2, r2) => f(e3, r2), Group: ({ base: e3 }, t2, r2) => I(e3, t2, r2), Object: ({ attributes: e3 }, t2, r2) => h(function* () {
1907
- const n2 = {};
1908
- for (const o2 of e3) {
1909
- const e4 = o2.type;
1910
- switch (o2.type) {
1911
- case "ObjectAttributeValue": {
1912
- const e5 = yield I(o2.value, t2, r2);
1913
- n2[o2.name] = yield e5.get();
1914
- break;
1915
- }
1916
- case "ObjectConditionalSplat": {
1917
- const e5 = yield I(o2.condition, t2, r2);
1918
- if (e5.type !== "boolean" || e5.data === !1) continue;
1919
- const i2 = yield I(o2.value, t2, r2);
1920
- i2.type === "object" && Object.assign(n2, i2.data);
1921
- break;
1922
- }
1923
- case "ObjectSplat": {
1924
- const e5 = yield I(o2.value, t2, r2);
1925
- e5.type === "object" && Object.assign(n2, e5.data);
1926
- break;
1927
- }
1928
- default:
1929
- throw new Error(`Unknown node type: ${e4}`);
1930
- }
1931
- }
1932
- return f(n2, r2);
1933
- }), Array: ({ elements: e3 }, r2, n2) => h(function* () {
1934
- if (n2 === "sync") {
1935
- const t2 = [];
1936
- for (const o2 of e3) {
1937
- const e4 = yield I(o2.value, r2, n2);
1938
- if (o2.isSplat) {
1939
- if (e4.isArray()) {
1940
- const r3 = yield e4.get();
1941
- t2.push(...r3);
1942
- }
1943
- } else t2.push(yield e4.get());
1944
- }
1945
- return new o(t2, "array");
1946
- }
1947
- return new t(async function* () {
1948
- for (const t2 of e3) {
1949
- const e4 = await I(t2.value, r2, n2);
1950
- if (t2.isSplat) {
1951
- if (e4.isArray()) for await (const t3 of e4) yield t3;
1952
- } else yield e4;
1953
- }
1954
- });
1955
- }), Tuple() {
1956
- throw new Error("tuples can not be evaluated");
1957
- }, Or: ({ left: e3, right: t2 }, r2, n2) => h(function* () {
1958
- const o2 = yield I(e3, r2, n2), c2 = yield I(t2, r2, n2);
1959
- return o2.type === "boolean" && o2.data === !0 || c2.type === "boolean" && c2.data === !0 ? s : o2.type !== "boolean" || c2.type !== "boolean" ? i : a;
1960
- }), And: ({ left: e3, right: t2 }, r2, n2) => h(function* () {
1961
- const o2 = yield I(e3, r2, n2), c2 = yield I(t2, r2, n2);
1962
- return o2.type === "boolean" && o2.data === !1 || c2.type === "boolean" && c2.data === !1 ? a : o2.type !== "boolean" || c2.type !== "boolean" ? i : s;
1963
- }), Not: ({ base: e3 }, t2, r2) => h(function* () {
1964
- const n2 = yield I(e3, t2, r2);
1965
- return n2.type !== "boolean" ? i : n2.data ? a : s;
1966
- }), Neg: ({ base: e3 }, t2, r2) => h(function* () {
1967
- const n2 = yield I(e3, t2, r2);
1968
- return n2.type !== "number" ? i : u(-n2.data);
1969
- }), Pos: ({ base: e3 }, t2, r2) => h(function* () {
1970
- const n2 = yield I(e3, t2, r2);
1971
- return n2.type !== "number" ? i : u(n2.data);
1972
- }), Asc: () => i, Desc: () => i, ArrayCoerce: ({ base: e3 }, t2, r2) => h(function* () {
1973
- const n2 = yield I(e3, t2, r2);
1974
- return n2.isArray() ? n2 : i;
1975
- }), Map: ({ base: e3, expr: r2 }, n2, s2) => h(function* () {
1976
- const a2 = yield I(e3, n2, s2);
1977
- if (!a2.isArray()) return i;
1978
- if (s2 === "sync") {
1979
- const e4 = yield a2.get(), t2 = [];
1980
- for (const o2 of e4) {
1981
- const e5 = f(o2, "sync"), i2 = n2.createHidden(e5), a3 = yield I(r2, i2, s2);
1982
- t2.push(yield a3.get());
1983
- }
1984
- return new o(t2, "array");
1985
- }
1986
- return new t(async function* () {
1987
- for await (const e4 of a2) {
1988
- const t2 = n2.createHidden(e4);
1989
- yield await I(r2, t2, s2);
1990
- }
1991
- });
1992
- }), FlatMap: ({ base: e3, expr: r2 }, n2, s2) => h(function* () {
1993
- const a2 = yield I(e3, n2, s2);
1994
- if (!a2.isArray()) return i;
1995
- if (s2 === "sync") {
1996
- const e4 = yield a2.get(), t2 = [];
1997
- for (const o2 of e4) {
1998
- const e5 = f(o2, "sync"), i2 = n2.createHidden(e5), a3 = yield I(r2, i2, s2);
1999
- if (a3.isArray()) {
2000
- const e6 = yield a3.get();
2001
- t2.push(...e6);
2002
- } else {
2003
- const e6 = yield a3.get();
2004
- t2.push(e6);
2005
- }
2006
- }
2007
- return new o(t2, "array");
2008
- }
2009
- return new t(async function* () {
2010
- for await (const e4 of a2) {
2011
- const t2 = n2.createHidden(e4), o2 = await I(r2, t2, s2);
2012
- if (o2.isArray()) for await (const e5 of o2) yield e5;
2013
- else yield o2;
2014
- }
2015
- });
2016
- }) };
2017
- function C(e3, t2 = {}) {
2018
- const r2 = f(t2.root, "sync"), n2 = f(t2.dataset, "sync"), o2 = { ...t2.params }, i2 = new O(o2, n2, r2, function(e4 = {}, t3) {
2019
- return { timestamp: e4.timestamp || /* @__PURE__ */ new Date(), identity: e4.identity === void 0 ? "me" : e4.identity, sanity: e4.sanity, after: e4.after ? f(e4.after, t3) : null, before: e4.before ? f(e4.before, t3) : null, dereference: e4.dereference };
2020
- }(t2, "sync"), null), s2 = I(e3, i2, "sync");
2021
- if (d(s2)) throw new Error("Unexpected promise when evaluating. This expression may not support evaluateSync.");
2022
- return s2;
2023
- }
2024
- function M(e3) {
2025
- switch (e3.type) {
2026
- case "Group":
2027
- return M(e3.base);
2028
- case "Value":
2029
- case "Parameter":
2030
- return !0;
2031
- case "Pos":
2032
- case "Neg":
2033
- return M(e3.base);
2034
- case "OpCall":
2035
- switch (e3.op) {
2036
- case "+":
2037
- case "-":
2038
- case "*":
2039
- case "/":
2040
- case "%":
2041
- case "**":
2042
- return M(e3.left) && M(e3.right);
2043
- default:
2044
- return !1;
2045
- }
2046
- default:
2047
- return !1;
2048
- }
2049
- }
2050
- const T = new O({}, i, i, { timestamp: /* @__PURE__ */ new Date(0), identity: "me", before: null, after: null }, null);
2051
- function P(e3) {
2052
- return M(e3) ? function(e4) {
2053
- const t2 = I(e4, T, "sync");
2054
- if (d(t2)) throw new Error("BUG: constant evaluate should never return a promise");
2055
- return t2;
2056
- }(e3) : null;
2057
- }
2058
- function N(e3, t2) {
2059
- return h(function* () {
2060
- if (e3.type === "object") return V(e3.data);
2061
- if (e3.isArray()) {
2062
- const r2 = yield U(e3, t2);
2063
- if (r2.length > 0) return r2.join(`
2064
-
2065
- `);
2066
- }
2067
- return null;
2068
- });
2069
- }
2070
- function U(e3, t2) {
2071
- return h(function* () {
2072
- const r2 = [], n2 = yield e3.get();
2073
- for (const e4 of n2) {
2074
- const n3 = f(e4, t2);
2075
- if (n3.type === "object") {
2076
- const e5 = V(n3.data);
2077
- e5 !== null && r2.push(e5);
2078
- } else if (n3.isArray()) {
2079
- const e5 = yield U(n3, t2);
2080
- r2.push(...e5);
2081
- }
2082
- }
2083
- return r2;
2084
- });
2085
- }
2086
- function V(e3) {
2087
- if (typeof e3._type != "string") return null;
2088
- const t2 = e3.children;
2089
- if (!Array.isArray(t2)) return null;
2090
- let r2 = "";
2091
- for (const e4 of t2) e4 && typeof e4 == "object" && typeof e4._type == "string" && e4._type === "span" && typeof e4.text == "string" && (r2 += e4.text);
2092
- return r2;
2093
- }
2094
- const D = 1.2;
2095
- function F(e3, t2, r2) {
2096
- return h(function* () {
2097
- if (e3.type === "OpCall" && e3.op === "match")
2098
- return function(e4, t3) {
2099
- return h(function* () {
2100
- const r3 = yield e4.get(), n2 = yield t3.get();
2101
- let o2, i2 = [];
2102
- if (Array.isArray(r3) ? i2 = r3.filter((e5) => typeof e5 == "string") : typeof r3 == "string" && (i2 = [r3]), Array.isArray(n2) ? o2 = n2.filter((e5) => typeof e5 == "string") : typeof n2 == "string" && (o2 = [n2]), !o2?.length) return 0;
2103
- const s2 = i2.flatMap(k), a2 = o2.flatMap(x);
2104
- if (s2.length === 0 || a2.length === 0) return 0;
2105
- let c2 = 0;
2106
- for (const e5 of a2) {
2107
- const t4 = s2.reduce((t5, r4) => t5 + (e5.test(r4) ? 1 : 0), 0);
2108
- c2 += 2.2 * t4 / (t4 + D);
2109
- }
2110
- return c2;
2111
- });
2112
- }(yield I(e3.left, t2, r2), yield I(e3.right, t2, r2));
2113
- if (e3.type === "FuncCall" && e3.name === "boost") {
2114
- const n2 = yield F(e3.args[0], t2, r2), o2 = yield I(e3.args[1], t2, r2);
2115
- return o2.type === "number" && n2 > 0 ? n2 + o2.data : 0;
2116
- }
2117
- switch (e3.type) {
2118
- case "Or":
2119
- return (yield F(e3.left, t2, r2)) + (yield F(e3.right, t2, r2));
2120
- case "And": {
2121
- const n2 = yield F(e3.left, t2, r2), o2 = yield F(e3.right, t2, r2);
2122
- return n2 === 0 || o2 === 0 ? 0 : n2 + o2;
2123
- }
2124
- default: {
2125
- const n2 = yield I(e3, t2, r2);
2126
- return n2.type === "boolean" && n2.data === !0 ? 1 : 0;
2127
- }
2128
- }
2129
- });
2130
- }
2131
- function R(e3, t2) {
2132
- switch (y(e3)) {
2133
- case "array":
2134
- for (const r2 of e3) if (R(r2, t2)) return !0;
2135
- break;
2136
- case "object":
2137
- if (e3._ref) return t2.has(e3._ref);
2138
- for (const r2 of Object.values(e3)) if (R(r2, t2)) return !0;
2139
- }
2140
- return !1;
2141
- }
2142
- const q = { anywhere: function() {
2143
- throw new Error("not implemented");
2144
- } };
2145
- q.anywhere.arity = 1, q.coalesce = function(e3, t2, r2) {
2146
- return h(function* () {
2147
- for (const n2 of e3) {
2148
- const e4 = yield I(n2, t2, r2);
2149
- if (e4.type !== "null") return e4;
2150
- }
2151
- return i;
2152
- });
2153
- }, q.count = function(e3, t2, r2) {
2154
- return h(function* () {
2155
- const n2 = yield I(e3[0], t2, r2);
2156
- return n2.isArray() ? u(yield n2.reduce((e4) => e4 + 1, 0)) : i;
2157
- });
2158
- }, q.count.arity = 1, q.dateTime = function(e3, t2, r2) {
2159
- return h(function* () {
2160
- const n2 = yield I(e3[0], t2, r2);
2161
- return n2.type === "datetime" ? n2 : n2.type !== "string" ? i : c.parseToValue(n2.data);
2162
- });
2163
- }, q.dateTime.arity = 1, q.defined = function(e3, t2, r2) {
2164
- return h(function* () {
2165
- return (yield I(e3[0], t2, r2)).type === "null" ? a : s;
2166
- });
2167
- }, q.defined.arity = 1, q.identity = function(e3, t2) {
2168
- return p(t2.context.identity);
2169
- }, q.identity.arity = 0, q.length = function(e3, t2, r2) {
2170
- return h(function* () {
2171
- const n2 = yield I(e3[0], t2, r2);
2172
- return n2.type === "string" ? u(function(e4) {
2173
- let t3 = 0;
2174
- for (let r3 = 0; r3 < e4.length; r3++) {
2175
- const n3 = e4.charCodeAt(r3);
2176
- n3 >= 55296 && n3 <= 56319 || t3++;
2177
- }
2178
- return t3;
2179
- }(n2.data)) : n2.isArray() ? u(yield n2.reduce((e4) => e4 + 1, 0)) : i;
2180
- });
2181
- }, q.length.arity = 1, q.path = function(t2, r2, n2) {
2182
- return h(function* () {
2183
- const s2 = yield I(t2[0], r2, n2);
2184
- return s2.type !== "string" ? i : (a2 = new e(s2.data), new o(a2, "path"));
2185
- var a2;
2186
- });
2187
- }, q.path.arity = 1, q.string = function(e3, t2, r2) {
2188
- return h(function* () {
2189
- const n2 = yield I(e3[0], t2, r2);
2190
- switch (n2.type) {
2191
- case "number":
2192
- case "string":
2193
- case "boolean":
2194
- case "datetime":
2195
- return p(`${n2.data}`);
2196
- default:
2197
- return i;
2198
- }
2199
- });
2200
- }, q.string.arity = 1, q.references = function(e3, t2, r2) {
2201
- return h(function* () {
2202
- const n2 = /* @__PURE__ */ new Set();
2203
- for (const o2 of e3) {
2204
- const e4 = yield I(o2, t2, r2);
2205
- if (e4.type === "string") n2.add(e4.data);
2206
- else if (e4.isArray()) {
2207
- const t3 = yield e4.get();
2208
- for (const e5 of t3) typeof e5 == "string" && n2.add(e5);
2209
- }
2210
- }
2211
- return n2.size === 0 ? a : R(yield t2.value.get(), n2) ? s : a;
2212
- });
2213
- }, q.references.arity = (e3) => e3 >= 1, q.round = function(e3, t2, r2) {
2214
- return h(function* () {
2215
- const n2 = yield I(e3[0], t2, r2);
2216
- if (n2.type !== "number") return i;
2217
- const o2 = n2.data;
2218
- let s2 = 0;
2219
- if (e3.length === 2) {
2220
- const n3 = yield I(e3[1], t2, r2);
2221
- if (n3.type !== "number" || n3.data < 0 || !Number.isInteger(n3.data)) return i;
2222
- s2 = n3.data;
2223
- }
2224
- return u(s2 === 0 ? o2 < 0 ? -Math.round(-o2) : Math.round(o2) : Number(o2.toFixed(s2)));
2225
- });
2226
- }, q.round.arity = (e3) => e3 >= 1 && e3 <= 2, q.now = function(e3, t2) {
2227
- return p(t2.context.timestamp.toISOString());
2228
- }, q.now.arity = 0, q.boost = function() {
2229
- throw new Error("unexpected boost call");
2230
- }, q.boost.arity = 2;
2231
- const G = { lower: function(e3, t2, r2) {
2232
- return h(function* () {
2233
- const n2 = yield I(e3[0], t2, r2);
2234
- return n2.type !== "string" ? i : p(n2.data.toLowerCase());
2235
- });
2236
- } };
2237
- G.lower.arity = 1, G.upper = function(e3, t2, r2) {
2238
- return h(function* () {
2239
- const n2 = yield I(e3[0], t2, r2);
2240
- return n2.type !== "string" ? i : p(n2.data.toUpperCase());
2241
- });
2242
- }, G.upper.arity = 1, G.split = function(e3, t2, r2) {
2243
- return h(function* () {
2244
- const n2 = yield I(e3[0], t2, r2);
2245
- if (n2.type !== "string") return i;
2246
- const o2 = yield I(e3[1], t2, r2);
2247
- return o2.type !== "string" ? i : n2.data.length === 0 ? f([], r2) : o2.data.length === 0 ? f(Array.from(n2.data), r2) : f(n2.data.split(o2.data), r2);
2248
- });
2249
- }, G.split.arity = 2, q.lower = G.lower, q.upper = G.upper, G.startsWith = function(e3, t2, r2) {
2250
- return h(function* () {
2251
- const n2 = yield I(e3[0], t2, r2);
2252
- if (n2.type !== "string") return i;
2253
- const o2 = yield I(e3[1], t2, r2);
2254
- return o2.type !== "string" ? i : n2.data.startsWith(o2.data) ? s : a;
2255
- });
2256
- }, G.startsWith.arity = 2;
2257
- const H = { join: function(e3, t2, r2) {
2258
- return h(function* () {
2259
- const n2 = yield I(e3[0], t2, r2);
2260
- if (!n2.isArray()) return i;
2261
- const o2 = yield I(e3[1], t2, r2);
2262
- if (o2.type !== "string") return i;
2263
- let s2 = "", a2 = !1;
2264
- const c2 = yield n2.get();
2265
- for (const e4 of c2) {
2266
- const t3 = f(e4, r2);
2267
- switch (a2 && (s2 += o2.data), t3.type) {
2268
- case "number":
2269
- case "string":
2270
- case "boolean":
2271
- case "datetime":
2272
- s2 += `${t3.data}`;
2273
- break;
2274
- default:
2275
- return i;
2276
- }
2277
- a2 = !0;
2278
- }
2279
- return f(s2, r2);
2280
- });
2281
- } };
2282
- H.join.arity = 2, H.compact = function(e3, r2, n2) {
2283
- return h(function* () {
2284
- const o2 = yield I(e3[0], r2, n2);
2285
- return o2.isArray() ? new t(async function* () {
2286
- for await (const e4 of o2) e4.type !== "null" && (yield e4);
2287
- }) : i;
2288
- });
2289
- }, H.compact.arity = 1, H.unique = function(e3, r2, n2) {
2290
- return h(function* () {
2291
- const s2 = yield I(e3[0], r2, n2);
2292
- if (!s2.isArray()) return i;
2293
- if (n2 === "sync") {
2294
- const e4 = yield s2.get(), t2 = /* @__PURE__ */ new Set(), r3 = [];
2295
- for (const n3 of e4) {
2296
- const e5 = f(n3, "sync");
2297
- switch (e5.type) {
2298
- case "number":
2299
- case "string":
2300
- case "boolean":
2301
- case "datetime":
2302
- t2.has(n3) || (t2.add(n3), r3.push(e5));
2303
- break;
2304
- default:
2305
- r3.push(e5);
2306
- }
2307
- }
2308
- return new o(r3, "array");
2309
- }
2310
- return new t(async function* () {
2311
- const e4 = /* @__PURE__ */ new Set();
2312
- for await (const t2 of s2) switch (t2.type) {
2313
- case "number":
2314
- case "string":
2315
- case "boolean":
2316
- case "datetime":
2317
- e4.has(t2.data) || (e4.add(t2.data), yield t2);
2318
- break;
2319
- default:
2320
- yield t2;
2321
- }
2322
- });
2323
- });
2324
- }, H.unique.arity = 1, H.intersects = function(e3, t2, r2) {
2325
- return h(function* () {
2326
- const n2 = yield I(e3[0], t2, r2);
2327
- if (!n2.isArray()) return i;
2328
- const o2 = yield I(e3[1], t2, r2);
2329
- return o2.isArray() ? (yield n2.first((e4) => !!o2.first((t3) => m(e4, t3)))) ? s : a : i;
2330
- });
2331
- }, H.intersects.arity = 2;
2332
- const B = { text: function(e3, t2, r2) {
2333
- return h(function* () {
2334
- const n2 = yield I(e3[0], t2, r2), o2 = yield N(n2, r2);
2335
- return o2 === null ? i : p(o2);
2336
- });
2337
- } };
2338
- B.text.arity = 1;
2339
- const W = { projectId: function(e3, t2) {
2340
- return t2.context.sanity ? p(t2.context.sanity.projectId) : i;
2341
- }, dataset: function(e3, t2) {
2342
- return t2.context.sanity ? p(t2.context.sanity.dataset) : i;
2343
- }, versionsOf: function(e3, t2, r2) {
2344
- return h(function* () {
2345
- if (!t2.source.isArray()) return i;
2346
- const n2 = yield I(e3[0], t2, r2);
2347
- if (n2.type !== "string") return i;
2348
- const o2 = n2.data;
2349
- return f(yield t2.source.reduce((e4, t3) => {
2350
- if (y(t3) === "object") {
2351
- const r3 = t3.get();
2352
- r3 && "_id" in r3 && r3._id.split(".").length === 2 && r3._id.endsWith(`.${o2}`) && "_version" in r3 && typeof r3._version == "object" && e4.push(r3._id);
2353
- }
2354
- return e4;
2355
- }, []), r2);
2356
- });
2357
- } };
2358
- W.versionsOf.arity = 1, W.partOfRelease = function(e3, t2, r2) {
2359
- return h(function* () {
2360
- if (!t2.source.isArray()) return i;
2361
- const n2 = yield I(e3[0], t2, r2);
2362
- if (n2.type !== "string") return i;
2363
- const o2 = n2.data;
2364
- return f(yield t2.source.reduce((e4, t3) => {
2365
- if (y(t3) === "object") {
2366
- const r3 = t3.get();
2367
- r3 && "_id" in r3 && r3._id.split(".").length === 2 && r3._id.startsWith(`${o2}.`) && "_version" in r3 && typeof r3._version == "object" && e4.push(r3._id);
2368
- }
2369
- return e4;
2370
- }, []), r2);
2371
- });
2372
- }, W.partOfRelease.arity = 1;
2373
- const Z = { order: function(e3, t2, r2, n2) {
2374
- return h(function* () {
2375
- if (!e3.isArray()) return i;
2376
- const o2 = [], s2 = [];
2377
- let a2 = 0;
2378
- for (let e4 of t2) {
2379
- let t3 = "asc";
2380
- e4.type === "Desc" ? (t3 = "desc", e4 = e4.base) : e4.type === "Asc" && (e4 = e4.base), o2.push(e4), s2.push(t3), a2++;
2381
- }
2382
- const c2 = [];
2383
- let u2 = 0;
2384
- const p2 = yield e3.get();
2385
- for (const e4 of p2) {
2386
- const t3 = f(e4, n2), i2 = r2.createNested(t3), s3 = [yield t3.get(), u2];
2387
- for (let e5 = 0; e5 < a2; e5++) {
2388
- const t4 = yield I(o2[e5], i2, n2);
2389
- s3.push(yield t4.get());
2390
- }
2391
- c2.push(s3), u2++;
2392
- }
2393
- return c2.sort((e4, t3) => {
2394
- for (let r3 = 0; r3 < a2; r3++) {
2395
- let n3 = E(e4[r3 + 2], t3[r3 + 2]);
2396
- if (s2[r3] === "desc" && (n3 = -n3), n3 !== 0) return n3;
2397
- }
2398
- return e4[1] - t3[1];
2399
- }), f(c2.map((e4) => e4[0]), n2);
2400
- });
2401
- } };
2402
- Z.order.arity = (e3) => e3 >= 1, Z.score = function(e3, t2, r2, n2) {
2403
- return h(function* () {
2404
- if (!e3.isArray()) return i;
2405
- const o2 = [], s2 = [], a2 = yield e3.get();
2406
- for (const e4 of a2) {
2407
- const i2 = f(e4, n2);
2408
- if (i2.type !== "object") {
2409
- o2.push(yield i2.get());
2410
- continue;
2411
- }
2412
- const a3 = r2.createNested(i2);
2413
- let c2 = typeof i2.data._score == "number" ? i2.data._score : 0;
2414
- for (const e5 of t2) c2 += yield F(e5, a3, n2);
2415
- const u2 = Object.assign({}, i2.data, { _score: c2 });
2416
- s2.push(u2);
2417
- }
2418
- return s2.sort((e4, t3) => t3._score - e4._score), f(s2, n2);
2419
- });
2420
- }, Z.score.arity = (e3) => e3 >= 1;
2421
- const z = { operation: function(e3, t2) {
2422
- const r2 = t2.context.before !== null, n2 = t2.context.after !== null;
2423
- return r2 && n2 ? p("update") : n2 ? p("create") : r2 ? p("delete") : i;
2424
- }, changedAny: () => {
2425
- throw new Error("not implemented");
2426
- } };
2427
- z.changedAny.arity = 1, z.changedAny.mode = "delta", z.changedOnly = () => {
2428
- throw new Error("not implemented");
2429
- }, z.changedOnly.arity = 1, z.changedOnly.mode = "delta";
2430
- const J = { changedAny: () => {
2431
- throw new Error("not implemented");
2432
- } };
2433
- J.changedAny.arity = 3, J.changedOnly = () => {
2434
- throw new Error("not implemented");
2435
- }, J.changedOnly.arity = 3;
2436
- const Q = { min: function(e3, t2, r2) {
2437
- return h(function* () {
2438
- const n2 = yield I(e3[0], t2, r2);
2439
- if (!n2.isArray() || (yield n2.first((e4) => e4.type !== "null" && e4.type !== "number"))) return i;
2440
- const o2 = yield n2.get();
2441
- let s2;
2442
- for (const e4 of o2) typeof e4 == "number" && (s2 === void 0 || e4 < s2) && (s2 = e4);
2443
- return f(s2, r2);
2444
- });
2445
- } };
2446
- Q.min.arity = 1, Q.max = function(e3, t2, r2) {
2447
- return h(function* () {
2448
- const n2 = yield I(e3[0], t2, r2);
2449
- if (!n2.isArray() || (yield n2.first((e4) => e4.type !== "null" && e4.type !== "number"))) return i;
2450
- const o2 = yield n2.get();
2451
- let s2;
2452
- for (const e4 of o2) typeof e4 == "number" && (s2 === void 0 || e4 > s2) && (s2 = e4);
2453
- return f(s2, r2);
2454
- });
2455
- }, Q.max.arity = 1, Q.sum = function(e3, t2, r2) {
2456
- return h(function* () {
2457
- const n2 = yield I(e3[0], t2, r2);
2458
- return !n2.isArray() || (yield n2.first((e4) => e4.type !== "null" && e4.type !== "number")) ? i : f(yield n2.reduce((e4, t3) => t3.type !== "number" ? e4 : e4 + t3.data, 0), r2);
2459
- });
2460
- }, Q.sum.arity = 1, Q.avg = function(e3, t2, r2) {
2461
- return h(function* () {
2462
- const n2 = yield I(e3[0], t2, r2);
2463
- if (!n2.isArray() || (yield n2.first((e4) => e4.type !== "null" && e4.type !== "number"))) return i;
2464
- const o2 = yield n2.reduce((e4, t3) => t3.type !== "number" ? e4 : e4 + 1, 0), s2 = yield n2.reduce((e4, t3) => t3.type !== "number" ? e4 : e4 + t3.data, 0);
2465
- return o2 === 0 ? i : f(s2 / o2, r2);
2466
- });
2467
- }, Q.avg.arity = 1;
2468
- const L = { now: function(e3, t2) {
2469
- return l(new c(t2.context.timestamp));
2470
- } };
2471
- L.now.arity = 0;
2472
- const Y = { global: q, string: G, array: H, pt: B, delta: z, diff: J, sanity: W, math: Q, dateTime: L };
2473
- class K {
2474
- string;
2475
- marks;
2476
- index;
2477
- parseOptions;
2478
- allowBoost = !1;
2479
- constructor(e3, t2, r2) {
2480
- this.string = e3, this.marks = t2, this.index = 0, this.parseOptions = r2;
2481
- }
2482
- hasMark(e3 = 0) {
2483
- return this.index + e3 < this.marks.length;
2484
- }
2485
- getMark(e3 = 0) {
2486
- return this.marks[this.index + e3];
2487
- }
2488
- shift() {
2489
- this.index += 1;
2490
- }
2491
- process(e3) {
2492
- const t2 = this.marks[this.index];
2493
- this.shift();
2494
- const r2 = e3[t2.name];
2495
- if (!r2) throw new Error(`Unknown handler: ${t2.name}`);
2496
- return r2.call(e3, this, t2);
2497
- }
2498
- processString() {
2499
- return this.shift(), this.processStringEnd();
2500
- }
2501
- processStringEnd() {
2502
- const e3 = this.marks[this.index - 1], t2 = this.marks[this.index];
2503
- return this.shift(), this.string.slice(e3.position, t2.position);
2504
- }
2505
- slice(e3) {
2506
- const t2 = this.marks[this.index].position;
2507
- return this.string.slice(t2, t2 + e3);
2508
- }
2509
- }
2510
- const X = /^([\t\n\v\f\r \u0085\u00A0]|(\/\/[^\n]*\n))+/, ee = /^\d+/, te = /^[a-zA-Z_][a-zA-Z_0-9]*/;
2511
- function re(e3, t2, r2) {
2512
- let n2, o2 = t2;
2513
- switch (e3[t2]) {
2514
- case "+": {
2515
- let r3 = re(e3, se(e3, t2 + 1), 10);
2516
- if (r3.type === "error") return r3;
2517
- n2 = [{ name: "pos", position: o2 }].concat(r3.marks), t2 = r3.position;
2518
- break;
2519
- }
2520
- case "-": {
2521
- let r3 = re(e3, se(e3, t2 + 1), 8);
2522
- if (r3.type === "error") return r3;
2523
- n2 = [{ name: "neg", position: o2 }].concat(r3.marks), t2 = r3.position;
2524
- break;
2525
- }
2526
- case "(": {
2527
- let r3 = re(e3, se(e3, t2 + 1), 0);
2528
- if (r3.type === "error") return r3;
2529
- switch (e3[t2 = se(e3, r3.position)]) {
2530
- case ",":
2531
- for (n2 = [{ name: "tuple", position: o2 }].concat(r3.marks), t2 = se(e3, t2 + 1); ; ) {
2532
- if (r3 = re(e3, t2, 0), r3.type === "error") return r3;
2533
- if (e3[t2 = se(e3, r3.position)] !== ",") break;
2534
- t2 = se(e3, t2 + 1);
2535
- }
2536
- if (e3[t2] !== ")") return { type: "error", position: t2 };
2537
- t2++, n2.push({ name: "tuple_end", position: t2 });
2538
- break;
2539
- case ")":
2540
- t2++, n2 = [{ name: "group", position: o2 }].concat(r3.marks);
2541
- break;
2542
- default:
2543
- return { type: "error", position: t2 };
2544
- }
2545
- break;
2546
- }
2547
- case "!": {
2548
- let r3 = re(e3, se(e3, t2 + 1), 10);
2549
- if (r3.type === "error") return r3;
2550
- n2 = [{ name: "not", position: o2 }].concat(r3.marks), t2 = r3.position;
2551
- break;
2552
- }
2553
- case "{": {
2554
- let r3 = ie(e3, t2);
2555
- if (r3.type === "error") return r3;
2556
- n2 = r3.marks, t2 = r3.position;
2557
- break;
2558
- }
2559
- case "[":
2560
- if (n2 = [{ name: "array", position: t2 }], e3[t2 = se(e3, t2 + 1)] !== "]") for (; ; ) {
2561
- e3.slice(t2, t2 + 3) === "..." && (n2.push({ name: "array_splat", position: t2 }), t2 = se(e3, t2 + 3));
2562
- let r3 = re(e3, t2, 0);
2563
- if (r3.type === "error") return r3;
2564
- if (n2 = n2.concat(r3.marks), e3[t2 = se(e3, t2 = r3.position)] !== "," || e3[t2 = se(e3, t2 + 1)] === "]") break;
2565
- }
2566
- if (e3[t2] !== "]") return { type: "error", position: t2 };
2567
- t2++, n2.push({ name: "array_end", position: t2 });
2568
- break;
2569
- case "'":
2570
- case '"': {
2571
- let r3 = function(e4, t3) {
2572
- let r4 = e4[t3];
2573
- t3 += 1;
2574
- const n3 = [{ name: "str", position: t3 }];
2575
- e: for (; ; t3++) {
2576
- if (t3 > e4.length) return { type: "error", position: t3 };
2577
- switch (e4[t3]) {
2578
- case r4:
2579
- n3.push({ name: "str_end", position: t3 }), t3++;
2580
- break e;
2581
- case "\\":
2582
- n3.push({ name: "str_pause", position: t3 }), e4[t3 + 1] === "u" ? e4[t3 + 2] === "{" ? (n3.push({ name: "unicode_hex", position: t3 + 3 }), t3 = e4.indexOf("}", t3 + 3), n3.push({ name: "unicode_hex_end", position: t3 })) : (n3.push({ name: "unicode_hex", position: t3 + 2 }), n3.push({ name: "unicode_hex_end", position: t3 + 6 }), t3 += 5) : (n3.push({ name: "single_escape", position: t3 + 1 }), t3 += 1), n3.push({ name: "str_start", position: t3 + 1 });
2583
- }
2584
- }
2585
- return { type: "success", marks: n3, position: t3 };
2586
- }(e3, t2);
2587
- if (r3.type === "error") return r3;
2588
- n2 = r3.marks, t2 = r3.position;
2589
- break;
2590
- }
2591
- case "^":
2592
- for (t2++, n2 = []; e3[t2] === "." && e3[t2 + 1] === "^"; ) n2.push({ name: "dblparent", position: o2 }), t2 += 2;
2593
- n2.push({ name: "parent", position: o2 });
2594
- break;
2595
- case "@":
2596
- n2 = [{ name: "this", position: o2 }], t2++;
2597
- break;
2598
- case "*":
2599
- n2 = [{ name: "everything", position: o2 }], t2++;
2600
- break;
2601
- case "$": {
2602
- let r3 = ae(e3, t2 + 1, te);
2603
- r3 && (n2 = [{ name: "param", position: o2 }, { name: "ident", position: o2 + 1 }, { name: "ident_end", position: t2 += 1 + r3 }]);
2604
- break;
2605
- }
2606
- default: {
2607
- let r3 = ae(e3, t2, ee);
2608
- if (r3) {
2609
- let i4 = "integer";
2610
- if (e3[t2 += r3] === ".") {
2611
- let r4 = ae(e3, t2 + 1, ee);
2612
- r4 && (i4 = "float", t2 += 1 + r4);
2613
- }
2614
- if (e3[t2] === "e" || e3[t2] === "E") {
2615
- i4 = "sci", (e3[++t2] === "+" || e3[t2] === "-") && t2++;
2616
- let r4 = ae(e3, t2, ee);
2617
- if (!r4) return { type: "error", position: t2 };
2618
- t2 += r4;
2619
- }
2620
- n2 = [{ name: i4, position: o2 }, { name: i4 + "_end", position: t2 }];
2621
- break;
2622
- }
2623
- let i3 = ae(e3, t2, te);
2624
- if (i3) {
2625
- switch (e3[t2 += i3]) {
2626
- case ":":
2627
- case "(": {
2628
- let r4 = oe(e3, o2, t2);
2629
- if (r4.type === "error") return r4;
2630
- n2 = r4.marks, t2 = r4.position;
2631
- break;
2632
- }
2633
- default:
2634
- n2 = [{ name: "this_attr", position: o2 }, { name: "ident", position: o2 }, { name: "ident_end", position: t2 }];
2635
- }
2636
- break;
2637
- }
2638
- }
2639
- }
2640
- if (!n2) return { type: "error", position: t2 };
2641
- let i2, s2 = 12;
2642
- e: for (; ; ) {
2643
- let a2 = se(e3, t2);
2644
- if (a2 === e3.length) {
2645
- t2 = a2;
2646
- break;
2647
- }
2648
- if (i2 = ne(e3, a2), i2.type !== "success") switch (e3[a2]) {
2649
- case "=":
2650
- switch (e3[a2 + 1]) {
2651
- case ">": {
2652
- if (r2 > 1 || s2 <= 1) break e;
2653
- let i3 = re(e3, se(e3, a2 + 2), 1);
2654
- if (i3.type === "error") return i3;
2655
- n2 = n2.concat(i3.marks), n2.unshift({ name: "pair", position: o2 }), t2 = i3.position, s2 = 1;
2656
- break;
2657
- }
2658
- case "=": {
2659
- if (r2 > 4 || s2 <= 4) break e;
2660
- let i3 = re(e3, se(e3, a2 + 2), 5);
2661
- if (i3.type === "error") return i3;
2662
- n2.unshift({ name: "comp", position: o2 }), n2.push({ name: "op", position: a2 }, { name: "op_end", position: a2 + 2 }), n2 = n2.concat(i3.marks), t2 = i3.position, s2 = 4;
2663
- break;
2664
- }
2665
- default:
2666
- break e;
2667
- }
2668
- break;
2669
- case "+": {
2670
- if (r2 > 6 || s2 < 6) break e;
2671
- let i3 = re(e3, se(e3, a2 + 1), 7);
2672
- if (i3.type === "error") return i3;
2673
- n2 = n2.concat(i3.marks), n2.unshift({ name: "add", position: o2 }), t2 = i3.position, s2 = 6;
2674
- break;
2675
- }
2676
- case "-": {
2677
- if (r2 > 6 || s2 < 6) break e;
2678
- let i3 = re(e3, se(e3, a2 + 1), 7);
2679
- if (i3.type === "error") return i3;
2680
- n2 = n2.concat(i3.marks), n2.unshift({ name: "sub", position: o2 }), t2 = i3.position, s2 = 6;
2681
- break;
2682
- }
2683
- case "*": {
2684
- if (e3[a2 + 1] === "*") {
2685
- if (r2 > 8 || s2 <= 8) break e;
2686
- let i4 = re(e3, se(e3, a2 + 2), 8);
2687
- if (i4.type === "error") return i4;
2688
- n2 = n2.concat(i4.marks), n2.unshift({ name: "pow", position: o2 }), t2 = i4.position, s2 = 8;
2689
- break;
2690
- }
2691
- if (r2 > 7 || s2 < 7) break e;
2692
- let i3 = re(e3, se(e3, a2 + 1), 8);
2693
- if (i3.type === "error") return i3;
2694
- n2 = n2.concat(i3.marks), n2.unshift({ name: "mul", position: o2 }), t2 = i3.position, s2 = 7;
2695
- break;
2696
- }
2697
- case "/": {
2698
- if (r2 > 7 || s2 < 7) break e;
2699
- let i3 = re(e3, se(e3, a2 + 1), 8);
2700
- if (i3.type === "error") return i3;
2701
- n2 = n2.concat(i3.marks), n2.unshift({ name: "div", position: o2 }), t2 = i3.position, s2 = 7;
2702
- break;
2703
- }
2704
- case "%": {
2705
- if (r2 > 7 || s2 < 7) break e;
2706
- let i3 = re(e3, se(e3, a2 + 1), 8);
2707
- if (i3.type === "error") return i3;
2708
- n2 = n2.concat(i3.marks), n2.unshift({ name: "mod", position: o2 }), t2 = i3.position, s2 = 7;
2709
- break;
2710
- }
2711
- case "<":
2712
- case ">": {
2713
- if (r2 > 4 || s2 <= 4) break e;
2714
- let i3 = a2 + 1;
2715
- e3[i3] === "=" && i3++;
2716
- let c2 = re(e3, se(e3, i3), 5);
2717
- if (c2.type === "error") return c2;
2718
- n2.unshift({ name: "comp", position: o2 }), n2.push({ name: "op", position: a2 }, { name: "op_end", position: i3 }), n2 = n2.concat(c2.marks), t2 = c2.position, s2 = 4;
2719
- break;
2720
- }
2721
- case "|":
2722
- if (e3[a2 + 1] === "|") {
2723
- if (r2 > 2 || s2 < 2) break e;
2724
- let i3 = re(e3, se(e3, a2 + 2), 3);
2725
- if (i3.type === "error") return i3;
2726
- n2 = n2.concat(i3.marks), n2.unshift({ name: "or", position: o2 }), t2 = i3.position, s2 = 2;
2727
- } else {
2728
- if (r2 > 11 || s2 < 11) break e;
2729
- let i3 = se(e3, a2 + 1), c2 = ae(e3, i3, te);
2730
- if (!c2) return { type: "error", position: i3 };
2731
- if (e3[t2 = i3 + c2] === "(" || e3[t2] === ":") {
2732
- let r3 = oe(e3, i3, t2);
2733
- if (r3.type === "error") return r3;
2734
- n2 = n2.concat(r3.marks), n2.unshift({ name: "pipecall", position: o2 }), t2 = r3.position, s2 = 11;
2735
- }
2736
- }
2737
- break;
2738
- case "&": {
2739
- if (e3[a2 + 1] != "&" || r2 > 3 || s2 < 3) break e;
2740
- let i3 = re(e3, se(e3, a2 + 2), 4);
2741
- if (i3.type === "error") return i3;
2742
- n2 = n2.concat(i3.marks), n2.unshift({ name: "and", position: o2 }), t2 = i3.position, s2 = 3;
2743
- break;
2744
- }
2745
- case "!": {
2746
- if (e3[a2 + 1] !== "=" || r2 > 4 || s2 <= 4) break e;
2747
- let i3 = re(e3, se(e3, a2 + 2), 5);
2748
- if (i3.type === "error") return i3;
2749
- n2.unshift({ name: "comp", position: o2 }), n2.push({ name: "op", position: a2 }, { name: "op_end", position: a2 + 2 }), n2 = n2.concat(i3.marks), t2 = i3.position, s2 = 4;
2750
- break;
2751
- }
2752
- case "d":
2753
- if (e3.slice(a2, a2 + 4) !== "desc" || r2 > 4 || s2 < 4) break e;
2754
- n2.unshift({ name: "desc", position: o2 }), t2 = a2 + 4, s2 = 4;
2755
- break;
2756
- case "a":
2757
- if (e3.slice(a2, a2 + 3) !== "asc" || r2 > 4 || s2 < 4) break e;
2758
- n2.unshift({ name: "asc", position: o2 }), t2 = a2 + 3, s2 = 4;
2759
- break;
2760
- default:
2761
- switch (ce(e3, a2, te)) {
2762
- case "in": {
2763
- if (r2 > 4 || s2 <= 4) break e;
2764
- let i3 = !1;
2765
- e3[t2 = se(e3, a2 + 2)] === "(" && (i3 = !0, t2 = se(e3, t2 + 1));
2766
- let c2 = t2, u2 = re(e3, t2, 5);
2767
- if (u2.type === "error") return u2;
2768
- if (e3[t2 = se(e3, u2.position)] === "." && e3[t2 + 1] === ".") {
2769
- let r3 = "inc_range";
2770
- e3[t2 + 2] === "." ? (r3 = "exc_range", t2 = se(e3, t2 + 3)) : t2 = se(e3, t2 + 2);
2771
- let i4 = re(e3, t2, 5);
2772
- if (i4.type === "error") return i4;
2773
- n2.unshift({ name: "in_range", position: o2 }), n2 = n2.concat({ name: r3, position: c2 }, u2.marks, i4.marks), t2 = i4.position;
2774
- } else n2.unshift({ name: "comp", position: o2 }), n2.push({ name: "op", position: a2 }, { name: "op_end", position: a2 + 2 }), n2 = n2.concat(u2.marks);
2775
- if (i3) {
2776
- if (e3[t2 = se(e3, t2)] !== ")") return { type: "error", position: t2 };
2777
- t2++;
2778
- }
2779
- s2 = 4;
2780
- break;
2781
- }
2782
- case "match": {
2783
- if (r2 > 4 || s2 <= 4) break e;
2784
- let i3 = re(e3, se(e3, a2 + 5), 5);
2785
- if (i3.type === "error") return i3;
2786
- n2.unshift({ name: "comp", position: o2 }), n2.push({ name: "op", position: a2 }, { name: "op_end", position: a2 + 5 }), n2 = n2.concat(i3.marks), t2 = i3.position, s2 = 4;
2787
- break;
2788
- }
2789
- default:
2790
- break e;
2791
- }
2792
- }
2793
- else {
2794
- for (n2.unshift({ name: "traverse", position: o2 }); i2.type === "success"; ) n2 = n2.concat(i2.marks), i2 = ne(e3, se(e3, t2 = i2.position));
2795
- n2.push({ name: "traversal_end", position: t2 });
2796
- }
2797
- }
2798
- return { type: "success", marks: n2, position: t2, failPosition: i2?.type === "error" && i2.position };
2799
- }
2800
- function ne(e3, t2) {
2801
- let r2 = t2;
2802
- switch (e3[t2]) {
2803
- case ".": {
2804
- let n3 = t2 = se(e3, t2 + 1), o3 = ae(e3, t2, te);
2805
- return o3 ? { type: "success", marks: [{ name: "attr_access", position: r2 }, { name: "ident", position: n3 }, { name: "ident_end", position: t2 += o3 }], position: t2 } : { type: "error", position: t2 };
2806
- }
2807
- case "-":
2808
- if (e3[t2 + 1] !== ">") return { type: "error", position: t2 };
2809
- let n2 = [{ name: "deref", position: r2 }], o2 = se(e3, t2 += 2), i2 = ae(e3, o2, te);
2810
- return i2 && (t2 = o2 + i2, n2.push({ name: "deref_attr", position: o2 }, { name: "ident", position: o2 }, { name: "ident_end", position: t2 })), { type: "success", marks: n2, position: t2 };
2811
- case "[": {
2812
- if (e3[t2 = se(e3, t2 + 1)] === "]") return { type: "success", marks: [{ name: "array_postfix", position: r2 }], position: t2 + 1 };
2813
- let n3 = t2, o3 = re(e3, t2, 0);
2814
- if (o3.type === "error") return o3;
2815
- if (e3[t2 = se(e3, o3.position)] === "." && e3[t2 + 1] === ".") {
2816
- let i3 = "inc_range";
2817
- e3[t2 + 2] === "." ? (i3 = "exc_range", t2 += 3) : t2 += 2;
2818
- let s2 = re(e3, t2 = se(e3, t2), 0);
2819
- return s2.type === "error" ? s2 : e3[t2 = se(e3, s2.position)] !== "]" ? { type: "error", position: t2 } : { type: "success", marks: [{ name: "slice", position: r2 }, { name: i3, position: n3 }].concat(o3.marks, s2.marks), position: t2 + 1 };
2820
- }
2821
- return e3[t2] !== "]" ? { type: "error", position: t2 } : { type: "success", marks: [{ name: "square_bracket", position: r2 }].concat(o3.marks), position: t2 + 1 };
2822
- }
2823
- case "|":
2824
- if (e3[t2 = se(e3, t2 + 1)] === "{") {
2825
- let n3 = ie(e3, t2);
2826
- return n3.type === "error" || n3.marks.unshift({ name: "projection", position: r2 }), n3;
2827
- }
2828
- break;
2829
- case "{": {
2830
- let n3 = ie(e3, t2);
2831
- return n3.type === "error" || n3.marks.unshift({ name: "projection", position: r2 }), n3;
2832
- }
2833
- }
2834
- return { type: "error", position: t2 };
2835
- }
2836
- function oe(e3, t2, r2) {
2837
- let n2 = [];
2838
- if (n2.push({ name: "func_call", position: t2 }), e3[r2] === ":" && e3[r2 + 1] === ":") {
2839
- n2.push({ name: "namespace", position: t2 }), n2.push({ name: "ident", position: t2 }, { name: "ident_end", position: r2 });
2840
- let o3 = ae(e3, r2 = se(e3, r2 + 2), te);
2841
- if (!o3) return { type: "error", position: r2 };
2842
- if (n2.push({ name: "ident", position: r2 }, { name: "ident_end", position: r2 + o3 }), e3[r2 = se(e3, r2 + o3)] !== "(") return { type: "error", position: r2 };
2843
- r2 = se(e3, ++r2);
2844
- } else n2.push({ name: "ident", position: t2 }, { name: "ident_end", position: r2 }), r2 = se(e3, r2 + 1);
2845
- let o2 = r2;
2846
- if (e3[r2] !== ")") for (; ; ) {
2847
- let t3 = re(e3, r2, 0);
2848
- if (t3.type === "error") return t3;
2849
- if (n2 = n2.concat(t3.marks), o2 = t3.position, e3[r2 = se(e3, t3.position)] !== "," || e3[r2 = se(e3, r2 + 1)] === ")") break;
2850
- }
2851
- return e3[r2] !== ")" ? { type: "error", position: r2 } : (n2.push({ name: "func_args_end", position: o2 }), { type: "success", marks: n2, position: r2 + 1 });
2852
- }
2853
- function ie(e3, t2) {
2854
- let r2 = [{ name: "object", position: t2 }];
2855
- for (t2 = se(e3, t2 + 1); e3[t2] !== "}"; ) {
2856
- let n2 = t2;
2857
- if (e3.slice(t2, t2 + 3) === "...") if (e3[t2 = se(e3, t2 + 3)] !== "}" && e3[t2] !== ",") {
2858
- let o2 = re(e3, t2, 0);
2859
- if (o2.type === "error") return o2;
2860
- r2.push({ name: "object_splat", position: n2 }), r2 = r2.concat(o2.marks), t2 = o2.position;
2861
- } else r2.push({ name: "object_splat_this", position: n2 });
2862
- else {
2863
- let o2 = re(e3, t2, 0);
2864
- if (o2.type === "error") return o2;
2865
- let i2 = se(e3, o2.position);
2866
- if (o2.marks[0].name === "str" && e3[i2] === ":") {
2867
- let s2 = re(e3, se(e3, i2 + 1), 0);
2868
- if (s2.type === "error") return s2;
2869
- r2.push({ name: "object_pair", position: n2 }), r2 = r2.concat(o2.marks, s2.marks), t2 = s2.position;
2870
- } else r2 = r2.concat({ name: "object_expr", position: t2 }, o2.marks), t2 = o2.position;
2871
- }
2872
- if (e3[t2 = se(e3, t2)] !== ",") break;
2873
- t2 = se(e3, t2 + 1);
2874
- }
2875
- return e3[t2] !== "}" ? { type: "error", position: t2 } : (t2++, r2.push({ name: "object_end", position: t2 }), { type: "success", marks: r2, position: t2 });
2876
- }
2877
- function se(e3, t2) {
2878
- return t2 + ae(e3, t2, X);
2879
- }
2880
- function ae(e3, t2, r2) {
2881
- let n2 = r2.exec(e3.slice(t2));
2882
- return n2 ? n2[0].length : 0;
2883
- }
2884
- function ce(e3, t2, r2) {
2885
- let n2 = r2.exec(e3.slice(t2));
2886
- return n2 ? n2[0] : null;
2887
- }
2888
- function ue(e3, t2) {
2889
- return (r2) => t2(e3(r2));
2890
- }
2891
- function pe(e3) {
2892
- return (t2) => ({ type: "Map", base: t2, expr: e3({ type: "This" }) });
2893
- }
2894
- function le(e3, t2) {
2895
- if (!t2) return { type: "a-a", build: e3 };
2896
- switch (t2.type) {
2897
- case "a-a":
2898
- return { type: "a-a", build: ue(e3, t2.build) };
2899
- case "a-b":
2900
- return { type: "a-b", build: ue(e3, t2.build) };
2901
- case "b-b":
2902
- return { type: "a-a", build: ue(e3, pe(t2.build)) };
2903
- case "b-a":
2904
- return { type: "a-a", build: ue(e3, (r2 = t2.build, (e4) => ({ type: "FlatMap", base: e4, expr: r2({ type: "This" }) }))) };
2905
- default:
2906
- throw new Error(`unknown type: ${t2.type}`);
2907
- }
2908
- var r2;
2909
- }
2910
- function fe(e3, t2) {
2911
- if (!t2) return { type: "b-b", build: e3 };
2912
- switch (t2.type) {
2913
- case "a-a":
2914
- case "b-a":
2915
- return { type: "b-a", build: ue(e3, t2.build) };
2916
- case "a-b":
2917
- case "b-b":
2918
- return { type: "b-b", build: ue(e3, t2.build) };
2919
- default:
2920
- throw new Error(`unknown type: ${t2.type}`);
2921
- }
2922
- }
2923
- const ye = { "'": "'", '"': '"', "\\": "\\", "/": "/", b: "\b", f: "\f", n: `
2924
- `, r: "\r", t: " " };
2925
- function de(e3) {
2926
- const t2 = parseInt(e3, 16);
2927
- return String.fromCharCode(t2);
2928
- }
2929
- class he extends Error {
2930
- name = "GroqQueryError";
2931
- }
2932
- const me = { group: (e3) => ({ type: "Group", base: e3.process(me) }), everything: () => ({ type: "Everything" }), this: () => ({ type: "This" }), parent: () => ({ type: "Parent", n: 1 }), dblparent: (e3) => ({ type: "Parent", n: e3.process(me).n + 1 }), traverse(e3) {
2933
- const t2 = e3.process(me), r2 = [];
2934
- for (; e3.getMark().name !== "traversal_end"; ) r2.push(e3.process(ge));
2935
- e3.shift();
2936
- let n2 = null;
2937
- for (let e4 = r2.length - 1; e4 >= 0; e4--) n2 = r2[e4](n2);
2938
- if ((t2.type === "Everything" || t2.type === "Array" || t2.type === "PipeFuncCall") && (n2 = le((e4) => e4, n2)), n2 === null) throw new Error("BUG: unexpected empty traversal");
2939
- return n2.build(t2);
2940
- }, this_attr(e3) {
2941
- const t2 = e3.processString();
2942
- return t2 === "null" ? { type: "Value", value: null } : t2 === "true" ? { type: "Value", value: !0 } : t2 === "false" ? { type: "Value", value: !1 } : { type: "AccessAttribute", name: t2 };
2943
- }, neg: (e3) => ({ type: "Neg", base: e3.process(me) }), pos: (e3) => ({ type: "Pos", base: e3.process(me) }), add: (e3) => ({ type: "OpCall", op: "+", left: e3.process(me), right: e3.process(me) }), sub: (e3) => ({ type: "OpCall", op: "-", left: e3.process(me), right: e3.process(me) }), mul: (e3) => ({ type: "OpCall", op: "*", left: e3.process(me), right: e3.process(me) }), div: (e3) => ({ type: "OpCall", op: "/", left: e3.process(me), right: e3.process(me) }), mod: (e3) => ({ type: "OpCall", op: "%", left: e3.process(me), right: e3.process(me) }), pow: (e3) => ({ type: "OpCall", op: "**", left: e3.process(me), right: e3.process(me) }), comp(e3) {
2944
- const t2 = e3.process(me);
2945
- return { type: "OpCall", op: e3.processString(), left: t2, right: e3.process(me) };
2946
- }, in_range(e3) {
2947
- const t2 = e3.process(me), r2 = e3.getMark().name === "inc_range";
2948
- return e3.shift(), { type: "InRange", base: t2, left: e3.process(me), right: e3.process(me), isInclusive: r2 };
2949
- }, str(e3) {
2950
- let t2 = "";
2951
- e: for (; e3.hasMark(); ) {
2952
- const r2 = e3.getMark();
2953
- switch (r2.name) {
2954
- case "str_end":
2955
- t2 += e3.processStringEnd();
2956
- break e;
2957
- case "str_pause":
2958
- t2 += e3.processStringEnd();
2959
- break;
2960
- case "str_start":
2961
- e3.shift();
2962
- break;
2963
- case "single_escape": {
2964
- const r3 = e3.slice(1);
2965
- e3.shift(), t2 += ye[r3];
2966
- break;
2967
- }
2968
- case "unicode_hex":
2969
- e3.shift(), t2 += de(e3.processStringEnd());
2970
- break;
2971
- default:
2972
- throw new Error(`unexpected mark: ${r2.name}`);
2973
- }
2974
- }
2975
- return { type: "Value", value: t2 };
2976
- }, integer(e3) {
2977
- const t2 = e3.processStringEnd();
2978
- return { type: "Value", value: Number(t2) };
2979
- }, float(e3) {
2980
- const t2 = e3.processStringEnd();
2981
- return { type: "Value", value: Number(t2) };
2982
- }, sci(e3) {
2983
- const t2 = e3.processStringEnd();
2984
- return { type: "Value", value: Number(t2) };
2985
- }, object(e3) {
2986
- const t2 = [];
2987
- for (; e3.getMark().name !== "object_end"; ) t2.push(e3.process(be));
2988
- return e3.shift(), { type: "Object", attributes: t2 };
2989
- }, array(e3) {
2990
- const t2 = [];
2991
- for (; e3.getMark().name !== "array_end"; ) {
2992
- let r2 = !1;
2993
- e3.getMark().name === "array_splat" && (r2 = !0, e3.shift());
2994
- const n2 = e3.process(me);
2995
- t2.push({ type: "ArrayElement", value: n2, isSplat: r2 });
2996
- }
2997
- return e3.shift(), { type: "Array", elements: t2 };
2998
- }, tuple(e3) {
2999
- const t2 = [];
3000
- for (; e3.getMark().name !== "tuple_end"; ) t2.push(e3.process(me));
3001
- return e3.shift(), { type: "Tuple", members: t2 };
3002
- }, func_call(e3) {
3003
- let t2 = "global";
3004
- e3.getMark().name === "namespace" && (e3.shift(), t2 = e3.processString());
3005
- const r2 = e3.processString();
3006
- if (t2 === "global" && r2 === "select") {
3007
- const t3 = { type: "Select", alternatives: [] };
3008
- for (; e3.getMark().name !== "func_args_end"; ) if (e3.getMark().name === "pair") {
3009
- if (t3.fallback) throw new he("unexpected argument to select()");
3010
- e3.shift();
3011
- const r3 = e3.process(me), n3 = e3.process(me);
3012
- t3.alternatives.push({ type: "SelectAlternative", condition: r3, value: n3 });
3013
- } else {
3014
- if (t3.fallback) throw new he("unexpected argument to select()");
3015
- const r3 = e3.process(me);
3016
- t3.fallback = r3;
3017
- }
3018
- return e3.shift(), t3;
3019
- }
3020
- const n2 = [];
3021
- for (; e3.getMark().name !== "func_args_end"; ) xe(t2, r2, n2.length) ? (e3.process(we), n2.push({ type: "Selector" })) : n2.push(e3.process(me));
3022
- if (e3.shift(), t2 === "global" && (r2 === "before" || r2 === "after") && e3.parseOptions.mode === "delta") return { type: "Context", key: r2 };
3023
- if (t2 === "global" && r2 === "boost" && !e3.allowBoost) throw new he("unexpected boost");
3024
- const o2 = Y[t2];
3025
- if (!o2) throw new he(`Undefined namespace: ${t2}`);
3026
- const i2 = o2[r2];
3027
- if (!i2) throw new he(`Undefined function: ${r2}`);
3028
- if (i2.arity !== void 0 && ve(r2, i2.arity, n2.length), i2.mode !== void 0 && i2.mode !== e3.parseOptions.mode) throw new he(`Undefined function: ${r2}`);
3029
- return { type: "FuncCall", func: i2, namespace: t2, name: r2, args: n2 };
3030
- }, pipecall(e3) {
3031
- const t2 = e3.process(me);
3032
- e3.shift();
3033
- let r2 = "global";
3034
- if (e3.getMark().name === "namespace" && (e3.shift(), r2 = e3.processString()), r2 !== "global") throw new he(`Undefined namespace: ${r2}`);
3035
- const n2 = e3.processString(), o2 = [], i2 = e3.allowBoost;
3036
- for (n2 === "score" && (e3.allowBoost = !0); ; ) {
3037
- const t3 = e3.getMark().name;
3038
- if (t3 === "func_args_end") break;
3039
- if (n2 === "order") {
3040
- if (t3 === "asc") {
3041
- e3.shift(), o2.push({ type: "Asc", base: e3.process(me) });
3042
- continue;
3043
- }
3044
- if (t3 === "desc") {
3045
- e3.shift(), o2.push({ type: "Desc", base: e3.process(me) });
3046
- continue;
3047
- }
3048
- }
3049
- o2.push(e3.process(me));
3050
- }
3051
- e3.shift(), e3.allowBoost = i2;
3052
- const s2 = Z[n2];
3053
- if (!s2) throw new he(`Undefined pipe function: ${n2}`);
3054
- return s2.arity && ve(n2, s2.arity, o2.length), { type: "PipeFuncCall", func: s2, base: t2, name: n2, args: o2 };
3055
- }, pair() {
3056
- throw new he("unexpected =>");
3057
- }, and: (e3) => ({ type: "And", left: e3.process(me), right: e3.process(me) }), or: (e3) => ({ type: "Or", left: e3.process(me), right: e3.process(me) }), not: (e3) => ({ type: "Not", base: e3.process(me) }), asc() {
3058
- throw new he("unexpected asc");
3059
- }, desc() {
3060
- throw new he("unexpected desc");
3061
- }, param(e3) {
3062
- const t2 = e3.processString();
3063
- return e3.parseOptions.params && e3.parseOptions.params.hasOwnProperty(t2) ? { type: "Value", value: e3.parseOptions.params[t2] } : { type: "Parameter", name: t2 };
3064
- } }, be = { object_expr(e3) {
3065
- if (e3.getMark().name === "pair")
3066
- return e3.shift(), { type: "ObjectConditionalSplat", condition: e3.process(me), value: e3.process(me) };
3067
- const t2 = e3.process(me);
3068
- return { type: "ObjectAttributeValue", name: ke(t2), value: t2 };
3069
- }, object_pair(e3) {
3070
- const t2 = e3.process(me);
3071
- if (t2.type !== "Value") throw new Error("name must be string");
3072
- const r2 = e3.process(me);
3073
- return { type: "ObjectAttributeValue", name: t2.value, value: r2 };
3074
- }, object_splat: (e3) => ({ type: "ObjectSplat", value: e3.process(me) }), object_splat_this: () => ({ type: "ObjectSplat", value: { type: "This" } }) }, ge = { square_bracket(e3) {
3075
- const t2 = e3.process(me), r2 = P(t2);
3076
- return r2 && r2.type === "number" ? (e4) => function(e5, t3) {
3077
- if (!t3) return { type: "a-b", build: e5 };
3078
- switch (t3.type) {
3079
- case "a-a":
3080
- case "b-a":
3081
- return { type: "a-a", build: ue(e5, t3.build) };
3082
- case "a-b":
3083
- case "b-b":
3084
- return { type: "a-b", build: ue(e5, t3.build) };
3085
- default:
3086
- throw new Error(`unknown type: ${t3.type}`);
3087
- }
3088
- }((e5) => ({ type: "AccessElement", base: e5, index: r2.data }), e4) : r2 && r2.type === "string" ? (e4) => fe((e5) => ({ type: "AccessAttribute", base: e5, name: r2.data }), e4) : (e4) => le((e5) => ({ type: "Filter", base: e5, expr: t2 }), e4);
3089
- }, slice(e3) {
3090
- const t2 = e3.getMark().name === "inc_range";
3091
- e3.shift();
3092
- const r2 = e3.process(me), n2 = e3.process(me), o2 = P(r2), i2 = P(n2);
3093
- if (!o2 || !i2 || o2.type !== "number" || i2.type !== "number") throw new he("slicing must use constant numbers");
3094
- return (e4) => le((e5) => ({ type: "Slice", base: e5, left: o2.data, right: i2.data, isInclusive: t2 }), e4);
3095
- }, projection(e3) {
3096
- const t2 = e3.process(me);
3097
- return (e4) => function(e5, t3) {
3098
- if (!t3) return { type: "b-b", build: e5 };
3099
- switch (t3.type) {
3100
- case "a-a":
3101
- return { type: "a-a", build: ue(pe(e5), t3.build) };
3102
- case "a-b":
3103
- return { type: "a-b", build: ue(pe(e5), t3.build) };
3104
- case "b-a":
3105
- return { type: "b-a", build: ue(e5, t3.build) };
3106
- case "b-b":
3107
- return { type: "b-b", build: ue(e5, t3.build) };
3108
- default:
3109
- throw new Error(`unknown type: ${t3.type}`);
3110
- }
3111
- }((e5) => ({ type: "Projection", base: e5, expr: t2 }), e4);
3112
- }, attr_access(e3) {
3113
- const t2 = e3.processString();
3114
- return (e4) => fe((e5) => ({ type: "AccessAttribute", base: e5, name: t2 }), e4);
3115
- }, deref(e3) {
3116
- let t2 = null;
3117
- return e3.getMark().name === "deref_attr" && (e3.shift(), t2 = e3.processString()), (e4) => fe((e5) => /* @__PURE__ */ ((e6) => t2 ? { type: "AccessAttribute", base: e6, name: t2 } : e6)({ type: "Deref", base: e5 }), e4);
3118
- }, array_postfix: () => (e3) => le((e4) => ({ type: "ArrayCoerce", base: e4 }), e3) }, we = { group: (e3) => (e3.process(we), null), everything() {
3119
- throw new Error("Invalid selector syntax");
3120
- }, this() {
3121
- throw new Error("Invalid selector syntax");
3122
- }, parent() {
3123
- throw new Error("Invalid selector syntax");
3124
- }, dblparent() {
3125
- throw new Error("Invalid selector syntax");
3126
- }, traverse(e3) {
3127
- for (e3.process(we); e3.getMark().name !== "traversal_end"; ) e3.process(ge);
3128
- return e3.shift(), null;
3129
- }, this_attr: (e3) => (e3.processString(), null), neg() {
3130
- throw new Error("Invalid selector syntax");
3131
- }, pos() {
3132
- throw new Error("Invalid selector syntax");
3133
- }, add() {
3134
- throw new Error("Invalid selector syntax");
3135
- }, sub() {
3136
- throw new Error("Invalid selector syntax");
3137
- }, mul() {
3138
- throw new Error("Invalid selector syntax");
3139
- }, div() {
3140
- throw new Error("Invalid selector syntax");
3141
- }, mod() {
3142
- throw new Error("Invalid selector syntax");
3143
- }, pow() {
3144
- throw new Error("Invalid selector syntax");
3145
- }, comp() {
3146
- throw new Error("Invalid selector syntax");
3147
- }, in_range() {
3148
- throw new Error("Invalid selector syntax");
3149
- }, str() {
3150
- throw new Error("Invalid selector syntax");
3151
- }, integer() {
3152
- throw new Error("Invalid selector syntax");
3153
- }, float() {
3154
- throw new Error("Invalid selector syntax");
3155
- }, sci() {
3156
- throw new Error("Invalid selector syntax");
3157
- }, object() {
3158
- throw new Error("Invalid selector syntax");
3159
- }, array() {
3160
- throw new Error("Invalid selector syntax");
3161
- }, tuple() {
3162
- throw new Error("Invalid selector syntax");
3163
- }, func_call(e3, t2) {
3164
- const r2 = me.func_call(e3, t2);
3165
- if (r2.name === "anywhere" && r2.args.length === 1) return null;
3166
- throw new Error("Invalid selector syntax");
3167
- }, pipecall() {
3168
- throw new Error("Invalid selector syntax");
3169
- }, pair() {
3170
- throw new Error("Invalid selector syntax");
3171
- }, and() {
3172
- throw new Error("Invalid selector syntax");
3173
- }, or() {
3174
- throw new Error("Invalid selector syntax");
3175
- }, not() {
3176
- throw new Error("Invalid selector syntax");
3177
- }, asc() {
3178
- throw new Error("Invalid selector syntax");
3179
- }, desc() {
3180
- throw new Error("Invalid selector syntax");
3181
- }, param() {
3182
- throw new Error("Invalid selector syntax");
3183
- } };
3184
- function ke(e3) {
3185
- if (e3.type === "AccessAttribute" && !e3.base) return e3.name;
3186
- if (e3.type === "PipeFuncCall" || e3.type === "Deref" || e3.type === "Map" || e3.type === "Projection" || e3.type === "Slice" || e3.type === "Filter" || e3.type === "AccessElement" || e3.type === "ArrayCoerce" || e3.type === "Group") return ke(e3.base);
3187
- throw new he(`Cannot determine property key for type: ${e3.type}`);
3188
- }
3189
- function ve(e3, t2, r2) {
3190
- if (typeof t2 == "number") {
3191
- if (r2 !== t2) throw new he(`Incorrect number of arguments to function ${e3}(). Expected ${t2}, got ${r2}.`);
3192
- } else if (t2 && !t2(r2)) throw new he(`Incorrect number of arguments to function ${e3}().`);
3193
- }
3194
- function xe(e3, t2, r2) {
3195
- return e3 == "diff" && r2 == 2 && ["changedAny", "changedOnly"].includes(t2);
3196
- }
3197
- class _e extends Error {
3198
- position;
3199
- name = "GroqSyntaxError";
3200
- constructor(e3) {
3201
- super(`Syntax error in GROQ query at position ${e3}`), this.position = e3;
3202
- }
3203
- }
3204
- function Ae(e3, t2 = {}) {
3205
- const r2 = function(e4) {
3206
- let t3 = 0;
3207
- t3 = se(e4, t3);
3208
- let r3 = re(e4, t3, 0);
3209
- return r3.type === "error" ? r3 : (t3 = se(e4, r3.position), t3 !== e4.length ? (r3.failPosition && (t3 = r3.failPosition - 1), { type: "error", position: t3 }) : (delete r3.position, delete r3.failPosition, r3));
3210
- }(e3);
3211
- if (r2.type === "error") throw new _e(r2.position);
3212
- return new K(e3, r2.marks, t2).process(me);
3213
- }
3214
1581
  class MultiKeyWeakMap {
3215
1582
  // The root of our nested WeakMap structure.
3216
1583
  #rootMap = /* @__PURE__ */ new WeakMap();
@@ -3233,7 +1600,7 @@ class MultiKeyWeakMap {
3233
1600
  */
3234
1601
  #arrangeKeys(keys) {
3235
1602
  const keyed = Array.from(new Set(keys)).map((key) => [this.#assignId(key), key]);
3236
- return keyed.sort((a2, b2) => a2[0] - b2[0]), keyed.map(([, key]) => key);
1603
+ return keyed.sort((a, b) => a[0] - b[0]), keyed.map(([, key]) => key);
3237
1604
  }
3238
1605
  /**
3239
1606
  * Recursively search the nested WeakMap structure for the value.
@@ -3287,8 +1654,8 @@ function createGrantsLookup(datasetAcl) {
3287
1654
  }
3288
1655
  return Object.fromEntries(
3289
1656
  Object.entries(filtersByGrant).map(([grant, filters]) => {
3290
- const combinedFilter = Array.from(filters).map((i2) => `(${i2})`).join("||");
3291
- return combinedFilter ? [grant, Ae(`$document {"_": ${combinedFilter}}._`)] : [grant, Ae("false")];
1657
+ const combinedFilter = Array.from(filters).map((i) => `(${i})`).join("||");
1658
+ return combinedFilter ? [grant, parse(`$document {"_": ${combinedFilter}}._`)] : [grant, parse("false")];
3292
1659
  })
3293
1660
  );
3294
1661
  }
@@ -3299,7 +1666,7 @@ const documentsCache = new MultiKeyWeakMap(), actionsCache = /* @__PURE__ */ new
3299
1666
  ],
3300
1667
  (documentStates, actions) => {
3301
1668
  const documentIds = new Set(
3302
- (Array.isArray(actions) ? actions : [actions]).map((i2) => i2.documentId).filter((i2) => typeof i2 == "string").flatMap((documentId) => [getPublishedId(documentId), getDraftId(documentId)])
1669
+ (Array.isArray(actions) ? actions : [actions]).map((i) => i.documentId).filter((i) => typeof i == "string").flatMap((documentId) => [getPublishedId(documentId), getDraftId(documentId)])
3303
1670
  ), documents = {};
3304
1671
  for (const documentId of documentIds) {
3305
1672
  const local = documentStates[documentId]?.local;
@@ -3327,7 +1694,8 @@ const documentsCache = new MultiKeyWeakMap(), actionsCache = /* @__PURE__ */ new
3327
1694
  }
3328
1695
  );
3329
1696
  function checkGrant$1(grantExpr, document2) {
3330
- return C(grantExpr, { params: { document: document2 } }).get();
1697
+ const value = evaluateSync(grantExpr, { params: { document: document2 } });
1698
+ return value.type === "boolean" && value.data;
3331
1699
  }
3332
1700
  const enNarrowConjunction = new Intl.ListFormat("en", { style: "narrow", type: "conjunction" });
3333
1701
  function calculatePermissions(...args) {
@@ -3382,16 +1750,17 @@ const _calculatePermissions = createSelector(
3382
1750
  }
3383
1751
  const allowed = reasons.length === 0;
3384
1752
  if (allowed) return { allowed };
3385
- const sortedReasons = reasons.map((reason, index) => ({ ...reason, index })).sort((a2, b2) => a2.type !== b2.type ? a2.type === "access" ? -1 : 1 : a2.message.localeCompare(b2.message, "en-US")).map(({ index: _index, ...reason }) => reason);
1753
+ const sortedReasons = reasons.map((reason, index) => ({ ...reason, index })).sort((a, b) => a.type !== b.type ? a.type === "access" ? -1 : 1 : a.message.localeCompare(b.message, "en-US")).map(({ index: _index, ...reason }) => reason);
3386
1754
  return {
3387
1755
  allowed,
3388
1756
  reasons: sortedReasons,
3389
- message: enNarrowConjunction.format(sortedReasons.map((i2) => i2.message))
1757
+ message: enNarrowConjunction.format(sortedReasons.map((i) => i.message))
3390
1758
  };
3391
1759
  }
3392
1760
  );
3393
1761
  function checkGrant(grantExpr, document2) {
3394
- return C(grantExpr, { params: { document: document2 } }).get();
1762
+ const value = evaluateSync(grantExpr, { params: { document: document2 } });
1763
+ return value.type === "boolean" && value.data;
3395
1764
  }
3396
1765
  class ActionError extends Error {
3397
1766
  documentId;
@@ -3652,7 +2021,7 @@ function strengthenOnPublish(draft) {
3652
2021
  ..._strengthenOnPublish.weak && { _weak: !0 }
3653
2022
  };
3654
2023
  }
3655
- return Array.isArray(value) ? value.map(strengthen) : Object.fromEntries(Object.entries(value).map(([k2, v2]) => [k2, strengthen(v2)]));
2024
+ return Array.isArray(value) ? value.map(strengthen) : Object.fromEntries(Object.entries(value).map(([k, v]) => [k, strengthen(v)]));
3656
2025
  }
3657
2026
  return strengthen(draft);
3658
2027
  }
@@ -3668,13 +2037,13 @@ function queueTransaction(prev, transaction) {
3668
2037
  };
3669
2038
  }
3670
2039
  function removeQueuedTransaction(prev, transactionId) {
3671
- const transaction = prev.queued.find((t2) => t2.transactionId === transactionId);
2040
+ const transaction = prev.queued.find((t) => t.transactionId === transactionId);
3672
2041
  return transaction ? {
3673
2042
  ...getDocumentIdsFromActions(transaction.actions).reduce(
3674
2043
  (acc, id) => removeSubscriptionIdFromDocument(acc, id, transactionId),
3675
2044
  prev
3676
2045
  ),
3677
- queued: prev.queued.filter((t2) => transactionId !== t2.transactionId)
2046
+ queued: prev.queued.filter((t) => transactionId !== t.transactionId)
3678
2047
  } : prev;
3679
2048
  }
3680
2049
  function applyFirstQueuedTransaction(prev) {
@@ -3697,7 +2066,7 @@ function applyFirstQueuedTransaction(prev) {
3697
2066
  return {
3698
2067
  ...prev,
3699
2068
  applied: [...prev.applied, applied],
3700
- queued: prev.queued.filter((t2) => t2.transactionId !== queued.transactionId),
2069
+ queued: prev.queued.filter((t) => t.transactionId !== queued.transactionId),
3701
2070
  documentStates: Object.entries(result.working).reduce(
3702
2071
  (acc, [id, next]) => {
3703
2072
  const prevDoc = acc[id];
@@ -3768,7 +2137,7 @@ function transitionAppliedTransactionsToOutgoing(prev) {
3768
2137
  return {
3769
2138
  ...prev,
3770
2139
  outgoing: transaction,
3771
- applied: prev.applied.filter((i2) => !consumedTransactions.includes(i2.transactionId)),
2140
+ applied: prev.applied.filter((i) => !consumedTransactions.includes(i.transactionId)),
3772
2141
  documentStates: Object.entries(previousRevs).reduce(
3773
2142
  (acc, [documentId, previousRev]) => {
3774
2143
  if (working[documentId]?._rev === previousRev) return acc;
@@ -3805,10 +2174,10 @@ function revertOutgoingTransaction(prev) {
3805
2174
  ])
3806
2175
  );
3807
2176
  const nextApplied = [];
3808
- for (const t2 of prev.applied)
2177
+ for (const t of prev.applied)
3809
2178
  try {
3810
- const next = processActions({ ...t2, working, grants: prev.grants });
3811
- working = next.working, nextApplied.push({ ...t2, ...next });
2179
+ const next = processActions({ ...t, working, grants: prev.grants });
2180
+ working = next.working, nextApplied.push({ ...t, ...next });
3812
2181
  } catch (error) {
3813
2182
  if (error instanceof ActionError) continue;
3814
2183
  throw error;
@@ -3818,7 +2187,7 @@ function revertOutgoingTransaction(prev) {
3818
2187
  applied: nextApplied,
3819
2188
  outgoing: void 0,
3820
2189
  documentStates: Object.fromEntries(
3821
- Object.entries(prev.documentStates).filter((e3) => !!e3[1]).map(([documentId, { unverifiedRevisions = {}, local, ...documentState }]) => {
2190
+ Object.entries(prev.documentStates).filter((e) => !!e[1]).map(([documentId, { unverifiedRevisions = {}, local, ...documentState }]) => {
3822
2191
  const next = {
3823
2192
  ...documentState,
3824
2193
  local: documentId in working ? working[documentId] : local,
@@ -3939,7 +2308,7 @@ function getDocumentIdsFromActions(action) {
3939
2308
  const actions = Array.isArray(action) ? action : [action];
3940
2309
  return Array.from(
3941
2310
  new Set(
3942
- actions.map((i2) => i2.documentId).filter((i2) => typeof i2 == "string").flatMap((documentId) => [getPublishedId$1(documentId), getDraftId(documentId)])
2311
+ actions.map((i) => i.documentId).filter((i) => typeof i == "string").flatMap((documentId) => [getPublishedId$1(documentId), getDraftId(documentId)])
3943
2312
  )
3944
2313
  );
3945
2314
  }
@@ -3993,7 +2362,7 @@ function createSharedListener(instance) {
3993
2362
  ),
3994
2363
  takeUntil(dispose$),
3995
2364
  share()
3996
- ), [welcome$, mutation$] = partition(events$, (e3) => e3.type === "welcome");
2365
+ ), [welcome$, mutation$] = partition(events$, (e) => e.type === "welcome");
3997
2366
  return {
3998
2367
  events: merge(
3999
2368
  // we replay the welcome event because that event kicks off fetching the document
@@ -4071,7 +2440,7 @@ const _resolveDocument = bindActionByDataset(
4071
2440
  getDocumentState(instance, {
4072
2441
  ...docHandle,
4073
2442
  path: void 0
4074
- }).observable.pipe(filter((i2) => i2 !== void 0))
2443
+ }).observable.pipe(filter((i) => i !== void 0))
4075
2444
  )
4076
2445
  ), getDocumentSyncStatus = bindActionByDataset(
4077
2446
  documentStore,
@@ -4094,7 +2463,7 @@ const _resolveDocument = bindActionByDataset(
4094
2463
  ), resolvePermissions = bindActionByDataset(
4095
2464
  documentStore,
4096
2465
  ({ instance }, actions) => firstValueFrom(
4097
- getPermissionsState(instance, actions).observable.pipe(filter((i2) => i2 !== void 0))
2466
+ getPermissionsState(instance, actions).observable.pipe(filter((i) => i !== void 0))
4098
2467
  )
4099
2468
  ), subscribeDocumentEvents = bindActionByDataset(
4100
2469
  documentStore,
@@ -4130,10 +2499,10 @@ const _resolveDocument = bindActionByDataset(
4130
2499
  const { events } = state.get();
4131
2500
  return state.observable.pipe(
4132
2501
  throttle(
4133
- (s2) => (
2502
+ (s) => (
4134
2503
  // if there is no outgoing transaction, we can throttle by the
4135
2504
  // initial outgoing throttle time…
4136
- s2.outgoing ? (
2505
+ s.outgoing ? (
4137
2506
  // …otherwise, wait until the outgoing has been cleared
4138
2507
  state.observable.pipe(first$1(({ outgoing }) => !outgoing))
4139
2508
  ) : timer(INITIAL_OUTGOING_THROTTLE_TIME)
@@ -4141,9 +2510,9 @@ const _resolveDocument = bindActionByDataset(
4141
2510
  { leading: !1, trailing: !0 }
4142
2511
  ),
4143
2512
  map(transitionAppliedTransactionsToOutgoing),
4144
- distinctUntilChanged((a2, b2) => a2.outgoing?.transactionId === b2.outgoing?.transactionId),
2513
+ distinctUntilChanged((a, b) => a.outgoing?.transactionId === b.outgoing?.transactionId),
4145
2514
  tap$1((next) => state.set("transitionAppliedTransactionsToOutgoing", next)),
4146
- map((s2) => s2.outgoing),
2515
+ map((s) => s.outgoing),
4147
2516
  distinctUntilChanged(),
4148
2517
  withLatestFrom(getClientState(instance, { apiVersion: API_VERSION$3 }).observable),
4149
2518
  concatMap(([outgoing, client]) => outgoing ? client.observable.action(outgoing.outgoingActions, {
@@ -4155,38 +2524,38 @@ const _resolveDocument = bindActionByDataset(
4155
2524
  ) : EMPTY),
4156
2525
  tap$1(({ outgoing, result }) => {
4157
2526
  state.set("cleanupOutgoingTransaction", cleanupOutgoingTransaction);
4158
- for (const e3 of getDocumentEvents(outgoing)) events.next(e3);
2527
+ for (const e of getDocumentEvents(outgoing)) events.next(e);
4159
2528
  events.next({ type: "accepted", outgoing, result });
4160
2529
  })
4161
2530
  ).subscribe({ error: (error) => state.set("setError", { error }) });
4162
2531
  }, subscribeToSubscriptionsAndListenToDocuments = (context) => {
4163
2532
  const { state } = context, { events } = state.get();
4164
2533
  return state.observable.pipe(
4165
- filter((s2) => !!s2.grants),
4166
- map((s2) => Object.keys(s2.documentStates)),
2534
+ filter((s) => !!s.grants),
2535
+ map((s) => Object.keys(s.documentStates)),
4167
2536
  distinctUntilChanged((curr, next) => {
4168
2537
  if (curr.length !== next.length) return !1;
4169
2538
  const currSet = new Set(curr);
4170
- return next.every((i2) => currSet.has(i2));
2539
+ return next.every((i) => currSet.has(i));
4171
2540
  }),
4172
2541
  startWith$1(/* @__PURE__ */ new Set()),
4173
2542
  pairwise$1(),
4174
2543
  switchMap((pair) => {
4175
- const [curr, next] = pair.map((ids) => new Set(ids)), added = Array.from(next).filter((i2) => !curr.has(i2)), removed = Array.from(curr).filter((i2) => !next.has(i2)), changes = [
2544
+ const [curr, next] = pair.map((ids) => new Set(ids)), added = Array.from(next).filter((i) => !curr.has(i)), removed = Array.from(curr).filter((i) => !next.has(i)), changes = [
4176
2545
  ...added.map((id) => ({ id, add: !0 })),
4177
2546
  ...removed.map((id) => ({ id, add: !1 }))
4178
- ].sort((a2, b2) => {
4179
- const aIsDraft = a2.id === getDraftId(a2.id), bIsDraft = b2.id === getDraftId(b2.id);
4180
- return aIsDraft && bIsDraft ? a2.id.localeCompare(b2.id, "en-US") : aIsDraft ? -1 : bIsDraft ? 1 : a2.id.localeCompare(b2.id, "en-US");
2547
+ ].sort((a, b) => {
2548
+ const aIsDraft = a.id === getDraftId(a.id), bIsDraft = b.id === getDraftId(b.id);
2549
+ return aIsDraft && bIsDraft ? a.id.localeCompare(b.id, "en-US") : aIsDraft ? -1 : bIsDraft ? 1 : a.id.localeCompare(b.id, "en-US");
4181
2550
  });
4182
2551
  return of(...changes);
4183
2552
  }),
4184
- groupBy$1((i2) => i2.id),
2553
+ groupBy$1((i) => i.id),
4185
2554
  mergeMap$1(
4186
2555
  (group) => group.pipe(
4187
- switchMap((e3) => e3.add ? listen$1(context, e3.id).pipe(
2556
+ switchMap((e) => e.add ? listen$1(context, e.id).pipe(
4188
2557
  catchError$1((error) => {
4189
- throw error instanceof OutOfSyncError && listen$1(context, e3.id), error;
2558
+ throw error instanceof OutOfSyncError && listen$1(context, e.id), error;
4190
2559
  }),
4191
2560
  tap$1(
4192
2561
  (remote) => state.set(
@@ -4250,23 +2619,23 @@ async function _applyDocumentActions({ instance, state }, actionOrActions, { tra
4250
2619
  actions,
4251
2620
  ...disableBatching && { disableBatching }
4252
2621
  }, fatalError$ = state.observable.pipe(
4253
- map((s2) => s2.error),
2622
+ map((s) => s.error),
4254
2623
  first$1(Boolean),
4255
2624
  map((error) => ({ type: "error", error }))
4256
2625
  ), transactionError$ = events.pipe(
4257
- filter((e3) => e3.type === "error"),
4258
- first$1((e3) => e3.transactionId === transactionId)
2626
+ filter((e) => e.type === "error"),
2627
+ first$1((e) => e.transactionId === transactionId)
4259
2628
  ), appliedTransaction$ = state.observable.pipe(
4260
- map((s2) => s2.applied),
2629
+ map((s) => s.applied),
4261
2630
  distinctUntilChanged(),
4262
- map((applied) => applied.find((t2) => t2.transactionId === transactionId)),
2631
+ map((applied) => applied.find((t) => t.transactionId === transactionId)),
4263
2632
  first$1(Boolean)
4264
2633
  ), successfulTransaction$ = events.pipe(
4265
- filter((e3) => e3.type === "accepted"),
4266
- first$1((e3) => e3.outgoing.batchedTransactionIds.includes(transactionId))
2634
+ filter((e) => e.type === "accepted"),
2635
+ first$1((e) => e.outgoing.batchedTransactionIds.includes(transactionId))
4267
2636
  ), rejectedTransaction$ = events.pipe(
4268
- filter((e3) => e3.type === "reverted"),
4269
- first$1((e3) => e3.outgoing.batchedTransactionIds.includes(transactionId))
2637
+ filter((e) => e.type === "reverted"),
2638
+ first$1((e) => e.outgoing.batchedTransactionIds.includes(transactionId))
4270
2639
  ), appliedTransactionOrError = firstValueFrom(
4271
2640
  race([fatalError$, transactionError$, appliedTransaction$])
4272
2641
  ), acceptedOrRejectedTransaction = firstValueFrom(
@@ -4380,22 +2749,22 @@ const favorites = createFetcherStore({
4380
2749
  return () => subscription.unsubscribe();
4381
2750
  }
4382
2751
  }, errorHandler$1 = (state) => (error) => state.set("setError", { error }), listenForLoadMoreAndFetch = ({ state, instance }) => state.observable.pipe(
4383
- map((s2) => new Set(Object.keys(s2.users))),
4384
- distinctUntilChanged((curr, next) => curr.size !== next.size ? !1 : Array.from(next).every((i2) => curr.has(i2))),
2752
+ map((s) => new Set(Object.keys(s.users))),
2753
+ distinctUntilChanged((curr, next) => curr.size !== next.size ? !1 : Array.from(next).every((i) => curr.has(i))),
4385
2754
  startWith$1(/* @__PURE__ */ new Set()),
4386
2755
  pairwise$1(),
4387
2756
  mergeMap$1(([curr, next]) => {
4388
- const added = Array.from(next).filter((i2) => !curr.has(i2)), removed = Array.from(curr).filter((i2) => !next.has(i2));
2757
+ const added = Array.from(next).filter((i) => !curr.has(i)), removed = Array.from(curr).filter((i) => !next.has(i));
4389
2758
  return [
4390
2759
  ...added.map((key) => ({ key, added: !0 })),
4391
2760
  ...removed.map((key) => ({ key, added: !1 }))
4392
2761
  ];
4393
2762
  }),
4394
- groupBy$1((i2) => i2.key),
2763
+ groupBy$1((i) => i.key),
4395
2764
  mergeMap$1(
4396
2765
  (group$) => group$.pipe(
4397
- switchMap((e3) => {
4398
- if (!e3.added) return EMPTY;
2766
+ switchMap((e) => {
2767
+ if (!e.added) return EMPTY;
4399
2768
  const { userId, batchSize, ...options } = parseUsersKey(group$.key);
4400
2769
  if (userId) {
4401
2770
  if (userId.startsWith("p"))
@@ -4453,15 +2822,15 @@ const favorites = createFetcherStore({
4453
2822
  ) : throwError(() => new Error("An organizationId or a projectId is required"));
4454
2823
  }
4455
2824
  const projectId = options.projectId, resourceType = options.resourceType ?? (options.organizationId ? "organization" : projectId ? "project" : "organization"), organizationId$ = options.organizationId ? of(options.organizationId) : getDashboardOrganizationId$1(instance).observable.pipe(
4456
- filter((i2) => typeof i2 == "string")
2825
+ filter((i) => typeof i == "string")
4457
2826
  ), resource$ = resourceType === "project" ? projectId ? of({ type: "project", id: projectId }) : throwError(() => new Error("Project ID required for this API.")) : organizationId$.pipe(map((id) => ({ type: "organization", id }))), client$ = getClientState(instance, {
4458
2827
  scope: "global",
4459
2828
  apiVersion: API_VERSION$1
4460
2829
  }).observable, loadMore$ = state.observable.pipe(
4461
- map((s2) => s2.users[group$.key]?.lastLoadMoreRequest),
2830
+ map((s) => s.users[group$.key]?.lastLoadMoreRequest),
4462
2831
  distinctUntilChanged()
4463
2832
  ), cursor$ = state.observable.pipe(
4464
- map((s2) => s2.users[group$.key]?.nextCursor),
2833
+ map((s) => s.users[group$.key]?.nextCursor),
4465
2834
  distinctUntilChanged(),
4466
2835
  filter((cursor) => cursor !== null)
4467
2836
  );
@@ -4524,7 +2893,7 @@ const favorites = createFetcherStore({
4524
2893
  state.set("initializeRequest", initializeRequest(key));
4525
2894
  const resolved$ = state.observable.pipe(
4526
2895
  map(getCurrent),
4527
- first$1((i2) => i2 !== void 0)
2896
+ first$1((i) => i !== void 0)
4528
2897
  );
4529
2898
  return firstValueFrom(race([resolved$, aborted$]));
4530
2899
  }
@@ -4538,7 +2907,7 @@ const favorites = createFetcherStore({
4538
2907
  throw new Error("No more users available to load for this resource.");
4539
2908
  const promise = firstValueFrom(
4540
2909
  users.observable.pipe(
4541
- filter((i2) => i2 !== void 0),
2910
+ filter((i) => i !== void 0),
4542
2911
  skip(1)
4543
2912
  )
4544
2913
  ), timestamp = (/* @__PURE__ */ new Date()).toISOString();
@@ -4548,7 +2917,7 @@ const favorites = createFetcherStore({
4548
2917
  usersStore,
4549
2918
  ({ instance }, { userId, ...options }) => getUsersState(instance, { userId, ...options }).observable.pipe(
4550
2919
  map((res) => res?.data[0]),
4551
- distinctUntilChanged((a2, b2) => a2?.profile.updatedAt === b2?.profile.updatedAt)
2920
+ distinctUntilChanged((a, b) => a?.profile.updatedAt === b?.profile.updatedAt)
4552
2921
  )
4553
2922
  ), resolveUser = bindActionGlobally(
4554
2923
  usersStore,
@@ -4659,9 +3028,9 @@ const handleIncomingMessage = (event) => {
4659
3028
  onSubscribe: (context) => {
4660
3029
  const subscription = context.state.observable.pipe(
4661
3030
  map(
4662
- (state) => Array.from(state.locations.values()).map((l2) => l2.userId).filter((id) => !!id)
3031
+ (state) => Array.from(state.locations.values()).map((l) => l.userId).filter((id) => !!id)
4663
3032
  ),
4664
- distinctUntilChanged((a2, b2) => a2.length === b2.length && a2.every((v2, i2) => v2 === b2[i2]))
3033
+ distinctUntilChanged((a, b) => a.length === b.length && a.every((v, i) => v === b[i]))
4665
3034
  ).pipe(
4666
3035
  switchMap((userIds) => {
4667
3036
  if (userIds.length === 0)
@@ -4671,7 +3040,7 @@ const handleIncomingMessage = (event) => {
4671
3040
  userId,
4672
3041
  resourceType: "project",
4673
3042
  projectId: context.instance.config.projectId
4674
- }).pipe(filter((v2) => !!v2))
3043
+ }).pipe(filter((v) => !!v))
4675
3044
  );
4676
3045
  return combineLatest(userObservables);
4677
3046
  })
@@ -4705,7 +3074,7 @@ function isWelcomeEvent(event) {
4705
3074
  }
4706
3075
  const listenQuery = (client, query, params = {}, options = {}) => {
4707
3076
  const fetchQuery = query, listenerQuery = query, fetchOnce$ = fetch(client, fetchQuery, params, options), events$ = listen(client, listenerQuery, params, options).pipe(
4708
- mergeMap((ev, i2) => i2 === 0 && !isWelcomeEvent(ev) ? throwError(
3077
+ mergeMap((ev, i) => i === 0 && !isWelcomeEvent(ev) ? throwError(
4709
3078
  () => new Error(
4710
3079
  ev.type === "reconnect" ? "Could not establish EventSource connection" : `Received unexpected type of first event "${ev.type}"`
4711
3080
  )
@@ -4722,21 +3091,21 @@ const listenQuery = (client, query, params = {}, options = {}) => {
4722
3091
  );
4723
3092
  };
4724
3093
  function sortReleases(releases = []) {
4725
- return [...releases].sort((a2, b2) => {
4726
- if (a2.metadata.releaseType === "undecided" && b2.metadata.releaseType !== "undecided")
3094
+ return [...releases].sort((a, b) => {
3095
+ if (a.metadata.releaseType === "undecided" && b.metadata.releaseType !== "undecided")
4727
3096
  return -1;
4728
- if (a2.metadata.releaseType !== "undecided" && b2.metadata.releaseType === "undecided")
3097
+ if (a.metadata.releaseType !== "undecided" && b.metadata.releaseType === "undecided")
4729
3098
  return 1;
4730
- if (a2.metadata.releaseType === "undecided" && b2.metadata.releaseType === "undecided")
4731
- return new Date(b2._createdAt).getTime() - new Date(a2._createdAt).getTime();
4732
- if (a2.metadata.releaseType === "scheduled" && b2.metadata.releaseType === "scheduled") {
4733
- const aPublishAt = a2.publishAt || a2.metadata.intendedPublishAt;
3099
+ if (a.metadata.releaseType === "undecided" && b.metadata.releaseType === "undecided")
3100
+ return new Date(b._createdAt).getTime() - new Date(a._createdAt).getTime();
3101
+ if (a.metadata.releaseType === "scheduled" && b.metadata.releaseType === "scheduled") {
3102
+ const aPublishAt = a.publishAt || a.metadata.intendedPublishAt;
4734
3103
  if (!aPublishAt)
4735
3104
  return 1;
4736
- const bPublishAt = b2.publishAt || b2.metadata.intendedPublishAt;
3105
+ const bPublishAt = b.publishAt || b.metadata.intendedPublishAt;
4737
3106
  return bPublishAt ? new Date(bPublishAt).getTime() - new Date(aPublishAt).getTime() : -1;
4738
3107
  }
4739
- return a2.metadata.releaseType === "asap" && b2.metadata.releaseType !== "asap" ? 1 : a2.metadata.releaseType !== "asap" && b2.metadata.releaseType === "asap" ? -1 : a2.metadata.releaseType === "asap" && b2.metadata.releaseType === "asap" ? new Date(b2._createdAt).getTime() - new Date(a2._createdAt).getTime() : 0;
3108
+ return a.metadata.releaseType === "asap" && b.metadata.releaseType !== "asap" ? 1 : a.metadata.releaseType !== "asap" && b.metadata.releaseType === "asap" ? -1 : a.metadata.releaseType === "asap" && b.metadata.releaseType === "asap" ? new Date(b._createdAt).getTime() - new Date(a._createdAt).getTime() : 0;
4740
3109
  });
4741
3110
  }
4742
3111
  const ARCHIVED_RELEASE_STATES = ["archived", "published"], releasesStore = {
@@ -4858,24 +3227,24 @@ const queryStore = {
4858
3227
  };
4859
3228
  }
4860
3229
  }, errorHandler = (state) => (error) => state.set("setError", { error }), listenForNewSubscribersAndFetch = ({ state, instance }) => state.observable.pipe(
4861
- map((s2) => new Set(Object.keys(s2.queries))),
4862
- distinctUntilChanged((curr, next) => curr.size !== next.size ? !1 : Array.from(next).every((i2) => curr.has(i2))),
3230
+ map((s) => new Set(Object.keys(s.queries))),
3231
+ distinctUntilChanged((curr, next) => curr.size !== next.size ? !1 : Array.from(next).every((i) => curr.has(i))),
4863
3232
  startWith$1(/* @__PURE__ */ new Set()),
4864
3233
  pairwise$1(),
4865
3234
  mergeMap$1(([curr, next]) => {
4866
- const added = Array.from(next).filter((i2) => !curr.has(i2)), removed = Array.from(curr).filter((i2) => !next.has(i2));
3235
+ const added = Array.from(next).filter((i) => !curr.has(i)), removed = Array.from(curr).filter((i) => !next.has(i));
4867
3236
  return [
4868
3237
  ...added.map((key) => ({ key, added: !0 })),
4869
3238
  ...removed.map((key) => ({ key, added: !1 }))
4870
3239
  ];
4871
3240
  }),
4872
- groupBy$1((i2) => i2.key),
3241
+ groupBy$1((i) => i.key),
4873
3242
  mergeMap$1(
4874
3243
  (group$) => group$.pipe(
4875
- switchMap((e3) => {
4876
- if (!e3.added) return EMPTY;
3244
+ switchMap((e) => {
3245
+ if (!e.added) return EMPTY;
4877
3246
  const lastLiveEventId$ = state.observable.pipe(
4878
- map((s2) => s2.queries[group$.key]?.lastLiveEventId),
3247
+ map((s) => s.queries[group$.key]?.lastLiveEventId),
4879
3248
  distinctUntilChanged()
4880
3249
  ), {
4881
3250
  query,
@@ -4919,18 +3288,26 @@ const queryStore = {
4919
3288
  apiVersion: QUERY_STORE_API_VERSION
4920
3289
  }).observable.pipe(
4921
3290
  switchMap(
4922
- (client) => client.live.events({ includeDrafts: !!client.config().token, tag: "query-store" })
3291
+ (client) => defer(
3292
+ () => client.live.events({ includeDrafts: !!client.config().token, tag: "query-store" })
3293
+ ).pipe(
3294
+ catchError$1((error) => {
3295
+ if (error instanceof CorsOriginError)
3296
+ return state.set("setError", { error }), EMPTY;
3297
+ throw error;
3298
+ })
3299
+ )
4923
3300
  ),
4924
3301
  share(),
4925
- filter((e3) => e3.type === "message")
3302
+ filter((e) => e.type === "message")
4926
3303
  );
4927
3304
  return state.observable.pipe(
4928
- mergeMap$1((s2) => Object.entries(s2.queries)),
3305
+ mergeMap$1((s) => Object.entries(s.queries)),
4929
3306
  groupBy$1(([key]) => key),
4930
3307
  mergeMap$1((group$) => {
4931
3308
  const syncTags$ = group$.pipe(
4932
3309
  map(([, queryState]) => queryState),
4933
- map((i2) => i2?.syncTags ?? EMPTY_ARRAY),
3310
+ map((i) => i?.syncTags ?? EMPTY_ARRAY),
4934
3311
  distinctUntilChanged()
4935
3312
  );
4936
3313
  return combineLatest([liveMessages$, syncTags$]).pipe(
@@ -4986,15 +3363,15 @@ const _resolveQuery = bindActionByDataset(
4986
3363
  state.set("initializeQuery", initializeQuery(key));
4987
3364
  const resolved$ = state.observable.pipe(
4988
3365
  map(getCurrent),
4989
- first$1((i2) => i2 !== void 0)
3366
+ first$1((i) => i !== void 0)
4990
3367
  );
4991
3368
  return firstValueFrom(race([resolved$, aborted$]));
4992
3369
  }
4993
3370
  );
4994
3371
  function hashString(str) {
4995
3372
  let hash = 0;
4996
- for (let i2 = 0; i2 < str.length; i2++)
4997
- hash = (hash * 31 + str.charCodeAt(i2)) % 2147483647;
3373
+ for (let i = 0; i < str.length; i++)
3374
+ hash = (hash * 31 + str.charCodeAt(i)) % 2147483647;
4998
3375
  return Math.abs(hash).toString(16).padStart(8, "0");
4999
3376
  }
5000
3377
  const TITLE_CANDIDATES = ["title", "name", "label", "heading", "header", "caption"], SUBTITLE_CANDIDATES = ["description", "subtitle", ...TITLE_CANDIDATES], PREVIEW_PROJECTION = `{
@@ -5076,8 +3453,8 @@ function processPreviewQuery({
5076
3453
  ...publishedResult?._updatedAt && { lastEditedPublishedAt: publishedResult._updatedAt }
5077
3454
  };
5078
3455
  return [id, { data: { ...preview, _status }, isPending: !1 }];
5079
- } catch (e3) {
5080
- return console.warn(e3), [id, STABLE_ERROR_PREVIEW];
3456
+ } catch (e) {
3457
+ return console.warn(e), [id, STABLE_ERROR_PREVIEW];
5081
3458
  }
5082
3459
  })
5083
3460
  );
@@ -5091,7 +3468,7 @@ function createPreviewQuery(documentIds) {
5091
3468
  }
5092
3469
  };
5093
3470
  }
5094
- const BATCH_DEBOUNCE_TIME$1 = 50, isSetEqual$1 = (a2, b2) => a2.size === b2.size && Array.from(a2).every((i2) => b2.has(i2)), subscribeToStateAndFetchBatches$1 = ({
3471
+ const BATCH_DEBOUNCE_TIME$1 = 50, isSetEqual$1 = (a, b) => a.size === b.size && Array.from(a).every((i) => b.has(i)), subscribeToStateAndFetchBatches$1 = ({
5095
3472
  state,
5096
3473
  instance
5097
3474
  }) => state.observable.pipe(
@@ -5191,14 +3568,24 @@ const _getPreviewState = bindActionByDataset(
5191
3568
  })
5192
3569
  ), resolvePreview = bindActionByDataset(
5193
3570
  previewStore,
5194
- ({ instance }, docHandle) => firstValueFrom(getPreviewState(instance, docHandle).observable.pipe(filter((i2) => !!i2.data)))
5195
- );
3571
+ ({ instance }, docHandle) => firstValueFrom(getPreviewState(instance, docHandle).observable.pipe(filter((i) => !!i.data)))
3572
+ ), PROJECTION_TAG = "projection", PROJECTION_PERSPECTIVE = "raw", PROJECTION_STATE_CLEAR_DELAY = 1e3, STABLE_EMPTY_PROJECTION = {
3573
+ data: null,
3574
+ isPending: !1
3575
+ };
3576
+ function validateProjection(projection) {
3577
+ if (!projection.startsWith("{") || !projection.endsWith("}"))
3578
+ throw new Error(
3579
+ `Invalid projection format: "${projection}". Projections must be enclosed in curly braces, e.g. "{title, 'author': author.name}"`
3580
+ );
3581
+ return projection;
3582
+ }
5196
3583
  function createProjectionQuery(documentIds, documentProjections) {
5197
3584
  const projections = Array.from(documentIds).flatMap((id) => {
5198
3585
  const projectionsForDoc = documentProjections[id];
5199
3586
  return projectionsForDoc ? Object.entries(projectionsForDoc).map(([projectionHash, projection]) => ({
5200
3587
  documentId: id,
5201
- projection,
3588
+ projection: validateProjection(projection),
5202
3589
  projectionHash
5203
3590
  })) : [];
5204
3591
  }).reduce((acc, { documentId, projection, projectionHash }) => {
@@ -5244,23 +3631,12 @@ function processProjectionQuery({ ids, results }) {
5244
3631
  }
5245
3632
  return finalValues;
5246
3633
  }
5247
- const PROJECTION_TAG = "projection", PROJECTION_PERSPECTIVE = "raw", PROJECTION_STATE_CLEAR_DELAY = 1e3, STABLE_EMPTY_PROJECTION = {
5248
- data: null,
5249
- isPending: !1
5250
- };
5251
- function validateProjection(projection) {
5252
- if (!projection.startsWith("{") || !projection.endsWith("}"))
5253
- throw new Error(
5254
- `Invalid projection format: "${projection}". Projections must be enclosed in curly braces, e.g. "{title, 'author': author.name}"`
5255
- );
5256
- return projection;
5257
- }
5258
- const BATCH_DEBOUNCE_TIME = 50, isSetEqual = (a2, b2) => a2.size === b2.size && Array.from(a2).every((i2) => b2.has(i2)), subscribeToStateAndFetchBatches = ({
3634
+ const BATCH_DEBOUNCE_TIME = 50, isSetEqual = (a, b) => a.size === b.size && Array.from(a).every((i) => b.has(i)), subscribeToStateAndFetchBatches = ({
5259
3635
  state,
5260
3636
  instance
5261
3637
  }) => {
5262
3638
  const documentProjections$ = state.observable.pipe(
5263
- map((s2) => s2.documentProjections),
3639
+ map((s) => s.documentProjections),
5264
3640
  distinctUntilChanged(isEqual)
5265
3641
  ), activeDocumentIds$ = state.observable.pipe(
5266
3642
  map(({ subscriptions }) => new Set(Object.keys(subscriptions))),
@@ -5521,7 +3897,12 @@ function validateFilter(filter2, index) {
5521
3897
  `${filterContext}: when using wildcard '*', it must be the only type in the array`
5522
3898
  );
5523
3899
  }
5524
- var version = "2.2.0";
3900
+ function getCorsErrorProjectId(error) {
3901
+ if (!(error instanceof CorsOriginError)) return null;
3902
+ const projMatch = (error.message || "").match(/manage\/project\/([^/?#]+)/);
3903
+ return projMatch ? projMatch[1] : null;
3904
+ }
3905
+ var version = "2.3.1";
5525
3906
  const CORE_SDK_VERSION = getEnv("PKG_VERSION") || `${version}-development`;
5526
3907
  export {
5527
3908
  AuthStateType,
@@ -5543,6 +3924,7 @@ export {
5543
3924
  getAuthState,
5544
3925
  getClient,
5545
3926
  getClientState,
3927
+ getCorsErrorProjectId,
5546
3928
  getCurrentUserState,
5547
3929
  getDashboardOrganizationId$1 as getDashboardOrganizationId,
5548
3930
  getDatasetsState,