@plasmicapp/data-sources 1.0.10 → 1.0.12

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.d.ts CHANGED
@@ -125,13 +125,20 @@ export declare interface FetcherProps extends DataOpConfig {
125
125
  queries?: Record<string, any>;
126
126
  }
127
127
 
128
+ export declare function isPlasmicUndefinedDataErrorPromise(x: any): x is PlasmicUndefinedDataErrorPromise;
129
+
128
130
  /** @deprecated See https://docs.plasmic.app/learn/integrations */
129
131
  export declare function makeCacheKey(dataOp: DataOp, opts?: {
130
132
  paginate?: Pagination;
131
133
  userAuthToken?: string | null;
132
134
  }): string;
133
135
 
134
- /** @internal Make a cache key for a query */
136
+ /**
137
+ * @internal Make a cache key for a query.
138
+ *
139
+ * Wrapped in `.$.` delimiters to match data op cache keys, so invalidation can match
140
+ * the id via `matchesQueryCacheKey` without colliding with other SWR cache keys.
141
+ */
135
142
  export declare function makeQueryCacheKey(id: string, params: any[]): string;
136
143
 
137
144
  /** @deprecated See https://docs.plasmic.app/learn/integrations */
@@ -142,6 +149,12 @@ export declare interface ManyRowsResult<T = any> {
142
149
  paginate?: Pagination;
143
150
  }
144
151
 
152
+ /**
153
+ * Returns whether `cacheKey` is invalidated by `invalidationKey`. Works for both server
154
+ * query cache keys (built by `makeQueryCacheKey`) and data op cache keys.
155
+ */
156
+ export declare function matchesQueryCacheKey(cacheKey: string, invalidationKey: string): boolean;
157
+
145
158
  /** @deprecated See https://docs.plasmic.app/learn/integrations */
146
159
  export declare function normalizeData(rawData: unknown): NormalizedData | undefined;
147
160
 
@@ -179,7 +192,7 @@ export declare interface PlasmicQueryResult<T = unknown> {
179
192
  isLoading: boolean;
180
193
  }
181
194
 
182
- declare interface PlasmicUndefinedDataErrorPromise extends Promise<any> {
195
+ export declare interface PlasmicUndefinedDataErrorPromise extends Promise<any> {
183
196
  plasmicType: "PlasmicUndefinedDataError";
184
197
  message: string;
185
198
  }
@@ -408,7 +421,10 @@ export declare function usePlasmicDataOp<T extends SingleRowResult | ManyRowsRes
408
421
  noUndefinedDataProxy?: boolean;
409
422
  }): ClientQueryResult<T["data"]>;
410
423
 
411
- /** @deprecated See https://docs.plasmic.app/learn/integrations */
424
+ /**
425
+ * Returns a function that invalidates cached query data. Accepts a list of invalidation keys
426
+ * or `plasmic_refresh_all` to invalidate everything.
427
+ */
412
428
  export declare function usePlasmicInvalidate(): (invalidatedKeys: string[] | null | undefined) => Promise<any[] | undefined>;
413
429
 
414
430
  export { }
package/dist/index.esm.js CHANGED
@@ -223,65 +223,93 @@ function usePlasmicFetch(key, resolvedParams, fetcherFn, resultMapper, undefined
223
223
  ]);
224
224
  }
225
225
 
226
- // src/serverQueries/client.ts
226
+ // src/hooks/usePlasmicDataOp.tsx
227
+ import { usePlasmicDataSourceContext } from "@plasmicapp/data-sources-context";
227
228
  import {
228
- useMutablePlasmicQueryData as useMutablePlasmicQueryData2,
229
- usePlasmicDataConfig as usePlasmicDataConfig2,
230
- wrapLoadingFetcher
229
+ usePlasmicDataConfig as usePlasmicDataConfig2
231
230
  } from "@plasmicapp/query";
232
- import * as React3 from "react";
231
+ import * as React2 from "react";
233
232
 
234
- // src/utils.ts
235
- function noopFn() {
233
+ // src/executor.tsx
234
+ import fetch from "@plasmicapp/isomorphic-unfetch";
235
+ import { wrapLoadingFetcher } from "@plasmicapp/query";
236
+ import stringify from "fast-stringify";
237
+
238
+ // src/placeholders.ts
239
+ var PLASMIC_UNDEFINED = "__PLASMIC_UNDEFINED";
240
+ function addPlaceholders(val) {
241
+ return val === void 0 ? PLASMIC_UNDEFINED : val;
236
242
  }
237
- function pick(obj, ...keys) {
238
- const res = {};
239
- for (const key of keys) {
240
- if (key in obj) {
241
- res[key] = obj[key];
242
- }
243
+ function addPlaceholdersToUserArgs(userArgs) {
244
+ if (!userArgs) {
245
+ return userArgs;
243
246
  }
244
- return res;
245
- }
246
- var tuple = (...args) => args;
247
- function mkIdMap(xs) {
248
- return new Map(xs.map((x) => tuple(x.id, x)));
249
- }
250
- function notNil(x) {
251
- return x !== null && x !== void 0;
252
- }
253
- function withoutNils(xs) {
254
- return xs.filter(notNil);
247
+ Object.entries(userArgs).forEach(([key, val]) => {
248
+ userArgs[key] = Array.isArray(val) ? val.map((v) => addPlaceholders(v)) : addPlaceholders(val);
249
+ });
250
+ return userArgs;
255
251
  }
256
- function mapRecordEntries(callback, record1, record2, record3) {
257
- return Object.entries(record1).map(([k, v1]) => {
258
- const v2 = record2 == null ? void 0 : record2[k];
259
- const v3 = record3 == null ? void 0 : record3[k];
260
- return callback(
261
- k,
262
- v1,
263
- v2,
264
- v3
252
+
253
+ // src/executor.tsx
254
+ var DEFAULT_HOST = "https://data.plasmic.app";
255
+ var UNAUTHORIZED_MESSAGE = "You do not have permission to perform this operation. Login to get access or contact the app owner to get access.";
256
+ function executePlasmicDataOp(op, opts) {
257
+ return __async(this, null, function* () {
258
+ const func = getConfig(
259
+ "__PLASMIC_EXECUTE_DATA_OP",
260
+ _executePlasmicDataOp
265
261
  );
262
+ op.userArgs = addPlaceholdersToUserArgs(op.userArgs);
263
+ const res = yield wrapLoadingFetcher(func)(op, opts);
264
+ return res;
266
265
  });
267
266
  }
268
- function mapRecords(callback, record1, record2, record3) {
269
- return Object.fromEntries(
270
- mapRecordEntries(
271
- (k, v1, v2, v3) => [k, callback(k, v1, v2, v3)],
272
- record1,
273
- record2,
274
- record3
275
- )
276
- );
267
+ function _executePlasmicDataOp(op, opts) {
268
+ return __async(this, null, function* () {
269
+ var _a;
270
+ if (op.roleId) {
271
+ if (!(opts == null ? void 0 : opts.user) || !opts.user.roleIds.includes(op.roleId)) {
272
+ console.error(UNAUTHORIZED_MESSAGE);
273
+ throw new Error(UNAUTHORIZED_MESSAGE);
274
+ }
275
+ }
276
+ const host = getConfig("__PLASMIC_DATA_HOST", DEFAULT_HOST);
277
+ const url = `${host}/api/v1/server-data/sources/${op.sourceId}/execute`;
278
+ const resp = yield fetch(url, {
279
+ method: "POST",
280
+ headers: __spreadValues({
281
+ "Content-Type": "application/json"
282
+ }, (opts == null ? void 0 : opts.userAuthToken) && {
283
+ "x-plasmic-data-user-auth-token": opts.userAuthToken
284
+ }),
285
+ body: stringify({
286
+ opId: op.opId,
287
+ userArgs: (_a = op.userArgs) != null ? _a : {},
288
+ paginate: opts == null ? void 0 : opts.paginate
289
+ })
290
+ });
291
+ if (resp.status !== 200) {
292
+ const text = yield resp.text();
293
+ throw new Error(text);
294
+ }
295
+ return yield resp.json();
296
+ });
297
+ }
298
+ function getConfig(key, defaultValue) {
299
+ var _a;
300
+ if (typeof globalThis === "undefined") {
301
+ return defaultValue;
302
+ } else {
303
+ return (_a = globalThis[key]) != null ? _a : defaultValue;
304
+ }
277
305
  }
278
-
279
- // src/serverQueries/common.ts
280
- import React2 from "react";
281
306
 
282
307
  // src/serverQueries/makeQueryCacheKey.ts
283
308
  function makeQueryCacheKey(id, params) {
284
- return `${id}:${safeStableStringify(params)}`;
309
+ return `$q.$.${id}.$.${safeStableStringify(params)}`;
310
+ }
311
+ function matchesQueryCacheKey(cacheKey, invalidationKey) {
312
+ return cacheKey.includes(`.$.${invalidationKey}.$.`);
285
313
  }
286
314
  var shortPlasmicPrefix = "\u03C1";
287
315
  function safeStableStringify(unstableValue) {
@@ -341,7 +369,198 @@ function sortObjectsDeep(value, visitedObjects) {
341
369
  }
342
370
  }
343
371
 
372
+ // src/utils.ts
373
+ function noopFn() {
374
+ }
375
+ function pick(obj, ...keys) {
376
+ const res = {};
377
+ for (const key of keys) {
378
+ if (key in obj) {
379
+ res[key] = obj[key];
380
+ }
381
+ }
382
+ return res;
383
+ }
384
+ var tuple = (...args) => args;
385
+ function mkIdMap(xs) {
386
+ return new Map(xs.map((x) => tuple(x.id, x)));
387
+ }
388
+ function notNil(x) {
389
+ return x !== null && x !== void 0;
390
+ }
391
+ function withoutNils(xs) {
392
+ return xs.filter(notNil);
393
+ }
394
+ function mapRecordEntries(callback, record1, record2, record3) {
395
+ return Object.entries(record1).map(([k, v1]) => {
396
+ const v2 = record2 == null ? void 0 : record2[k];
397
+ const v3 = record3 == null ? void 0 : record3[k];
398
+ return callback(
399
+ k,
400
+ v1,
401
+ v2,
402
+ v3
403
+ );
404
+ });
405
+ }
406
+ function mapRecords(callback, record1, record2, record3) {
407
+ return Object.fromEntries(
408
+ mapRecordEntries(
409
+ (k, v1, v2, v3) => [k, callback(k, v1, v2, v3)],
410
+ record1,
411
+ record2,
412
+ record3
413
+ )
414
+ );
415
+ }
416
+
417
+ // src/hooks/usePlasmicDataOp.tsx
418
+ function makeCacheKey(dataOp, opts) {
419
+ const queryDependencies = JSON.stringify({
420
+ sourceId: dataOp.sourceId,
421
+ opId: dataOp.opId,
422
+ args: dataOp.userArgs,
423
+ userAuthToken: opts == null ? void 0 : opts.userAuthToken,
424
+ paginate: opts == null ? void 0 : opts.paginate
425
+ });
426
+ return dataOp.cacheKey ? `${dataOp.cacheKey}${queryDependencies}` : queryDependencies;
427
+ }
428
+ function usePlasmicInvalidate() {
429
+ const { cache, fallback, mutate } = usePlasmicDataConfig2();
430
+ return (invalidatedKeys) => __async(null, null, function* () {
431
+ const getKeysToInvalidate = () => {
432
+ var _a, _b;
433
+ if (!invalidatedKeys) {
434
+ return [];
435
+ }
436
+ const allKeys = Array.from(
437
+ /* @__PURE__ */ new Set([
438
+ ...Array.from(cache.keys()),
439
+ ...fallback ? Object.keys(fallback) : [],
440
+ // If this is running within the Studio, we also take the
441
+ // opportunity to invalidate the Studio cache. The keys that
442
+ // Studio may have can be a superset of `cache` here, because
443
+ // `cache` is updated as swr hooks are mounted and unmounted,
444
+ // but Studio's data cache keys don't get removed when hooks
445
+ // are unmounted. This makes it possible for Studio to hold
446
+ // onto a stale cache entry that doesn't get invalidated.
447
+ // For example, Studio may render page1, with key X, then goes
448
+ // to page 2, which performs a mutate. At this point, Studio
449
+ // has a cache entry for key X, but `cache` does not, because
450
+ // page2 does not use that query. But page 2 may perform a
451
+ // mutation that invalidates X. So we need to invalidate not
452
+ // only keys in `cache`, but also keys that Studio is still
453
+ // holding onto.
454
+ ...(_b = (_a = globalThis.__PLASMIC_GET_ALL_CACHE_KEYS) == null ? void 0 : _a.call(globalThis)) != null ? _b : []
455
+ ])
456
+ ).filter((key) => typeof key === "string");
457
+ if (invalidatedKeys.includes("plasmic_refresh_all")) {
458
+ return allKeys;
459
+ }
460
+ return allKeys.filter(
461
+ (key) => invalidatedKeys.some((k) => matchesQueryCacheKey(key, k))
462
+ );
463
+ };
464
+ const keys = getKeysToInvalidate();
465
+ if (keys.length === 0) {
466
+ return;
467
+ }
468
+ const invalidateKey = (key) => __async(null, null, function* () {
469
+ const studioInvalidate = globalThis.__PLASMIC_MUTATE_DATA_OP;
470
+ if (studioInvalidate) {
471
+ yield studioInvalidate(key);
472
+ }
473
+ return mutate(key);
474
+ });
475
+ return yield Promise.all(keys.map((key) => invalidateKey(key)));
476
+ });
477
+ }
478
+ function resolveDataOp(dataOp) {
479
+ if (typeof dataOp === "function") {
480
+ try {
481
+ return dataOp();
482
+ } catch (err) {
483
+ if (isPlasmicUndefinedDataErrorPromise(err)) {
484
+ return err;
485
+ }
486
+ return null;
487
+ }
488
+ } else {
489
+ return dataOp;
490
+ }
491
+ }
492
+ function usePlasmicDataOp(dataOp, opts) {
493
+ const resolvedDataOp = resolveDataOp(dataOp);
494
+ const ctx = usePlasmicDataSourceContext();
495
+ const key = !resolvedDataOp || isPlasmicUndefinedDataErrorPromise(resolvedDataOp) ? null : makeCacheKey(resolvedDataOp, {
496
+ paginate: opts == null ? void 0 : opts.paginate,
497
+ userAuthToken: ctx == null ? void 0 : ctx.userAuthToken
498
+ });
499
+ const fetcher = (op) => {
500
+ return executePlasmicDataOp(op, {
501
+ userAuthToken: (ctx == null ? void 0 : ctx.userAuthToken) || void 0,
502
+ user: ctx == null ? void 0 : ctx.user,
503
+ paginate: opts == null ? void 0 : opts.paginate
504
+ });
505
+ };
506
+ const resultMapper = (result) => {
507
+ var _a;
508
+ return __spreadValues(__spreadValues({}, (_a = result.data) != null ? _a : {}), pick(result, "error", "isLoading"));
509
+ };
510
+ return usePlasmicFetch(
511
+ key,
512
+ resolvedDataOp,
513
+ fetcher,
514
+ resultMapper,
515
+ ["data", "schema", "error"],
516
+ {
517
+ noUndefinedDataProxy: opts == null ? void 0 : opts.noUndefinedDataProxy
518
+ }
519
+ );
520
+ }
521
+ function usePlasmicDataMutationOp(dataOp) {
522
+ const ctx = usePlasmicDataSourceContext();
523
+ const userToken = ctx == null ? void 0 : ctx.userAuthToken;
524
+ const getRealDataOp = React2.useCallback(() => __async(null, null, function* () {
525
+ const tryGetRealDataOp = () => __async(null, null, function* () {
526
+ const resolved = resolveDataOp(dataOp);
527
+ if (!resolved) {
528
+ return null;
529
+ } else if (isPlasmicUndefinedDataErrorPromise(resolved)) {
530
+ yield resolved;
531
+ return tryGetRealDataOp();
532
+ } else {
533
+ return resolved;
534
+ }
535
+ });
536
+ return yield tryGetRealDataOp();
537
+ }), [dataOp]);
538
+ return React2.useCallback(() => __async(null, null, function* () {
539
+ var _a;
540
+ const { sourceId, opId, userArgs } = (_a = yield getRealDataOp()) != null ? _a : {};
541
+ if (!sourceId || !opId) {
542
+ return void 0;
543
+ }
544
+ return executePlasmicDataOp(
545
+ { sourceId, opId, userArgs },
546
+ {
547
+ userAuthToken: userToken || void 0,
548
+ user: ctx == null ? void 0 : ctx.user
549
+ }
550
+ );
551
+ }), [getRealDataOp, userToken]);
552
+ }
553
+
554
+ // src/serverQueries/client.ts
555
+ import {
556
+ useMutablePlasmicQueryData as useMutablePlasmicQueryData3,
557
+ usePlasmicDataConfig as usePlasmicDataConfig3,
558
+ wrapLoadingFetcher as wrapLoadingFetcher2
559
+ } from "@plasmicapp/query";
560
+ import * as React4 from "react";
561
+
344
562
  // src/serverQueries/common.ts
563
+ import React3 from "react";
345
564
  function createDollarQueries(queryNames) {
346
565
  return Object.fromEntries(
347
566
  queryNames.map((queryName) => {
@@ -581,7 +800,7 @@ var SettablePromise = class {
581
800
  }
582
801
  };
583
802
  function usePrevious(value) {
584
- const ref = React2.useRef(void 0);
803
+ const ref = React3.useRef(void 0);
585
804
  const prev = ref.current;
586
805
  ref.current = value;
587
806
  return prev;
@@ -637,8 +856,8 @@ function createInitial$State($ctx, $props, $q, stateSpecs) {
637
856
  var GLOBAL_CACHE = /* @__PURE__ */ new Map();
638
857
  function usePlasmicQueries(tree, $ctx, $props, $state) {
639
858
  var _a;
640
- const wrappedQueries = React3.useMemo(() => wrapQueries(tree.queries), [tree]);
641
- const $queries = React3.useMemo(
859
+ const wrappedQueries = React4.useMemo(() => wrapQueries(tree.queries), [tree]);
860
+ const $queries = React4.useMemo(
642
861
  () => createDollarQueries(Object.keys(tree.queries)),
643
862
  [tree]
644
863
  );
@@ -646,7 +865,7 @@ function usePlasmicQueries(tree, $ctx, $props, $state) {
646
865
  if (!$state) {
647
866
  $state = createInitial$State($ctx, $props, $queryStates, tree.stateSpecs);
648
867
  }
649
- const { fallback: prefetchedCache, cache: swrCache } = usePlasmicDataConfig2();
868
+ const { fallback: prefetchedCache, cache: swrCache } = usePlasmicDataConfig3();
650
869
  const paramsResults = {};
651
870
  const executionCtx = {
652
871
  $ctx,
@@ -685,7 +904,7 @@ function usePlasmicQueries(tree, $ctx, $props, $state) {
685
904
  delete paramsResults[k];
686
905
  }
687
906
  }
688
- const stopRef = React3.useRef();
907
+ const stopRef = React4.useRef();
689
908
  (_a = stopRef.current) == null ? void 0 : _a.call(stopRef);
690
909
  let stopped = false;
691
910
  const stop = new Promise((resolve) => {
@@ -694,7 +913,7 @@ function usePlasmicQueries(tree, $ctx, $props, $state) {
694
913
  resolve();
695
914
  };
696
915
  });
697
- React3.useEffect(() => () => {
916
+ React4.useEffect(() => () => {
698
917
  var _a2;
699
918
  return (_a2 = stopRef.current) == null ? void 0 : _a2.call(stopRef);
700
919
  }, []);
@@ -742,7 +961,7 @@ function wrapQueries(queries) {
742
961
  if (cached) {
743
962
  return cached.promise;
744
963
  }
745
- const promise = wrapLoadingFetcher(query.fn)(...args);
964
+ const promise = wrapLoadingFetcher2(query.fn)(...args);
746
965
  GLOBAL_CACHE.set(cacheKey, new SyncPromise(promise));
747
966
  return promise;
748
967
  };
@@ -811,7 +1030,7 @@ function initPlasmicQueriesSync($queries, queries, paramsResults, executionCtx,
811
1030
  }
812
1031
  function usePlasmicQuery($query, query, paramsResult) {
813
1032
  const $queryState = $query;
814
- const { key, fetcher } = React3.useMemo(() => {
1033
+ const { key, fetcher } = React4.useMemo(() => {
815
1034
  switch (paramsResult.status) {
816
1035
  case "blocked":
817
1036
  case "error": {
@@ -858,7 +1077,7 @@ function usePlasmicQuery($query, query, paramsResult) {
858
1077
  }
859
1078
  }
860
1079
  }, [query, paramsResult]);
861
- const result = useMutablePlasmicQueryData2(key, fetcher, {
1080
+ const result = useMutablePlasmicQueryData3(key, fetcher, {
862
1081
  // If revalidateIfStale is true, then if there's a cache entry with a key,
863
1082
  // but no mounted hook with that key yet, and when the hook mounts with the key,
864
1083
  // swr will revalidate. This may be reasonable behavior, but for us, this
@@ -1166,226 +1385,6 @@ import { usePlasmicDataConfig as usePlasmicDataConfig4 } from "@plasmicapp/query
1166
1385
 
1167
1386
  // src/components/Fetcher.tsx
1168
1387
  import React5 from "react";
1169
-
1170
- // src/hooks/usePlasmicDataOp.tsx
1171
- import { usePlasmicDataSourceContext } from "@plasmicapp/data-sources-context";
1172
- import {
1173
- usePlasmicDataConfig as usePlasmicDataConfig3
1174
- } from "@plasmicapp/query";
1175
- import * as React4 from "react";
1176
-
1177
- // src/executor.tsx
1178
- import fetch from "@plasmicapp/isomorphic-unfetch";
1179
- import { wrapLoadingFetcher as wrapLoadingFetcher2 } from "@plasmicapp/query";
1180
- import stringify from "fast-stringify";
1181
-
1182
- // src/placeholders.ts
1183
- var PLASMIC_UNDEFINED = "__PLASMIC_UNDEFINED";
1184
- function addPlaceholders(val) {
1185
- return val === void 0 ? PLASMIC_UNDEFINED : val;
1186
- }
1187
- function addPlaceholdersToUserArgs(userArgs) {
1188
- if (!userArgs) {
1189
- return userArgs;
1190
- }
1191
- Object.entries(userArgs).forEach(([key, val]) => {
1192
- userArgs[key] = Array.isArray(val) ? val.map((v) => addPlaceholders(v)) : addPlaceholders(val);
1193
- });
1194
- return userArgs;
1195
- }
1196
-
1197
- // src/executor.tsx
1198
- var DEFAULT_HOST = "https://data.plasmic.app";
1199
- var UNAUTHORIZED_MESSAGE = "You do not have permission to perform this operation. Login to get access or contact the app owner to get access.";
1200
- function executePlasmicDataOp(op, opts) {
1201
- return __async(this, null, function* () {
1202
- const func = getConfig(
1203
- "__PLASMIC_EXECUTE_DATA_OP",
1204
- _executePlasmicDataOp
1205
- );
1206
- op.userArgs = addPlaceholdersToUserArgs(op.userArgs);
1207
- const res = yield wrapLoadingFetcher2(func)(op, opts);
1208
- return res;
1209
- });
1210
- }
1211
- function _executePlasmicDataOp(op, opts) {
1212
- return __async(this, null, function* () {
1213
- var _a;
1214
- if (op.roleId) {
1215
- if (!(opts == null ? void 0 : opts.user) || !opts.user.roleIds.includes(op.roleId)) {
1216
- console.error(UNAUTHORIZED_MESSAGE);
1217
- throw new Error(UNAUTHORIZED_MESSAGE);
1218
- }
1219
- }
1220
- const host = getConfig("__PLASMIC_DATA_HOST", DEFAULT_HOST);
1221
- const url = `${host}/api/v1/server-data/sources/${op.sourceId}/execute`;
1222
- const resp = yield fetch(url, {
1223
- method: "POST",
1224
- headers: __spreadValues({
1225
- "Content-Type": "application/json"
1226
- }, (opts == null ? void 0 : opts.userAuthToken) && {
1227
- "x-plasmic-data-user-auth-token": opts.userAuthToken
1228
- }),
1229
- body: stringify({
1230
- opId: op.opId,
1231
- userArgs: (_a = op.userArgs) != null ? _a : {},
1232
- paginate: opts == null ? void 0 : opts.paginate
1233
- })
1234
- });
1235
- if (resp.status !== 200) {
1236
- const text = yield resp.text();
1237
- throw new Error(text);
1238
- }
1239
- return yield resp.json();
1240
- });
1241
- }
1242
- function getConfig(key, defaultValue) {
1243
- var _a;
1244
- if (typeof globalThis === "undefined") {
1245
- return defaultValue;
1246
- } else {
1247
- return (_a = globalThis[key]) != null ? _a : defaultValue;
1248
- }
1249
- }
1250
-
1251
- // src/hooks/usePlasmicDataOp.tsx
1252
- function makeCacheKey(dataOp, opts) {
1253
- const queryDependencies = JSON.stringify({
1254
- sourceId: dataOp.sourceId,
1255
- opId: dataOp.opId,
1256
- args: dataOp.userArgs,
1257
- userAuthToken: opts == null ? void 0 : opts.userAuthToken,
1258
- paginate: opts == null ? void 0 : opts.paginate
1259
- });
1260
- return dataOp.cacheKey ? `${dataOp.cacheKey}${queryDependencies}` : queryDependencies;
1261
- }
1262
- function usePlasmicInvalidate() {
1263
- const { cache, fallback, mutate } = usePlasmicDataConfig3();
1264
- return (invalidatedKeys) => __async(null, null, function* () {
1265
- const getKeysToInvalidate = () => {
1266
- var _a, _b;
1267
- if (!invalidatedKeys) {
1268
- return [];
1269
- }
1270
- const allKeys = Array.from(
1271
- /* @__PURE__ */ new Set([
1272
- ...Array.from(cache.keys()),
1273
- ...fallback ? Object.keys(fallback) : [],
1274
- // If this is running within the Studio, we also take the
1275
- // opportunity to invalidate the Studio cache. The keys that
1276
- // Studio may have can be a superset of `cache` here, because
1277
- // `cache` is updated as swr hooks are mounted and unmounted,
1278
- // but Studio's data cache keys don't get removed when hooks
1279
- // are unmounted. This makes it possible for Studio to hold
1280
- // onto a stale cache entry that doesn't get invalidated.
1281
- // For example, Studio may render page1, with key X, then goes
1282
- // to page 2, which performs a mutate. At this point, Studio
1283
- // has a cache entry for key X, but `cache` does not, because
1284
- // page2 does not use that query. But page 2 may perform a
1285
- // mutation that invalidates X. So we need to invalidate not
1286
- // only keys in `cache`, but also keys that Studio is still
1287
- // holding onto.
1288
- ...(_b = (_a = globalThis.__PLASMIC_GET_ALL_CACHE_KEYS) == null ? void 0 : _a.call(globalThis)) != null ? _b : []
1289
- ])
1290
- ).filter((key) => typeof key === "string");
1291
- if (invalidatedKeys.includes("plasmic_refresh_all")) {
1292
- return allKeys;
1293
- }
1294
- return allKeys.filter(
1295
- (key) => invalidatedKeys.some((k) => key.includes(`.$.${k}.$.`))
1296
- );
1297
- };
1298
- const keys = getKeysToInvalidate();
1299
- if (keys.length === 0) {
1300
- return;
1301
- }
1302
- const invalidateKey = (key) => __async(null, null, function* () {
1303
- const studioInvalidate = globalThis.__PLASMIC_MUTATE_DATA_OP;
1304
- if (studioInvalidate) {
1305
- yield studioInvalidate(key);
1306
- }
1307
- return mutate(key);
1308
- });
1309
- return yield Promise.all(keys.map((key) => invalidateKey(key)));
1310
- });
1311
- }
1312
- function resolveDataOp(dataOp) {
1313
- if (typeof dataOp === "function") {
1314
- try {
1315
- return dataOp();
1316
- } catch (err) {
1317
- if (isPlasmicUndefinedDataErrorPromise(err)) {
1318
- return err;
1319
- }
1320
- return null;
1321
- }
1322
- } else {
1323
- return dataOp;
1324
- }
1325
- }
1326
- function usePlasmicDataOp(dataOp, opts) {
1327
- const resolvedDataOp = resolveDataOp(dataOp);
1328
- const ctx = usePlasmicDataSourceContext();
1329
- const key = !resolvedDataOp || isPlasmicUndefinedDataErrorPromise(resolvedDataOp) ? null : makeCacheKey(resolvedDataOp, {
1330
- paginate: opts == null ? void 0 : opts.paginate,
1331
- userAuthToken: ctx == null ? void 0 : ctx.userAuthToken
1332
- });
1333
- const fetcher = (op) => {
1334
- return executePlasmicDataOp(op, {
1335
- userAuthToken: (ctx == null ? void 0 : ctx.userAuthToken) || void 0,
1336
- user: ctx == null ? void 0 : ctx.user,
1337
- paginate: opts == null ? void 0 : opts.paginate
1338
- });
1339
- };
1340
- const resultMapper = (result) => {
1341
- var _a;
1342
- return __spreadValues(__spreadValues({}, (_a = result.data) != null ? _a : {}), pick(result, "error", "isLoading"));
1343
- };
1344
- return usePlasmicFetch(
1345
- key,
1346
- resolvedDataOp,
1347
- fetcher,
1348
- resultMapper,
1349
- ["data", "schema", "error"],
1350
- {
1351
- noUndefinedDataProxy: opts == null ? void 0 : opts.noUndefinedDataProxy
1352
- }
1353
- );
1354
- }
1355
- function usePlasmicDataMutationOp(dataOp) {
1356
- const ctx = usePlasmicDataSourceContext();
1357
- const userToken = ctx == null ? void 0 : ctx.userAuthToken;
1358
- const getRealDataOp = React4.useCallback(() => __async(null, null, function* () {
1359
- const tryGetRealDataOp = () => __async(null, null, function* () {
1360
- const resolved = resolveDataOp(dataOp);
1361
- if (!resolved) {
1362
- return null;
1363
- } else if (isPlasmicUndefinedDataErrorPromise(resolved)) {
1364
- yield resolved;
1365
- return tryGetRealDataOp();
1366
- } else {
1367
- return resolved;
1368
- }
1369
- });
1370
- return yield tryGetRealDataOp();
1371
- }), [dataOp]);
1372
- return React4.useCallback(() => __async(null, null, function* () {
1373
- var _a;
1374
- const { sourceId, opId, userArgs } = (_a = yield getRealDataOp()) != null ? _a : {};
1375
- if (!sourceId || !opId) {
1376
- return void 0;
1377
- }
1378
- return executePlasmicDataOp(
1379
- { sourceId, opId, userArgs },
1380
- {
1381
- userAuthToken: userToken || void 0,
1382
- user: ctx == null ? void 0 : ctx.user
1383
- }
1384
- );
1385
- }), [getRealDataOp, userToken]);
1386
- }
1387
-
1388
- // src/components/Fetcher.tsx
1389
1388
  function Fetcher(props) {
1390
1389
  var _a;
1391
1390
  const { dataOp, children, name, pageIndex, pageSize } = props;
@@ -1550,8 +1549,10 @@ export {
1550
1549
  deriveFieldConfigs,
1551
1550
  executePlasmicDataOp,
1552
1551
  executeServerQuery,
1552
+ isPlasmicUndefinedDataErrorPromise,
1553
1553
  makeCacheKey,
1554
1554
  makeQueryCacheKey,
1555
+ matchesQueryCacheKey,
1555
1556
  normalizeData,
1556
1557
  throwIfPlasmicUndefinedDataError,
1557
1558
  executePlasmicQueries as unstable_executePlasmicQueries,