@tinkoff/router 0.2.7 → 0.2.8

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 (60) hide show
  1. package/lib/components/react/context.browser.js +7 -0
  2. package/lib/components/react/context.es.js +7 -0
  3. package/lib/components/react/context.js +13 -0
  4. package/lib/components/react/provider.browser.js +12 -0
  5. package/lib/components/react/provider.es.js +12 -0
  6. package/lib/components/react/provider.js +16 -0
  7. package/lib/components/react/useNavigate.browser.js +17 -0
  8. package/lib/components/react/useNavigate.es.js +17 -0
  9. package/lib/components/react/useNavigate.js +21 -0
  10. package/lib/components/react/useRoute.browser.js +8 -0
  11. package/lib/components/react/useRoute.es.js +8 -0
  12. package/lib/components/react/useRoute.js +12 -0
  13. package/lib/components/react/useRouter.browser.js +8 -0
  14. package/lib/components/react/useRouter.es.js +8 -0
  15. package/lib/components/react/useRouter.js +12 -0
  16. package/lib/components/react/useUrl.browser.js +8 -0
  17. package/lib/components/react/useUrl.es.js +8 -0
  18. package/lib/components/react/useUrl.js +12 -0
  19. package/lib/history/base.browser.js +11 -0
  20. package/lib/history/base.es.js +11 -0
  21. package/lib/history/base.js +15 -0
  22. package/lib/history/client.browser.js +121 -0
  23. package/lib/history/client.es.js +121 -0
  24. package/lib/history/client.js +125 -0
  25. package/lib/history/server.es.js +15 -0
  26. package/lib/history/server.js +19 -0
  27. package/lib/history/wrapper.browser.js +72 -0
  28. package/lib/history/wrapper.es.js +72 -0
  29. package/lib/history/wrapper.js +80 -0
  30. package/lib/index.browser.js +12 -1169
  31. package/lib/index.es.js +12 -1097
  32. package/lib/index.js +36 -1124
  33. package/lib/logger.browser.js +15 -0
  34. package/lib/logger.es.js +15 -0
  35. package/lib/logger.js +23 -0
  36. package/lib/router/abstract.browser.js +395 -0
  37. package/lib/router/abstract.es.js +395 -0
  38. package/lib/router/abstract.js +404 -0
  39. package/lib/router/browser.browser.js +166 -0
  40. package/lib/router/client.browser.js +116 -0
  41. package/lib/router/client.es.js +116 -0
  42. package/lib/router/client.js +120 -0
  43. package/lib/router/clientNoSpa.browser.js +17 -0
  44. package/lib/router/clientNoSpa.es.js +17 -0
  45. package/lib/router/clientNoSpa.js +21 -0
  46. package/lib/router/server.es.js +85 -0
  47. package/lib/router/server.js +89 -0
  48. package/lib/tree/constants.browser.js +6 -0
  49. package/lib/tree/constants.es.js +6 -0
  50. package/lib/tree/constants.js +13 -0
  51. package/lib/tree/tree.browser.js +148 -0
  52. package/lib/tree/tree.es.js +148 -0
  53. package/lib/tree/tree.js +158 -0
  54. package/lib/tree/utils.browser.js +77 -0
  55. package/lib/tree/utils.es.js +77 -0
  56. package/lib/tree/utils.js +90 -0
  57. package/lib/utils.browser.js +35 -0
  58. package/lib/utils.es.js +35 -0
  59. package/lib/utils.js +48 -0
  60. package/package.json +5 -6
package/lib/index.es.js CHANGED
@@ -1,1097 +1,12 @@
1
- import { parse as parse$1, rawResolveUrl, rawParse, convertRawUrl, rawAssignUrl, isInvalidUrl } from '@tinkoff/url';
2
- import isString from '@tinkoff/utils/is/string';
3
- import isObject from '@tinkoff/utils/is/object';
4
- import map from '@tinkoff/utils/array/map';
5
- import T from '@tinkoff/utils/function/T';
6
- import noop from '@tinkoff/utils/function/noop';
7
- import each from '@tinkoff/utils/array/each';
8
- import find from '@tinkoff/utils/array/find';
9
- import findIndex from '@tinkoff/utils/array/findIndex';
10
- import { jsx } from 'react/jsx-runtime';
11
- import { useSyncExternalStore } from 'use-sync-external-store/shim';
12
- import { createContext, useContext, useCallback } from 'react';
13
- import { useShallowEqual } from '@tinkoff/react-hooks';
14
-
15
- const PARAMETER_DELIMITER = ':';
16
- const WILDCARD_REGEXP = /\*/;
17
- const HISTORY_FALLBACK_REGEXP = /<history-fallback>/;
18
- const PARAM_PARSER_REGEXP = /([^(?]+)(?:\((.+)\))?(\?)?/;
19
-
20
- const isFilePath = (pathname) => {
21
- return /\/.+\.[^/]+$/.test(pathname);
22
- };
23
- const normalizeTrailingSlash = (pathname, trailingSlash = false) => {
24
- const hasTrailingSlash = pathname.endsWith('/');
25
- if (trailingSlash) {
26
- return hasTrailingSlash || isFilePath(pathname) ? pathname : `${pathname}/`;
27
- }
28
- return pathname.length > 1 && hasTrailingSlash ? pathname.slice(0, -1) : pathname;
29
- };
30
- const normalizeManySlashes = (hrefOrPath) => {
31
- const [href, ...search] = hrefOrPath.split('?');
32
- return [href.replace(/\/+/g, '/').replace(/^(\w+):\//, '$1://'), ...search].join('?');
33
- };
34
- const isSameHost = typeof window === 'undefined'
35
- ? T
36
- : (url) => {
37
- return !url.host || url.host === window.location.host;
38
- };
39
- const makeNavigateOptions = (options) => {
40
- if (typeof options === 'string') {
41
- return { url: options };
42
- }
43
- return options;
44
- };
45
- const registerHook = (hooksSet, hook) => {
46
- hooksSet.add(hook);
47
- return () => {
48
- hooksSet.delete(hook);
49
- };
50
- };
51
-
52
- const getParts = (pathname) => pathname
53
- .split('/')
54
- .slice(pathname.startsWith('/') ? 1 : 0, pathname.endsWith('/') ? -1 : Infinity);
55
- const isHistoryFallback = (part) => {
56
- return HISTORY_FALLBACK_REGEXP.test(part);
57
- };
58
- const isWildcard = (part) => {
59
- return WILDCARD_REGEXP.test(part);
60
- };
61
- const isParameterized = (part) => {
62
- return part.includes(PARAMETER_DELIMITER);
63
- };
64
- const parseParameter = (part) => {
65
- const [prefix = '', param, postfix = ''] = part.split(PARAMETER_DELIMITER);
66
- const match = PARAM_PARSER_REGEXP.exec(param);
67
- if (!match) {
68
- throw new Error('parameters should satisfy pattern "prefix:paramName(regexp)\\?:postfix"');
69
- }
70
- const [, paramName, regexp, optional] = match;
71
- const useRegexp = prefix || postfix || regexp;
72
- return {
73
- type: 3 /* PartType.parameter */,
74
- paramName,
75
- regexp: useRegexp
76
- ? new RegExp(`^${prefix}(${regexp || '.+'})${optional ? '?' : ''}${postfix}$`)
77
- : undefined,
78
- optional: !!optional && !prefix && !postfix,
79
- };
80
- };
81
- const parse = (part) => {
82
- if (isHistoryFallback(part)) {
83
- return { type: 1 /* PartType.historyFallback */ };
84
- }
85
- if (isWildcard(part)) {
86
- return { type: 2 /* PartType.wildcard */ };
87
- }
88
- if (isParameterized(part)) {
89
- return parseParameter(part);
90
- }
91
- return { type: 0 /* PartType.literal */, value: part };
92
- };
93
- const makePath = (pathname, params) => {
94
- const parts = getParts(pathname);
95
- const result = map((part) => {
96
- var _a;
97
- if (isHistoryFallback(part) || isWildcard(part)) {
98
- throw new Error(`Pathname should be only a string with dynamic parameters, not a special string, got ${pathname}`);
99
- }
100
- if (isParameterized(part)) {
101
- const [prefix = '', param = '', postfix = ''] = part.split(PARAMETER_DELIMITER);
102
- const match = PARAM_PARSER_REGEXP.exec(param);
103
- if (!match) {
104
- throw new Error('parameters should satisfy pattern "prefix:paramName(regexp)\\?:postfix"');
105
- }
106
- const [, paramName, regexp, optional] = match;
107
- const value = (_a = params[paramName]) === null || _a === void 0 ? void 0 : _a.toString();
108
- if (optional && !value) {
109
- return '';
110
- }
111
- if (!value) {
112
- throw new Error(`value for parameter for ${paramName} should be defined in params`);
113
- }
114
- if (regexp && !new RegExp(regexp).test(value)) {
115
- throw new Error(`passed parameter for ${paramName} should satisfy regxep: ${regexp}, got: ${value}`);
116
- }
117
- return prefix + value + postfix || part;
118
- }
119
- return part;
120
- }, parts).join('/');
121
- return normalizeTrailingSlash(`/${result}`, pathname.endsWith('/'));
122
- };
123
-
124
- // eslint-disable-next-line import/no-mutable-exports
125
- let logger = {
126
- trace: noop,
127
- debug: noop,
128
- info: noop,
129
- warn: noop,
130
- error: noop,
131
- };
132
- const setLogger = (newLogger) => {
133
- logger = newLogger;
134
- };
135
-
136
- class AbstractRouter {
137
- constructor({ trailingSlash, mergeSlashes, beforeResolve = [], beforeNavigate = [], afterNavigate = [], beforeUpdateCurrent = [], afterUpdateCurrent = [], guards = [], onChange = [], onRedirect, onNotFound, onBlock, }) {
138
- this.started = false;
139
- this.trailingSlash = false;
140
- this.strictTrailingSlash = true;
141
- this.mergeSlashes = false;
142
- this.trailingSlash = trailingSlash !== null && trailingSlash !== void 0 ? trailingSlash : false;
143
- this.strictTrailingSlash = typeof trailingSlash === 'undefined';
144
- this.mergeSlashes = mergeSlashes !== null && mergeSlashes !== void 0 ? mergeSlashes : false;
145
- this.hooks = new Map([
146
- ['beforeResolve', new Set(beforeResolve)],
147
- ['beforeNavigate', new Set(beforeNavigate)],
148
- ['afterNavigate', new Set(afterNavigate)],
149
- ['beforeUpdateCurrent', new Set(beforeUpdateCurrent)],
150
- ['afterUpdateCurrent', new Set(afterUpdateCurrent)],
151
- ]);
152
- this.guards = new Set(guards);
153
- this.syncHooks = new Map([['change', new Set(onChange)]]);
154
- this.onRedirect = onRedirect;
155
- this.onNotFound = onNotFound;
156
- this.onBlock = onBlock;
157
- }
158
- // start is using as marker that any preparation for proper work has done in the app
159
- // and now router can manage any navigations
160
- async start() {
161
- logger.debug({
162
- event: 'start',
163
- });
164
- this.started = true;
165
- }
166
- getCurrentRoute() {
167
- var _a, _b, _c;
168
- // when something will try to get currentRoute while navigating, it will get route which router currently navigating
169
- // in case some handler supposed to load data of route or similar
170
- return (_b = (_a = this.currentNavigation) === null || _a === void 0 ? void 0 : _a.to) !== null && _b !== void 0 ? _b : (_c = this.lastNavigation) === null || _c === void 0 ? void 0 : _c.to;
171
- }
172
- getCurrentUrl() {
173
- var _a, _b, _c;
174
- // same as getCurrentRoute
175
- return (_b = (_a = this.currentNavigation) === null || _a === void 0 ? void 0 : _a.url) !== null && _b !== void 0 ? _b : (_c = this.lastNavigation) === null || _c === void 0 ? void 0 : _c.url;
176
- }
177
- getLastRoute() {
178
- var _a;
179
- return (_a = this.lastNavigation) === null || _a === void 0 ? void 0 : _a.to;
180
- }
181
- getLastUrl() {
182
- var _a;
183
- return (_a = this.lastNavigation) === null || _a === void 0 ? void 0 : _a.url;
184
- }
185
- commitNavigation(navigation) {
186
- logger.debug({
187
- event: 'commit-navigation',
188
- navigation,
189
- });
190
- if (!navigation.history) {
191
- // in case we came from history do not history back to prevent infinity recursive calls
192
- this.history.save(navigation);
193
- }
194
- this.lastNavigation = navigation;
195
- this.currentNavigation = null;
196
- this.runSyncHooks('change', navigation);
197
- }
198
- async updateCurrentRoute(updateRouteOptions) {
199
- return this.internalUpdateCurrentRoute(updateRouteOptions, {});
200
- }
201
- async internalUpdateCurrentRoute(updateRouteOptions, { history }) {
202
- var _a;
203
- const prevNavigation = (_a = this.currentNavigation) !== null && _a !== void 0 ? _a : this.lastNavigation;
204
- if (!prevNavigation) {
205
- throw new Error('updateCurrentRoute should only be called after navigate to some route');
206
- }
207
- const { replace, params, navigateState } = updateRouteOptions;
208
- const { to: from, url: fromUrl } = prevNavigation;
209
- const navigation = {
210
- type: 'updateCurrentRoute',
211
- from,
212
- to: this.resolveRoute({ params, navigateState }, { wildcard: true }),
213
- url: this.resolveUrl(updateRouteOptions),
214
- fromUrl,
215
- replace,
216
- history,
217
- navigateState,
218
- code: updateRouteOptions.code,
219
- };
220
- logger.debug({
221
- event: 'update-current-route',
222
- updateRouteOptions,
223
- navigation,
224
- });
225
- await this.run(navigation);
226
- }
227
- async runUpdateCurrentRoute(navigation) {
228
- await this.runHooks('beforeUpdateCurrent', navigation);
229
- this.commitNavigation(navigation);
230
- await this.runHooks('afterUpdateCurrent', navigation);
231
- }
232
- async navigate(navigateOptions) {
233
- return this.internalNavigate(makeNavigateOptions(navigateOptions), {});
234
- }
235
- async internalNavigate(navigateOptions, { history, redirect }) {
236
- var _a;
237
- const { url, replace, params, navigateState, code } = navigateOptions;
238
- const prevNavigation = redirect
239
- ? this.lastNavigation
240
- : (_a = this.currentNavigation) !== null && _a !== void 0 ? _a : this.lastNavigation;
241
- if (!url && !prevNavigation) {
242
- throw new Error('Navigate url should be specified and cannot be omitted for first navigation');
243
- }
244
- const resolvedUrl = this.resolveUrl(navigateOptions);
245
- const { to: from, url: fromUrl } = prevNavigation !== null && prevNavigation !== void 0 ? prevNavigation : {};
246
- const redirectFrom = redirect ? this.currentNavigation.to : undefined;
247
- let navigation = {
248
- type: 'navigate',
249
- from,
250
- url: resolvedUrl,
251
- fromUrl,
252
- replace,
253
- history,
254
- navigateState,
255
- code,
256
- redirect,
257
- redirectFrom,
258
- };
259
- await this.runHooks('beforeResolve', navigation);
260
- const to = this.resolveRoute({ url: resolvedUrl, params, navigateState }, { wildcard: true });
261
- if (to) {
262
- navigation = {
263
- ...navigation,
264
- to,
265
- };
266
- }
267
- logger.debug({
268
- event: 'navigation',
269
- navigation,
270
- });
271
- if (!navigation.to) {
272
- return this.notfound(navigation);
273
- }
274
- await this.run(navigation);
275
- }
276
- async runNavigate(navigation) {
277
- // check for redirect in new route description
278
- if (navigation.to.redirect) {
279
- return this.redirect(navigation, makeNavigateOptions(navigation.to.redirect));
280
- }
281
- await this.runGuards(navigation);
282
- await this.runHooks('beforeNavigate', navigation);
283
- this.commitNavigation(navigation);
284
- await this.runHooks('afterNavigate', navigation);
285
- }
286
- async run(navigation) {
287
- this.currentNavigation = navigation;
288
- if (navigation.type === 'navigate') {
289
- await this.runNavigate(navigation);
290
- }
291
- if (navigation.type === 'updateCurrentRoute') {
292
- await this.runUpdateCurrentRoute(navigation);
293
- }
294
- }
295
- resolve(resolveOptions, options) {
296
- const opts = typeof resolveOptions === 'string' ? { url: resolveOptions } : resolveOptions;
297
- return this.resolveRoute({ ...opts, url: parse$1(opts.url) }, options);
298
- }
299
- back(options) {
300
- return this.go(-1, options);
301
- }
302
- forward() {
303
- return this.go(1);
304
- }
305
- async go(to, options) {
306
- logger.debug({
307
- event: 'history.go',
308
- to,
309
- });
310
- return this.history.go(to, options);
311
- }
312
- isNavigating() {
313
- return !!this.currentNavigation;
314
- }
315
- async dehydrate() {
316
- throw new Error('Not implemented');
317
- }
318
- async rehydrate(navigation) {
319
- throw new Error('Not implemented');
320
- }
321
- addRoute(route) {
322
- var _a;
323
- (_a = this.tree) === null || _a === void 0 ? void 0 : _a.addRoute(route);
324
- }
325
- async redirect(navigation, target) {
326
- var _a;
327
- logger.debug({
328
- event: 'redirect',
329
- navigation,
330
- target,
331
- });
332
- return (_a = this.onRedirect) === null || _a === void 0 ? void 0 : _a.call(this, {
333
- ...navigation,
334
- from: navigation.to,
335
- fromUrl: navigation.url,
336
- to: null,
337
- url: this.resolveUrl(target),
338
- });
339
- }
340
- async notfound(navigation) {
341
- var _a;
342
- logger.debug({
343
- event: 'not-found',
344
- navigation,
345
- });
346
- return (_a = this.onNotFound) === null || _a === void 0 ? void 0 : _a.call(this, navigation);
347
- }
348
- async block(navigation) {
349
- logger.debug({
350
- event: 'blocked',
351
- navigation,
352
- });
353
- this.currentNavigation = null;
354
- if (this.onBlock) {
355
- return this.onBlock(navigation);
356
- }
357
- throw new Error('Navigation blocked');
358
- }
359
- normalizePathname(pathname) {
360
- let normalized = pathname;
361
- if (this.mergeSlashes) {
362
- normalized = normalizeManySlashes(normalized);
363
- }
364
- if (!this.strictTrailingSlash) {
365
- normalized = normalizeTrailingSlash(normalized, this.trailingSlash);
366
- }
367
- return normalized;
368
- }
369
- resolveUrl({ url, query = {}, params, preserveQuery, hash }) {
370
- var _a;
371
- const currentRoute = this.getCurrentRoute();
372
- const currentUrl = this.getCurrentUrl();
373
- const resultUrl = url ? rawResolveUrl((_a = currentUrl === null || currentUrl === void 0 ? void 0 : currentUrl.href) !== null && _a !== void 0 ? _a : '', url) : rawParse(currentUrl.href);
374
- let { pathname } = resultUrl;
375
- if (params) {
376
- if (url) {
377
- pathname = makePath(resultUrl.pathname, params);
378
- }
379
- else if (currentRoute) {
380
- pathname = makePath(currentRoute.path, { ...currentRoute.params, ...params });
381
- }
382
- }
383
- if (isSameHost(resultUrl)) {
384
- pathname = this.normalizePathname(pathname);
385
- }
386
- return convertRawUrl(rawAssignUrl(resultUrl, {
387
- pathname,
388
- search: url ? resultUrl.search : '',
389
- query: {
390
- ...(preserveQuery ? this.getCurrentUrl().query : {}),
391
- ...query,
392
- },
393
- hash: hash !== null && hash !== void 0 ? hash : resultUrl.hash,
394
- }));
395
- }
396
- resolveRoute({ url, params, navigateState }, { wildcard } = {}) {
397
- var _a, _b;
398
- let route = url ? (_a = this.tree) === null || _a === void 0 ? void 0 : _a.getRoute(url.pathname) : this.getCurrentRoute();
399
- if (wildcard && !route && url) {
400
- // if ordinary route not found look for a wildcard route
401
- route = (_b = this.tree) === null || _b === void 0 ? void 0 : _b.getWildcard(url.pathname);
402
- }
403
- if (!route) {
404
- return;
405
- }
406
- // if condition is true route data not changed, so no need to create new reference for route object
407
- if (!params && navigateState === route.navigateState) {
408
- return route;
409
- }
410
- return {
411
- ...route,
412
- params: { ...route.params, ...params },
413
- navigateState,
414
- };
415
- }
416
- async runGuards(navigation) {
417
- logger.debug({
418
- event: 'guards.run',
419
- navigation,
420
- });
421
- if (!this.guards) {
422
- logger.debug({
423
- event: 'guards.empty',
424
- navigation,
425
- });
426
- return;
427
- }
428
- const results = await Promise.all(Array.from(this.guards).map((guard) => Promise.resolve(guard(navigation)).catch((error) => {
429
- logger.warn({
430
- event: 'guard.error',
431
- error,
432
- });
433
- })));
434
- logger.debug({
435
- event: 'guards.done',
436
- navigation,
437
- results,
438
- });
439
- for (const result of results) {
440
- if (result === false) {
441
- return this.block(navigation);
442
- }
443
- if (isString(result) || isObject(result)) {
444
- return this.redirect(navigation, makeNavigateOptions(result));
445
- }
446
- }
447
- }
448
- registerGuard(guard) {
449
- return registerHook(this.guards, guard);
450
- }
451
- runSyncHooks(hookName, navigation) {
452
- logger.debug({
453
- event: 'sync-hooks.run',
454
- hookName,
455
- navigation,
456
- });
457
- const hooks = this.syncHooks.get(hookName);
458
- if (!hooks) {
459
- logger.debug({
460
- event: 'sync-hooks.empty',
461
- hookName,
462
- navigation,
463
- });
464
- return;
465
- }
466
- for (const hook of hooks) {
467
- try {
468
- hook(navigation);
469
- }
470
- catch (error) {
471
- logger.warn({
472
- event: 'sync-hooks.error',
473
- error,
474
- });
475
- }
476
- }
477
- logger.debug({
478
- event: 'sync-hooks.done',
479
- hookName,
480
- navigation,
481
- });
482
- }
483
- registerSyncHook(hookName, hook) {
484
- return registerHook(this.syncHooks.get(hookName), hook);
485
- }
486
- async runHooks(hookName, navigation) {
487
- logger.debug({
488
- event: 'hooks.run',
489
- hookName,
490
- navigation,
491
- });
492
- const hooks = this.hooks.get(hookName);
493
- if (!hooks) {
494
- logger.debug({
495
- event: 'hooks.empty',
496
- hookName,
497
- navigation,
498
- });
499
- return;
500
- }
501
- await Promise.all(Array.from(hooks).map((hook) => Promise.resolve(hook(navigation)).catch((error) => {
502
- logger.warn({
503
- event: 'hook.error',
504
- error,
505
- });
506
- // rethrow error for beforeResolve to prevent showing not found page
507
- // if app has problems while loading info about routes
508
- if (hookName === 'beforeResolve') {
509
- throw error;
510
- }
511
- })));
512
- logger.debug({
513
- event: 'hooks.done',
514
- hookName,
515
- navigation,
516
- });
517
- }
518
- registerHook(hookName, hook) {
519
- return registerHook(this.hooks.get(hookName), hook);
520
- }
521
- }
522
-
523
- class History {
524
- init(navigation) { }
525
- listen(listener) {
526
- this.listener = listener;
527
- }
528
- setTree(tree) {
529
- this.tree = tree;
530
- }
531
- }
532
-
533
- class ServerHistory extends History {
534
- save() { }
535
- go() {
536
- logger.warn({
537
- event: 'history.server',
538
- message: 'Trying to change history on server',
539
- });
540
- return Promise.resolve();
541
- }
542
- }
543
-
544
- const createTree = (route) => {
545
- return {
546
- route,
547
- children: Object.create(null),
548
- parameters: [],
549
- };
550
- };
551
- const createNavigationRoute = (route, pathname, params) => {
552
- return {
553
- ...route,
554
- actualPath: pathname,
555
- params: params !== null && params !== void 0 ? params : {},
556
- };
557
- };
558
- class RouteTree {
559
- constructor(routes) {
560
- this.tree = createTree();
561
- each((route) => this.addRoute(route), routes);
562
- }
563
- // eslint-disable-next-line max-statements
564
- addRoute(route) {
565
- const parts = getParts(route.path);
566
- let currentTree = this.tree;
567
- for (let i = 0; i < parts.length; i++) {
568
- const part = parts[i];
569
- const parsed = parse(part);
570
- if (parsed.type === 1 /* PartType.historyFallback */) {
571
- currentTree.historyFallbackRoute = route;
572
- return;
573
- }
574
- if (parsed.type === 2 /* PartType.wildcard */) {
575
- currentTree.wildcardRoute = route;
576
- return;
577
- }
578
- if (parsed.type === 3 /* PartType.parameter */) {
579
- const { paramName, regexp, optional } = parsed;
580
- // prevent from creating new entries for same route
581
- const found = find((par) => par.key === part, currentTree.parameters);
582
- if (found) {
583
- currentTree = found.tree;
584
- }
585
- else {
586
- const parameter = {
587
- key: part,
588
- paramName,
589
- regexp,
590
- optional,
591
- tree: createTree(),
592
- };
593
- if (regexp && !optional) {
594
- // insert parameters with regexp before
595
- const index = findIndex((par) => !par.regexp, currentTree.parameters);
596
- currentTree.parameters.splice(index, 0, parameter);
597
- }
598
- else {
599
- currentTree.parameters.push(parameter);
600
- }
601
- currentTree = parameter.tree;
602
- }
603
- }
604
- else {
605
- if (!currentTree.children[part]) {
606
- currentTree.children[part] = createTree();
607
- }
608
- currentTree = currentTree.children[part];
609
- }
610
- }
611
- currentTree.route = route;
612
- }
613
- getRoute(pathname) {
614
- return this.findRoute(pathname, 'route');
615
- }
616
- getWildcard(pathname) {
617
- return this.findRoute(pathname, 'wildcardRoute');
618
- }
619
- getHistoryFallback(pathname) {
620
- const route = this.findRoute(pathname, 'historyFallbackRoute');
621
- return (route && {
622
- ...route,
623
- // remove <history-fallback> from path
624
- actualPath: route.path.replace(HISTORY_FALLBACK_REGEXP, '') || '/',
625
- });
626
- }
627
- // eslint-disable-next-line max-statements
628
- findRoute(pathname, propertyName) {
629
- // we should use exact match only for classic route
630
- // as special routes (for not-found and history-fallback) are defined for whole subtree
631
- const exactMatch = propertyName === 'route';
632
- const parts = getParts(pathname);
633
- const queue = [
634
- [this.tree, 0],
635
- ];
636
- while (queue.length) {
637
- const [currentTree, index, params] = queue.pop();
638
- const { children, parameters } = currentTree;
639
- // this flag mean we can only check for optional parameters
640
- // as we didn't find static route for this path, but still may find
641
- // some inner route inside optional branch
642
- // the value of parameter will be empty in this case ofc
643
- let optionalOnly = false;
644
- if (index >= parts.length) {
645
- if (currentTree[propertyName]) {
646
- return createNavigationRoute(currentTree[propertyName], pathname, params);
647
- }
648
- // here we cant check any options except for optional parameters
649
- optionalOnly = true;
650
- }
651
- // first add to queue special routes (not-found or history-fallback) to check it after other cases, as it will be processed last
652
- if (!exactMatch && currentTree[propertyName]) {
653
- queue.push([currentTree, parts.length, params]);
654
- }
655
- const part = parts[index];
656
- const child = children[part];
657
- // then add checks for only optional
658
- for (const param of parameters) {
659
- const { optional, tree } = param;
660
- if (optional) {
661
- queue.push([tree, index, params]);
662
- }
663
- }
664
- if (optionalOnly) {
665
- continue;
666
- }
667
- // for non-optional cases
668
- for (let i = parameters.length - 1; i >= 0; i--) {
669
- const param = parameters[i];
670
- const { paramName, tree, regexp } = param;
671
- const match = regexp === null || regexp === void 0 ? void 0 : regexp.exec(part);
672
- const paramValue = regexp ? match === null || match === void 0 ? void 0 : match[1] : part;
673
- if (paramValue) {
674
- queue.push([tree, index + 1, { ...params, [paramName]: paramValue }]);
675
- }
676
- }
677
- if (child) {
678
- // add checks for static child subtree last as it will be processed first after queue.pop
679
- queue.push([child, index + 1, params]);
680
- }
681
- }
682
- }
683
- }
684
-
685
- class Router extends AbstractRouter {
686
- constructor(options) {
687
- var _a;
688
- super(options);
689
- this.blocked = false;
690
- this.tree = new RouteTree(options.routes);
691
- this.defaultRedirectCode = (_a = options.defaultRedirectCode) !== null && _a !== void 0 ? _a : 308;
692
- this.history = new ServerHistory();
693
- }
694
- async dehydrate() {
695
- logger.debug({
696
- event: 'dehydrate',
697
- navigation: this.lastNavigation,
698
- });
699
- return this.lastNavigation;
700
- }
701
- async internalNavigate(navigateOptions, internalOptions) {
702
- // any navigation after initial should be considered as redirects
703
- if (this.getCurrentRoute()) {
704
- return this.redirect(this.lastNavigation, navigateOptions);
705
- }
706
- return super.internalNavigate(navigateOptions, internalOptions);
707
- }
708
- async run(navigation) {
709
- if (this.redirectCode) {
710
- return this.redirect(navigation, { url: navigation.url.href, code: this.redirectCode });
711
- }
712
- await super.run(navigation);
713
- }
714
- async redirect(navigation, target) {
715
- logger.debug({
716
- event: 'redirect',
717
- navigation,
718
- target,
719
- });
720
- this.blocked = true;
721
- return this.onRedirect({
722
- ...navigation,
723
- from: navigation.to,
724
- fromUrl: navigation.url,
725
- to: null,
726
- url: this.resolveUrl(target),
727
- code: target.code,
728
- });
729
- }
730
- async notfound(navigation) {
731
- this.blocked = true;
732
- return super.notfound(navigation);
733
- }
734
- normalizePathname(pathname) {
735
- const normalized = super.normalizePathname(pathname);
736
- if (normalized !== pathname) {
737
- this.redirectCode = this.defaultRedirectCode;
738
- }
739
- return normalized;
740
- }
741
- resolveUrl(options) {
742
- if (options.url && isInvalidUrl(options.url)) {
743
- this.redirectCode = this.defaultRedirectCode;
744
- }
745
- return super.resolveUrl(options);
746
- }
747
- async runHooks(hookName, navigation) {
748
- // do not run hooks if another parallel navigation has been called
749
- if (this.blocked) {
750
- return;
751
- }
752
- return super.runHooks(hookName, navigation);
753
- }
754
- async runGuards(navigation) {
755
- // do not run guards if another parallel navigation has been called
756
- if (this.blocked) {
757
- return;
758
- }
759
- return super.runGuards(navigation);
760
- }
761
- }
762
-
763
- const supportsHtml5History = typeof window !== 'undefined' && window.history && window.history.pushState;
764
- const wrapHistory = ({ onNavigate }) => {
765
- if (!supportsHtml5History) {
766
- const navigate = (data, title, url) => {
767
- window.location.href = url.toString();
768
- };
769
- window.history.pushState = navigate;
770
- window.history.replaceState = navigate;
771
- return {
772
- navigate: ({ path }) => navigate({}, '', path),
773
- history: () => {
774
- throw new Error('Method not implemented');
775
- },
776
- init: noop,
777
- subscribe: noop,
778
- };
779
- }
780
- let browserHistory = window.history;
781
- if ('__originalHistory' in window.history) {
782
- browserHistory = window.history.__originalHistory;
783
- }
784
- else {
785
- window.history.__originalHistory = {
786
- pushState: browserHistory.pushState.bind(window.history),
787
- replaceState: browserHistory.replaceState.bind(window.history),
788
- go: browserHistory.go.bind(window.history),
789
- };
790
- }
791
- const pushState = browserHistory.pushState.bind(window.history);
792
- const replaceState = browserHistory.replaceState.bind(window.history);
793
- const go = browserHistory.go.bind(window.history);
794
- const navigate = ({ path, replace, state }) => {
795
- if (replace) {
796
- replaceState(state, '', path);
797
- }
798
- else {
799
- pushState(state, '', path);
800
- }
801
- };
802
- const history = (delta) => {
803
- go(delta);
804
- };
805
- const browserNavigate = (replace = false) => {
806
- return (navigateState, title, url) => {
807
- onNavigate({ url: url.toString(), replace, navigateState });
808
- };
809
- };
810
- window.history.pushState = browserNavigate(false);
811
- window.history.replaceState = browserNavigate(true);
812
- window.history.go = history;
813
- window.history.back = () => history(-1);
814
- window.history.forward = () => history(1);
815
- return {
816
- navigate,
817
- history,
818
- init: (state) => {
819
- replaceState(state, '');
820
- },
821
- subscribe: (handler) => {
822
- window.addEventListener('popstate', ({ state }) => {
823
- handler({
824
- path: window.location.pathname + window.location.search + window.location.hash,
825
- state,
826
- });
827
- });
828
- },
829
- };
830
- };
831
-
832
- const isHistoryState = (state) => {
833
- return state && typeof state.key === 'string';
834
- };
835
- const generateKey = (navigation) => {
836
- const { to } = navigation;
837
- if (to) {
838
- return `${to.name}_${to.path}`;
839
- }
840
- };
841
- const generateState = (navigation, currentState) => {
842
- const key = generateKey(navigation);
843
- let { type } = navigation;
844
- if (navigation.replace && currentState) {
845
- type = currentState.type === type ? type : 'navigate';
846
- }
847
- return {
848
- key,
849
- type,
850
- navigateState: navigation.navigateState,
851
- };
852
- };
853
- class ClientHistory extends History {
854
- constructor() {
855
- super();
856
- this.currentIndex = 0;
857
- this.historyWrapper = wrapHistory({
858
- onNavigate: ({ url, replace, navigateState }) => {
859
- this.listener({
860
- url,
861
- replace,
862
- navigateState,
863
- });
864
- },
865
- });
866
- }
867
- init(navigation) {
868
- var _a;
869
- this.currentState = isHistoryState((_a = window.history) === null || _a === void 0 ? void 0 : _a.state)
870
- ? window.history.state
871
- : generateState(navigation);
872
- this.historyWrapper.init(this.currentState);
873
- this.historyWrapper.subscribe(async ({ path, state }) => {
874
- var _a, _b;
875
- try {
876
- let navigationType;
877
- let navigateState;
878
- if (isHistoryState(state)) {
879
- const { key: prevKey, type: prevType } = this.currentState;
880
- const { key, type } = state;
881
- this.currentState = state;
882
- navigateState = state.navigateState;
883
- if (key === prevKey &&
884
- (type === 'updateCurrentRoute' || prevType === 'updateCurrentRoute')) {
885
- navigationType = 'updateCurrentRoute';
886
- }
887
- else {
888
- navigationType = 'navigate';
889
- }
890
- }
891
- else {
892
- // if it is not HistoryState than it is probably not a state from @tinkoff/router so reset it
893
- this.currentIndex = 0;
894
- }
895
- await this.listener({
896
- type: navigationType,
897
- history: true,
898
- url: path,
899
- navigateState,
900
- });
901
- (_a = this.goPromiseResolve) === null || _a === void 0 ? void 0 : _a.call(this);
902
- }
903
- catch (err) {
904
- (_b = this.goPromiseReject) === null || _b === void 0 ? void 0 : _b.call(this, err);
905
- }
906
- });
907
- }
908
- save(navigation) {
909
- const { replace, url } = navigation;
910
- if (!replace) {
911
- this.currentIndex++;
912
- }
913
- this.currentState = generateState(navigation, this.currentState);
914
- this.historyWrapper.navigate({
915
- path: url.path,
916
- replace,
917
- state: this.currentState,
918
- });
919
- }
920
- go(to, options) {
921
- var _a;
922
- const index = this.currentIndex + to;
923
- if (index < 0) {
924
- if (options === null || options === void 0 ? void 0 : options.historyFallback) {
925
- return this.listener({
926
- url: options.historyFallback,
927
- type: 'navigate',
928
- history: false,
929
- });
930
- }
931
- const historyFallbackRoute = (_a = this.tree) === null || _a === void 0 ? void 0 : _a.getHistoryFallback(window.location.pathname);
932
- if (historyFallbackRoute) {
933
- return this.listener({
934
- url: historyFallbackRoute.actualPath,
935
- type: 'navigate',
936
- history: false,
937
- });
938
- }
939
- }
940
- const promise = new Promise((resolve, reject) => {
941
- this.goPromiseResolve = resolve;
942
- this.goPromiseReject = reject;
943
- });
944
- this.historyWrapper.history(to);
945
- return promise;
946
- }
947
- }
948
-
949
- class ClientRouter extends AbstractRouter {
950
- constructor(options) {
951
- super(options);
952
- this.history = new ClientHistory();
953
- this.history.listen(async ({ type, url, navigateState, replace, history }) => {
954
- var _a;
955
- const currentUrl = this.getCurrentUrl();
956
- const { pathname, query } = this.resolveUrl({ url });
957
- const isSameUrlNavigation = currentUrl.pathname === pathname;
958
- if (type === 'updateCurrentRoute' || (!type && isSameUrlNavigation)) {
959
- const route = (_a = this.tree) === null || _a === void 0 ? void 0 : _a.getRoute(pathname);
960
- await this.internalUpdateCurrentRoute({
961
- params: route === null || route === void 0 ? void 0 : route.params,
962
- query,
963
- replace,
964
- navigateState,
965
- }, { history });
966
- }
967
- else {
968
- await this.internalNavigate({
969
- url,
970
- replace,
971
- navigateState,
972
- }, { history });
973
- }
974
- });
975
- }
976
- async rehydrate(navigation) {
977
- logger.debug({
978
- event: 'rehydrate',
979
- navigation,
980
- });
981
- const url = parse$1(window.location.href);
982
- this.currentNavigation = {
983
- ...navigation,
984
- type: 'navigate',
985
- url,
986
- };
987
- this.lastNavigation = this.currentNavigation;
988
- // rerun guard check in case it differs from server side
989
- await this.runGuards(this.currentNavigation);
990
- // and init any history listeners
991
- this.history.init(this.currentNavigation);
992
- this.currentNavigation = null;
993
- // add dehydrated route to tree to prevent its loading
994
- if (navigation.to) {
995
- this.addRoute({
996
- name: navigation.to.name,
997
- path: navigation.to.path,
998
- config: navigation.to.config,
999
- // in case we have loaded page from some path-changing proxy
1000
- // save this actual path as alias
1001
- alias: url.pathname,
1002
- });
1003
- }
1004
- }
1005
- resolveRoute(...options) {
1006
- const { url } = options[0];
1007
- // navigation for other hosts should be considered as external navigation
1008
- if (url && !isSameHost(url)) {
1009
- return;
1010
- }
1011
- return super.resolveRoute(...options);
1012
- }
1013
- async notfound(navigation) {
1014
- var _a, _b;
1015
- await super.notfound(navigation);
1016
- // in case we didn't find any matched route just force hard page navigation
1017
- const prevUrl = (_b = (_a = navigation.fromUrl) === null || _a === void 0 ? void 0 : _a.href) !== null && _b !== void 0 ? _b : window.location.href;
1018
- const nextUrl = navigation.url.href;
1019
- const isNoSpaNavigation = navigation.from && !navigation.to;
1020
- // prevent redirect cycle on the same page,
1021
- // except cases when we run no-spa navigations,
1022
- // because we need hard reload in this cases
1023
- if (isNoSpaNavigation ? true : prevUrl !== nextUrl) {
1024
- if (navigation.replace) {
1025
- window.location.replace(nextUrl);
1026
- }
1027
- else {
1028
- window.location.assign(nextUrl);
1029
- }
1030
- }
1031
- // prevent routing from any continues navigation returning promise which will be not resolved
1032
- return new Promise(() => { });
1033
- }
1034
- async block(navigation) {
1035
- return this.notfound(navigation);
1036
- }
1037
- async redirect(navigation, target) {
1038
- await super.redirect(navigation, target);
1039
- return this.internalNavigate({
1040
- ...target,
1041
- replace: target.replace || navigation.replace,
1042
- }, {
1043
- redirect: true,
1044
- });
1045
- }
1046
- }
1047
-
1048
- const omitHash = (url) => url.href.replace(/#.*$/, '');
1049
- class NoSpaRouter extends ClientRouter {
1050
- run(navigation) {
1051
- const { type, fromUrl, url } = navigation;
1052
- // support only updateCurrentRoute or hash navigations
1053
- if (type === 'updateCurrentRoute' || omitHash(url) === omitHash(fromUrl)) {
1054
- return super.run(navigation);
1055
- }
1056
- return this.notfound(navigation);
1057
- }
1058
- // do not call any hooks as it is only supports url updates with hash
1059
- async runHooks() { }
1060
- }
1061
-
1062
- const RouterContext = createContext(null);
1063
- const RouteContext = createContext(null);
1064
- const UrlContext = createContext(null);
1065
-
1066
- const Provider = ({ router, serverState, children }) => {
1067
- const route = useSyncExternalStore((cb) => router.registerSyncHook('change', cb), () => router.getLastRoute(), serverState ? () => serverState.currentRoute : () => router.getLastRoute());
1068
- const url = useSyncExternalStore((cb) => router.registerSyncHook('change', cb), () => router.getLastUrl(), serverState ? () => serverState.currentUrl : () => router.getLastUrl());
1069
- return (jsx(RouterContext.Provider, { value: router, children: jsx(RouteContext.Provider, { value: route, children: jsx(UrlContext.Provider, { value: url, children: children }) }) }));
1070
- };
1071
- Provider.displayName = 'Provider';
1072
-
1073
- const useRouter = () => {
1074
- return useContext(RouterContext);
1075
- };
1076
-
1077
- const useRoute = () => {
1078
- return useContext(RouteContext);
1079
- };
1080
-
1081
- const useUrl = () => {
1082
- return useContext(UrlContext);
1083
- };
1084
-
1085
- const convertToNavigateOptions = (options) => {
1086
- return typeof options === 'string' ? { url: options } : options;
1087
- };
1088
- const useNavigate = (rootOptions) => {
1089
- const router = useRouter();
1090
- const rootOpts = useShallowEqual(convertToNavigateOptions(rootOptions));
1091
- return useCallback((specificOptions) => {
1092
- const opts = rootOpts !== null && rootOpts !== void 0 ? rootOpts : convertToNavigateOptions(specificOptions);
1093
- return router.navigate(opts);
1094
- }, [rootOpts, router]);
1095
- };
1096
-
1097
- export { AbstractRouter, History, NoSpaRouter, Provider, RouteTree, Router, getParts, isHistoryFallback, isParameterized, isWildcard, logger, makePath, parse, setLogger, useNavigate, useRoute, useRouter, useUrl };
1
+ export { Router } from './router/server.es.js';
2
+ export { NoSpaRouter } from './router/clientNoSpa.es.js';
3
+ export { AbstractRouter } from './router/abstract.es.js';
4
+ export { History } from './history/base.es.js';
5
+ export { logger, setLogger } from './logger.es.js';
6
+ export { Provider } from './components/react/provider.es.js';
7
+ export { useRouter } from './components/react/useRouter.es.js';
8
+ export { useRoute } from './components/react/useRoute.es.js';
9
+ export { useUrl } from './components/react/useUrl.es.js';
10
+ export { useNavigate } from './components/react/useNavigate.es.js';
11
+ export { RouteTree } from './tree/tree.es.js';
12
+ export { getParts, isHistoryFallback, isParameterized, isWildcard, makePath, parse } from './tree/utils.es.js';