@zenstackhq/swr 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/runtime/index.js CHANGED
@@ -1,352 +1,370 @@
1
1
  "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __defProps = Object.defineProperties;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
7
+ var __getOwnPropNames = Object.getOwnPropertyNames;
8
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
9
+ var __getProtoOf = Object.getPrototypeOf;
10
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
11
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
12
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
+ var __spreadValues = (a, b) => {
14
+ for (var prop in b || (b = {}))
15
+ if (__hasOwnProp.call(b, prop))
16
+ __defNormalProp(a, prop, b[prop]);
17
+ if (__getOwnPropSymbols)
18
+ for (var prop of __getOwnPropSymbols(b)) {
19
+ if (__propIsEnum.call(b, prop))
20
+ __defNormalProp(a, prop, b[prop]);
7
21
  }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || function (mod) {
19
- if (mod && mod.__esModule) return mod;
20
- var result = {};
21
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
- __setModuleDefault(result, mod);
23
- return result;
22
+ return a;
24
23
  };
25
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
26
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
24
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
25
+ var __objRest = (source, exclude) => {
26
+ var target = {};
27
+ for (var prop in source)
28
+ if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
29
+ target[prop] = source[prop];
30
+ if (source != null && __getOwnPropSymbols)
31
+ for (var prop of __getOwnPropSymbols(source)) {
32
+ if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
33
+ target[prop] = source[prop];
34
+ }
35
+ return target;
27
36
  };
28
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
29
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
30
- return new (P || (P = Promise))(function (resolve, reject) {
31
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
32
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
33
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
34
- step((generator = generator.apply(thisArg, _arguments || [])).next());
35
- });
37
+ var __export = (target, all) => {
38
+ for (var name in all)
39
+ __defProp(target, name, { get: all[name], enumerable: true });
36
40
  };
37
- var __rest = (this && this.__rest) || function (s, e) {
38
- var t = {};
39
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
40
- t[p] = s[p];
41
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
42
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
43
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
44
- t[p[i]] = s[p[i]];
45
- }
46
- return t;
41
+ var __copyProps = (to, from, except, desc) => {
42
+ if (from && typeof from === "object" || typeof from === "function") {
43
+ for (let key of __getOwnPropNames(from))
44
+ if (!__hasOwnProp.call(to, key) && key !== except)
45
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
46
+ }
47
+ return to;
47
48
  };
48
- var __importDefault = (this && this.__importDefault) || function (mod) {
49
- return (mod && mod.__esModule) ? mod : { "default": mod };
49
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
50
+ // If the importer is in node compatibility mode or this is not an ESM
51
+ // file that has been converted to a CommonJS file using a Babel-
52
+ // compatible transform (i.e. "__esModule" has not been set), then set
53
+ // "default" to the CommonJS "module.exports" for node compatibility.
54
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
55
+ mod
56
+ ));
57
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
58
+ var __async = (__this, __arguments, generator) => {
59
+ return new Promise((resolve, reject) => {
60
+ var fulfilled = (value) => {
61
+ try {
62
+ step(generator.next(value));
63
+ } catch (e) {
64
+ reject(e);
65
+ }
66
+ };
67
+ var rejected = (value) => {
68
+ try {
69
+ step(generator.throw(value));
70
+ } catch (e) {
71
+ reject(e);
72
+ }
73
+ };
74
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
75
+ step((generator = generator.apply(__this, __arguments)).next());
76
+ });
50
77
  };
51
- Object.defineProperty(exports, "__esModule", { value: true });
52
- exports.fetcher = exports.useInvalidation = exports.mutationRequest = exports.useModelMutation = exports.useInfiniteModelQuery = exports.useModelQuery = exports.getQueryKey = exports.useHooksContext = exports.Provider = exports.RequestHandlerContext = void 0;
53
- /* eslint-disable @typescript-eslint/no-explicit-any */
54
- const browser_1 = require("@zenstackhq/runtime/browser");
55
- const cross_1 = require("@zenstackhq/runtime/cross");
56
- const crossFetch = __importStar(require("cross-fetch"));
57
- const lower_case_first_1 = require("lower-case-first");
58
- const react_1 = require("react");
59
- const swr_1 = __importStar(require("swr"));
60
- const infinite_1 = __importStar(require("swr/infinite"));
61
- const mutation_1 = __importDefault(require("swr/mutation"));
62
- __exportStar(require("./prisma-types"), exports);
63
- const DEFAULT_QUERY_ENDPOINT = '/api/model';
64
- /**
65
- * Context for configuring react hooks.
66
- */
67
- exports.RequestHandlerContext = (0, react_1.createContext)({
68
- endpoint: DEFAULT_QUERY_ENDPOINT,
69
- fetch: undefined,
78
+
79
+ // src/runtime/index.ts
80
+ var runtime_exports = {};
81
+ __export(runtime_exports, {
82
+ Provider: () => Provider,
83
+ RequestHandlerContext: () => RequestHandlerContext,
84
+ fetcher: () => fetcher,
85
+ getQueryKey: () => getQueryKey,
86
+ mutationRequest: () => mutationRequest,
87
+ useHooksContext: () => useHooksContext,
88
+ useInfiniteModelQuery: () => useInfiniteModelQuery,
89
+ useInvalidation: () => useInvalidation,
90
+ useModelMutation: () => useModelMutation,
91
+ useModelQuery: () => useModelQuery
70
92
  });
71
- /**
72
- * Context provider.
73
- */
74
- exports.Provider = exports.RequestHandlerContext.Provider;
75
- /**
76
- * Hooks context.
77
- */
93
+ module.exports = __toCommonJS(runtime_exports);
94
+ var import_browser = require("@zenstackhq/runtime/browser");
95
+ var import_cross = require("@zenstackhq/runtime/cross");
96
+ var crossFetch = __toESM(require("cross-fetch"));
97
+ var import_lower_case_first = require("lower-case-first");
98
+ var import_react = require("react");
99
+ var import_swr = __toESM(require("swr"));
100
+ var import_infinite = __toESM(require("swr/infinite"));
101
+ var import_mutation = __toESM(require("swr/mutation"));
102
+ var DEFAULT_QUERY_ENDPOINT = "/api/model";
103
+ var RequestHandlerContext = (0, import_react.createContext)({
104
+ endpoint: DEFAULT_QUERY_ENDPOINT,
105
+ fetch: void 0
106
+ });
107
+ var Provider = RequestHandlerContext.Provider;
78
108
  function useHooksContext() {
79
- const _a = (0, react_1.useContext)(exports.RequestHandlerContext), { endpoint } = _a, rest = __rest(_a, ["endpoint"]);
80
- return Object.assign({ endpoint: endpoint !== null && endpoint !== void 0 ? endpoint : DEFAULT_QUERY_ENDPOINT }, rest);
109
+ const _a = (0, import_react.useContext)(RequestHandlerContext), { endpoint } = _a, rest = __objRest(_a, ["endpoint"]);
110
+ return __spreadValues({ endpoint: endpoint != null ? endpoint : DEFAULT_QUERY_ENDPOINT }, rest);
81
111
  }
82
- exports.useHooksContext = useHooksContext;
83
- const QUERY_KEY_PREFIX = 'zenstack:query';
84
- const MUTATION_KEY_PREFIX = 'zenstack:mutation';
85
- /**
86
- * Computes query key for the given model, operation, query args, and options.
87
- */
88
- function getQueryKey(model, operation, args, infinite, optimisticUpdate) {
89
- return JSON.stringify({
90
- prefix: QUERY_KEY_PREFIX,
91
- model,
92
- operation,
93
- args,
94
- infinite: infinite === true,
95
- optimisticUpdate: optimisticUpdate !== false,
96
- });
112
+ var QUERY_KEY_PREFIX = "zenstack:query";
113
+ var MUTATION_KEY_PREFIX = "zenstack:mutation";
114
+ function getQueryKey(model, operation, args, infinite, optimisticUpdate2) {
115
+ return JSON.stringify({
116
+ prefix: QUERY_KEY_PREFIX,
117
+ model,
118
+ operation,
119
+ args,
120
+ infinite: infinite === true,
121
+ optimisticUpdate: optimisticUpdate2 !== false
122
+ });
97
123
  }
98
- exports.getQueryKey = getQueryKey;
99
124
  function getMutationKey(model, operation) {
100
- // use a random key since we don't have 1:1 mapping between mutation and query
101
- // https://github.com/vercel/swr/discussions/2461#discussioncomment-5281784
102
- return JSON.stringify({ prefix: MUTATION_KEY_PREFIX, model, operation, r: Date.now() });
125
+ return JSON.stringify({ prefix: MUTATION_KEY_PREFIX, model, operation, r: Date.now() });
103
126
  }
104
127
  function parseQueryKey(key) {
105
- let keyValue = key;
106
- if (typeof key === 'string') {
107
- try {
108
- keyValue = JSON.parse(key);
109
- }
110
- catch (_a) {
111
- return undefined;
112
- }
128
+ let keyValue = key;
129
+ if (typeof key === "string") {
130
+ try {
131
+ keyValue = JSON.parse(key);
132
+ } catch (e) {
133
+ return void 0;
113
134
  }
114
- return (keyValue === null || keyValue === void 0 ? void 0 : keyValue.prefix) === QUERY_KEY_PREFIX ? keyValue : undefined;
135
+ }
136
+ return (keyValue == null ? void 0 : keyValue.prefix) === QUERY_KEY_PREFIX ? keyValue : void 0;
115
137
  }
116
- /**
117
- * Makes a model query with SWR.
118
- *
119
- * @param model Model name
120
- * @param operation Prisma operation (e.g, `findMany`)
121
- * @param args The request args object, which will be superjson-stringified and appended as "?q=" parameter
122
- * @param options Query options
123
- * @returns SWR response
124
- */
125
138
  function useModelQuery(model, operation, args, options) {
126
- var _a;
127
- const { endpoint, fetch } = useHooksContext();
128
- const key = (options === null || options === void 0 ? void 0 : options.disabled)
129
- ? null
130
- : getQueryKey(model, operation, args, false, (options === null || options === void 0 ? void 0 : options.optimisticUpdate) !== false);
131
- const url = makeUrl(`${endpoint}/${(0, lower_case_first_1.lowerCaseFirst)(model)}/${operation}`, args);
132
- return (0, swr_1.default)(key, () => fetcher(url, undefined, fetch, false), Object.assign(Object.assign({}, options), { fallbackData: (_a = options === null || options === void 0 ? void 0 : options.initialData) !== null && _a !== void 0 ? _a : options === null || options === void 0 ? void 0 : options.fallbackData }));
139
+ var _a;
140
+ const { endpoint, fetch: fetch2 } = useHooksContext();
141
+ const key = (options == null ? void 0 : options.disabled) ? null : getQueryKey(model, operation, args, false, (options == null ? void 0 : options.optimisticUpdate) !== false);
142
+ const url = makeUrl(`${endpoint}/${(0, import_lower_case_first.lowerCaseFirst)(model)}/${operation}`, args);
143
+ return (0, import_swr.default)(key, () => fetcher(url, void 0, fetch2, false), __spreadProps(__spreadValues({}, options), {
144
+ fallbackData: (_a = options == null ? void 0 : options.initialData) != null ? _a : options == null ? void 0 : options.fallbackData
145
+ }));
133
146
  }
134
- exports.useModelQuery = useModelQuery;
135
- /**
136
- * Makes an infinite GET request with SWR.
137
- *
138
- * @param model Model name
139
- * @param operation Prisma operation (e.g, `findMany`)
140
- * @param getNextArgs Function for computing the query args for a page
141
- * @param options Query options
142
- * @returns SWR infinite query response
143
- */
144
147
  function useInfiniteModelQuery(model, operation, getNextArgs, options) {
145
- var _a;
146
- const { endpoint, fetch } = useHooksContext();
147
- const getKey = (pageIndex, previousPageData) => {
148
- if (options === null || options === void 0 ? void 0 : options.disabled) {
149
- return null;
150
- }
151
- const nextArgs = getNextArgs(pageIndex, previousPageData);
152
- return nextArgs !== null // null means reached the end
153
- ? getQueryKey(model, operation, nextArgs, true, false)
154
- : null;
155
- };
156
- return (0, infinite_1.default)(getKey, (key) => {
157
- const parsedKey = parseQueryKey(key);
158
- if (parsedKey) {
159
- const { model, operation, args } = parsedKey;
160
- const url = makeUrl(`${endpoint}/${(0, lower_case_first_1.lowerCaseFirst)(model)}/${operation}`, args);
161
- return fetcher(url, undefined, fetch, false);
162
- }
163
- else {
164
- throw new Error('Invalid query key: ' + key);
165
- }
166
- }, Object.assign(Object.assign({}, options), { fallbackData: (_a = options === null || options === void 0 ? void 0 : options.initialData) !== null && _a !== void 0 ? _a : options === null || options === void 0 ? void 0 : options.fallbackData }));
148
+ var _a;
149
+ const { endpoint, fetch: fetch2 } = useHooksContext();
150
+ const getKey = (pageIndex, previousPageData) => {
151
+ if (options == null ? void 0 : options.disabled) {
152
+ return null;
153
+ }
154
+ const nextArgs = getNextArgs(pageIndex, previousPageData);
155
+ return nextArgs !== null ? getQueryKey(model, operation, nextArgs, true, false) : null;
156
+ };
157
+ return (0, import_infinite.default)(
158
+ getKey,
159
+ (key) => {
160
+ const parsedKey = parseQueryKey(key);
161
+ if (parsedKey) {
162
+ const { model: model2, operation: operation2, args } = parsedKey;
163
+ const url = makeUrl(`${endpoint}/${(0, import_lower_case_first.lowerCaseFirst)(model2)}/${operation2}`, args);
164
+ return fetcher(url, void 0, fetch2, false);
165
+ } else {
166
+ throw new Error("Invalid query key: " + key);
167
+ }
168
+ },
169
+ __spreadProps(__spreadValues({}, options), {
170
+ fallbackData: (_a = options == null ? void 0 : options.initialData) != null ? _a : options == null ? void 0 : options.fallbackData
171
+ })
172
+ );
167
173
  }
168
- exports.useInfiniteModelQuery = useInfiniteModelQuery;
169
174
  function useModelMutation(model, method, operation, modelMeta, options, checkReadBack) {
170
- const { endpoint, fetch, logging } = useHooksContext();
171
- const invalidate = (options === null || options === void 0 ? void 0 : options.revalidate) !== false ? useInvalidation(model, modelMeta) : undefined;
172
- const { cache, mutate } = (0, swr_1.useSWRConfig)();
173
- return (0, mutation_1.default)(getMutationKey(model, operation), (_key, { arg }) => {
174
- if (options === null || options === void 0 ? void 0 : options.optimisticUpdate) {
175
- optimisticUpdate(model, operation, arg, modelMeta, cache, mutate, logging);
176
- }
177
- const url = `${endpoint}/${(0, lower_case_first_1.lowerCaseFirst)(model)}/${operation}`;
178
- return mutationRequest(method, url, arg, invalidate, fetch, checkReadBack);
179
- }, options);
175
+ const { endpoint, fetch: fetch2, logging } = useHooksContext();
176
+ const invalidate = (options == null ? void 0 : options.revalidate) !== false ? useInvalidation(model, modelMeta) : void 0;
177
+ const { cache, mutate } = (0, import_swr.useSWRConfig)();
178
+ return (0, import_mutation.default)(
179
+ getMutationKey(model, operation),
180
+ (_key, { arg }) => {
181
+ if (options == null ? void 0 : options.optimisticUpdate) {
182
+ optimisticUpdate(model, operation, arg, modelMeta, cache, mutate, logging);
183
+ }
184
+ const url = `${endpoint}/${(0, import_lower_case_first.lowerCaseFirst)(model)}/${operation}`;
185
+ return mutationRequest(method, url, arg, invalidate, fetch2, checkReadBack);
186
+ },
187
+ options
188
+ );
180
189
  }
181
- exports.useModelMutation = useModelMutation;
182
- /**
183
- * Makes a mutation request.
184
- *
185
- * @param url The request URL
186
- * @param data The request data
187
- * @param invalidate Function for invalidating a query
188
- */
189
- function mutationRequest(method, url, data, invalidate, fetch, checkReadBack) {
190
- return __awaiter(this, void 0, void 0, function* () {
191
- const reqUrl = method === 'DELETE' ? makeUrl(url, data) : url;
192
- const r = yield fetcher(reqUrl, {
193
- method,
194
- headers: {
195
- 'content-type': 'application/json',
196
- },
197
- body: data ? marshal(data) : undefined,
198
- }, fetch, checkReadBack);
199
- if (invalidate) {
200
- yield invalidate(getOperationFromUrl(url), data);
201
- }
202
- return r;
203
- });
190
+ function mutationRequest(method, url, data, invalidate, fetch2, checkReadBack) {
191
+ return __async(this, null, function* () {
192
+ const reqUrl = method === "DELETE" ? makeUrl(url, data) : url;
193
+ const r = yield fetcher(
194
+ reqUrl,
195
+ {
196
+ method,
197
+ headers: {
198
+ "content-type": "application/json"
199
+ },
200
+ body: data ? marshal(data) : void 0
201
+ },
202
+ fetch2,
203
+ checkReadBack
204
+ );
205
+ if (invalidate) {
206
+ yield invalidate(getOperationFromUrl(url), data);
207
+ }
208
+ return r;
209
+ });
204
210
  }
205
- exports.mutationRequest = mutationRequest;
206
211
  function useInvalidation(model, modelMeta) {
207
- // https://swr.vercel.app/docs/advanced/cache#mutate-multiple-keys-from-regex
208
- const { logging } = useHooksContext();
209
- const { cache, mutate } = (0, swr_1.useSWRConfig)();
210
- return (operation, args) => __awaiter(this, void 0, void 0, function* () {
211
- if (!(cache instanceof Map)) {
212
- throw new Error('mutate requires the cache provider to be a Map instance');
213
- }
214
- const mutatedModels = yield (0, cross_1.getMutatedModels)(model, operation, args, modelMeta);
215
- const keys = Array.from(cache.keys()).filter((key) => {
216
- const parsedKey = parseQueryKey(key);
217
- if (!parsedKey) {
218
- return false;
219
- }
220
- const modelsRead = (0, cross_1.getReadModels)(parsedKey.model, modelMeta, parsedKey.args);
221
- return modelsRead.some((m) => mutatedModels.includes(m));
222
- });
223
- if (logging) {
224
- keys.forEach((key) => {
225
- console.log(`Invalidating query ${key} due to mutation "${model}.${operation}"`);
226
- });
227
- }
228
- const mutations = keys.map((key) => {
229
- const parsedKey = parseQueryKey(key);
230
- // FIX: special handling for infinite query keys, but still not working
231
- // https://github.com/vercel/swr/discussions/2843
232
- return mutate((parsedKey === null || parsedKey === void 0 ? void 0 : parsedKey.infinite) ? (0, infinite_1.unstable_serialize)(() => key) : key);
233
- });
234
- return Promise.all(mutations);
212
+ const { logging } = useHooksContext();
213
+ const { cache, mutate } = (0, import_swr.useSWRConfig)();
214
+ return (operation, args) => __async(this, null, function* () {
215
+ if (!(cache instanceof Map)) {
216
+ throw new Error("mutate requires the cache provider to be a Map instance");
217
+ }
218
+ const mutatedModels = yield (0, import_cross.getMutatedModels)(model, operation, args, modelMeta);
219
+ const keys = Array.from(cache.keys()).filter((key) => {
220
+ const parsedKey = parseQueryKey(key);
221
+ if (!parsedKey) {
222
+ return false;
223
+ }
224
+ const modelsRead = (0, import_cross.getReadModels)(parsedKey.model, modelMeta, parsedKey.args);
225
+ return modelsRead.some((m) => mutatedModels.includes(m));
235
226
  });
236
- }
237
- exports.useInvalidation = useInvalidation;
238
- /**
239
- * Makes fetch request for queries and mutations.
240
- */
241
- function fetcher(url, options, fetch, checkReadBack) {
242
- var _a, _b, _c;
243
- return __awaiter(this, void 0, void 0, function* () {
244
- const _fetch = fetch !== null && fetch !== void 0 ? fetch : crossFetch.fetch;
245
- const res = yield _fetch(url, options);
246
- if (!res.ok) {
247
- const errData = unmarshal(yield res.text());
248
- if (checkReadBack !== false &&
249
- ((_a = errData.error) === null || _a === void 0 ? void 0 : _a.prisma) &&
250
- ((_b = errData.error) === null || _b === void 0 ? void 0 : _b.code) === 'P2004' &&
251
- ((_c = errData.error) === null || _c === void 0 ? void 0 : _c.reason) === 'RESULT_NOT_READABLE') {
252
- // policy doesn't allow mutation result to be read back, just return undefined
253
- return undefined;
254
- }
255
- const error = new Error('An error occurred while fetching the data.');
256
- error.info = errData.error;
257
- error.status = res.status;
258
- throw error;
259
- }
260
- const textResult = yield res.text();
261
- try {
262
- return unmarshal(textResult).data;
263
- }
264
- catch (err) {
265
- console.error(`Unable to deserialize data:`, textResult);
266
- throw err;
267
- }
227
+ if (logging) {
228
+ keys.forEach((key) => {
229
+ console.log(`Invalidating query ${key} due to mutation "${model}.${operation}"`);
230
+ });
231
+ }
232
+ const mutations = keys.map((key) => {
233
+ const parsedKey = parseQueryKey(key);
234
+ return mutate((parsedKey == null ? void 0 : parsedKey.infinite) ? (0, import_infinite.unstable_serialize)(() => key) : key);
268
235
  });
236
+ return Promise.all(mutations);
237
+ });
269
238
  }
270
- exports.fetcher = fetcher;
271
- function marshal(value) {
272
- const { data, meta } = (0, browser_1.serialize)(value);
273
- if (meta) {
274
- return JSON.stringify(Object.assign(Object.assign({}, data), { meta: { serialization: meta } }));
239
+ function fetcher(url, options, fetch2, checkReadBack) {
240
+ return __async(this, null, function* () {
241
+ var _a, _b, _c;
242
+ const _fetch = fetch2 != null ? fetch2 : crossFetch.fetch;
243
+ const res = yield _fetch(url, options);
244
+ if (!res.ok) {
245
+ const errData = unmarshal(yield res.text());
246
+ if (checkReadBack !== false && ((_a = errData.error) == null ? void 0 : _a.prisma) && ((_b = errData.error) == null ? void 0 : _b.code) === "P2004" && ((_c = errData.error) == null ? void 0 : _c.reason) === "RESULT_NOT_READABLE") {
247
+ return void 0;
248
+ }
249
+ const error = new Error(
250
+ "An error occurred while fetching the data."
251
+ );
252
+ error.info = errData.error;
253
+ error.status = res.status;
254
+ throw error;
275
255
  }
276
- else {
277
- return JSON.stringify(data);
256
+ const textResult = yield res.text();
257
+ try {
258
+ return unmarshal(textResult).data;
259
+ } catch (err) {
260
+ console.error(`Unable to deserialize data:`, textResult);
261
+ throw err;
278
262
  }
263
+ });
264
+ }
265
+ function marshal(value) {
266
+ const { data, meta } = (0, import_browser.serialize)(value);
267
+ if (meta) {
268
+ return JSON.stringify(__spreadProps(__spreadValues({}, data), { meta: { serialization: meta } }));
269
+ } else {
270
+ return JSON.stringify(data);
271
+ }
279
272
  }
280
273
  function unmarshal(value) {
281
- var _a;
282
- const parsed = JSON.parse(value);
283
- if (parsed.data && ((_a = parsed.meta) === null || _a === void 0 ? void 0 : _a.serialization)) {
284
- const deserializedData = (0, browser_1.deserialize)(parsed.data, parsed.meta.serialization);
285
- return Object.assign(Object.assign({}, parsed), { data: deserializedData });
286
- }
287
- else {
288
- return parsed;
289
- }
274
+ var _a;
275
+ const parsed = JSON.parse(value);
276
+ if (parsed.data && ((_a = parsed.meta) == null ? void 0 : _a.serialization)) {
277
+ const deserializedData = (0, import_browser.deserialize)(parsed.data, parsed.meta.serialization);
278
+ return __spreadProps(__spreadValues({}, parsed), { data: deserializedData });
279
+ } else {
280
+ return parsed;
281
+ }
290
282
  }
291
283
  function makeUrl(url, args) {
292
- if (!args) {
293
- return url;
294
- }
295
- const { data, meta } = (0, browser_1.serialize)(args);
296
- let result = `${url}?q=${encodeURIComponent(JSON.stringify(data))}`;
297
- if (meta) {
298
- result += `&meta=${encodeURIComponent(JSON.stringify({ serialization: meta }))}`;
299
- }
300
- return result;
284
+ if (!args) {
285
+ return url;
286
+ }
287
+ const { data, meta } = (0, import_browser.serialize)(args);
288
+ let result = `${url}?q=${encodeURIComponent(JSON.stringify(data))}`;
289
+ if (meta) {
290
+ result += `&meta=${encodeURIComponent(JSON.stringify({ serialization: meta }))}`;
291
+ }
292
+ return result;
301
293
  }
302
294
  function getOperationFromUrl(url) {
303
- const parts = url.split('/');
304
- const r = parts.pop();
305
- if (!r) {
306
- throw new Error(`Invalid URL: ${url}`);
307
- }
308
- else {
309
- return r;
310
- }
295
+ const parts = url.split("/");
296
+ const r = parts.pop();
297
+ if (!r) {
298
+ throw new Error(`Invalid URL: ${url}`);
299
+ } else {
300
+ return r;
301
+ }
311
302
  }
312
303
  function optimisticUpdate(mutationModel, mutationOp, mutationArgs, modelMeta, cache, mutator, logging = false) {
313
- return __awaiter(this, void 0, void 0, function* () {
314
- const optimisticPromises = [];
315
- for (const key of cache.keys()) {
316
- const parsedKey = parseQueryKey(key);
317
- if (!parsedKey) {
318
- continue;
319
- }
320
- if (!parsedKey.optimisticUpdate) {
321
- if (logging) {
322
- console.log(`Skipping optimistic update for ${key} due to opt-out`);
323
- }
324
- continue;
325
- }
326
- const cacheValue = cache.get(key);
327
- if (!cacheValue) {
328
- continue;
329
- }
330
- if (cacheValue.error) {
331
- if (logging) {
332
- console.warn(`Skipping optimistic update for ${key} due to error:`, cacheValue.error);
333
- }
334
- continue;
335
- }
336
- const mutatedData = yield (0, cross_1.applyMutation)(parsedKey.model, parsedKey.operation, cacheValue.data, mutationModel, mutationOp, mutationArgs, modelMeta, logging);
337
- if (mutatedData !== undefined) {
338
- // mutation applicable to this query, update cache
339
- if (logging) {
340
- console.log(`Optimistically updating query ${JSON.stringify(key)} due to mutation "${mutationModel}.${mutationOp}"`);
341
- }
342
- optimisticPromises.push(mutator(key, mutatedData, {
343
- // don't trigger revalidation here since we will do it
344
- // when the remote mutation succeeds
345
- revalidate: false,
346
- }));
347
- }
304
+ return __async(this, null, function* () {
305
+ const optimisticPromises = [];
306
+ for (const key of cache.keys()) {
307
+ const parsedKey = parseQueryKey(key);
308
+ if (!parsedKey) {
309
+ continue;
310
+ }
311
+ if (!parsedKey.optimisticUpdate) {
312
+ if (logging) {
313
+ console.log(`Skipping optimistic update for ${key} due to opt-out`);
348
314
  }
349
- return Promise.all(optimisticPromises);
350
- });
315
+ continue;
316
+ }
317
+ const cacheValue = cache.get(key);
318
+ if (!cacheValue) {
319
+ continue;
320
+ }
321
+ if (cacheValue.error) {
322
+ if (logging) {
323
+ console.warn(`Skipping optimistic update for ${key} due to error:`, cacheValue.error);
324
+ }
325
+ continue;
326
+ }
327
+ const mutatedData = yield (0, import_cross.applyMutation)(
328
+ parsedKey.model,
329
+ parsedKey.operation,
330
+ cacheValue.data,
331
+ mutationModel,
332
+ mutationOp,
333
+ mutationArgs,
334
+ modelMeta,
335
+ logging
336
+ );
337
+ if (mutatedData !== void 0) {
338
+ if (logging) {
339
+ console.log(
340
+ `Optimistically updating query ${JSON.stringify(
341
+ key
342
+ )} due to mutation "${mutationModel}.${mutationOp}"`
343
+ );
344
+ }
345
+ optimisticPromises.push(
346
+ mutator(key, mutatedData, {
347
+ // don't trigger revalidation here since we will do it
348
+ // when the remote mutation succeeds
349
+ revalidate: false
350
+ })
351
+ );
352
+ }
353
+ }
354
+ return Promise.all(optimisticPromises);
355
+ });
351
356
  }
357
+ // Annotate the CommonJS export names for ESM import in node:
358
+ 0 && (module.exports = {
359
+ Provider,
360
+ RequestHandlerContext,
361
+ fetcher,
362
+ getQueryKey,
363
+ mutationRequest,
364
+ useHooksContext,
365
+ useInfiniteModelQuery,
366
+ useInvalidation,
367
+ useModelMutation,
368
+ useModelQuery
369
+ });
352
370
  //# sourceMappingURL=index.js.map