@demokit-ai/swr 0.1.0 → 0.3.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/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2025 Kasava, Inc.
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/dist/index.cjs CHANGED
@@ -1,18 +1,61 @@
1
- 'use strict';
2
-
3
- var react = require('react');
4
- var swr = require('swr');
5
- var core = require('@demokit-ai/core');
6
- var jsxRuntime = require('react/jsx-runtime');
7
- var useSWRMutation = require('swr/mutation');
8
-
9
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
10
29
 
11
- var useSWRMutation__default = /*#__PURE__*/_interopDefault(useSWRMutation);
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ DemoSWRProvider: () => DemoSWRProvider,
34
+ createDemoFetcher: () => createDemoFetcher,
35
+ createDemoMiddleware: () => createDemoMiddleware,
36
+ defaultFetcher: () => defaultFetcher,
37
+ findMatchingFixture: () => findMatchingFixture,
38
+ matchQueryKey: () => import_core.matchQueryKey,
39
+ normalizeFixtureMap: () => normalizeFixtureMap,
40
+ normalizeKey: () => normalizeKey,
41
+ parsePatternString: () => parsePatternString,
42
+ useDemoSWR: () => useDemoSWR,
43
+ useDemoSWRMutation: () => useDemoSWRMutation,
44
+ useIsDemoSWRMode: () => useIsDemoSWRMode
45
+ });
46
+ module.exports = __toCommonJS(index_exports);
12
47
 
13
48
  // src/provider.tsx
14
- var DemoSWRContext = react.createContext(void 0);
49
+ var import_react2 = require("react");
50
+ var import_swr = require("swr");
51
+
52
+ // src/context.ts
53
+ var import_react = require("react");
54
+ var DemoSWRContext = (0, import_react.createContext)(void 0);
15
55
  DemoSWRContext.displayName = "DemoSWRContext";
56
+
57
+ // src/matcher.ts
58
+ var import_core = require("@demokit-ai/core");
16
59
  function normalizeKey(key) {
17
60
  if (typeof key === "string") {
18
61
  return [key];
@@ -48,7 +91,7 @@ function normalizeFixtureMap(fixtures) {
48
91
  }
49
92
  function findMatchingFixture(fixtures, key) {
50
93
  const normalizedKey = normalizeKey(key);
51
- const result = core.findMatchingQueryKeyPattern(fixtures, normalizedKey);
94
+ const result = (0, import_core.findMatchingQueryKeyPattern)(fixtures, normalizedKey);
52
95
  if (result) {
53
96
  const [, handler, matchResult] = result;
54
97
  return [handler, { params: matchResult.params, normalizedKey }];
@@ -137,6 +180,9 @@ function createDemoMiddleware(options) {
137
180
  };
138
181
  return middleware;
139
182
  }
183
+
184
+ // src/provider.tsx
185
+ var import_jsx_runtime = require("react/jsx-runtime");
140
186
  function DemoSWRProvider({
141
187
  children,
142
188
  fixtures = /* @__PURE__ */ new Map(),
@@ -146,12 +192,12 @@ function DemoSWRProvider({
146
192
  fallback = {},
147
193
  swrConfig = {}
148
194
  }) {
149
- const fixturesRef = react.useRef(normalizeFixtureMap(fixtures));
150
- const mutationFixturesRef = react.useRef(
195
+ const fixturesRef = (0, import_react2.useRef)(normalizeFixtureMap(fixtures));
196
+ const mutationFixturesRef = (0, import_react2.useRef)(
151
197
  mutations instanceof Map ? mutations : new Map(Object.entries(mutations))
152
198
  );
153
199
  const isDemoMode = enabled;
154
- const demoMiddleware = react.useMemo(
200
+ const demoMiddleware = (0, import_react2.useMemo)(
155
201
  () => createDemoMiddleware({
156
202
  fixtures: fixturesRef.current,
157
203
  isEnabled: () => isDemoMode,
@@ -159,7 +205,7 @@ function DemoSWRProvider({
159
205
  }),
160
206
  [isDemoMode, delay]
161
207
  );
162
- const demoFetcher = react.useMemo(
208
+ const demoFetcher = (0, import_react2.useMemo)(
163
209
  () => createDemoFetcher({
164
210
  fixtures: fixturesRef.current,
165
211
  isEnabled: () => isDemoMode,
@@ -168,7 +214,7 @@ function DemoSWRProvider({
168
214
  }),
169
215
  [isDemoMode, delay]
170
216
  );
171
- const combinedFallback = react.useMemo(() => {
217
+ const combinedFallback = (0, import_react2.useMemo)(() => {
172
218
  if (!isDemoMode) return swrConfig.fallback || {};
173
219
  const staticFixtures = {};
174
220
  for (const [pattern, handler] of fixturesRef.current) {
@@ -183,7 +229,7 @@ function DemoSWRProvider({
183
229
  ...swrConfig.fallback || {}
184
230
  };
185
231
  }, [isDemoMode, fallback, swrConfig.fallback]);
186
- const config = react.useMemo(
232
+ const config = (0, import_react2.useMemo)(
187
233
  () => ({
188
234
  ...swrConfig,
189
235
  use: [...swrConfig.use || [], demoMiddleware],
@@ -197,9 +243,9 @@ function DemoSWRProvider({
197
243
  }),
198
244
  [swrConfig, demoMiddleware, combinedFallback, isDemoMode]
199
245
  );
200
- const getFetcher = react.useCallback(() => demoFetcher, [demoFetcher]);
201
- const getMiddleware = react.useCallback(() => demoMiddleware, [demoMiddleware]);
202
- const contextValue = react.useMemo(
246
+ const getFetcher = (0, import_react2.useCallback)(() => demoFetcher, [demoFetcher]);
247
+ const getMiddleware = (0, import_react2.useCallback)(() => demoMiddleware, [demoMiddleware]);
248
+ const contextValue = (0, import_react2.useMemo)(
203
249
  () => ({
204
250
  isDemoMode,
205
251
  setFixture: (pattern, handler) => {
@@ -219,10 +265,15 @@ function DemoSWRProvider({
219
265
  }),
220
266
  [isDemoMode, getFetcher, getMiddleware]
221
267
  );
222
- return /* @__PURE__ */ jsxRuntime.jsx(DemoSWRContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsxRuntime.jsx(swr.SWRConfig, { value: config, children }) });
268
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DemoSWRContext.Provider, { value: contextValue, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_swr.SWRConfig, { value: config, children }) });
223
269
  }
270
+
271
+ // src/hooks.ts
272
+ var import_react3 = require("react");
273
+ var import_mutation = __toESM(require("swr/mutation"), 1);
274
+ var import_swr2 = require("swr");
224
275
  function useDemoSWR() {
225
- const context = react.useContext(DemoSWRContext);
276
+ const context = (0, import_react3.useContext)(DemoSWRContext);
226
277
  if (context === void 0) {
227
278
  throw new Error(
228
279
  "useDemoSWR must be used within a DemoSWRProvider. Make sure to wrap your app with <DemoSWRProvider>."
@@ -235,14 +286,14 @@ function useIsDemoSWRMode() {
235
286
  }
236
287
  function useDemoSWRMutation(key, options) {
237
288
  const { fetcher, demoFixture, demoDelay = 0, ...mutationOptions } = options;
238
- const { mutate } = swr.useSWRConfig();
289
+ const { mutate } = (0, import_swr2.useSWRConfig)();
239
290
  let isDemoMode = false;
240
291
  try {
241
292
  const demoState = useDemoSWR();
242
293
  isDemoMode = demoState.isDemoMode;
243
294
  } catch {
244
295
  }
245
- const demoAwareFetcher = react.useCallback(
296
+ const demoAwareFetcher = (0, import_react3.useCallback)(
246
297
  async (mutationKey, { arg }) => {
247
298
  if (!isDemoMode) {
248
299
  return fetcher(mutationKey, { arg });
@@ -271,23 +322,21 @@ function useDemoSWRMutation(key, options) {
271
322
  },
272
323
  [isDemoMode, fetcher, demoFixture, demoDelay, key, mutate]
273
324
  );
274
- return useSWRMutation__default.default(key, demoAwareFetcher, mutationOptions);
325
+ return (0, import_mutation.default)(key, demoAwareFetcher, mutationOptions);
275
326
  }
276
-
277
- Object.defineProperty(exports, "matchQueryKey", {
278
- enumerable: true,
279
- get: function () { return core.matchQueryKey; }
327
+ // Annotate the CommonJS export names for ESM import in node:
328
+ 0 && (module.exports = {
329
+ DemoSWRProvider,
330
+ createDemoFetcher,
331
+ createDemoMiddleware,
332
+ defaultFetcher,
333
+ findMatchingFixture,
334
+ matchQueryKey,
335
+ normalizeFixtureMap,
336
+ normalizeKey,
337
+ parsePatternString,
338
+ useDemoSWR,
339
+ useDemoSWRMutation,
340
+ useIsDemoSWRMode
280
341
  });
281
- exports.DemoSWRProvider = DemoSWRProvider;
282
- exports.createDemoFetcher = createDemoFetcher;
283
- exports.createDemoMiddleware = createDemoMiddleware;
284
- exports.defaultFetcher = defaultFetcher;
285
- exports.findMatchingFixture = findMatchingFixture;
286
- exports.normalizeFixtureMap = normalizeFixtureMap;
287
- exports.normalizeKey = normalizeKey;
288
- exports.parsePatternString = parsePatternString;
289
- exports.useDemoSWR = useDemoSWR;
290
- exports.useDemoSWRMutation = useDemoSWRMutation;
291
- exports.useIsDemoSWRMode = useIsDemoSWRMode;
292
- //# sourceMappingURL=index.cjs.map
293
342
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/context.ts","../src/matcher.ts","../src/fetcher.ts","../src/middleware.ts","../src/provider.tsx","../src/hooks.ts"],"names":["createContext","findMatchingQueryKeyPattern","useRef","useMemo","useCallback","jsx","SWRConfig","useContext","useSWRConfig","useSWRMutation"],"mappings":";;;;;;;;;;;;;AASO,IAAM,cAAA,GAAiBA,oBAAwC,MAAS,CAAA;AAE/E,cAAA,CAAe,WAAA,GAAc,gBAAA;ACCtB,SAAS,aAAa,GAAA,EAAmC;AAC9D,EAAA,IAAI,OAAO,QAAQ,QAAA,EAAU;AAC3B,IAAA,OAAO,CAAC,GAAG,CAAA;AAAA,EACb;AAEA,EAAA,OAAO,GAAA,CAAI,GAAA,CAAI,CAAC,OAAA,KAAY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;AAAA,UACb;AAAA,SACF;AAEA,QAAA,IAAI,OAAO,gBAAgB,UAAA,EAAY;AACrC,UAAA,MAAM,SAAA,GAAY,WAAA;AAGlB,UAAA,OAAO,UAAU,OAAO,CAAA;AAAA,QAC1B;AACA,QAAA,OAAO,WAAA;AAAA,MACT;AAGA,MAAA,OAAA,CAAQ,IAAA;AAAA,QACN,gDAAgD,GAAG,CAAA,gCAAA;AAAA,OACrD;AACA,MAAA,OAAO,OAAA,CAAQ,WAAA,EAAa,EAAE,GAAA,EAAK,CAAA;AAAA,IACrC,CAAA;AAAA,IACA,CAAC,UAAA,EAAY,OAAA,EAAS,WAAA,EAAa,SAAA,EAAW,KAAK,MAAM;AAAA,GAC3D;AAEA,EAAA,OAAOK,+BAAA,CAAe,GAAA,EAAK,gBAAA,EAAkB,eAAe,CAAA;AAC9D","file":"index.cjs","sourcesContent":["'use client'\n\nimport { createContext } from 'react'\nimport type { DemoSWRState } from './types'\n\n/**\n * Context for DemoSWR state\n * @internal\n */\nexport const DemoSWRContext = createContext<DemoSWRState | undefined>(undefined)\n\nDemoSWRContext.displayName = 'DemoSWRContext'\n","import { matchQueryKey, findMatchingQueryKeyPattern } from '@demokit-ai/core'\nimport type { QueryKey } from '@demokit-ai/core'\nimport type { SWRFixtureHandler, SWRFixtureMap, SWRFixtureMapObject } from './types'\n\n/**\n * Normalize an SWR key to a QueryKey for matching\n *\n * SWR keys can be:\n * - Strings: '/api/users' -> ['/api/users']\n * - Arrays: ['/api/users', id] -> ['/api/users', id]\n * - Functions that return keys (not handled here)\n */\nexport function normalizeKey(key: string | unknown[]): QueryKey {\n if (typeof key === 'string') {\n return [key]\n }\n\n return key.map((element) => {\n if (element === null || element === undefined) {\n return element\n }\n if (typeof element === 'object') {\n return element as Record<string, unknown>\n }\n return element as string | number | boolean\n })\n}\n\n/**\n * Parse a JSON string pattern into a QueryKey\n * Handles both array notation and simple string patterns\n *\n * @example\n * parsePatternString('[\"/api/users\"]') // ['/api/users']\n * parsePatternString('[\"/api/users\", \":id\"]') // ['/api/users', ':id']\n * parsePatternString('/api/users') // ['/api/users']\n */\nexport function parsePatternString(pattern: string): QueryKey {\n // Try to parse as JSON array\n if (pattern.startsWith('[')) {\n try {\n return JSON.parse(pattern) as QueryKey\n } catch {\n // Fall through to simple string\n }\n }\n\n // Simple string becomes single-element array\n return [pattern]\n}\n\n/**\n * Convert object-based fixture map to Map-based fixture map\n */\nexport function normalizeFixtureMap(fixtures: SWRFixtureMapObject | SWRFixtureMap): SWRFixtureMap {\n if (fixtures instanceof Map) {\n return fixtures\n }\n\n const map = new Map<QueryKey, SWRFixtureHandler>()\n for (const [pattern, handler] of Object.entries(fixtures)) {\n map.set(parsePatternString(pattern), handler)\n }\n return map\n}\n\n/**\n * Find a matching fixture for an SWR key\n *\n * @param fixtures - Map of key patterns to handlers\n * @param key - The SWR key to match\n * @returns Tuple of [handler, match result] or null if no match\n */\nexport function findMatchingFixture(\n fixtures: SWRFixtureMap,\n key: string | unknown[]\n): [SWRFixtureHandler, { params: Record<string, unknown>; normalizedKey: QueryKey }] | null {\n const normalizedKey = normalizeKey(key)\n const result = findMatchingQueryKeyPattern(fixtures, normalizedKey)\n\n if (result) {\n const [, handler, matchResult] = result\n return [handler, { params: matchResult.params, normalizedKey }]\n }\n\n return null\n}\n\n/**\n * Re-export the matchQueryKey function for direct use\n */\nexport { matchQueryKey }","import type { QueryKey } from '@demokit-ai/core'\nimport type { SWRFixtureMap, SWRFixtureContext } from './types'\nimport { findMatchingFixture, normalizeKey } from './matcher'\n\n/**\n * Options for creating a demo-aware fetcher\n */\nexport interface CreateDemoFetcherOptions {\n /**\n * Map of key patterns to fixture handlers\n */\n fixtures: SWRFixtureMap\n\n /**\n * Function to check if demo mode is enabled\n */\n isEnabled: () => boolean\n\n /**\n * Delay in ms before returning fixture data\n * @default 0\n */\n delay?: number\n\n /**\n * Fallback fetcher to use when demo mode is disabled\n * or no fixture matches\n */\n fallbackFetcher?: <T>(key: string | unknown[]) => Promise<T>\n}\n\n/**\n * Create a demo-aware fetcher function for SWR\n *\n * This fetcher intercepts requests when demo mode is enabled\n * and returns fixture data instead of making real API calls.\n *\n * @example\n * const fixtures = new Map([\n * [['/api/users'], [{ id: '1', name: 'Demo User' }]],\n * [['/api/users', ':id'], ({ params }) => ({ id: params.id, name: 'User' })],\n * ])\n *\n * const fetcher = createDemoFetcher({\n * fixtures,\n * isEnabled: () => isDemoMode,\n * delay: 100,\n * })\n *\n * // Use with SWR\n * const { data } = useSWR('/api/users', fetcher)\n */\nexport function createDemoFetcher(options: CreateDemoFetcherOptions) {\n const { fixtures, isEnabled, delay = 0, fallbackFetcher } = options\n\n return async function demoFetcher<TData = unknown>(key: string | unknown[]): Promise<TData> {\n // If demo mode is not enabled, use fallback\n if (!isEnabled()) {\n if (fallbackFetcher) {\n return fallbackFetcher<TData>(key)\n }\n throw new Error(\n `[DemoKit SWR] No fallback fetcher provided and demo mode is disabled. ` +\n `Key: ${JSON.stringify(key)}`\n )\n }\n\n // Find matching fixture\n const match = findMatchingFixture(fixtures, key)\n\n if (!match) {\n // No fixture found, try fallback\n if (fallbackFetcher) {\n return fallbackFetcher<TData>(key)\n }\n throw new Error(`[DemoKit SWR] No fixture found for key: ${JSON.stringify(key)}`)\n }\n\n const [handler, { params, normalizedKey }] = match\n\n // Apply delay if configured\n if (delay > 0) {\n await new Promise((resolve) => setTimeout(resolve, delay))\n }\n\n // Build context\n const context: SWRFixtureContext = {\n key,\n normalizedKey,\n params,\n match: { matched: true, params },\n }\n\n // Execute handler\n if (typeof handler === 'function') {\n return handler(context) as TData\n }\n\n // Return static value\n return handler as TData\n }\n}\n\n/**\n * Default fetcher that uses fetch API\n * Used as fallback when demo mode is disabled\n */\nexport async function defaultFetcher<TData = unknown>(key: string | unknown[]): Promise<TData> {\n const url = typeof key === 'string' ? key : String(key[0])\n const response = await fetch(url)\n\n if (!response.ok) {\n const error = new Error('An error occurred while fetching the data.')\n throw error\n }\n\n return response.json()\n}\n","import type { Middleware } from 'swr'\nimport type { SWRFixtureMap, SWRFixtureContext } from './types'\nimport { findMatchingFixture } from './matcher'\n\n/**\n * Options for creating the demo middleware\n */\nexport interface CreateDemoMiddlewareOptions {\n /**\n * Map of key patterns to fixture handlers\n */\n fixtures: SWRFixtureMap\n\n /**\n * Function to check if demo mode is enabled\n */\n isEnabled: () => boolean\n\n /**\n * Delay in ms before returning fixture data\n * @default 0\n */\n delay?: number\n}\n\n/**\n * Create a demo-aware SWR middleware\n *\n * This middleware intercepts SWR requests when demo mode is enabled\n * and returns fixture data instead of using the original fetcher.\n *\n * @example\n * import { SWRConfig } from 'swr'\n * import { createDemoMiddleware } from '@demokit-ai/swr'\n *\n * const fixtures = new Map([\n * [['/api/users'], [{ id: '1', name: 'Demo User' }]],\n * [['/api/users', ':id'], ({ params }) => ({ id: params.id, name: 'User' })],\n * ])\n *\n * const demoMiddleware = createDemoMiddleware({\n * fixtures,\n * isEnabled: () => isDemoMode,\n * delay: 100,\n * })\n *\n * function App() {\n * return (\n * <SWRConfig value={{ use: [demoMiddleware] }}>\n * <YourApp />\n * </SWRConfig>\n * )\n * }\n */\nexport function createDemoMiddleware(options: CreateDemoMiddlewareOptions): Middleware {\n const { fixtures, isEnabled, delay = 0 } = options\n\n // Use the simpler middleware pattern that SWR expects\n const middleware: Middleware = (useSWRNext) => (key, fetcher, config) => {\n // Create an extended fetcher that checks for demo mode\n const extendedFetcher =\n fetcher === null\n ? null\n : async (...args: Parameters<typeof fetcher>) => {\n // Resolve the key if it's a function\n const resolvedKey = typeof key === 'function' ? key() : key\n\n // If no key, let SWR handle it\n if (resolvedKey === null || resolvedKey === undefined) {\n return fetcher(...args)\n }\n\n // If demo mode is not enabled, use original fetcher\n if (!isEnabled()) {\n return fetcher(...args)\n }\n\n // Normalize key for matching\n const keyToMatch =\n typeof resolvedKey === 'string' ? resolvedKey : (resolvedKey as unknown[])\n\n // Find matching fixture\n const match = findMatchingFixture(fixtures, keyToMatch)\n\n if (!match) {\n // No fixture found, use original fetcher\n return fetcher(...args)\n }\n\n const [handler, { params, normalizedKey }] = match\n\n // Apply delay if configured\n if (delay > 0) {\n await new Promise((resolve) => setTimeout(resolve, delay))\n }\n\n // Build context\n const context: SWRFixtureContext = {\n key: resolvedKey,\n normalizedKey,\n params,\n match: { matched: true, params },\n }\n\n // Execute handler\n if (typeof handler === 'function') {\n return handler(context)\n }\n\n // Return static value\n return handler\n }\n\n return useSWRNext(key, extendedFetcher, config)\n }\n\n return middleware\n}\n","'use client'\n\nimport { useMemo, useRef, useCallback } from 'react'\nimport { SWRConfig } from 'swr'\nimport type { QueryKey } from '@demokit-ai/core'\nimport { DemoSWRContext } from './context'\nimport { createDemoFetcher, defaultFetcher } from './fetcher'\nimport { createDemoMiddleware } from './middleware'\nimport { normalizeFixtureMap } from './matcher'\nimport type {\n DemoSWRProviderProps,\n SWRFixtureHandler,\n SWRFixtureMap,\n SWRMutationFixtureHandler,\n SWRMutationFixtureMap,\n DemoSWRState,\n} from './types'\n\n/**\n * Provider component for DemoKit SWR integration\n *\n * Wraps SWRConfig and intercepts fetches when demo mode is enabled.\n * Uses SWR's middleware pattern for maximum flexibility.\n *\n * @example\n * // With object-based fixtures\n * <DemoSWRProvider\n * enabled={true}\n * fixtures={{\n * '/api/users': [{ id: '1', name: 'Demo User' }],\n * '[\"/api/users\", \":id\"]': ({ params }) => ({ id: params.id, name: 'Demo User' }),\n * '[\"/api/projects\", { status: \":status\" }]': ({ params }) => [\n * { id: '1', name: 'Project', status: params.status },\n * ],\n * }}\n * delay={100}\n * >\n * <App />\n * </DemoSWRProvider>\n *\n * @example\n * // With Map-based fixtures\n * const fixtures = new Map([\n * [['/api/users'], [{ id: '1', name: 'Demo User' }]],\n * [['/api/users', ':id'], ({ params }) => ({ id: params.id, name: 'Demo User' })],\n * ])\n *\n * <DemoSWRProvider enabled={true} fixtures={fixtures}>\n * <App />\n * </DemoSWRProvider>\n *\n * @example\n * // With cache seeding via fallback\n * <DemoSWRProvider\n * enabled={true}\n * fixtures={fixtures}\n * fallback={{\n * '/api/users': [{ id: '1', name: 'Pre-loaded User' }],\n * }}\n * >\n * <App />\n * </DemoSWRProvider>\n */\nexport function DemoSWRProvider({\n children,\n fixtures = new Map(),\n mutations = new Map(),\n enabled = false,\n delay = 0,\n fallback = {},\n swrConfig = {},\n}: DemoSWRProviderProps) {\n // Normalize fixtures\n const fixturesRef = useRef<SWRFixtureMap>(normalizeFixtureMap(fixtures))\n const mutationFixturesRef = useRef<SWRMutationFixtureMap>(\n mutations instanceof Map ? mutations : new Map(Object.entries(mutations))\n )\n\n const isDemoMode = enabled\n\n // Create demo middleware\n const demoMiddleware = useMemo(\n () =>\n createDemoMiddleware({\n fixtures: fixturesRef.current,\n isEnabled: () => isDemoMode,\n delay,\n }),\n [isDemoMode, delay]\n )\n\n // Create demo fetcher (for direct use)\n const demoFetcher = useMemo(\n () =>\n createDemoFetcher({\n fixtures: fixturesRef.current,\n isEnabled: () => isDemoMode,\n delay,\n fallbackFetcher: defaultFetcher,\n }),\n [isDemoMode, delay]\n )\n\n // Build fallback data from static fixtures + provided fallback\n const combinedFallback = useMemo(() => {\n if (!isDemoMode) return swrConfig.fallback || {}\n\n const staticFixtures: Record<string, unknown> = {}\n\n // Add static fixture values to fallback\n for (const [pattern, handler] of fixturesRef.current) {\n if (typeof handler !== 'function') {\n // Use the pattern as key for static fixtures\n const key = pattern.length === 1 ? String(pattern[0]) : JSON.stringify(pattern)\n staticFixtures[key] = handler\n }\n }\n\n return {\n ...staticFixtures,\n ...fallback,\n ...(swrConfig.fallback || {}),\n }\n }, [isDemoMode, fallback, swrConfig.fallback])\n\n // Build SWR config\n const config = useMemo(\n () => ({\n ...swrConfig,\n use: [...(swrConfig.use || []), demoMiddleware],\n fallback: combinedFallback,\n // In demo mode, don't retry and keep data fresh longer\n ...(isDemoMode\n ? {\n revalidateOnFocus: false,\n revalidateOnReconnect: false,\n shouldRetryOnError: false,\n }\n : {}),\n }),\n [swrConfig, demoMiddleware, combinedFallback, isDemoMode]\n )\n\n // Context value with manipulation methods\n const getFetcher = useCallback(() => demoFetcher, [demoFetcher])\n const getMiddleware = useCallback(() => demoMiddleware, [demoMiddleware])\n\n const contextValue = useMemo<DemoSWRState>(\n () => ({\n isDemoMode,\n\n setFixture: (pattern: QueryKey, handler: SWRFixtureHandler) => {\n fixturesRef.current.set(pattern, handler)\n },\n\n removeFixture: (pattern: QueryKey) => {\n fixturesRef.current.delete(pattern)\n },\n\n setMutationFixture: (name: string, handler: SWRMutationFixtureHandler) => {\n mutationFixturesRef.current.set(name, handler)\n },\n\n removeMutationFixture: (name: string) => {\n mutationFixturesRef.current.delete(name)\n },\n\n getFetcher,\n getMiddleware,\n }),\n [isDemoMode, getFetcher, getMiddleware]\n )\n\n return (\n <DemoSWRContext.Provider value={contextValue}>\n <SWRConfig value={config}>{children}</SWRConfig>\n </DemoSWRContext.Provider>\n )\n}\n","'use client'\n\nimport { useContext, useCallback } from 'react'\nimport useSWRMutation, { type SWRMutationConfiguration, type SWRMutationResponse } from 'swr/mutation'\nimport { useSWRConfig } from 'swr'\nimport { DemoSWRContext } from './context'\nimport type { DemoSWRState, SWRMutationFixtureContext, SWRMutationFixtureHandler } from './types'\n\n/**\n * Hook to access DemoSWR state and controls\n *\n * @returns DemoSWR context value\n * @throws Error if used outside of DemoSWRProvider\n *\n * @example\n * function MyComponent() {\n * const { isDemoMode, setFixture } = useDemoSWR()\n *\n * // Dynamically add a fixture\n * const handleAddFixture = () => {\n * setFixture(['/api/users', 'custom'], { id: 'custom', name: 'Custom User' })\n * }\n *\n * return (\n * <button onClick={handleAddFixture}>Add Custom Fixture</button>\n * )\n * }\n */\nexport function useDemoSWR(): DemoSWRState {\n const context = useContext(DemoSWRContext)\n\n if (context === undefined) {\n throw new Error(\n 'useDemoSWR must be used within a DemoSWRProvider. ' +\n 'Make sure to wrap your app with <DemoSWRProvider>.'\n )\n }\n\n return context\n}\n\n/**\n * Hook to check if demo mode is enabled\n * Shorthand for useDemoSWR().isDemoMode\n *\n * @example\n * function MyComponent() {\n * const isDemoMode = useIsDemoSWRMode()\n *\n * return isDemoMode ? <DemoBadge /> : null\n * }\n */\nexport function useIsDemoSWRMode(): boolean {\n return useDemoSWR().isDemoMode\n}\n\n/**\n * Options for useDemoSWRMutation hook\n */\nexport interface UseDemoSWRMutationOptions<TData, TError, TArg>\n extends Omit<SWRMutationConfiguration<TData, TError, string, TArg>, 'fetcher'> {\n /**\n * The real mutation function to use when demo mode is disabled\n */\n fetcher: (key: string, options: { arg: TArg }) => Promise<TData>\n\n /**\n * Demo fixture handler for this mutation\n */\n demoFixture?: SWRMutationFixtureHandler<TData, TArg>\n\n /**\n * Delay in ms before returning demo data\n * @default 0\n */\n demoDelay?: number\n}\n\n/**\n * A mutation hook that automatically uses demo fixtures when demo mode is enabled\n *\n * Works with useSWRMutation from swr/mutation.\n *\n * @example\n * const { trigger: createUser, isMutating } = useDemoSWRMutation('/api/users', {\n * fetcher: async (key, { arg }) => api.createUser(arg),\n * demoFixture: ({ arg, mutate }) => {\n * // Create demo user\n * const newUser = { id: crypto.randomUUID(), ...arg }\n *\n * // Update the users cache\n * mutate('/api/users', (current: User[] = []) => [...current, newUser])\n *\n * return newUser\n * },\n * onSuccess: (data) => {\n * console.log('Created user:', data)\n * },\n * })\n *\n * // Use like normal useSWRMutation\n * createUser({ name: 'New User', email: 'user@example.com' })\n */\nexport function useDemoSWRMutation<TData = unknown, TError = unknown, TArg = unknown>(\n key: string,\n options: UseDemoSWRMutationOptions<TData, TError, TArg>\n): SWRMutationResponse<TData, TError, string, TArg> {\n const { fetcher, demoFixture, demoDelay = 0, ...mutationOptions } = options\n\n const { mutate } = useSWRConfig()\n\n // Try to get demo state - may not be in DemoSWRProvider context\n let isDemoMode = false\n try {\n const demoState = useDemoSWR()\n isDemoMode = demoState.isDemoMode\n } catch {\n // Not in DemoSWRProvider context, use real mutation\n }\n\n // Create the demo-aware mutation function\n const demoAwareFetcher = useCallback(\n async (mutationKey: string, { arg }: { arg: TArg }): Promise<TData> => {\n // If not in demo mode, use real mutation\n if (!isDemoMode) {\n return fetcher(mutationKey, { arg })\n }\n\n // Apply delay if configured\n if (demoDelay > 0) {\n await new Promise((resolve) => setTimeout(resolve, demoDelay))\n }\n\n // If a demo fixture is provided, use it\n if (demoFixture !== undefined) {\n const context: SWRMutationFixtureContext<TData, TArg> = {\n key: mutationKey,\n arg,\n currentData: undefined, // SWR mutation doesn't have direct access to current data\n mutate: mutate as SWRMutationFixtureContext<TData, TArg>['mutate'],\n }\n\n if (typeof demoFixture === 'function') {\n const fixtureFn = demoFixture as (\n context: SWRMutationFixtureContext<TData, TArg>\n ) => TData | Promise<TData>\n return fixtureFn(context)\n }\n return demoFixture as TData\n }\n\n // No fixture found, fall back to real mutation\n console.warn(\n `[DemoKit SWR] No mutation fixture found for \"${key}\". Using real mutation function.`\n )\n return fetcher(mutationKey, { arg })\n },\n [isDemoMode, fetcher, demoFixture, demoDelay, key, mutate]\n )\n\n return useSWRMutation(key, demoAwareFetcher, mutationOptions)\n}\n"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/provider.tsx","../src/context.ts","../src/matcher.ts","../src/fetcher.ts","../src/middleware.ts","../src/hooks.ts"],"sourcesContent":["/**\n * @demokit-ai/swr\n *\n * SWR adapter for DemoKit.\n * Mock fetches and mutations when demo mode is enabled using SWR's middleware pattern.\n *\n * @example\n * import { DemoSWRProvider } from '@demokit-ai/swr'\n *\n * // Define fixtures\n * const fixtures = {\n * '/api/users': [\n * { id: '1', name: 'Demo User' },\n * { id: '2', name: 'Another User' },\n * ],\n * '[\"/api/users\", \":id\"]': ({ params }) => ({\n * id: params.id,\n * name: `User ${params.id}`,\n * }),\n * '[\"/api/projects\", { status: \":status\" }]': ({ params }) => [\n * { id: '1', name: 'Project', status: params.status },\n * ],\n * }\n *\n * // Wrap your app\n * <DemoSWRProvider fixtures={fixtures} enabled={true}>\n * <App />\n * </DemoSWRProvider>\n *\n * @packageDocumentation\n */\n\n// Provider\nexport { DemoSWRProvider } from './provider'\n\n// Hooks\nexport { useDemoSWR, useIsDemoSWRMode, useDemoSWRMutation } from './hooks'\nexport type { UseDemoSWRMutationOptions } from './hooks'\n\n// Fetcher utilities\nexport { createDemoFetcher, defaultFetcher } from './fetcher'\nexport type { CreateDemoFetcherOptions } from './fetcher'\n\n// Middleware\nexport { createDemoMiddleware } from './middleware'\nexport type { CreateDemoMiddlewareOptions } from './middleware'\n\n// Matcher utilities\nexport {\n findMatchingFixture,\n normalizeKey,\n normalizeFixtureMap,\n parsePatternString,\n matchQueryKey,\n} from './matcher'\n\n// Types\nexport type {\n SWRFixtureContext,\n SWRFixtureHandler,\n SWRFixtureMap,\n SWRFixtureMapObject,\n SWRMutationFixtureContext,\n SWRMutationFixtureHandler,\n SWRMutationFixtureMap,\n SWRMutationFixtureMapObject,\n DemoSWRProviderConfig,\n DemoSWRProviderProps,\n DemoSWRState,\n} from './types'\n","'use client'\n\nimport { useMemo, useRef, useCallback } from 'react'\nimport { SWRConfig } from 'swr'\nimport type { QueryKey } from '@demokit-ai/core'\nimport { DemoSWRContext } from './context'\nimport { createDemoFetcher, defaultFetcher } from './fetcher'\nimport { createDemoMiddleware } from './middleware'\nimport { normalizeFixtureMap } from './matcher'\nimport type {\n DemoSWRProviderProps,\n SWRFixtureHandler,\n SWRFixtureMap,\n SWRMutationFixtureHandler,\n SWRMutationFixtureMap,\n DemoSWRState,\n} from './types'\n\n/**\n * Provider component for DemoKit SWR integration\n *\n * Wraps SWRConfig and intercepts fetches when demo mode is enabled.\n * Uses SWR's middleware pattern for maximum flexibility.\n *\n * @example\n * // With object-based fixtures\n * <DemoSWRProvider\n * enabled={true}\n * fixtures={{\n * '/api/users': [{ id: '1', name: 'Demo User' }],\n * '[\"/api/users\", \":id\"]': ({ params }) => ({ id: params.id, name: 'Demo User' }),\n * '[\"/api/projects\", { status: \":status\" }]': ({ params }) => [\n * { id: '1', name: 'Project', status: params.status },\n * ],\n * }}\n * delay={100}\n * >\n * <App />\n * </DemoSWRProvider>\n *\n * @example\n * // With Map-based fixtures\n * const fixtures = new Map([\n * [['/api/users'], [{ id: '1', name: 'Demo User' }]],\n * [['/api/users', ':id'], ({ params }) => ({ id: params.id, name: 'Demo User' })],\n * ])\n *\n * <DemoSWRProvider enabled={true} fixtures={fixtures}>\n * <App />\n * </DemoSWRProvider>\n *\n * @example\n * // With cache seeding via fallback\n * <DemoSWRProvider\n * enabled={true}\n * fixtures={fixtures}\n * fallback={{\n * '/api/users': [{ id: '1', name: 'Pre-loaded User' }],\n * }}\n * >\n * <App />\n * </DemoSWRProvider>\n */\nexport function DemoSWRProvider({\n children,\n fixtures = new Map(),\n mutations = new Map(),\n enabled = false,\n delay = 0,\n fallback = {},\n swrConfig = {},\n}: DemoSWRProviderProps) {\n // Normalize fixtures\n const fixturesRef = useRef<SWRFixtureMap>(normalizeFixtureMap(fixtures))\n const mutationFixturesRef = useRef<SWRMutationFixtureMap>(\n mutations instanceof Map ? mutations : new Map(Object.entries(mutations))\n )\n\n const isDemoMode = enabled\n\n // Create demo middleware\n const demoMiddleware = useMemo(\n () =>\n createDemoMiddleware({\n fixtures: fixturesRef.current,\n isEnabled: () => isDemoMode,\n delay,\n }),\n [isDemoMode, delay]\n )\n\n // Create demo fetcher (for direct use)\n const demoFetcher = useMemo(\n () =>\n createDemoFetcher({\n fixtures: fixturesRef.current,\n isEnabled: () => isDemoMode,\n delay,\n fallbackFetcher: defaultFetcher,\n }),\n [isDemoMode, delay]\n )\n\n // Build fallback data from static fixtures + provided fallback\n const combinedFallback = useMemo(() => {\n if (!isDemoMode) return swrConfig.fallback || {}\n\n const staticFixtures: Record<string, unknown> = {}\n\n // Add static fixture values to fallback\n for (const [pattern, handler] of fixturesRef.current) {\n if (typeof handler !== 'function') {\n // Use the pattern as key for static fixtures\n const key = pattern.length === 1 ? String(pattern[0]) : JSON.stringify(pattern)\n staticFixtures[key] = handler\n }\n }\n\n return {\n ...staticFixtures,\n ...fallback,\n ...(swrConfig.fallback || {}),\n }\n }, [isDemoMode, fallback, swrConfig.fallback])\n\n // Build SWR config\n const config = useMemo(\n () => ({\n ...swrConfig,\n use: [...(swrConfig.use || []), demoMiddleware],\n fallback: combinedFallback,\n // In demo mode, don't retry and keep data fresh longer\n ...(isDemoMode\n ? {\n revalidateOnFocus: false,\n revalidateOnReconnect: false,\n shouldRetryOnError: false,\n }\n : {}),\n }),\n [swrConfig, demoMiddleware, combinedFallback, isDemoMode]\n )\n\n // Context value with manipulation methods\n const getFetcher = useCallback(() => demoFetcher, [demoFetcher])\n const getMiddleware = useCallback(() => demoMiddleware, [demoMiddleware])\n\n const contextValue = useMemo<DemoSWRState>(\n () => ({\n isDemoMode,\n\n setFixture: (pattern: QueryKey, handler: SWRFixtureHandler) => {\n fixturesRef.current.set(pattern, handler)\n },\n\n removeFixture: (pattern: QueryKey) => {\n fixturesRef.current.delete(pattern)\n },\n\n setMutationFixture: (name: string, handler: SWRMutationFixtureHandler) => {\n mutationFixturesRef.current.set(name, handler)\n },\n\n removeMutationFixture: (name: string) => {\n mutationFixturesRef.current.delete(name)\n },\n\n getFetcher,\n getMiddleware,\n }),\n [isDemoMode, getFetcher, getMiddleware]\n )\n\n return (\n <DemoSWRContext.Provider value={contextValue}>\n <SWRConfig value={config}>{children}</SWRConfig>\n </DemoSWRContext.Provider>\n )\n}\n","'use client'\n\nimport { createContext } from 'react'\nimport type { DemoSWRState } from './types'\n\n/**\n * Context for DemoSWR state\n * @internal\n */\nexport const DemoSWRContext = createContext<DemoSWRState | undefined>(undefined)\n\nDemoSWRContext.displayName = 'DemoSWRContext'\n","import { matchQueryKey, findMatchingQueryKeyPattern } from '@demokit-ai/core'\nimport type { QueryKey } from '@demokit-ai/core'\nimport type { SWRFixtureHandler, SWRFixtureMap, SWRFixtureMapObject } from './types'\n\n/**\n * Normalize an SWR key to a QueryKey for matching\n *\n * SWR keys can be:\n * - Strings: '/api/users' -> ['/api/users']\n * - Arrays: ['/api/users', id] -> ['/api/users', id]\n * - Functions that return keys (not handled here)\n */\nexport function normalizeKey(key: string | unknown[]): QueryKey {\n if (typeof key === 'string') {\n return [key]\n }\n\n return key.map((element) => {\n if (element === null || element === undefined) {\n return element\n }\n if (typeof element === 'object') {\n return element as Record<string, unknown>\n }\n return element as string | number | boolean\n })\n}\n\n/**\n * Parse a JSON string pattern into a QueryKey\n * Handles both array notation and simple string patterns\n *\n * @example\n * parsePatternString('[\"/api/users\"]') // ['/api/users']\n * parsePatternString('[\"/api/users\", \":id\"]') // ['/api/users', ':id']\n * parsePatternString('/api/users') // ['/api/users']\n */\nexport function parsePatternString(pattern: string): QueryKey {\n // Try to parse as JSON array\n if (pattern.startsWith('[')) {\n try {\n return JSON.parse(pattern) as QueryKey\n } catch {\n // Fall through to simple string\n }\n }\n\n // Simple string becomes single-element array\n return [pattern]\n}\n\n/**\n * Convert object-based fixture map to Map-based fixture map\n */\nexport function normalizeFixtureMap(fixtures: SWRFixtureMapObject | SWRFixtureMap): SWRFixtureMap {\n if (fixtures instanceof Map) {\n return fixtures\n }\n\n const map = new Map<QueryKey, SWRFixtureHandler>()\n for (const [pattern, handler] of Object.entries(fixtures)) {\n map.set(parsePatternString(pattern), handler)\n }\n return map\n}\n\n/**\n * Find a matching fixture for an SWR key\n *\n * @param fixtures - Map of key patterns to handlers\n * @param key - The SWR key to match\n * @returns Tuple of [handler, match result] or null if no match\n */\nexport function findMatchingFixture(\n fixtures: SWRFixtureMap,\n key: string | unknown[]\n): [SWRFixtureHandler, { params: Record<string, unknown>; normalizedKey: QueryKey }] | null {\n const normalizedKey = normalizeKey(key)\n const result = findMatchingQueryKeyPattern(fixtures, normalizedKey)\n\n if (result) {\n const [, handler, matchResult] = result\n return [handler, { params: matchResult.params, normalizedKey }]\n }\n\n return null\n}\n\n/**\n * Re-export the matchQueryKey function for direct use\n */\nexport { matchQueryKey }","import type { QueryKey } from '@demokit-ai/core'\nimport type { SWRFixtureMap, SWRFixtureContext } from './types'\nimport { findMatchingFixture, normalizeKey } from './matcher'\n\n/**\n * Options for creating a demo-aware fetcher\n */\nexport interface CreateDemoFetcherOptions {\n /**\n * Map of key patterns to fixture handlers\n */\n fixtures: SWRFixtureMap\n\n /**\n * Function to check if demo mode is enabled\n */\n isEnabled: () => boolean\n\n /**\n * Delay in ms before returning fixture data\n * @default 0\n */\n delay?: number\n\n /**\n * Fallback fetcher to use when demo mode is disabled\n * or no fixture matches\n */\n fallbackFetcher?: <T>(key: string | unknown[]) => Promise<T>\n}\n\n/**\n * Create a demo-aware fetcher function for SWR\n *\n * This fetcher intercepts requests when demo mode is enabled\n * and returns fixture data instead of making real API calls.\n *\n * @example\n * const fixtures = new Map([\n * [['/api/users'], [{ id: '1', name: 'Demo User' }]],\n * [['/api/users', ':id'], ({ params }) => ({ id: params.id, name: 'User' })],\n * ])\n *\n * const fetcher = createDemoFetcher({\n * fixtures,\n * isEnabled: () => isDemoMode,\n * delay: 100,\n * })\n *\n * // Use with SWR\n * const { data } = useSWR('/api/users', fetcher)\n */\nexport function createDemoFetcher(options: CreateDemoFetcherOptions) {\n const { fixtures, isEnabled, delay = 0, fallbackFetcher } = options\n\n return async function demoFetcher<TData = unknown>(key: string | unknown[]): Promise<TData> {\n // If demo mode is not enabled, use fallback\n if (!isEnabled()) {\n if (fallbackFetcher) {\n return fallbackFetcher<TData>(key)\n }\n throw new Error(\n `[DemoKit SWR] No fallback fetcher provided and demo mode is disabled. ` +\n `Key: ${JSON.stringify(key)}`\n )\n }\n\n // Find matching fixture\n const match = findMatchingFixture(fixtures, key)\n\n if (!match) {\n // No fixture found, try fallback\n if (fallbackFetcher) {\n return fallbackFetcher<TData>(key)\n }\n throw new Error(`[DemoKit SWR] No fixture found for key: ${JSON.stringify(key)}`)\n }\n\n const [handler, { params, normalizedKey }] = match\n\n // Apply delay if configured\n if (delay > 0) {\n await new Promise((resolve) => setTimeout(resolve, delay))\n }\n\n // Build context\n const context: SWRFixtureContext = {\n key,\n normalizedKey,\n params,\n match: { matched: true, params },\n }\n\n // Execute handler\n if (typeof handler === 'function') {\n return handler(context) as TData\n }\n\n // Return static value\n return handler as TData\n }\n}\n\n/**\n * Default fetcher that uses fetch API\n * Used as fallback when demo mode is disabled\n */\nexport async function defaultFetcher<TData = unknown>(key: string | unknown[]): Promise<TData> {\n const url = typeof key === 'string' ? key : String(key[0])\n const response = await fetch(url)\n\n if (!response.ok) {\n const error = new Error('An error occurred while fetching the data.')\n throw error\n }\n\n return response.json()\n}\n","import type { Middleware } from 'swr'\nimport type { SWRFixtureMap, SWRFixtureContext } from './types'\nimport { findMatchingFixture } from './matcher'\n\n/**\n * Options for creating the demo middleware\n */\nexport interface CreateDemoMiddlewareOptions {\n /**\n * Map of key patterns to fixture handlers\n */\n fixtures: SWRFixtureMap\n\n /**\n * Function to check if demo mode is enabled\n */\n isEnabled: () => boolean\n\n /**\n * Delay in ms before returning fixture data\n * @default 0\n */\n delay?: number\n}\n\n/**\n * Create a demo-aware SWR middleware\n *\n * This middleware intercepts SWR requests when demo mode is enabled\n * and returns fixture data instead of using the original fetcher.\n *\n * @example\n * import { SWRConfig } from 'swr'\n * import { createDemoMiddleware } from '@demokit-ai/swr'\n *\n * const fixtures = new Map([\n * [['/api/users'], [{ id: '1', name: 'Demo User' }]],\n * [['/api/users', ':id'], ({ params }) => ({ id: params.id, name: 'User' })],\n * ])\n *\n * const demoMiddleware = createDemoMiddleware({\n * fixtures,\n * isEnabled: () => isDemoMode,\n * delay: 100,\n * })\n *\n * function App() {\n * return (\n * <SWRConfig value={{ use: [demoMiddleware] }}>\n * <YourApp />\n * </SWRConfig>\n * )\n * }\n */\nexport function createDemoMiddleware(options: CreateDemoMiddlewareOptions): Middleware {\n const { fixtures, isEnabled, delay = 0 } = options\n\n // Use the simpler middleware pattern that SWR expects\n const middleware: Middleware = (useSWRNext) => (key, fetcher, config) => {\n // Create an extended fetcher that checks for demo mode\n const extendedFetcher =\n fetcher === null\n ? null\n : async (...args: Parameters<typeof fetcher>) => {\n // Resolve the key if it's a function\n const resolvedKey = typeof key === 'function' ? key() : key\n\n // If no key, let SWR handle it\n if (resolvedKey === null || resolvedKey === undefined) {\n return fetcher(...args)\n }\n\n // If demo mode is not enabled, use original fetcher\n if (!isEnabled()) {\n return fetcher(...args)\n }\n\n // Normalize key for matching\n const keyToMatch =\n typeof resolvedKey === 'string' ? resolvedKey : (resolvedKey as unknown[])\n\n // Find matching fixture\n const match = findMatchingFixture(fixtures, keyToMatch)\n\n if (!match) {\n // No fixture found, use original fetcher\n return fetcher(...args)\n }\n\n const [handler, { params, normalizedKey }] = match\n\n // Apply delay if configured\n if (delay > 0) {\n await new Promise((resolve) => setTimeout(resolve, delay))\n }\n\n // Build context\n const context: SWRFixtureContext = {\n key: resolvedKey,\n normalizedKey,\n params,\n match: { matched: true, params },\n }\n\n // Execute handler\n if (typeof handler === 'function') {\n return handler(context)\n }\n\n // Return static value\n return handler\n }\n\n return useSWRNext(key, extendedFetcher, config)\n }\n\n return middleware\n}\n","'use client'\n\nimport { useContext, useCallback } from 'react'\nimport useSWRMutation, { type SWRMutationConfiguration, type SWRMutationResponse } from 'swr/mutation'\nimport { useSWRConfig } from 'swr'\nimport { DemoSWRContext } from './context'\nimport type { DemoSWRState, SWRMutationFixtureContext, SWRMutationFixtureHandler } from './types'\n\n/**\n * Hook to access DemoSWR state and controls\n *\n * @returns DemoSWR context value\n * @throws Error if used outside of DemoSWRProvider\n *\n * @example\n * function MyComponent() {\n * const { isDemoMode, setFixture } = useDemoSWR()\n *\n * // Dynamically add a fixture\n * const handleAddFixture = () => {\n * setFixture(['/api/users', 'custom'], { id: 'custom', name: 'Custom User' })\n * }\n *\n * return (\n * <button onClick={handleAddFixture}>Add Custom Fixture</button>\n * )\n * }\n */\nexport function useDemoSWR(): DemoSWRState {\n const context = useContext(DemoSWRContext)\n\n if (context === undefined) {\n throw new Error(\n 'useDemoSWR must be used within a DemoSWRProvider. ' +\n 'Make sure to wrap your app with <DemoSWRProvider>.'\n )\n }\n\n return context\n}\n\n/**\n * Hook to check if demo mode is enabled\n * Shorthand for useDemoSWR().isDemoMode\n *\n * @example\n * function MyComponent() {\n * const isDemoMode = useIsDemoSWRMode()\n *\n * return isDemoMode ? <DemoBadge /> : null\n * }\n */\nexport function useIsDemoSWRMode(): boolean {\n return useDemoSWR().isDemoMode\n}\n\n/**\n * Options for useDemoSWRMutation hook\n */\nexport interface UseDemoSWRMutationOptions<TData, TError, TArg>\n extends Omit<SWRMutationConfiguration<TData, TError, string, TArg>, 'fetcher'> {\n /**\n * The real mutation function to use when demo mode is disabled\n */\n fetcher: (key: string, options: { arg: TArg }) => Promise<TData>\n\n /**\n * Demo fixture handler for this mutation\n */\n demoFixture?: SWRMutationFixtureHandler<TData, TArg>\n\n /**\n * Delay in ms before returning demo data\n * @default 0\n */\n demoDelay?: number\n}\n\n/**\n * A mutation hook that automatically uses demo fixtures when demo mode is enabled\n *\n * Works with useSWRMutation from swr/mutation.\n *\n * @example\n * const { trigger: createUser, isMutating } = useDemoSWRMutation('/api/users', {\n * fetcher: async (key, { arg }) => api.createUser(arg),\n * demoFixture: ({ arg, mutate }) => {\n * // Create demo user\n * const newUser = { id: crypto.randomUUID(), ...arg }\n *\n * // Update the users cache\n * mutate('/api/users', (current: User[] = []) => [...current, newUser])\n *\n * return newUser\n * },\n * onSuccess: (data) => {\n * console.log('Created user:', data)\n * },\n * })\n *\n * // Use like normal useSWRMutation\n * createUser({ name: 'New User', email: 'user@example.com' })\n */\nexport function useDemoSWRMutation<TData = unknown, TError = unknown, TArg = unknown>(\n key: string,\n options: UseDemoSWRMutationOptions<TData, TError, TArg>\n): SWRMutationResponse<TData, TError, string, TArg> {\n const { fetcher, demoFixture, demoDelay = 0, ...mutationOptions } = options\n\n const { mutate } = useSWRConfig()\n\n // Try to get demo state - may not be in DemoSWRProvider context\n let isDemoMode = false\n try {\n const demoState = useDemoSWR()\n isDemoMode = demoState.isDemoMode\n } catch {\n // Not in DemoSWRProvider context, use real mutation\n }\n\n // Create the demo-aware mutation function\n const demoAwareFetcher = useCallback(\n async (mutationKey: string, { arg }: { arg: TArg }): Promise<TData> => {\n // If not in demo mode, use real mutation\n if (!isDemoMode) {\n return fetcher(mutationKey, { arg })\n }\n\n // Apply delay if configured\n if (demoDelay > 0) {\n await new Promise((resolve) => setTimeout(resolve, demoDelay))\n }\n\n // If a demo fixture is provided, use it\n if (demoFixture !== undefined) {\n const context: SWRMutationFixtureContext<TData, TArg> = {\n key: mutationKey,\n arg,\n currentData: undefined, // SWR mutation doesn't have direct access to current data\n mutate: mutate as SWRMutationFixtureContext<TData, TArg>['mutate'],\n }\n\n if (typeof demoFixture === 'function') {\n const fixtureFn = demoFixture as (\n context: SWRMutationFixtureContext<TData, TArg>\n ) => TData | Promise<TData>\n return fixtureFn(context)\n }\n return demoFixture as TData\n }\n\n // No fixture found, fall back to real mutation\n console.warn(\n `[DemoKit SWR] No mutation fixture found for \"${key}\". Using real mutation function.`\n )\n return fetcher(mutationKey, { arg })\n },\n [isDemoMode, fetcher, demoFixture, demoDelay, key, mutate]\n )\n\n return useSWRMutation(key, demoAwareFetcher, mutationOptions)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEA,IAAAA,gBAA6C;AAC7C,iBAA0B;;;ACD1B,mBAA8B;AAOvB,IAAM,qBAAiB,4BAAwC,MAAS;AAE/E,eAAe,cAAc;;;ACX7B,kBAA2D;AAYpD,SAAS,aAAa,KAAmC;AAC9D,MAAI,OAAO,QAAQ,UAAU;AAC3B,WAAO,CAAC,GAAG;AAAA,EACb;AAEA,SAAO,IAAI,IAAI,CAAC,YAAY;AAC1B,QAAI,YAAY,QAAQ,YAAY,QAAW;AAC7C,aAAO;AAAA,IACT;AACA,QAAI,OAAO,YAAY,UAAU;AAC/B,aAAO;AAAA,IACT;AACA,WAAO;AAAA,EACT,CAAC;AACH;AAWO,SAAS,mBAAmB,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package/dist/index.js CHANGED
@@ -1,13 +1,14 @@
1
- import { createContext, useRef, useMemo, useCallback, useContext } from 'react';
2
- import { SWRConfig, useSWRConfig } from 'swr';
3
- import { findMatchingQueryKeyPattern } from '@demokit-ai/core';
4
- export { matchQueryKey } from '@demokit-ai/core';
5
- import { jsx } from 'react/jsx-runtime';
6
- import useSWRMutation from 'swr/mutation';
7
-
8
1
  // src/provider.tsx
2
+ import { useMemo, useRef, useCallback } from "react";
3
+ import { SWRConfig } from "swr";
4
+
5
+ // src/context.ts
6
+ import { createContext } from "react";
9
7
  var DemoSWRContext = createContext(void 0);
10
8
  DemoSWRContext.displayName = "DemoSWRContext";
9
+
10
+ // src/matcher.ts
11
+ import { matchQueryKey, findMatchingQueryKeyPattern } from "@demokit-ai/core";
11
12
  function normalizeKey(key) {
12
13
  if (typeof key === "string") {
13
14
  return [key];
@@ -132,6 +133,9 @@ function createDemoMiddleware(options) {
132
133
  };
133
134
  return middleware;
134
135
  }
136
+
137
+ // src/provider.tsx
138
+ import { jsx } from "react/jsx-runtime";
135
139
  function DemoSWRProvider({
136
140
  children,
137
141
  fixtures = /* @__PURE__ */ new Map(),
@@ -216,6 +220,11 @@ function DemoSWRProvider({
216
220
  );
217
221
  return /* @__PURE__ */ jsx(DemoSWRContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsx(SWRConfig, { value: config, children }) });
218
222
  }
223
+
224
+ // src/hooks.ts
225
+ import { useContext, useCallback as useCallback2 } from "react";
226
+ import useSWRMutation from "swr/mutation";
227
+ import { useSWRConfig } from "swr";
219
228
  function useDemoSWR() {
220
229
  const context = useContext(DemoSWRContext);
221
230
  if (context === void 0) {
@@ -237,7 +246,7 @@ function useDemoSWRMutation(key, options) {
237
246
  isDemoMode = demoState.isDemoMode;
238
247
  } catch {
239
248
  }
240
- const demoAwareFetcher = useCallback(
249
+ const demoAwareFetcher = useCallback2(
241
250
  async (mutationKey, { arg }) => {
242
251
  if (!isDemoMode) {
243
252
  return fetcher(mutationKey, { arg });
@@ -268,7 +277,18 @@ function useDemoSWRMutation(key, options) {
268
277
  );
269
278
  return useSWRMutation(key, demoAwareFetcher, mutationOptions);
270
279
  }
271
-
272
- export { DemoSWRProvider, createDemoFetcher, createDemoMiddleware, defaultFetcher, findMatchingFixture, normalizeFixtureMap, normalizeKey, parsePatternString, useDemoSWR, useDemoSWRMutation, useIsDemoSWRMode };
273
- //# sourceMappingURL=index.js.map
280
+ export {
281
+ DemoSWRProvider,
282
+ createDemoFetcher,
283
+ createDemoMiddleware,
284
+ defaultFetcher,
285
+ findMatchingFixture,
286
+ matchQueryKey,
287
+ normalizeFixtureMap,
288
+ normalizeKey,
289
+ parsePatternString,
290
+ useDemoSWR,
291
+ useDemoSWRMutation,
292
+ useIsDemoSWRMode
293
+ };
274
294
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/context.ts","../src/matcher.ts","../src/fetcher.ts","../src/middleware.ts","../src/provider.tsx","../src/hooks.ts"],"names":["useCallback"],"mappings":";;;;;;;;AASO,IAAM,cAAA,GAAiB,cAAwC,MAAS,CAAA;AAE/E,cAAA,CAAe,WAAA,GAAc,gBAAA;ACCtB,SAAS,aAAa,GAAA,EAAmC;AAC9D,EAAA,IAAI,OAAO,QAAQ,QAAA,EAAU;AAC3B,IAAA,OAAO,CAAC,GAAG,CAAA;AAAA,EACb;AAEA,EAAA,OAAO,GAAA,CAAI,GAAA,CAAI,CAAC,OAAA,KAAY;AAC1B,IAAA,IAAI,OAAA,KAAY,IAAA,IAAQ,OAAA,KAAY,MAAA,EAAW;AAC7C,MAAA,OAAO,OAAA;AAAA,IACT;AACA,IAAA,IAAI,OAAO,YAAY,QAAA,EAAU;AAC/B,MAAA,OAAO,OAAA;AAAA,IACT;AACA,IAAA,OAAO,OAAA;AAAA,EACT,CAAC,CAAA;AACH;AAWO,SAAS,mBAAmB,OAAA,EAA2B;AAE5D,EAAA,IAAI,OAAA,CAAQ,UAAA,C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,CAAA;AAAA,IACrC,CAAA;AAAA,IACA,CAAC,UAAA,EAAY,OAAA,EAAS,WAAA,EAAa,SAAA,EAAW,KAAK,MAAM;AAAA,GAC3D;AAEA,EAAA,OAAO,cAAA,CAAe,GAAA,EAAK,gBAAA,EAAkB,eAAe,CAAA;AAC9D","file":"index.js","sourcesContent":["'use client'\n\nimport { createContext } from 'react'\nimport type { DemoSWRState } from './types'\n\n/**\n * Context for DemoSWR state\n * @internal\n */\nexport const DemoSWRContext = createContext<DemoSWRState | undefined>(undefined)\n\nDemoSWRContext.displayName = 'DemoSWRContext'\n","import { matchQueryKey, findMatchingQueryKeyPattern } from '@demokit-ai/core'\nimport type { QueryKey } from '@demokit-ai/core'\nimport type { SWRFixtureHandler, SWRFixtureMap, SWRFixtureMapObject } from './types'\n\n/**\n * Normalize an SWR key to a QueryKey for matching\n *\n * SWR keys can be:\n * - Strings: '/api/users' -> ['/api/users']\n * - Arrays: ['/api/users', id] -> ['/api/users', id]\n * - Functions that return keys (not handled here)\n */\nexport function normalizeKey(key: string | unknown[]): QueryKey {\n if (typeof key === 'string') {\n return [key]\n }\n\n return key.map((element) => {\n if (element === null || element === undefined) {\n return element\n }\n if (typeof element === 'object') {\n return element as Record<string, unknown>\n }\n return element as string | number | boolean\n })\n}\n\n/**\n * Parse a JSON string pattern into a QueryKey\n * Handles both array notation and simple string patterns\n *\n * @example\n * parsePatternString('[\"/api/users\"]') // ['/api/users']\n * parsePatternString('[\"/api/users\", \":id\"]') // ['/api/users', ':id']\n * parsePatternString('/api/users') // ['/api/users']\n */\nexport function parsePatternString(pattern: string): QueryKey {\n // Try to parse as JSON array\n if (pattern.startsWith('[')) {\n try {\n return JSON.parse(pattern) as QueryKey\n } catch {\n // Fall through to simple string\n }\n }\n\n // Simple string becomes single-element array\n return [pattern]\n}\n\n/**\n * Convert object-based fixture map to Map-based fixture map\n */\nexport function normalizeFixtureMap(fixtures: SWRFixtureMapObject | SWRFixtureMap): SWRFixtureMap {\n if (fixtures instanceof Map) {\n return fixtures\n }\n\n const map = new Map<QueryKey, SWRFixtureHandler>()\n for (const [pattern, handler] of Object.entries(fixtures)) {\n map.set(parsePatternString(pattern), handler)\n }\n return map\n}\n\n/**\n * Find a matching fixture for an SWR key\n *\n * @param fixtures - Map of key patterns to handlers\n * @param key - The SWR key to match\n * @returns Tuple of [handler, match result] or null if no match\n */\nexport function findMatchingFixture(\n fixtures: SWRFixtureMap,\n key: string | unknown[]\n): [SWRFixtureHandler, { params: Record<string, unknown>; normalizedKey: QueryKey }] | null {\n const normalizedKey = normalizeKey(key)\n const result = findMatchingQueryKeyPattern(fixtures, normalizedKey)\n\n if (result) {\n const [, handler, matchResult] = result\n return [handler, { params: matchResult.params, normalizedKey }]\n }\n\n return null\n}\n\n/**\n * Re-export the matchQueryKey function for direct use\n */\nexport { matchQueryKey }","import type { QueryKey } from '@demokit-ai/core'\nimport type { SWRFixtureMap, SWRFixtureContext } from './types'\nimport { findMatchingFixture, normalizeKey } from './matcher'\n\n/**\n * Options for creating a demo-aware fetcher\n */\nexport interface CreateDemoFetcherOptions {\n /**\n * Map of key patterns to fixture handlers\n */\n fixtures: SWRFixtureMap\n\n /**\n * Function to check if demo mode is enabled\n */\n isEnabled: () => boolean\n\n /**\n * Delay in ms before returning fixture data\n * @default 0\n */\n delay?: number\n\n /**\n * Fallback fetcher to use when demo mode is disabled\n * or no fixture matches\n */\n fallbackFetcher?: <T>(key: string | unknown[]) => Promise<T>\n}\n\n/**\n * Create a demo-aware fetcher function for SWR\n *\n * This fetcher intercepts requests when demo mode is enabled\n * and returns fixture data instead of making real API calls.\n *\n * @example\n * const fixtures = new Map([\n * [['/api/users'], [{ id: '1', name: 'Demo User' }]],\n * [['/api/users', ':id'], ({ params }) => ({ id: params.id, name: 'User' })],\n * ])\n *\n * const fetcher = createDemoFetcher({\n * fixtures,\n * isEnabled: () => isDemoMode,\n * delay: 100,\n * })\n *\n * // Use with SWR\n * const { data } = useSWR('/api/users', fetcher)\n */\nexport function createDemoFetcher(options: CreateDemoFetcherOptions) {\n const { fixtures, isEnabled, delay = 0, fallbackFetcher } = options\n\n return async function demoFetcher<TData = unknown>(key: string | unknown[]): Promise<TData> {\n // If demo mode is not enabled, use fallback\n if (!isEnabled()) {\n if (fallbackFetcher) {\n return fallbackFetcher<TData>(key)\n }\n throw new Error(\n `[DemoKit SWR] No fallback fetcher provided and demo mode is disabled. ` +\n `Key: ${JSON.stringify(key)}`\n )\n }\n\n // Find matching fixture\n const match = findMatchingFixture(fixtures, key)\n\n if (!match) {\n // No fixture found, try fallback\n if (fallbackFetcher) {\n return fallbackFetcher<TData>(key)\n }\n throw new Error(`[DemoKit SWR] No fixture found for key: ${JSON.stringify(key)}`)\n }\n\n const [handler, { params, normalizedKey }] = match\n\n // Apply delay if configured\n if (delay > 0) {\n await new Promise((resolve) => setTimeout(resolve, delay))\n }\n\n // Build context\n const context: SWRFixtureContext = {\n key,\n normalizedKey,\n params,\n match: { matched: true, params },\n }\n\n // Execute handler\n if (typeof handler === 'function') {\n return handler(context) as TData\n }\n\n // Return static value\n return handler as TData\n }\n}\n\n/**\n * Default fetcher that uses fetch API\n * Used as fallback when demo mode is disabled\n */\nexport async function defaultFetcher<TData = unknown>(key: string | unknown[]): Promise<TData> {\n const url = typeof key === 'string' ? key : String(key[0])\n const response = await fetch(url)\n\n if (!response.ok) {\n const error = new Error('An error occurred while fetching the data.')\n throw error\n }\n\n return response.json()\n}\n","import type { Middleware } from 'swr'\nimport type { SWRFixtureMap, SWRFixtureContext } from './types'\nimport { findMatchingFixture } from './matcher'\n\n/**\n * Options for creating the demo middleware\n */\nexport interface CreateDemoMiddlewareOptions {\n /**\n * Map of key patterns to fixture handlers\n */\n fixtures: SWRFixtureMap\n\n /**\n * Function to check if demo mode is enabled\n */\n isEnabled: () => boolean\n\n /**\n * Delay in ms before returning fixture data\n * @default 0\n */\n delay?: number\n}\n\n/**\n * Create a demo-aware SWR middleware\n *\n * This middleware intercepts SWR requests when demo mode is enabled\n * and returns fixture data instead of using the original fetcher.\n *\n * @example\n * import { SWRConfig } from 'swr'\n * import { createDemoMiddleware } from '@demokit-ai/swr'\n *\n * const fixtures = new Map([\n * [['/api/users'], [{ id: '1', name: 'Demo User' }]],\n * [['/api/users', ':id'], ({ params }) => ({ id: params.id, name: 'User' })],\n * ])\n *\n * const demoMiddleware = createDemoMiddleware({\n * fixtures,\n * isEnabled: () => isDemoMode,\n * delay: 100,\n * })\n *\n * function App() {\n * return (\n * <SWRConfig value={{ use: [demoMiddleware] }}>\n * <YourApp />\n * </SWRConfig>\n * )\n * }\n */\nexport function createDemoMiddleware(options: CreateDemoMiddlewareOptions): Middleware {\n const { fixtures, isEnabled, delay = 0 } = options\n\n // Use the simpler middleware pattern that SWR expects\n const middleware: Middleware = (useSWRNext) => (key, fetcher, config) => {\n // Create an extended fetcher that checks for demo mode\n const extendedFetcher =\n fetcher === null\n ? null\n : async (...args: Parameters<typeof fetcher>) => {\n // Resolve the key if it's a function\n const resolvedKey = typeof key === 'function' ? key() : key\n\n // If no key, let SWR handle it\n if (resolvedKey === null || resolvedKey === undefined) {\n return fetcher(...args)\n }\n\n // If demo mode is not enabled, use original fetcher\n if (!isEnabled()) {\n return fetcher(...args)\n }\n\n // Normalize key for matching\n const keyToMatch =\n typeof resolvedKey === 'string' ? resolvedKey : (resolvedKey as unknown[])\n\n // Find matching fixture\n const match = findMatchingFixture(fixtures, keyToMatch)\n\n if (!match) {\n // No fixture found, use original fetcher\n return fetcher(...args)\n }\n\n const [handler, { params, normalizedKey }] = match\n\n // Apply delay if configured\n if (delay > 0) {\n await new Promise((resolve) => setTimeout(resolve, delay))\n }\n\n // Build context\n const context: SWRFixtureContext = {\n key: resolvedKey,\n normalizedKey,\n params,\n match: { matched: true, params },\n }\n\n // Execute handler\n if (typeof handler === 'function') {\n return handler(context)\n }\n\n // Return static value\n return handler\n }\n\n return useSWRNext(key, extendedFetcher, config)\n }\n\n return middleware\n}\n","'use client'\n\nimport { useMemo, useRef, useCallback } from 'react'\nimport { SWRConfig } from 'swr'\nimport type { QueryKey } from '@demokit-ai/core'\nimport { DemoSWRContext } from './context'\nimport { createDemoFetcher, defaultFetcher } from './fetcher'\nimport { createDemoMiddleware } from './middleware'\nimport { normalizeFixtureMap } from './matcher'\nimport type {\n DemoSWRProviderProps,\n SWRFixtureHandler,\n SWRFixtureMap,\n SWRMutationFixtureHandler,\n SWRMutationFixtureMap,\n DemoSWRState,\n} from './types'\n\n/**\n * Provider component for DemoKit SWR integration\n *\n * Wraps SWRConfig and intercepts fetches when demo mode is enabled.\n * Uses SWR's middleware pattern for maximum flexibility.\n *\n * @example\n * // With object-based fixtures\n * <DemoSWRProvider\n * enabled={true}\n * fixtures={{\n * '/api/users': [{ id: '1', name: 'Demo User' }],\n * '[\"/api/users\", \":id\"]': ({ params }) => ({ id: params.id, name: 'Demo User' }),\n * '[\"/api/projects\", { status: \":status\" }]': ({ params }) => [\n * { id: '1', name: 'Project', status: params.status },\n * ],\n * }}\n * delay={100}\n * >\n * <App />\n * </DemoSWRProvider>\n *\n * @example\n * // With Map-based fixtures\n * const fixtures = new Map([\n * [['/api/users'], [{ id: '1', name: 'Demo User' }]],\n * [['/api/users', ':id'], ({ params }) => ({ id: params.id, name: 'Demo User' })],\n * ])\n *\n * <DemoSWRProvider enabled={true} fixtures={fixtures}>\n * <App />\n * </DemoSWRProvider>\n *\n * @example\n * // With cache seeding via fallback\n * <DemoSWRProvider\n * enabled={true}\n * fixtures={fixtures}\n * fallback={{\n * '/api/users': [{ id: '1', name: 'Pre-loaded User' }],\n * }}\n * >\n * <App />\n * </DemoSWRProvider>\n */\nexport function DemoSWRProvider({\n children,\n fixtures = new Map(),\n mutations = new Map(),\n enabled = false,\n delay = 0,\n fallback = {},\n swrConfig = {},\n}: DemoSWRProviderProps) {\n // Normalize fixtures\n const fixturesRef = useRef<SWRFixtureMap>(normalizeFixtureMap(fixtures))\n const mutationFixturesRef = useRef<SWRMutationFixtureMap>(\n mutations instanceof Map ? mutations : new Map(Object.entries(mutations))\n )\n\n const isDemoMode = enabled\n\n // Create demo middleware\n const demoMiddleware = useMemo(\n () =>\n createDemoMiddleware({\n fixtures: fixturesRef.current,\n isEnabled: () => isDemoMode,\n delay,\n }),\n [isDemoMode, delay]\n )\n\n // Create demo fetcher (for direct use)\n const demoFetcher = useMemo(\n () =>\n createDemoFetcher({\n fixtures: fixturesRef.current,\n isEnabled: () => isDemoMode,\n delay,\n fallbackFetcher: defaultFetcher,\n }),\n [isDemoMode, delay]\n )\n\n // Build fallback data from static fixtures + provided fallback\n const combinedFallback = useMemo(() => {\n if (!isDemoMode) return swrConfig.fallback || {}\n\n const staticFixtures: Record<string, unknown> = {}\n\n // Add static fixture values to fallback\n for (const [pattern, handler] of fixturesRef.current) {\n if (typeof handler !== 'function') {\n // Use the pattern as key for static fixtures\n const key = pattern.length === 1 ? String(pattern[0]) : JSON.stringify(pattern)\n staticFixtures[key] = handler\n }\n }\n\n return {\n ...staticFixtures,\n ...fallback,\n ...(swrConfig.fallback || {}),\n }\n }, [isDemoMode, fallback, swrConfig.fallback])\n\n // Build SWR config\n const config = useMemo(\n () => ({\n ...swrConfig,\n use: [...(swrConfig.use || []), demoMiddleware],\n fallback: combinedFallback,\n // In demo mode, don't retry and keep data fresh longer\n ...(isDemoMode\n ? {\n revalidateOnFocus: false,\n revalidateOnReconnect: false,\n shouldRetryOnError: false,\n }\n : {}),\n }),\n [swrConfig, demoMiddleware, combinedFallback, isDemoMode]\n )\n\n // Context value with manipulation methods\n const getFetcher = useCallback(() => demoFetcher, [demoFetcher])\n const getMiddleware = useCallback(() => demoMiddleware, [demoMiddleware])\n\n const contextValue = useMemo<DemoSWRState>(\n () => ({\n isDemoMode,\n\n setFixture: (pattern: QueryKey, handler: SWRFixtureHandler) => {\n fixturesRef.current.set(pattern, handler)\n },\n\n removeFixture: (pattern: QueryKey) => {\n fixturesRef.current.delete(pattern)\n },\n\n setMutationFixture: (name: string, handler: SWRMutationFixtureHandler) => {\n mutationFixturesRef.current.set(name, handler)\n },\n\n removeMutationFixture: (name: string) => {\n mutationFixturesRef.current.delete(name)\n },\n\n getFetcher,\n getMiddleware,\n }),\n [isDemoMode, getFetcher, getMiddleware]\n )\n\n return (\n <DemoSWRContext.Provider value={contextValue}>\n <SWRConfig value={config}>{children}</SWRConfig>\n </DemoSWRContext.Provider>\n )\n}\n","'use client'\n\nimport { useContext, useCallback } from 'react'\nimport useSWRMutation, { type SWRMutationConfiguration, type SWRMutationResponse } from 'swr/mutation'\nimport { useSWRConfig } from 'swr'\nimport { DemoSWRContext } from './context'\nimport type { DemoSWRState, SWRMutationFixtureContext, SWRMutationFixtureHandler } from './types'\n\n/**\n * Hook to access DemoSWR state and controls\n *\n * @returns DemoSWR context value\n * @throws Error if used outside of DemoSWRProvider\n *\n * @example\n * function MyComponent() {\n * const { isDemoMode, setFixture } = useDemoSWR()\n *\n * // Dynamically add a fixture\n * const handleAddFixture = () => {\n * setFixture(['/api/users', 'custom'], { id: 'custom', name: 'Custom User' })\n * }\n *\n * return (\n * <button onClick={handleAddFixture}>Add Custom Fixture</button>\n * )\n * }\n */\nexport function useDemoSWR(): DemoSWRState {\n const context = useContext(DemoSWRContext)\n\n if (context === undefined) {\n throw new Error(\n 'useDemoSWR must be used within a DemoSWRProvider. ' +\n 'Make sure to wrap your app with <DemoSWRProvider>.'\n )\n }\n\n return context\n}\n\n/**\n * Hook to check if demo mode is enabled\n * Shorthand for useDemoSWR().isDemoMode\n *\n * @example\n * function MyComponent() {\n * const isDemoMode = useIsDemoSWRMode()\n *\n * return isDemoMode ? <DemoBadge /> : null\n * }\n */\nexport function useIsDemoSWRMode(): boolean {\n return useDemoSWR().isDemoMode\n}\n\n/**\n * Options for useDemoSWRMutation hook\n */\nexport interface UseDemoSWRMutationOptions<TData, TError, TArg>\n extends Omit<SWRMutationConfiguration<TData, TError, string, TArg>, 'fetcher'> {\n /**\n * The real mutation function to use when demo mode is disabled\n */\n fetcher: (key: string, options: { arg: TArg }) => Promise<TData>\n\n /**\n * Demo fixture handler for this mutation\n */\n demoFixture?: SWRMutationFixtureHandler<TData, TArg>\n\n /**\n * Delay in ms before returning demo data\n * @default 0\n */\n demoDelay?: number\n}\n\n/**\n * A mutation hook that automatically uses demo fixtures when demo mode is enabled\n *\n * Works with useSWRMutation from swr/mutation.\n *\n * @example\n * const { trigger: createUser, isMutating } = useDemoSWRMutation('/api/users', {\n * fetcher: async (key, { arg }) => api.createUser(arg),\n * demoFixture: ({ arg, mutate }) => {\n * // Create demo user\n * const newUser = { id: crypto.randomUUID(), ...arg }\n *\n * // Update the users cache\n * mutate('/api/users', (current: User[] = []) => [...current, newUser])\n *\n * return newUser\n * },\n * onSuccess: (data) => {\n * console.log('Created user:', data)\n * },\n * })\n *\n * // Use like normal useSWRMutation\n * createUser({ name: 'New User', email: 'user@example.com' })\n */\nexport function useDemoSWRMutation<TData = unknown, TError = unknown, TArg = unknown>(\n key: string,\n options: UseDemoSWRMutationOptions<TData, TError, TArg>\n): SWRMutationResponse<TData, TError, string, TArg> {\n const { fetcher, demoFixture, demoDelay = 0, ...mutationOptions } = options\n\n const { mutate } = useSWRConfig()\n\n // Try to get demo state - may not be in DemoSWRProvider context\n let isDemoMode = false\n try {\n const demoState = useDemoSWR()\n isDemoMode = demoState.isDemoMode\n } catch {\n // Not in DemoSWRProvider context, use real mutation\n }\n\n // Create the demo-aware mutation function\n const demoAwareFetcher = useCallback(\n async (mutationKey: string, { arg }: { arg: TArg }): Promise<TData> => {\n // If not in demo mode, use real mutation\n if (!isDemoMode) {\n return fetcher(mutationKey, { arg })\n }\n\n // Apply delay if configured\n if (demoDelay > 0) {\n await new Promise((resolve) => setTimeout(resolve, demoDelay))\n }\n\n // If a demo fixture is provided, use it\n if (demoFixture !== undefined) {\n const context: SWRMutationFixtureContext<TData, TArg> = {\n key: mutationKey,\n arg,\n currentData: undefined, // SWR mutation doesn't have direct access to current data\n mutate: mutate as SWRMutationFixtureContext<TData, TArg>['mutate'],\n }\n\n if (typeof demoFixture === 'function') {\n const fixtureFn = demoFixture as (\n context: SWRMutationFixtureContext<TData, TArg>\n ) => TData | Promise<TData>\n return fixtureFn(context)\n }\n return demoFixture as TData\n }\n\n // No fixture found, fall back to real mutation\n console.warn(\n `[DemoKit SWR] No mutation fixture found for \"${key}\". Using real mutation function.`\n )\n return fetcher(mutationKey, { arg })\n },\n [isDemoMode, fetcher, demoFixture, demoDelay, key, mutate]\n )\n\n return useSWRMutation(key, demoAwareFetcher, mutationOptions)\n}\n"]}
1
+ {"version":3,"sources":["../src/provider.tsx","../src/context.ts","../src/matcher.ts","../src/fetcher.ts","../src/middleware.ts","../src/hooks.ts"],"sourcesContent":["'use client'\n\nimport { useMemo, useRef, useCallback } from 'react'\nimport { SWRConfig } from 'swr'\nimport type { QueryKey } from '@demokit-ai/core'\nimport { DemoSWRContext } from './context'\nimport { createDemoFetcher, defaultFetcher } from './fetcher'\nimport { createDemoMiddleware } from './middleware'\nimport { normalizeFixtureMap } from './matcher'\nimport type {\n DemoSWRProviderProps,\n SWRFixtureHandler,\n SWRFixtureMap,\n SWRMutationFixtureHandler,\n SWRMutationFixtureMap,\n DemoSWRState,\n} from './types'\n\n/**\n * Provider component for DemoKit SWR integration\n *\n * Wraps SWRConfig and intercepts fetches when demo mode is enabled.\n * Uses SWR's middleware pattern for maximum flexibility.\n *\n * @example\n * // With object-based fixtures\n * <DemoSWRProvider\n * enabled={true}\n * fixtures={{\n * '/api/users': [{ id: '1', name: 'Demo User' }],\n * '[\"/api/users\", \":id\"]': ({ params }) => ({ id: params.id, name: 'Demo User' }),\n * '[\"/api/projects\", { status: \":status\" }]': ({ params }) => [\n * { id: '1', name: 'Project', status: params.status },\n * ],\n * }}\n * delay={100}\n * >\n * <App />\n * </DemoSWRProvider>\n *\n * @example\n * // With Map-based fixtures\n * const fixtures = new Map([\n * [['/api/users'], [{ id: '1', name: 'Demo User' }]],\n * [['/api/users', ':id'], ({ params }) => ({ id: params.id, name: 'Demo User' })],\n * ])\n *\n * <DemoSWRProvider enabled={true} fixtures={fixtures}>\n * <App />\n * </DemoSWRProvider>\n *\n * @example\n * // With cache seeding via fallback\n * <DemoSWRProvider\n * enabled={true}\n * fixtures={fixtures}\n * fallback={{\n * '/api/users': [{ id: '1', name: 'Pre-loaded User' }],\n * }}\n * >\n * <App />\n * </DemoSWRProvider>\n */\nexport function DemoSWRProvider({\n children,\n fixtures = new Map(),\n mutations = new Map(),\n enabled = false,\n delay = 0,\n fallback = {},\n swrConfig = {},\n}: DemoSWRProviderProps) {\n // Normalize fixtures\n const fixturesRef = useRef<SWRFixtureMap>(normalizeFixtureMap(fixtures))\n const mutationFixturesRef = useRef<SWRMutationFixtureMap>(\n mutations instanceof Map ? mutations : new Map(Object.entries(mutations))\n )\n\n const isDemoMode = enabled\n\n // Create demo middleware\n const demoMiddleware = useMemo(\n () =>\n createDemoMiddleware({\n fixtures: fixturesRef.current,\n isEnabled: () => isDemoMode,\n delay,\n }),\n [isDemoMode, delay]\n )\n\n // Create demo fetcher (for direct use)\n const demoFetcher = useMemo(\n () =>\n createDemoFetcher({\n fixtures: fixturesRef.current,\n isEnabled: () => isDemoMode,\n delay,\n fallbackFetcher: defaultFetcher,\n }),\n [isDemoMode, delay]\n )\n\n // Build fallback data from static fixtures + provided fallback\n const combinedFallback = useMemo(() => {\n if (!isDemoMode) return swrConfig.fallback || {}\n\n const staticFixtures: Record<string, unknown> = {}\n\n // Add static fixture values to fallback\n for (const [pattern, handler] of fixturesRef.current) {\n if (typeof handler !== 'function') {\n // Use the pattern as key for static fixtures\n const key = pattern.length === 1 ? String(pattern[0]) : JSON.stringify(pattern)\n staticFixtures[key] = handler\n }\n }\n\n return {\n ...staticFixtures,\n ...fallback,\n ...(swrConfig.fallback || {}),\n }\n }, [isDemoMode, fallback, swrConfig.fallback])\n\n // Build SWR config\n const config = useMemo(\n () => ({\n ...swrConfig,\n use: [...(swrConfig.use || []), demoMiddleware],\n fallback: combinedFallback,\n // In demo mode, don't retry and keep data fresh longer\n ...(isDemoMode\n ? {\n revalidateOnFocus: false,\n revalidateOnReconnect: false,\n shouldRetryOnError: false,\n }\n : {}),\n }),\n [swrConfig, demoMiddleware, combinedFallback, isDemoMode]\n )\n\n // Context value with manipulation methods\n const getFetcher = useCallback(() => demoFetcher, [demoFetcher])\n const getMiddleware = useCallback(() => demoMiddleware, [demoMiddleware])\n\n const contextValue = useMemo<DemoSWRState>(\n () => ({\n isDemoMode,\n\n setFixture: (pattern: QueryKey, handler: SWRFixtureHandler) => {\n fixturesRef.current.set(pattern, handler)\n },\n\n removeFixture: (pattern: QueryKey) => {\n fixturesRef.current.delete(pattern)\n },\n\n setMutationFixture: (name: string, handler: SWRMutationFixtureHandler) => {\n mutationFixturesRef.current.set(name, handler)\n },\n\n removeMutationFixture: (name: string) => {\n mutationFixturesRef.current.delete(name)\n },\n\n getFetcher,\n getMiddleware,\n }),\n [isDemoMode, getFetcher, getMiddleware]\n )\n\n return (\n <DemoSWRContext.Provider value={contextValue}>\n <SWRConfig value={config}>{children}</SWRConfig>\n </DemoSWRContext.Provider>\n )\n}\n","'use client'\n\nimport { createContext } from 'react'\nimport type { DemoSWRState } from './types'\n\n/**\n * Context for DemoSWR state\n * @internal\n */\nexport const DemoSWRContext = createContext<DemoSWRState | undefined>(undefined)\n\nDemoSWRContext.displayName = 'DemoSWRContext'\n","import { matchQueryKey, findMatchingQueryKeyPattern } from '@demokit-ai/core'\nimport type { QueryKey } from '@demokit-ai/core'\nimport type { SWRFixtureHandler, SWRFixtureMap, SWRFixtureMapObject } from './types'\n\n/**\n * Normalize an SWR key to a QueryKey for matching\n *\n * SWR keys can be:\n * - Strings: '/api/users' -> ['/api/users']\n * - Arrays: ['/api/users', id] -> ['/api/users', id]\n * - Functions that return keys (not handled here)\n */\nexport function normalizeKey(key: string | unknown[]): QueryKey {\n if (typeof key === 'string') {\n return [key]\n }\n\n return key.map((element) => {\n if (element === null || element === undefined) {\n return element\n }\n if (typeof element === 'object') {\n return element as Record<string, unknown>\n }\n return element as string | number | boolean\n })\n}\n\n/**\n * Parse a JSON string pattern into a QueryKey\n * Handles both array notation and simple string patterns\n *\n * @example\n * parsePatternString('[\"/api/users\"]') // ['/api/users']\n * parsePatternString('[\"/api/users\", \":id\"]') // ['/api/users', ':id']\n * parsePatternString('/api/users') // ['/api/users']\n */\nexport function parsePatternString(pattern: string): QueryKey {\n // Try to parse as JSON array\n if (pattern.startsWith('[')) {\n try {\n return JSON.parse(pattern) as QueryKey\n } catch {\n // Fall through to simple string\n }\n }\n\n // Simple string becomes single-element array\n return [pattern]\n}\n\n/**\n * Convert object-based fixture map to Map-based fixture map\n */\nexport function normalizeFixtureMap(fixtures: SWRFixtureMapObject | SWRFixtureMap): SWRFixtureMap {\n if (fixtures instanceof Map) {\n return fixtures\n }\n\n const map = new Map<QueryKey, SWRFixtureHandler>()\n for (const [pattern, handler] of Object.entries(fixtures)) {\n map.set(parsePatternString(pattern), handler)\n }\n return map\n}\n\n/**\n * Find a matching fixture for an SWR key\n *\n * @param fixtures - Map of key patterns to handlers\n * @param key - The SWR key to match\n * @returns Tuple of [handler, match result] or null if no match\n */\nexport function findMatchingFixture(\n fixtures: SWRFixtureMap,\n key: string | unknown[]\n): [SWRFixtureHandler, { params: Record<string, unknown>; normalizedKey: QueryKey }] | null {\n const normalizedKey = normalizeKey(key)\n const result = findMatchingQueryKeyPattern(fixtures, normalizedKey)\n\n if (result) {\n const [, handler, matchResult] = result\n return [handler, { params: matchResult.params, normalizedKey }]\n }\n\n return null\n}\n\n/**\n * Re-export the matchQueryKey function for direct use\n */\nexport { matchQueryKey }","import type { QueryKey } from '@demokit-ai/core'\nimport type { SWRFixtureMap, SWRFixtureContext } from './types'\nimport { findMatchingFixture, normalizeKey } from './matcher'\n\n/**\n * Options for creating a demo-aware fetcher\n */\nexport interface CreateDemoFetcherOptions {\n /**\n * Map of key patterns to fixture handlers\n */\n fixtures: SWRFixtureMap\n\n /**\n * Function to check if demo mode is enabled\n */\n isEnabled: () => boolean\n\n /**\n * Delay in ms before returning fixture data\n * @default 0\n */\n delay?: number\n\n /**\n * Fallback fetcher to use when demo mode is disabled\n * or no fixture matches\n */\n fallbackFetcher?: <T>(key: string | unknown[]) => Promise<T>\n}\n\n/**\n * Create a demo-aware fetcher function for SWR\n *\n * This fetcher intercepts requests when demo mode is enabled\n * and returns fixture data instead of making real API calls.\n *\n * @example\n * const fixtures = new Map([\n * [['/api/users'], [{ id: '1', name: 'Demo User' }]],\n * [['/api/users', ':id'], ({ params }) => ({ id: params.id, name: 'User' })],\n * ])\n *\n * const fetcher = createDemoFetcher({\n * fixtures,\n * isEnabled: () => isDemoMode,\n * delay: 100,\n * })\n *\n * // Use with SWR\n * const { data } = useSWR('/api/users', fetcher)\n */\nexport function createDemoFetcher(options: CreateDemoFetcherOptions) {\n const { fixtures, isEnabled, delay = 0, fallbackFetcher } = options\n\n return async function demoFetcher<TData = unknown>(key: string | unknown[]): Promise<TData> {\n // If demo mode is not enabled, use fallback\n if (!isEnabled()) {\n if (fallbackFetcher) {\n return fallbackFetcher<TData>(key)\n }\n throw new Error(\n `[DemoKit SWR] No fallback fetcher provided and demo mode is disabled. ` +\n `Key: ${JSON.stringify(key)}`\n )\n }\n\n // Find matching fixture\n const match = findMatchingFixture(fixtures, key)\n\n if (!match) {\n // No fixture found, try fallback\n if (fallbackFetcher) {\n return fallbackFetcher<TData>(key)\n }\n throw new Error(`[DemoKit SWR] No fixture found for key: ${JSON.stringify(key)}`)\n }\n\n const [handler, { params, normalizedKey }] = match\n\n // Apply delay if configured\n if (delay > 0) {\n await new Promise((resolve) => setTimeout(resolve, delay))\n }\n\n // Build context\n const context: SWRFixtureContext = {\n key,\n normalizedKey,\n params,\n match: { matched: true, params },\n }\n\n // Execute handler\n if (typeof handler === 'function') {\n return handler(context) as TData\n }\n\n // Return static value\n return handler as TData\n }\n}\n\n/**\n * Default fetcher that uses fetch API\n * Used as fallback when demo mode is disabled\n */\nexport async function defaultFetcher<TData = unknown>(key: string | unknown[]): Promise<TData> {\n const url = typeof key === 'string' ? key : String(key[0])\n const response = await fetch(url)\n\n if (!response.ok) {\n const error = new Error('An error occurred while fetching the data.')\n throw error\n }\n\n return response.json()\n}\n","import type { Middleware } from 'swr'\nimport type { SWRFixtureMap, SWRFixtureContext } from './types'\nimport { findMatchingFixture } from './matcher'\n\n/**\n * Options for creating the demo middleware\n */\nexport interface CreateDemoMiddlewareOptions {\n /**\n * Map of key patterns to fixture handlers\n */\n fixtures: SWRFixtureMap\n\n /**\n * Function to check if demo mode is enabled\n */\n isEnabled: () => boolean\n\n /**\n * Delay in ms before returning fixture data\n * @default 0\n */\n delay?: number\n}\n\n/**\n * Create a demo-aware SWR middleware\n *\n * This middleware intercepts SWR requests when demo mode is enabled\n * and returns fixture data instead of using the original fetcher.\n *\n * @example\n * import { SWRConfig } from 'swr'\n * import { createDemoMiddleware } from '@demokit-ai/swr'\n *\n * const fixtures = new Map([\n * [['/api/users'], [{ id: '1', name: 'Demo User' }]],\n * [['/api/users', ':id'], ({ params }) => ({ id: params.id, name: 'User' })],\n * ])\n *\n * const demoMiddleware = createDemoMiddleware({\n * fixtures,\n * isEnabled: () => isDemoMode,\n * delay: 100,\n * })\n *\n * function App() {\n * return (\n * <SWRConfig value={{ use: [demoMiddleware] }}>\n * <YourApp />\n * </SWRConfig>\n * )\n * }\n */\nexport function createDemoMiddleware(options: CreateDemoMiddlewareOptions): Middleware {\n const { fixtures, isEnabled, delay = 0 } = options\n\n // Use the simpler middleware pattern that SWR expects\n const middleware: Middleware = (useSWRNext) => (key, fetcher, config) => {\n // Create an extended fetcher that checks for demo mode\n const extendedFetcher =\n fetcher === null\n ? null\n : async (...args: Parameters<typeof fetcher>) => {\n // Resolve the key if it's a function\n const resolvedKey = typeof key === 'function' ? key() : key\n\n // If no key, let SWR handle it\n if (resolvedKey === null || resolvedKey === undefined) {\n return fetcher(...args)\n }\n\n // If demo mode is not enabled, use original fetcher\n if (!isEnabled()) {\n return fetcher(...args)\n }\n\n // Normalize key for matching\n const keyToMatch =\n typeof resolvedKey === 'string' ? resolvedKey : (resolvedKey as unknown[])\n\n // Find matching fixture\n const match = findMatchingFixture(fixtures, keyToMatch)\n\n if (!match) {\n // No fixture found, use original fetcher\n return fetcher(...args)\n }\n\n const [handler, { params, normalizedKey }] = match\n\n // Apply delay if configured\n if (delay > 0) {\n await new Promise((resolve) => setTimeout(resolve, delay))\n }\n\n // Build context\n const context: SWRFixtureContext = {\n key: resolvedKey,\n normalizedKey,\n params,\n match: { matched: true, params },\n }\n\n // Execute handler\n if (typeof handler === 'function') {\n return handler(context)\n }\n\n // Return static value\n return handler\n }\n\n return useSWRNext(key, extendedFetcher, config)\n }\n\n return middleware\n}\n","'use client'\n\nimport { useContext, useCallback } from 'react'\nimport useSWRMutation, { type SWRMutationConfiguration, type SWRMutationResponse } from 'swr/mutation'\nimport { useSWRConfig } from 'swr'\nimport { DemoSWRContext } from './context'\nimport type { DemoSWRState, SWRMutationFixtureContext, SWRMutationFixtureHandler } from './types'\n\n/**\n * Hook to access DemoSWR state and controls\n *\n * @returns DemoSWR context value\n * @throws Error if used outside of DemoSWRProvider\n *\n * @example\n * function MyComponent() {\n * const { isDemoMode, setFixture } = useDemoSWR()\n *\n * // Dynamically add a fixture\n * const handleAddFixture = () => {\n * setFixture(['/api/users', 'custom'], { id: 'custom', name: 'Custom User' })\n * }\n *\n * return (\n * <button onClick={handleAddFixture}>Add Custom Fixture</button>\n * )\n * }\n */\nexport function useDemoSWR(): DemoSWRState {\n const context = useContext(DemoSWRContext)\n\n if (context === undefined) {\n throw new Error(\n 'useDemoSWR must be used within a DemoSWRProvider. ' +\n 'Make sure to wrap your app with <DemoSWRProvider>.'\n )\n }\n\n return context\n}\n\n/**\n * Hook to check if demo mode is enabled\n * Shorthand for useDemoSWR().isDemoMode\n *\n * @example\n * function MyComponent() {\n * const isDemoMode = useIsDemoSWRMode()\n *\n * return isDemoMode ? <DemoBadge /> : null\n * }\n */\nexport function useIsDemoSWRMode(): boolean {\n return useDemoSWR().isDemoMode\n}\n\n/**\n * Options for useDemoSWRMutation hook\n */\nexport interface UseDemoSWRMutationOptions<TData, TError, TArg>\n extends Omit<SWRMutationConfiguration<TData, TError, string, TArg>, 'fetcher'> {\n /**\n * The real mutation function to use when demo mode is disabled\n */\n fetcher: (key: string, options: { arg: TArg }) => Promise<TData>\n\n /**\n * Demo fixture handler for this mutation\n */\n demoFixture?: SWRMutationFixtureHandler<TData, TArg>\n\n /**\n * Delay in ms before returning demo data\n * @default 0\n */\n demoDelay?: number\n}\n\n/**\n * A mutation hook that automatically uses demo fixtures when demo mode is enabled\n *\n * Works with useSWRMutation from swr/mutation.\n *\n * @example\n * const { trigger: createUser, isMutating } = useDemoSWRMutation('/api/users', {\n * fetcher: async (key, { arg }) => api.createUser(arg),\n * demoFixture: ({ arg, mutate }) => {\n * // Create demo user\n * const newUser = { id: crypto.randomUUID(), ...arg }\n *\n * // Update the users cache\n * mutate('/api/users', (current: User[] = []) => [...current, newUser])\n *\n * return newUser\n * },\n * onSuccess: (data) => {\n * console.log('Created user:', data)\n * },\n * })\n *\n * // Use like normal useSWRMutation\n * createUser({ name: 'New User', email: 'user@example.com' })\n */\nexport function useDemoSWRMutation<TData = unknown, TError = unknown, TArg = unknown>(\n key: string,\n options: UseDemoSWRMutationOptions<TData, TError, TArg>\n): SWRMutationResponse<TData, TError, string, TArg> {\n const { fetcher, demoFixture, demoDelay = 0, ...mutationOptions } = options\n\n const { mutate } = useSWRConfig()\n\n // Try to get demo state - may not be in DemoSWRProvider context\n let isDemoMode = false\n try {\n const demoState = useDemoSWR()\n isDemoMode = demoState.isDemoMode\n } catch {\n // Not in DemoSWRProvider context, use real mutation\n }\n\n // Create the demo-aware mutation function\n const demoAwareFetcher = useCallback(\n async (mutationKey: string, { arg }: { arg: TArg }): Promise<TData> => {\n // If not in demo mode, use real mutation\n if (!isDemoMode) {\n return fetcher(mutationKey, { arg })\n }\n\n // Apply delay if configured\n if (demoDelay > 0) {\n await new Promise((resolve) => setTimeout(resolve, demoDelay))\n }\n\n // If a demo fixture is provided, use it\n if (demoFixture !== undefined) {\n const context: SWRMutationFixtureContext<TData, TArg> = {\n key: mutationKey,\n arg,\n currentData: undefined, // SWR mutation doesn't have direct access to current data\n mutate: mutate as SWRMutationFixtureContext<TData, TArg>['mutate'],\n }\n\n if (typeof demoFixture === 'function') {\n const fixtureFn = demoFixture as (\n context: SWRMutationFixtureContext<TData, TArg>\n ) => TData | Promise<TData>\n return fixtureFn(context)\n }\n return demoFixture as TData\n }\n\n // No fixture found, fall back to real mutation\n console.warn(\n `[DemoKit SWR] No mutation fixture found for \"${key}\". Using real mutation function.`\n )\n return fetcher(mutationKey, { arg })\n },\n [isDemoMode, fetcher, demoFixture, demoDelay, key, mutate]\n )\n\n return useSWRMutation(key, demoAwareFetcher, mutationOptions)\n}\n"],"mappings":";AAEA,SAAS,SAAS,QAAQ,mBAAmB;AAC7C,SAAS,iBAAiB;;;ACD1B,SAAS,qBAAqB;AAOvB,IAAM,iBAAiB,cAAwC,MAAS;AAE/E,eAAe,cAAc;;;ACX7B,SAAS,eAAe,mCAAmC;AAYpD,SAAS,aAAa,KAAmC;AAC9D,MAAI,OAAO,QAAQ,UAAU;AAC3B,WAAO,CAAC,GAAG;AAAA,EACb;AAEA,SAAO,IAAI,IAAI,CAAC,YAAY;AAC1B,QAAI,YAAY,QAAQ,YAAY,QAAW;AAC7C,aAAO;AAAA,IACT;AACA,QAAI,OAAO,YAAY,UAAU;AAC/B,aAAO;AAAA,IACT;AACA,WAAO;AAAA,EACT,CAAC;AACH;AAWO,SAAS,mBAAmB,SAA2B;AAE5D,MAAI,QAAQ,WAAW,GAAG,GAAG;AAC3B,QAAI;AACF,aAAO,KAAK,MAAM,OAAO;AAAA,IAC3B,QAAQ;AAAA,IAER;AAAA,EACF;AAGA,SAAO,CAAC,OAAO;AACjB;AAKO,SAAS,oBAAoB,UAA8D;AAChG,MAAI,oBAAoB,KAAK;AAC3B,WAAO;AAAA,EACT;AAEA,QAAM,MAA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W,EAAE;AACtB;AAiDO,SAAS,mBACd,KACA,SACkD;AAClD,QAAM,EAAE,SAAS,aAAa,YAAY,GAAG,GAAG,gBAAgB,IAAI;AAEpE,QAAM,EAAE,OAAO,IAAI,aAAa;AAGhC,MAAI,aAAa;AACjB,MAAI;AACF,UAAM,YAAY,WAAW;AAC7B,iBAAa,UAAU;AAAA,EACzB,QAAQ;AAAA,EAER;AAGA,QAAM,mBAAmBC;AAAA,IACvB,OAAO,aAAqB,EAAE,IAAI,MAAqC;AAErE,UAAI,CAAC,YAAY;AACf,eAAO,QAAQ,aAAa,EAAE,IAAI,CAAC;AAAA,MACrC;AAGA,UAAI,YAAY,GAAG;AACjB,cAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,SAAS,CAAC;AAAA,MAC/D;AAGA,UAAI,gBAAgB,QAAW;AAC7B,cAAM,UAAkD;AAAA,UACtD,KAAK;AAAA,UACL;AAAA,UACA,aAAa;AAAA;AAAA,UACb;AAAA,QACF;AAEA,YAAI,OAAO,gBAAgB,YAAY;AACrC,gBAAM,YAAY;AAGlB,iBAAO,UAAU,OAAO;AAAA,QAC1B;AACA,eAAO;AAAA,MACT;AAGA,cAAQ;AAAA,QACN,gDAAgD,GAAG;AAAA,MACrD;AACA,aAAO,QAAQ,aAAa,EAAE,IAAI,CAAC;AAAA,IACrC;AAAA,IACA,CAAC,YAAY,SAAS,aAAa,WAAW,KAAK,MAAM;AAAA,EAC3D;AAEA,SAAO,eAAe,KAAK,kBAAkB,eAAe;AAC9D;","names":["useCallback","useCallback"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@demokit-ai/swr",
3
- "version": "0.1.0",
4
- "description": "SWR adapter for DemoKit - mock fetchers and middleware for demo mode",
3
+ "version": "0.3.0",
4
+ "description": "SWR integration for DemoKit",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
7
7
  "module": "./dist/index.js",
@@ -21,44 +21,29 @@
21
21
  "files": [
22
22
  "dist"
23
23
  ],
24
- "scripts": {
25
- "build": "tsup",
26
- "dev": "tsup --watch",
27
- "test": "vitest",
28
- "typecheck": "tsc --noEmit"
29
- },
30
24
  "dependencies": {
31
- "@demokit-ai/core": "*",
32
- "@demokit-ai/react": "*"
25
+ "@demokit-ai/core": "0.3.0",
26
+ "@demokit-ai/react": "0.3.0"
33
27
  },
34
28
  "devDependencies": {
35
29
  "@types/react": "^19.0.0",
36
- "@types/react-dom": "^19.0.0",
37
- "react": "^19.0.0",
38
- "react-dom": "^19.0.0",
39
30
  "swr": "^2.2.5",
40
31
  "tsup": "^8.3.5",
41
- "typescript": "^5.7.2",
42
- "vitest": "^2.1.8"
32
+ "typescript": "^5.7.2"
43
33
  },
44
34
  "peerDependencies": {
45
35
  "react": ">=17.0.0",
46
- "react-dom": ">=17.0.0",
47
36
  "swr": ">=2.0.0"
48
37
  },
49
- "keywords": [
50
- "demo",
51
- "mock",
52
- "swr",
53
- "fixtures",
54
- "testing",
55
- "middleware"
56
- ],
57
- "license": "MIT",
58
- "repository": {
59
- "type": "git",
60
- "url": "https://github.com/your-org/demokit",
61
- "directory": "packages/swr"
38
+ "engines": {
39
+ "node": ">=18"
62
40
  },
63
- "sideEffects": false
41
+ "license": "Apache-2.0",
42
+ "sideEffects": false,
43
+ "scripts": {
44
+ "build": "tsup",
45
+ "dev": "tsup --watch --no-dts",
46
+ "typecheck": "tsc --noEmit",
47
+ "clean": "rm -rf dist"
48
+ }
64
49
  }