@tanstack/router-core 0.0.1-alpha.0 → 0.0.1-alpha.10

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.
Files changed (64) hide show
  1. package/build/cjs/node_modules/@babel/runtime/helpers/esm/extends.js +33 -0
  2. package/build/cjs/node_modules/@babel/runtime/helpers/esm/extends.js.map +1 -0
  3. package/build/cjs/node_modules/history/index.js +815 -0
  4. package/build/cjs/node_modules/history/index.js.map +1 -0
  5. package/build/cjs/node_modules/tiny-invariant/dist/esm/tiny-invariant.js +30 -0
  6. package/build/cjs/node_modules/tiny-invariant/dist/esm/tiny-invariant.js.map +1 -0
  7. package/build/cjs/packages/router-core/src/index.js +35 -1421
  8. package/build/cjs/packages/router-core/src/index.js.map +1 -1
  9. package/build/cjs/packages/router-core/src/path.js +222 -0
  10. package/build/cjs/packages/router-core/src/path.js.map +1 -0
  11. package/build/cjs/packages/router-core/src/qss.js +1 -1
  12. package/build/cjs/packages/router-core/src/qss.js.map +1 -1
  13. package/build/cjs/packages/router-core/src/route.js +126 -0
  14. package/build/cjs/packages/router-core/src/route.js.map +1 -0
  15. package/build/cjs/packages/router-core/src/routeConfig.js +69 -0
  16. package/build/cjs/packages/router-core/src/routeConfig.js.map +1 -0
  17. package/build/cjs/packages/router-core/src/routeMatch.js +247 -0
  18. package/build/cjs/packages/router-core/src/routeMatch.js.map +1 -0
  19. package/build/cjs/packages/router-core/src/router.js +809 -0
  20. package/build/cjs/packages/router-core/src/router.js.map +1 -0
  21. package/build/cjs/packages/router-core/src/searchParams.js +70 -0
  22. package/build/cjs/packages/router-core/src/searchParams.js.map +1 -0
  23. package/build/cjs/packages/router-core/src/utils.js +118 -0
  24. package/build/cjs/packages/router-core/src/utils.js.map +1 -0
  25. package/build/esm/index.js +1350 -1231
  26. package/build/esm/index.js.map +1 -1
  27. package/build/stats-html.html +1 -1
  28. package/build/stats-react.json +388 -46
  29. package/build/types/index.d.ts +401 -343
  30. package/build/umd/index.development.js +1218 -1091
  31. package/build/umd/index.development.js.map +1 -1
  32. package/build/umd/index.production.js +1 -1
  33. package/build/umd/index.production.js.map +1 -1
  34. package/package.json +3 -3
  35. package/src/frameworks.ts +13 -0
  36. package/src/index.ts +15 -2969
  37. package/src/link.ts +291 -0
  38. package/src/path.ts +236 -0
  39. package/src/qss.ts +1 -1
  40. package/src/route.ts +181 -0
  41. package/src/routeConfig.ts +523 -0
  42. package/src/routeInfo.ts +228 -0
  43. package/src/routeMatch.ts +340 -0
  44. package/src/router.ts +1211 -0
  45. package/src/searchParams.ts +54 -0
  46. package/src/utils.ts +157 -0
  47. package/build/cjs/packages/location-core/src/index.js +0 -1313
  48. package/build/cjs/packages/location-core/src/index.js.map +0 -1
  49. package/build/cjs/packages/location-core/src/qss.js +0 -70
  50. package/build/cjs/packages/location-core/src/qss.js.map +0 -1
  51. package/build/cjs/packages/router-core/src/createRoutes.js +0 -106
  52. package/build/cjs/packages/router-core/src/createRoutes.js.map +0 -1
  53. package/build/cjs/packages/router-core/src/createRoutes.test.js +0 -160
  54. package/build/cjs/packages/router-core/src/createRoutes.test.js.map +0 -1
  55. package/build/types/createRoutes.d.ts +0 -10
  56. package/build/types/createRoutes.test.d.ts +0 -1
  57. package/build/types/qss.d.ts +0 -2
  58. package/build/types/react-router/src/createRoutes.test.d.ts +0 -0
  59. package/build/types/react-router/src/index.d.ts +0 -59
  60. package/build/types/router-core/src/createRoutes.test.d.ts +0 -1
  61. package/build/types/router-core/src/index.d.ts +0 -504
  62. package/build/types/router-core/src/qss.d.ts +0 -2
  63. package/src/createRoutes.test.ts +0 -318
  64. package/src/package.json +0 -48
@@ -1,1313 +0,0 @@
1
- /**
2
- * location-core
3
- *
4
- * Copyright (c) TanStack
5
- *
6
- * This source code is licensed under the MIT license found in the
7
- * LICENSE.md file in the root directory of this source tree.
8
- *
9
- * @license MIT
10
- */
11
- 'use strict';
12
-
13
- Object.defineProperty(exports, '__esModule', { value: true });
14
-
15
- var _rollupPluginBabelHelpers = require('../../../_virtual/_rollupPluginBabelHelpers.js');
16
- var index = require('../../../node_modules/history/index.js');
17
- var qss = require('./qss.js');
18
-
19
- const _excluded = ["basepath", "routes"];
20
-
21
- // Source
22
- // Detect if we're in the DOM
23
- const isDOM = Boolean(typeof window !== 'undefined' && window.document && window.document.createElement); // This is the default history object if none is defined
24
-
25
- const createDefaultHistory = () => isDOM ? index.createBrowserHistory() : index.createMemoryHistory();
26
-
27
- class Subscribable {
28
- constructor() {
29
- this.preNotify = () => {};
30
-
31
- this.listeners = [];
32
- }
33
-
34
- subscribe(listener) {
35
- this.listeners.push(listener);
36
- return () => {
37
- this.listeners = this.listeners.filter(x => x !== listener);
38
- };
39
- }
40
-
41
- notify() {
42
- this.preNotify();
43
- this.listeners.forEach(listener => listener());
44
- }
45
-
46
- }
47
-
48
- class RouterInstance extends Subscribable {
49
- // Options:
50
- // The history object to be used internally
51
- // A history will be created automatically if not provided.
52
- // Internal:
53
- constructor(options) {
54
- var _this, _options$stringifySea, _options$parseSearch, _experimental__snaps;
55
-
56
- super();
57
- _this = this;
58
- this.isTransitioning = false;
59
- this.routesById = {};
60
- this.navigationPromise = Promise.resolve();
61
-
62
- this.resolveNavigation = () => {};
63
-
64
- this.loadPromise = Promise.resolve();
65
-
66
- this.resolveLoad = () => {};
67
-
68
- this.startedLoadingAt = Date.now();
69
- this.resolveEarly = false;
70
-
71
- this.preNotify = () => {
72
- var _this$state$action;
73
-
74
- const match = last(this.state.matches);
75
- let loaderData = {};
76
-
77
- if (match) {
78
- const recurse = m => {
79
- if (m.parentMatch) {
80
- recurse(m.parentMatch);
81
- }
82
-
83
- loaderData = _rollupPluginBabelHelpers["extends"]({}, loaderData, m.data);
84
- };
85
-
86
- recurse(match);
87
- }
88
-
89
- const isPending = !!this.state.pending || this.state.matches.find(d => d.status === 'loading');
90
- const isLoading = ((_this$state$action = this.state.action) == null ? void 0 : _this$state$action.status) === 'pending' || isPending;
91
- this.state = _rollupPluginBabelHelpers["extends"]({}, this.state, {
92
- status: isLoading ? 'loading' : 'idle',
93
- loaderData: replaceEqualDeep(this.state.loaderData, loaderData),
94
- lastUpdated: Date.now()
95
- });
96
- };
97
-
98
- this.parseLocation = (location, previousLocation) => {
99
- var _location$hash$split$;
100
-
101
- const parsedSearch = this.parseSearch(location.search);
102
- return {
103
- pathname: location.pathname,
104
- searchStr: location.search,
105
- search: replaceEqualDeep(previousLocation == null ? void 0 : previousLocation.search, parsedSearch),
106
- hash: (_location$hash$split$ = location.hash.split('#').reverse()[0]) != null ? _location$hash$split$ : '',
107
- href: "" + location.pathname + location.search + location.hash,
108
- state: location.state,
109
- key: location.key
110
- };
111
- };
112
-
113
- this.buildLocation = function (basepath, dest) {
114
- var _dest$from, _dest$to, _dest$__preSearchFilt, _functionalUpdate, _dest$__preSearchFilt2, _dest$__postSearchFil;
115
-
116
- if (basepath === void 0) {
117
- basepath = '/';
118
- }
119
-
120
- if (dest === void 0) {
121
- dest = {};
122
- }
123
-
124
- const resolvedFrom = _rollupPluginBabelHelpers["extends"]({}, _this.location, {
125
- pathname: dest.fromCurrent ? _this.location.pathname : (_dest$from = dest.from) != null ? _dest$from : _this.location.pathname
126
- });
127
-
128
- const pathname = resolvePath(basepath, resolvedFrom.pathname, "" + ((_dest$to = dest.to) != null ? _dest$to : '.')); // Pre filters first
129
-
130
- const preFilteredSearch = (_dest$__preSearchFilt = dest.__preSearchFilters) != null && _dest$__preSearchFilt.length ? dest.__preSearchFilters.reduce((prev, next) => next(prev), resolvedFrom.search) : resolvedFrom.search; // Then the link/navigate function
131
-
132
- const destSearch = dest.search === true ? preFilteredSearch // Preserve resolvedFrom true
133
- : dest.search ? (_functionalUpdate = functionalUpdate(dest.search, preFilteredSearch)) != null ? _functionalUpdate : {} // Updater
134
- : (_dest$__preSearchFilt2 = dest.__preSearchFilters) != null && _dest$__preSearchFilt2.length ? preFilteredSearch // Preserve resolvedFrom filters
135
- : {}; // Then post filters
136
-
137
- const postFilteredSearch = (_dest$__postSearchFil = dest.__postSearchFilters) != null && _dest$__postSearchFil.length ? dest.__postSearchFilters.reduce((prev, next) => next(prev), destSearch) : destSearch;
138
- const search = replaceEqualDeep(resolvedFrom.search, postFilteredSearch);
139
-
140
- const searchStr = _this.stringifySearch(search);
141
-
142
- let hash = dest.hash === true ? resolvedFrom.hash : functionalUpdate(dest.hash, resolvedFrom.hash);
143
- hash = hash ? "#" + hash : '';
144
- return {
145
- pathname,
146
- search,
147
- searchStr,
148
- state: resolvedFrom.state,
149
- hash,
150
- href: "" + pathname + searchStr + hash,
151
- key: dest.key
152
- };
153
- };
154
-
155
- this.commitLocation = (next, replace, opts) => {
156
- console.log('commit');
157
- if (this.navigateTimeout) clearTimeout(this.navigateTimeout);
158
- let nextAction = 'replace';
159
-
160
- if (!replace) {
161
- nextAction = 'push';
162
- }
163
-
164
- const isSameUrl = this.parseLocation(this.history.location).href === next.href;
165
-
166
- if (isSameUrl && !next.key) {
167
- nextAction = 'replace';
168
- }
169
-
170
- if (nextAction === 'replace') {
171
- this.history.replace({
172
- pathname: next.pathname,
173
- hash: next.hash,
174
- search: next.searchStr
175
- });
176
- } else {
177
- this.history.push({
178
- pathname: next.pathname,
179
- hash: next.hash,
180
- search: next.searchStr
181
- });
182
- }
183
-
184
- this.navigationPromise = new Promise(resolve => {
185
- this.resolveNavigation = resolve;
186
- this.resolveEarly = !!(opts != null && opts.resolveEarly);
187
- console.log(this.resolveEarly);
188
- });
189
- return this.navigationPromise;
190
- };
191
-
192
- this.mount = () => {
193
- const next = this.buildLocation(this.basepath, {
194
- to: '.',
195
- search: true,
196
- hash: true
197
- }); // If the current location isn't updated, trigger a navigation
198
- // to the current location. Otherwise, load the current location.
199
-
200
- if (next.href !== this.location.href) {
201
- return this.commitLocation(next, true);
202
- } else {
203
- return this.loadLocation();
204
- }
205
- };
206
-
207
- this.update = _ref => {
208
- let {
209
- basepath,
210
- routes
211
- } = _ref,
212
- opts = _rollupPluginBabelHelpers.objectWithoutPropertiesLoose(_ref, _excluded);
213
-
214
- Object.assign(this, opts);
215
- this.basepath = cleanPath("/" + (basepath != null ? basepath : ''));
216
- this.routesById = {};
217
-
218
- const recurseRoutes = (routes, parent) => {
219
- return routes.map(route => {
220
- var _route$path, _route$pendingMs, _route$pendingMinMs, _route$children;
221
-
222
- const path = (_route$path = route.path) != null ? _route$path : '*';
223
- const id = joinPaths([(parent == null ? void 0 : parent.id) === 'root' ? '' : parent == null ? void 0 : parent.id, "" + (path == null ? void 0 : path.replace(/(.)\/$/, '$1')) + (route.id ? "-" + route.id : '')]);
224
- route = _rollupPluginBabelHelpers["extends"]({}, route, {
225
- pendingMs: (_route$pendingMs = route.pendingMs) != null ? _route$pendingMs : opts == null ? void 0 : opts.defaultPendingMs,
226
- pendingMinMs: (_route$pendingMinMs = route.pendingMinMs) != null ? _route$pendingMinMs : opts == null ? void 0 : opts.defaultPendingMinMs,
227
- id
228
- });
229
-
230
- if (this.routesById[id]) {
231
- if (process.env.NODE_ENV !== 'production') {
232
- console.warn("Duplicate routes found with id: " + id, this.routesById, route);
233
- }
234
-
235
- throw new Error();
236
- }
237
-
238
- this.routesById[id] = route;
239
- route.children = (_route$children = route.children) != null && _route$children.length ? recurseRoutes(route.children, route) : undefined;
240
- return route;
241
- });
242
- };
243
-
244
- this.routes = recurseRoutes(routes != null ? routes : []);
245
- this.rootMatch = {
246
- id: 'root',
247
- params: {},
248
- search: {},
249
- pathname: this.basepath,
250
- data: {},
251
- status: 'success'
252
- };
253
- };
254
-
255
- this.buildNext = opts => {
256
- const next = this.buildLocation(this.basepath, opts);
257
- const matches = this.matchRoutes(next);
258
-
259
- const __preSearchFilters = matches.map(match => {
260
- var _match$route$preSearc;
261
-
262
- return (_match$route$preSearc = match.route.preSearchFilters) != null ? _match$route$preSearc : [];
263
- }).flat().filter(Boolean);
264
-
265
- const __postSearchFilters = matches.map(match => {
266
- var _match$route$postSear;
267
-
268
- return (_match$route$postSear = match.route.postSearchFilters) != null ? _match$route$postSear : [];
269
- }).flat().filter(Boolean);
270
-
271
- return this.buildLocation(this.basepath, _rollupPluginBabelHelpers["extends"]({}, opts, {
272
- __preSearchFilters,
273
- __postSearchFilters
274
- }));
275
- };
276
-
277
- this.navigate = (opts, otherOpts) => {
278
- console.log('navigate', opts);
279
- const next = this.buildNext(opts);
280
- return this.commitLocation(next, opts.replace, otherOpts);
281
- };
282
-
283
- this.cancelMatches = () => {
284
- var _this$state$pending$m, _this$state$pending;
285
- [...this.state.matches, ...((_this$state$pending$m = (_this$state$pending = this.state.pending) == null ? void 0 : _this$state$pending.matches) != null ? _this$state$pending$m : [])].forEach(match => {
286
- match.cancel();
287
- });
288
- };
289
-
290
- this.loadLocation = async next => {
291
- console.log('load location', next);
292
- const now = Date.now();
293
- this.startedLoadingAt = now;
294
-
295
- if (next) {
296
- // Ingest the new location
297
- this.location = next;
298
- } // Cancel any pending matches
299
-
300
-
301
- this.cancelMatches(); // Match the routes
302
-
303
- const unloadedMatches = this.matchRoutes(this.location);
304
- const resolvedMatches = this.resolveMatches(unloadedMatches);
305
- this.state = _rollupPluginBabelHelpers["extends"]({}, this.state, {
306
- pending: {
307
- matches: resolvedMatches,
308
- location: this.location
309
- }
310
- });
311
- this.notify();
312
- console.log('hello1');
313
-
314
- if (this.resolveEarly) {
315
- console.log('hello2');
316
- this.resolveEarly = false;
317
- this.resolveNavigation();
318
- }
319
-
320
- this.loadPromise = new Promise(resolve => {
321
- this.resolveLoad = resolve;
322
- }); // Load the matches
323
-
324
- const matches = await this.loadMatches(resolvedMatches, {
325
- withPending: true
326
- });
327
-
328
- if (this.startedLoadingAt !== now) {
329
- // Ignore side-effects of match loading
330
- return;
331
- }
332
-
333
- const previousMatches = this.state.matches;
334
- previousMatches.filter(d => {
335
- return !matches.find(dd => dd.id === d.id);
336
- }).forEach(d => {
337
- d.onExit == null ? void 0 : d.onExit(d);
338
- });
339
- previousMatches.filter(d => {
340
- return matches.find(dd => dd.id === d.id);
341
- }).forEach(d => {
342
- d.route.onTransition == null ? void 0 : d.route.onTransition(d);
343
- });
344
- matches.filter(d => {
345
- return !previousMatches.find(dd => dd.id === d.id);
346
- }).forEach(d => {
347
- d.onExit = d.route.onMatch == null ? void 0 : d.route.onMatch(d);
348
- });
349
- this.state = _rollupPluginBabelHelpers["extends"]({}, this.state, {
350
- location: this.location,
351
- matches: matches,
352
- pending: undefined
353
- });
354
- this.notify();
355
- this.resolveNavigation();
356
- this.resolveLoad();
357
- };
358
-
359
- this.preloadCache = {};
360
-
361
- this.cleanPreloadCache = () => {
362
- var _this$state$matches, _this$state$pending$m2, _this$state$pending2;
363
-
364
- const activeMatchIds = [...((_this$state$matches = this == null ? void 0 : this.state.matches) != null ? _this$state$matches : []), ...((_this$state$pending$m2 = this == null ? void 0 : (_this$state$pending2 = this.state.pending) == null ? void 0 : _this$state$pending2.matches) != null ? _this$state$pending$m2 : [])].map(d => d.id);
365
- const now = Date.now();
366
- Object.keys(this.preloadCache).forEach(matchId => {
367
- const entry = this.preloadCache[matchId];
368
-
369
- if (activeMatchIds.includes(matchId)) {
370
- return;
371
- }
372
-
373
- if (entry.expiresAt < now) {
374
- delete this.preloadCache[matchId];
375
- }
376
- });
377
- };
378
-
379
- this.loadRoute = async function (navigateOpts, loaderOpts) {
380
- if (navigateOpts === void 0) {
381
- navigateOpts = _this.location;
382
- }
383
-
384
- const next = _this.buildNext(navigateOpts);
385
-
386
- const unloadedMatches = _this.matchRoutes(next);
387
-
388
- const matches = _this.resolveMatches(unloadedMatches);
389
-
390
- await _this.loadMatches(matches, {
391
- preload: true,
392
- maxAge: loaderOpts.maxAge
393
- });
394
- return matches;
395
- };
396
-
397
- this.matchRoutes = location => {
398
- var _this$routes;
399
-
400
- this.cleanPreloadCache();
401
- const matches = [];
402
-
403
- if (!((_this$routes = this.routes) != null && _this$routes.length)) {
404
- return matches;
405
- }
406
-
407
- const recurse = async (routes, parentMatch) => {
408
- var _route$children3;
409
-
410
- let {
411
- pathname,
412
- params
413
- } = parentMatch;
414
- const filteredRoutes = this != null && this.filterRoutes ? this == null ? void 0 : this.filterRoutes(routes) : routes;
415
- const route = filteredRoutes == null ? void 0 : filteredRoutes.find(route => {
416
- var _route$children2, _route$caseSensitive;
417
-
418
- const fullRoutePathName = joinPaths([pathname, route.path]);
419
- const fuzzy = !!(route.path !== '/' || (_route$children2 = route.children) != null && _route$children2.length);
420
- const matchParams = matchRoute(location, {
421
- to: fullRoutePathName,
422
- search: route.search,
423
- fuzzy,
424
- caseSensitive: (_route$caseSensitive = route.caseSensitive) != null ? _route$caseSensitive : this.caseSensitive
425
- });
426
-
427
- if (matchParams) {
428
- params = _rollupPluginBabelHelpers["extends"]({}, params, matchParams);
429
- }
430
-
431
- return !!matchParams;
432
- });
433
-
434
- if (!route) {
435
- return;
436
- }
437
-
438
- const interpolatedPath = interpolatePath(route.path, params);
439
- pathname = joinPaths([pathname, interpolatedPath]);
440
- const interpolatedId = interpolatePath(route.id, params, true);
441
- const match = {
442
- id: interpolatedId,
443
- route,
444
- params,
445
- pathname,
446
- search: location.search
447
- };
448
- matches.push(match);
449
-
450
- if ((_route$children3 = route.children) != null && _route$children3.length) {
451
- recurse(route.children, match);
452
- }
453
- };
454
-
455
- recurse(this.routes, this.rootMatch);
456
- return matches;
457
- };
458
-
459
- this.resolveMatches = unloadedMatches => {
460
- var _this$state$pending$m3, _this$state$pending3;
461
-
462
- if (!(unloadedMatches != null && unloadedMatches.length)) {
463
- return [];
464
- }
465
-
466
- const existingMatches = [...this.state.matches, ...((_this$state$pending$m3 = (_this$state$pending3 = this.state.pending) == null ? void 0 : _this$state$pending3.matches) != null ? _this$state$pending$m3 : [])];
467
- const matches = unloadedMatches.map((unloadedMatch, i) => {
468
- var _this$preloadCache$un;
469
-
470
- return existingMatches.find(d => d.id === unloadedMatch.id) || ((_this$preloadCache$un = this.preloadCache[unloadedMatch.id]) == null ? void 0 : _this$preloadCache$un.match) || new RouteMatch(this, unloadedMatch);
471
- });
472
- matches.forEach((match, index) => {
473
- match.setParentMatch(matches[index - 1]);
474
- });
475
- return matches;
476
- };
477
-
478
- this.loadMatches = async (resolvedMatches, loaderOpts) => {
479
- const matchPromises = resolvedMatches.map(async match => {
480
- if (match.isInvalid || match.status === 'error' || match.status === 'idle') {
481
- const promise = match.load();
482
- if (loaderOpts != null && loaderOpts.withPending) match.startPending();
483
-
484
- if (loaderOpts != null && loaderOpts.preload) {
485
- this.preloadCache[match.id] = {
486
- expiresAt: Date.now() + (loaderOpts == null ? void 0 : loaderOpts.maxAge),
487
- match
488
- };
489
- }
490
-
491
- return promise;
492
- }
493
-
494
- return match.loaderPromise;
495
- });
496
- await Promise.all(matchPromises);
497
- return resolvedMatches;
498
- };
499
-
500
- this.invalidateRoute = opts => {
501
- var _this$state$pending$m4, _this$state$pending4;
502
-
503
- const next = this.buildNext(opts);
504
- const unloadedMatchIds = this.matchRoutes(next).map(d => d.id);
505
- [...this.state.matches, ...((_this$state$pending$m4 = (_this$state$pending4 = this.state.pending) == null ? void 0 : _this$state$pending4.matches) != null ? _this$state$pending$m4 : [])].forEach(match => {
506
- if (unloadedMatchIds.includes(match.id)) {
507
- match.isInvalid = true;
508
- }
509
- });
510
-
511
- if (process.env.NODE_ENV === 'development') {
512
- this.notify();
513
- }
514
- };
515
-
516
- this.reload = () => this.navigate({
517
- to: '',
518
- fromCurrent: true,
519
- replace: true
520
- });
521
-
522
- this.getAction = (matchOpts, opts) => {
523
- const next = this.buildNext(matchOpts);
524
- const matches = this.matchRoutes(next);
525
- const match = matches.find(d => d.pathname === next.pathname);
526
-
527
- if (!match) {
528
- return {
529
- status: 'idle',
530
- send: () => {}
531
- };
532
- }
533
-
534
- let action = this.state.actions[match.id] || (() => {
535
- this.state.actions[match.id] = {
536
- status: 'idle',
537
- send: null
538
- };
539
- return this.state.actions[match.id];
540
- })();
541
-
542
- Object.assign(action, {
543
- match,
544
- send: async (payload, actionOpts) => {
545
- var _actionOpts$invalidat;
546
-
547
- if (!match) {
548
- return;
549
- }
550
-
551
- const invalidate = (_actionOpts$invalidat = actionOpts == null ? void 0 : actionOpts.invalidate) != null ? _actionOpts$invalidat : true;
552
-
553
- if (opts != null && opts.isActive) {
554
- this.state.action = action;
555
- }
556
-
557
- action.status = 'pending';
558
- this.notify();
559
-
560
- try {
561
- const res = await (match == null ? void 0 : match.route.action == null ? void 0 : match.route.action(payload, {
562
- match,
563
- router: this
564
- }));
565
-
566
- if (invalidate) {
567
- this.invalidateRoute({
568
- to: '.',
569
- fromCurrent: true
570
- });
571
- await this.reload();
572
- }
573
-
574
- action.status = 'success';
575
- return res;
576
- } catch (err) {
577
- action.error = err;
578
- action.status = 'error';
579
- } finally {
580
- this.notify();
581
- }
582
- }
583
- });
584
- return action;
585
- };
586
-
587
- this.getOutletElement = matches => {
588
- const match = matches[0];
589
- return (() => {
590
- var _match$errorElement, _ref3;
591
-
592
- if (!match) {
593
- return null;
594
- }
595
-
596
- const errorElement = (_match$errorElement = match.errorElement) != null ? _match$errorElement : this.defaultErrorElement;
597
-
598
- if (match.status === 'error') {
599
- if (errorElement) {
600
- return errorElement;
601
- }
602
-
603
- if (!this.useErrorBoundary) {
604
- return 'An unknown/unhandled error occurred!';
605
- }
606
-
607
- throw match.error;
608
- }
609
-
610
- if (match.status === 'loading' || match.status === 'idle') {
611
- if (match.isPending) {
612
- var _match$pendingElement;
613
-
614
- const pendingElement = (_match$pendingElement = match.pendingElement) != null ? _match$pendingElement : this.defaultPendingElement;
615
-
616
- if (match.route.pendingMs || pendingElement) {
617
- var _ref2;
618
-
619
- return (_ref2 = pendingElement) != null ? _ref2 : null;
620
- }
621
- }
622
-
623
- return null;
624
- }
625
-
626
- return (_ref3 = match.element) != null ? _ref3 : this.defaultElement;
627
- })();
628
- };
629
-
630
- this.resolvePath = (from, path) => {
631
- return resolvePath(this.basepath, from, cleanPath(path));
632
- };
633
-
634
- this.matchRoute = (matchLocation, opts) => {
635
- matchLocation = _rollupPluginBabelHelpers["extends"]({}, matchLocation, {
636
- to: matchLocation.to ? this.resolvePath(matchLocation.from || this.rootMatch.pathname, "" + matchLocation.to) : undefined
637
- });
638
-
639
- if (opts != null && opts.pending) {
640
- var _this$state$pending5;
641
-
642
- if (!((_this$state$pending5 = this.state.pending) != null && _this$state$pending5.location)) {
643
- return undefined;
644
- }
645
-
646
- return matchRoute(this.state.pending.location, matchLocation);
647
- }
648
-
649
- return matchRoute(this.state.location, matchLocation);
650
- };
651
-
652
- this.buildLinkInfo = _ref4 => {
653
- var _preload, _ref5, _ref6;
654
-
655
- let {
656
- to = '.',
657
- search,
658
- hash,
659
- target,
660
- replace,
661
- getActiveProps = () => ({
662
- className: 'active'
663
- }),
664
- getInactiveProps = () => ({}),
665
- activeOptions,
666
- preload,
667
- preloadMaxAge: userPreloadMaxAge,
668
- preloadDelay: userPreloadDelay,
669
- disabled,
670
- from,
671
- ref
672
- } = _ref4;
673
-
674
- // If this link simply reloads the current route,
675
- // make sure it has a new key so it will trigger a data refresh
676
- // If this `to` is a valid external URL, return
677
- // null for LinkUtils
678
- try {
679
- new URL("" + to);
680
- return null;
681
- } catch (e) {}
682
-
683
- const next = this.buildNext({
684
- to,
685
- search,
686
- hash,
687
- from
688
- });
689
- preload = (_preload = preload) != null ? _preload : this.defaultLinkPreload;
690
- const preloadMaxAge = (_ref5 = userPreloadMaxAge != null ? userPreloadMaxAge : this.defaultLinkPreloadMaxAge) != null ? _ref5 : 2000;
691
- const preloadDelay = (_ref6 = userPreloadDelay != null ? userPreloadDelay : this.defaultLinkPreloadDelay) != null ? _ref6 : 50; // Compare path/hash for matches
692
-
693
- const pathIsEqual = this.state.location.pathname === next.pathname;
694
- const currentPathSplit = this.state.location.pathname.split('/');
695
- const nextPathSplit = next.pathname.split('/');
696
- const pathIsFuzzyEqual = nextPathSplit.every((d, i) => d === currentPathSplit[i]);
697
- const hashIsEqual = this.state.location.hash === next.hash; // Combine the matches based on user options
698
-
699
- const pathTest = activeOptions != null && activeOptions.exact ? pathIsEqual : pathIsFuzzyEqual;
700
- const hashTest = activeOptions != null && activeOptions.includeHash ? hashIsEqual : true; // The final "active" test
701
-
702
- const isActive = pathTest && hashTest; // Get the active props
703
-
704
- const activeProps = isActive ? getActiveProps() : {}; // Get the inactive props
705
-
706
- const inactiveProps = isActive ? {} : getInactiveProps(); // The click handler
707
-
708
- const handleClick = e => {
709
- if (!disabled && !isCtrlEvent(e) && !e.defaultPrevented && (!target || target === '_self') && e.button === 0) {
710
- e.preventDefault();
711
-
712
- if (pathIsEqual && !search && !hash) {
713
- this.invalidateRoute({
714
- to,
715
- search,
716
- from
717
- });
718
- } // All is well? Navigate!)
719
-
720
-
721
- this.navigate({
722
- to,
723
- search,
724
- hash,
725
- replace,
726
- from
727
- });
728
- }
729
- }; // The click handler
730
-
731
-
732
- const handleFocus = e => {
733
- if (preload && preloadMaxAge > 0) {
734
- this.loadRoute({
735
- to,
736
- search,
737
- hash,
738
- from
739
- }, {
740
- maxAge: preloadMaxAge
741
- });
742
- }
743
- };
744
-
745
- const handleEnter = e => {
746
- if (preload && preloadMaxAge > 0) {
747
- if (ref.preloadTimeout) {
748
- return;
749
- }
750
-
751
- ref.preloadTimeout = setTimeout(() => {
752
- ref.preloadTimeout = null;
753
- this.loadRoute({
754
- to,
755
- search,
756
- hash,
757
- from
758
- }, {
759
- maxAge: preloadMaxAge
760
- });
761
- }, preloadDelay);
762
- }
763
- };
764
-
765
- const handleLeave = e => {
766
- if (ref.preloadTimeout) {
767
- clearTimeout(ref.preloadTimeout);
768
- ref.preloadTimeout = null;
769
- }
770
- };
771
-
772
- return {
773
- next,
774
- handleFocus,
775
- handleClick,
776
- handleEnter,
777
- handleLeave,
778
- activeProps,
779
- inactiveProps,
780
- isActive
781
- };
782
- };
783
-
784
- this.__experimental__createSnapshot = () => {
785
- return _rollupPluginBabelHelpers["extends"]({}, this.state, {
786
- matches: this.state.matches.map(_ref7 => {
787
- let {
788
- data,
789
- id
790
- } = _ref7;
791
- return {
792
- id,
793
- data
794
- };
795
- })
796
- });
797
- };
798
-
799
- this.history = (options == null ? void 0 : options.history) || createDefaultHistory();
800
- this.stringifySearch = (_options$stringifySea = options == null ? void 0 : options.stringifySearch) != null ? _options$stringifySea : defaultStringifySearch;
801
- this.parseSearch = (_options$parseSearch = options == null ? void 0 : options.parseSearch) != null ? _options$parseSearch : defaultParseSearch;
802
- this.location = this.parseLocation(this.history.location);
803
- this.destroy = this.history.listen(event => {
804
- console.log('listen');
805
- this.loadLocation(this.parseLocation(event.location, this.location));
806
- });
807
- let _matches = [];
808
-
809
- const __experimental__snapshot = options == null ? void 0 : options.__experimental__snapshot;
810
-
811
- this.state = {
812
- status: 'idle',
813
- location: (_experimental__snaps = __experimental__snapshot == null ? void 0 : __experimental__snapshot.location) != null ? _experimental__snaps : this.location,
814
- matches: _matches,
815
- actions: {},
816
- loaderData: {},
817
- lastUpdated: Date.now()
818
- };
819
- }
820
-
821
- }
822
- class RouteMatch {
823
- constructor(router, unloadedMatch) {
824
- this.isInvalid = false;
825
- this.status = 'idle';
826
- this.data = {};
827
- this.isPending = false;
828
- this.abortController = new AbortController();
829
-
830
- this.resolve = () => {};
831
-
832
- this.notify = () => {
833
- this.resolve();
834
- this.router.notify();
835
- };
836
-
837
- this.cancel = () => {
838
- var _this$abortController;
839
-
840
- (_this$abortController = this.abortController) == null ? void 0 : _this$abortController.abort();
841
- this.cancelPending();
842
- };
843
-
844
- this.startPending = () => {
845
- if (this.pendingTimeout || this.status !== 'loading' || typeof this.route.pendingMs === 'undefined') {
846
- return;
847
- }
848
-
849
- this.pendingTimeout = setTimeout(() => {
850
- this.isPending = true;
851
- this.resolve();
852
-
853
- if (typeof this.route.pendingMinMs !== 'undefined') {
854
- this.pendingMinPromise = new Promise(r => setTimeout(r, this.route.pendingMinMs));
855
- }
856
- }, this.route.pendingMs);
857
- };
858
-
859
- this.cancelPending = () => {
860
- this.isPending = false;
861
- clearTimeout(this.pendingTimeout);
862
- };
863
-
864
- this.setParentMatch = parentMatch => {
865
- this.parentMatch = parentMatch;
866
- };
867
-
868
- this.load = () => {
869
- // If the match was in an error state, set it
870
- // to a loading state again. Otherwise, keep it
871
- // as loading or resolved
872
- if (this.status === 'error' || this.status === 'idle') {
873
- this.status = 'loading';
874
- } // We started loading the route, so it's no longer invalid
875
-
876
-
877
- this.isInvalid = false;
878
- return new Promise(async resolve => {
879
- this.resolve = resolve;
880
-
881
- if (!this.loaderPromise) {
882
- this.loaderPromise = (async () => {
883
- const importer = this.route.import; // First, run any importers
884
-
885
- if (importer) {
886
- this.importPromise = importer({
887
- params: this.params,
888
- search: this.search
889
- }).then(imported => {
890
- this.route = _rollupPluginBabelHelpers["extends"]({}, this.route, imported);
891
- });
892
- } // Wait for the importer to finish before
893
- // attempting to load elements and data
894
-
895
-
896
- await this.importPromise; // Next, load the elements and data in parallel
897
-
898
- this.elementsPromise = (async () => {
899
- // then run all element and data loaders in parallel
900
- // For each element type, potentially load it asynchronously
901
- const elementTypes = ['element', 'errorElement', 'pendingElement'];
902
- await Promise.all(elementTypes.map(async type => {
903
- const routeElement = this.route[type];
904
-
905
- if (this[type]) {
906
- return;
907
- }
908
-
909
- if (typeof routeElement === 'function') {
910
- const res = await routeElement(this);
911
- this[type] = res;
912
- } else {
913
- this[type] = this.route[type];
914
- }
915
- }));
916
- })();
917
-
918
- this.dataPromise = Promise.resolve().then(async () => {
919
- try {
920
- var _this$route$loader, _this$route;
921
-
922
- const data = await ((_this$route$loader = (_this$route = this.route).loader) == null ? void 0 : _this$route$loader.call(_this$route, this, {
923
- match: this,
924
- signal: this.abortController.signal,
925
- router: this.router
926
- }));
927
- this.data = replaceEqualDeep(this.data, data || {});
928
- this.error = undefined;
929
- this.status = 'success';
930
- this.updatedAt = Date.now();
931
- } catch (err) {
932
- if (process.env.NODE_ENV === 'development') {
933
- console.error(err);
934
- }
935
-
936
- this.error = err;
937
- this.status = 'error';
938
- this.updatedAt = Date.now();
939
- }
940
- });
941
-
942
- try {
943
- await Promise.all([this.elementsPromise, this.dataPromise]);
944
-
945
- if (this.pendingMinPromise) {
946
- await this.pendingMinPromise;
947
- delete this.pendingMinPromise;
948
- }
949
- } finally {
950
- this.cancelPending();
951
- this.isPending = false;
952
- this.notify();
953
- }
954
- })();
955
- }
956
-
957
- await this.loaderPromise;
958
- delete this.loaderPromise;
959
- });
960
- };
961
-
962
- this.router = router;
963
- Object.assign(this, unloadedMatch);
964
- }
965
-
966
- }
967
- function matchRoute(currentLocation, matchLocation) {
968
- const pathParams = matchByPath(currentLocation, matchLocation);
969
- const searchMatched = matchBySearch(currentLocation, matchLocation);
970
-
971
- if (matchLocation.to && !pathParams) {
972
- return;
973
- }
974
-
975
- if (matchLocation.search && !searchMatched) {
976
- return;
977
- }
978
-
979
- return pathParams != null ? pathParams : {};
980
- }
981
-
982
- function interpolatePath(path, params, leaveWildcard) {
983
- const interpolatedPathSegments = parsePathname(path);
984
- return joinPaths(interpolatedPathSegments.map(segment => {
985
- if (segment.value === '*' && !leaveWildcard) {
986
- return '';
987
- }
988
-
989
- if (segment.type === 'param') {
990
- var _segment$value$substr;
991
-
992
- return (_segment$value$substr = params[segment.value.substring(1)]) != null ? _segment$value$substr : '';
993
- }
994
-
995
- return segment.value;
996
- }));
997
- }
998
-
999
- function warning(cond, message) {
1000
- if (!cond) {
1001
- if (typeof console !== 'undefined') console.warn(message);
1002
-
1003
- try {
1004
- throw new Error(message);
1005
- } catch (_unused) {}
1006
- }
1007
-
1008
- return true;
1009
- }
1010
-
1011
- function isFunction(d) {
1012
- return typeof d === 'function';
1013
- }
1014
-
1015
- function functionalUpdate(updater, previous) {
1016
- if (isFunction(updater)) {
1017
- return updater(previous);
1018
- }
1019
-
1020
- return updater;
1021
- }
1022
-
1023
- function joinPaths(paths) {
1024
- return cleanPath(paths.filter(Boolean).join('/'));
1025
- }
1026
-
1027
- function cleanPath(path) {
1028
- // remove double slashes
1029
- return ("" + path).replace(/\/{2,}/g, '/');
1030
- }
1031
- function matchByPath(currentLocation, matchLocation) {
1032
- var _matchLocation$to;
1033
-
1034
- const baseSegments = parsePathname(currentLocation.pathname);
1035
- const routeSegments = parsePathname("" + ((_matchLocation$to = matchLocation.to) != null ? _matchLocation$to : '*'));
1036
- const params = {};
1037
-
1038
- let isMatch = (() => {
1039
- for (let i = 0; i < Math.max(baseSegments.length, routeSegments.length); i++) {
1040
- const baseSegment = baseSegments[i];
1041
- const routeSegment = routeSegments[i];
1042
- const isLastRouteSegment = i === routeSegments.length - 1;
1043
- const isLastBaseSegment = i === baseSegments.length - 1;
1044
-
1045
- if (routeSegment) {
1046
- if (routeSegment.type === 'wildcard') {
1047
- if (baseSegment != null && baseSegment.value) {
1048
- params['*'] = joinPaths(baseSegments.slice(i).map(d => d.value));
1049
- return true;
1050
- }
1051
-
1052
- return false;
1053
- }
1054
-
1055
- if (routeSegment.type === 'pathname') {
1056
- if (routeSegment.value === '/' && !(baseSegment != null && baseSegment.value)) {
1057
- return true;
1058
- }
1059
-
1060
- if (baseSegment) {
1061
- if (matchLocation.caseSensitive) {
1062
- if (routeSegment.value !== baseSegment.value) {
1063
- return false;
1064
- }
1065
- } else if (routeSegment.value.toLowerCase() !== baseSegment.value.toLowerCase()) {
1066
- return false;
1067
- }
1068
- }
1069
- }
1070
-
1071
- if (!baseSegment) {
1072
- return false;
1073
- }
1074
-
1075
- if (routeSegment.type === 'param') {
1076
- params[routeSegment.value.substring(1)] = baseSegment.value;
1077
- }
1078
- }
1079
-
1080
- if (isLastRouteSegment && !isLastBaseSegment) {
1081
- return !!matchLocation.fuzzy;
1082
- }
1083
- }
1084
-
1085
- return true;
1086
- })();
1087
-
1088
- return isMatch ? params : undefined;
1089
- }
1090
-
1091
- function matchBySearch(currentLocation, matchLocation) {
1092
- return !!(matchLocation.search && matchLocation.search(currentLocation.search));
1093
- }
1094
-
1095
- function parsePathname(pathname) {
1096
- if (!pathname) {
1097
- return [];
1098
- }
1099
-
1100
- pathname = cleanPath(pathname);
1101
- const segments = [];
1102
-
1103
- if (pathname.slice(0, 1) === '/') {
1104
- pathname = pathname.substring(1);
1105
- segments.push({
1106
- type: 'pathname',
1107
- value: '/'
1108
- });
1109
- }
1110
-
1111
- if (!pathname) {
1112
- return segments;
1113
- } // Remove empty segments and '.' segments
1114
-
1115
-
1116
- const split = pathname.split('/').filter(Boolean);
1117
- segments.push(...split.map(part => {
1118
- if (part.startsWith('*')) {
1119
- return {
1120
- type: 'wildcard',
1121
- value: part
1122
- };
1123
- }
1124
-
1125
- if (part.charAt(0) === ':') {
1126
- return {
1127
- type: 'param',
1128
- value: part
1129
- };
1130
- }
1131
-
1132
- return {
1133
- type: 'pathname',
1134
- value: part
1135
- };
1136
- }));
1137
-
1138
- if (pathname.slice(-1) === '/') {
1139
- pathname = pathname.substring(1);
1140
- segments.push({
1141
- type: 'pathname',
1142
- value: '/'
1143
- });
1144
- }
1145
-
1146
- return segments;
1147
- }
1148
- function resolvePath(basepath, base, to) {
1149
- base = base.replace(new RegExp("^" + basepath), '/').replace(/(.+)\/$/, (_, group) => group);
1150
- to = to.replace(new RegExp("^" + basepath), '/');
1151
- let baseSegments = parsePathname(base);
1152
- const toSegments = parsePathname(to);
1153
- toSegments.forEach((toSegment, index) => {
1154
- if (toSegment.value === '/') {
1155
- if (!index) {
1156
- // Leading slash
1157
- baseSegments = [toSegment];
1158
- } else if (index === toSegments.length - 1) {
1159
- // Trailing Slash
1160
- baseSegments.push(toSegment);
1161
- } else ;
1162
- } else if (toSegment.value === '..') {
1163
- baseSegments.pop();
1164
- } else if (toSegment.value === '.') {
1165
- return;
1166
- } else {
1167
- baseSegments.push(toSegment);
1168
- }
1169
- });
1170
- const joined = joinPaths([basepath, ...baseSegments.map(d => d.value)]);
1171
- return cleanPath(joined);
1172
- }
1173
- /**
1174
- * This function returns `a` if `b` is deeply equal.
1175
- * If not, it will replace any deeply equal children of `b` with those of `a`.
1176
- * This can be used for structural sharing between JSON values for example.
1177
- */
1178
-
1179
- function replaceEqualDeep(prev, next) {
1180
- if (prev === next) {
1181
- return prev;
1182
- }
1183
-
1184
- const array = Array.isArray(prev) && Array.isArray(next);
1185
-
1186
- if (array || isPlainObject(prev) && isPlainObject(next)) {
1187
- const aSize = array ? prev.length : Object.keys(prev).length;
1188
- const bItems = array ? next : Object.keys(next);
1189
- const bSize = bItems.length;
1190
- const copy = array ? [] : {};
1191
- let equalItems = 0;
1192
-
1193
- for (let i = 0; i < bSize; i++) {
1194
- const key = array ? i : bItems[i];
1195
- copy[key] = replaceEqualDeep(prev[key], next[key]);
1196
-
1197
- if (copy[key] === prev[key]) {
1198
- equalItems++;
1199
- }
1200
- }
1201
-
1202
- return aSize === bSize && equalItems === aSize ? prev : copy;
1203
- }
1204
-
1205
- return next;
1206
- } // Copied from: https://github.com/jonschlinkert/is-plain-object
1207
-
1208
- function isPlainObject(o) {
1209
- if (!hasObjectPrototype(o)) {
1210
- return false;
1211
- } // If has modified constructor
1212
-
1213
-
1214
- const ctor = o.constructor;
1215
-
1216
- if (typeof ctor === 'undefined') {
1217
- return true;
1218
- } // If has modified prototype
1219
-
1220
-
1221
- const prot = ctor.prototype;
1222
-
1223
- if (!hasObjectPrototype(prot)) {
1224
- return false;
1225
- } // If constructor does not have an Object-specific method
1226
-
1227
-
1228
- if (!prot.hasOwnProperty('isPrototypeOf')) {
1229
- return false;
1230
- } // Most likely a plain Object
1231
-
1232
-
1233
- return true;
1234
- }
1235
-
1236
- function hasObjectPrototype(o) {
1237
- return Object.prototype.toString.call(o) === '[object Object]';
1238
- }
1239
-
1240
- const defaultParseSearch = parseSearchWith(JSON.parse);
1241
- const defaultStringifySearch = stringifySearchWith(JSON.stringify);
1242
- function parseSearchWith(parser) {
1243
- return searchStr => {
1244
- if (searchStr.substring(0, 1) === '?') {
1245
- searchStr = searchStr.substring(1);
1246
- }
1247
-
1248
- let query = qss.decode(searchStr); // Try to parse any query params that might be json
1249
-
1250
- for (let key in query) {
1251
- const value = query[key];
1252
-
1253
- if (typeof value === 'string') {
1254
- try {
1255
- query[key] = parser(value);
1256
- } catch (err) {//
1257
- }
1258
- }
1259
- }
1260
-
1261
- return query;
1262
- };
1263
- }
1264
- function stringifySearchWith(stringify) {
1265
- return search => {
1266
- search = _rollupPluginBabelHelpers["extends"]({}, search);
1267
-
1268
- if (search) {
1269
- Object.keys(search).forEach(key => {
1270
- const val = search[key];
1271
-
1272
- if (typeof val === 'undefined' || val === undefined) {
1273
- delete search[key];
1274
- } else if (val && typeof val === 'object' && val !== null) {
1275
- try {
1276
- search[key] = stringify(val);
1277
- } catch (err) {// silent
1278
- }
1279
- }
1280
- });
1281
- }
1282
-
1283
- const searchStr = qss.encode(search).toString();
1284
- return searchStr ? "?" + searchStr : '';
1285
- };
1286
- }
1287
-
1288
- function isCtrlEvent(e) {
1289
- return !!(e.metaKey || e.altKey || e.ctrlKey || e.shiftKey);
1290
- }
1291
-
1292
- function last(arr) {
1293
- return arr[arr.length - 1];
1294
- }
1295
-
1296
- exports.createBrowserHistory = index.createBrowserHistory;
1297
- exports.createHashHistory = index.createHashHistory;
1298
- exports.createMemoryHistory = index.createMemoryHistory;
1299
- exports.RouteMatch = RouteMatch;
1300
- exports.RouterInstance = RouterInstance;
1301
- exports.cleanPath = cleanPath;
1302
- exports.defaultParseSearch = defaultParseSearch;
1303
- exports.defaultStringifySearch = defaultStringifySearch;
1304
- exports.functionalUpdate = functionalUpdate;
1305
- exports.matchByPath = matchByPath;
1306
- exports.matchRoute = matchRoute;
1307
- exports.parsePathname = parsePathname;
1308
- exports.parseSearchWith = parseSearchWith;
1309
- exports.replaceEqualDeep = replaceEqualDeep;
1310
- exports.resolvePath = resolvePath;
1311
- exports.stringifySearchWith = stringifySearchWith;
1312
- exports.warning = warning;
1313
- //# sourceMappingURL=index.js.map