@tramvai/module-common 2.70.0 → 2.72.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.
Files changed (123) hide show
  1. package/lib/CommonModule.browser.js +100 -0
  2. package/lib/CommonModule.es.js +100 -0
  3. package/lib/CommonModule.js +106 -0
  4. package/lib/actions/ActionModule.browser.js +79 -0
  5. package/lib/actions/ActionModule.es.js +79 -0
  6. package/lib/actions/ActionModule.js +82 -0
  7. package/lib/actions/actionChecker.browser.js +52 -0
  8. package/lib/actions/actionChecker.es.js +52 -0
  9. package/lib/actions/actionChecker.js +56 -0
  10. package/lib/actions/actionExecution.browser.js +107 -0
  11. package/lib/actions/actionExecution.es.js +107 -0
  12. package/lib/actions/actionExecution.js +118 -0
  13. package/lib/actions/actionPageRunner.browser.browser.js +33 -0
  14. package/lib/actions/actionPageRunner.es.js +61 -0
  15. package/lib/actions/actionPageRunner.js +65 -0
  16. package/lib/actions/actionRegistry.browser.js +33 -0
  17. package/lib/actions/actionRegistry.es.js +33 -0
  18. package/lib/actions/actionRegistry.js +45 -0
  19. package/lib/actions/actionTramvaiReducer.browser.js +10 -0
  20. package/lib/actions/actionTramvaiReducer.es.js +10 -0
  21. package/lib/actions/actionTramvaiReducer.js +15 -0
  22. package/lib/actions/conditions/always.browser.js +10 -0
  23. package/lib/actions/conditions/always.es.js +10 -0
  24. package/lib/actions/conditions/always.js +14 -0
  25. package/lib/actions/conditions/helpers.browser.js +4 -0
  26. package/lib/actions/conditions/helpers.es.js +4 -0
  27. package/lib/actions/conditions/helpers.js +9 -0
  28. package/lib/actions/conditions/onlyBrowser.browser.js +12 -0
  29. package/lib/actions/conditions/onlyBrowser.es.js +12 -0
  30. package/lib/actions/conditions/onlyBrowser.js +16 -0
  31. package/lib/actions/conditions/onlyServer.browser.js +12 -0
  32. package/lib/actions/conditions/onlyServer.es.js +12 -0
  33. package/lib/actions/conditions/onlyServer.js +16 -0
  34. package/lib/actions/conditions/pageBrowser.browser.js +13 -0
  35. package/lib/actions/conditions/pageBrowser.es.js +13 -0
  36. package/lib/actions/conditions/pageBrowser.js +17 -0
  37. package/lib/actions/conditions/pageServer.browser.js +13 -0
  38. package/lib/actions/conditions/pageServer.es.js +13 -0
  39. package/lib/actions/conditions/pageServer.js +17 -0
  40. package/lib/actions/constants.browser.js +9 -0
  41. package/lib/actions/constants.es.js +9 -0
  42. package/lib/actions/constants.js +13 -0
  43. package/lib/bundleManager/bundleManager.browser.js +105 -0
  44. package/lib/bundleManager/bundleManager.es.js +105 -0
  45. package/lib/bundleManager/bundleManager.js +115 -0
  46. package/lib/cache/CacheModule.browser.js +58 -0
  47. package/lib/cache/CacheModule.es.js +58 -0
  48. package/lib/cache/CacheModule.js +62 -0
  49. package/lib/cache/cacheFactory.browser.js +7 -0
  50. package/lib/cache/cacheFactory.es.js +7 -0
  51. package/lib/cache/cacheFactory.js +15 -0
  52. package/lib/cache/clientProviders.browser.js +3 -0
  53. package/lib/cache/papi.es.js +18 -0
  54. package/lib/cache/papi.js +22 -0
  55. package/lib/cache/serverProviders.es.js +18 -0
  56. package/lib/cache/serverProviders.js +22 -0
  57. package/lib/child-app/ChildAppModule.browser.js +38 -0
  58. package/lib/child-app/ChildAppModule.es.js +38 -0
  59. package/lib/child-app/ChildAppModule.js +40 -0
  60. package/lib/child-app/actions.browser.js +19 -0
  61. package/lib/child-app/actions.es.js +19 -0
  62. package/lib/child-app/actions.js +23 -0
  63. package/lib/child-app/clientProviders.browser.js +18 -0
  64. package/lib/child-app/command.browser.js +35 -0
  65. package/lib/child-app/command.es.js +35 -0
  66. package/lib/child-app/command.js +40 -0
  67. package/lib/child-app/serverProviders.es.js +3 -0
  68. package/lib/child-app/serverProviders.js +7 -0
  69. package/lib/child-app/state.browser.js +13 -0
  70. package/lib/child-app/state.es.js +13 -0
  71. package/lib/child-app/state.js +17 -0
  72. package/lib/command/CommandModule.browser.js +52 -0
  73. package/lib/command/CommandModule.es.js +52 -0
  74. package/lib/command/CommandModule.js +54 -0
  75. package/lib/command/commandLineRunner.browser.js +147 -0
  76. package/lib/command/commandLineRunner.es.js +147 -0
  77. package/lib/command/commandLineRunner.js +151 -0
  78. package/lib/command/defaultLines.browser.js +25 -0
  79. package/lib/command/defaultLines.es.js +25 -0
  80. package/lib/command/defaultLines.js +29 -0
  81. package/lib/componentRegistry/componentRegistry.browser.js +25 -0
  82. package/lib/componentRegistry/componentRegistry.es.js +25 -0
  83. package/lib/componentRegistry/componentRegistry.js +34 -0
  84. package/lib/createConsumerContext/createConsumerContext.browser.js +62 -0
  85. package/lib/createConsumerContext/createConsumerContext.es.js +62 -0
  86. package/lib/createConsumerContext/createConsumerContext.js +67 -0
  87. package/lib/executionContext/executionContextManager.browser.js +57 -0
  88. package/lib/executionContext/executionContextManager.es.js +57 -0
  89. package/lib/executionContext/executionContextManager.js +61 -0
  90. package/lib/index.browser.js +13 -1300
  91. package/lib/index.es.js +13 -1318
  92. package/lib/index.js +38 -1341
  93. package/lib/providers/clientProviders.browser.js +22 -0
  94. package/lib/providers/serverProviders.es.js +3 -0
  95. package/lib/providers/serverProviders.js +7 -0
  96. package/lib/pubsub/PubSubModule.browser.js +44 -0
  97. package/lib/pubsub/PubSubModule.es.js +44 -0
  98. package/lib/pubsub/PubSubModule.js +46 -0
  99. package/lib/requestManager/RequestManagerModule.browser.browser.js +38 -0
  100. package/lib/requestManager/RequestManagerModule.es.js +35 -0
  101. package/lib/requestManager/RequestManagerModule.js +37 -0
  102. package/lib/requestManager/RequestManagerStore.browser.js +8 -0
  103. package/lib/requestManager/RequestManagerStore.es.js +8 -0
  104. package/lib/requestManager/RequestManagerStore.js +13 -0
  105. package/lib/requestManager/requestManager.browser.js +57 -0
  106. package/lib/requestManager/requestManager.es.js +57 -0
  107. package/lib/requestManager/requestManager.js +61 -0
  108. package/lib/requestManager/sharedProviders.browser.js +23 -0
  109. package/lib/requestManager/sharedProviders.es.js +23 -0
  110. package/lib/requestManager/sharedProviders.js +27 -0
  111. package/lib/responseManager/ResponseManagerModule.browser.browser.js +21 -0
  112. package/lib/responseManager/ResponseManagerModule.es.js +13 -0
  113. package/lib/responseManager/ResponseManagerModule.js +15 -0
  114. package/lib/responseManager/responseManager.browser.js +52 -0
  115. package/lib/responseManager/responseManager.es.js +52 -0
  116. package/lib/responseManager/responseManager.js +61 -0
  117. package/lib/responseManager/sharedProviders.browser.js +13 -0
  118. package/lib/responseManager/sharedProviders.es.js +13 -0
  119. package/lib/responseManager/sharedProviders.js +17 -0
  120. package/lib/state/StateModule.browser.js +54 -0
  121. package/lib/state/StateModule.es.js +54 -0
  122. package/lib/state/StateModule.js +60 -0
  123. package/package.json +24 -25
@@ -1,1301 +1,14 @@
1
- import { __decorate } from 'tslib';
2
- import eachObj from '@tinkoff/utils/object/each';
3
- import { createBundle, provide, Scope, Module, commandLineListTokens, COMMAND_LINE_RUNNER_TOKEN, COMMAND_LINES_TOKEN, DI_TOKEN, isTramvaiAction, ACTION_PARAMETERS, createToken, ACTIONS_LIST_TOKEN, IS_DI_CHILD_CONTAINER_TOKEN, BUNDLE_LIST_TOKEN } from '@tramvai/core';
4
- import { EnvironmentModule } from '@tramvai/module-environment';
5
- import { CookieModule } from '@tramvai/module-cookie';
6
- export { COOKIE_MANAGER_TOKEN } from '@tramvai/module-cookie';
7
- import { LogModule } from '@tramvai/module-log';
8
- import { Hooks } from '@tinkoff/hook-runner';
9
- import { REQUEST_MANAGER_TOKEN, COMBINE_REDUCERS, STORE_TOKEN, RESPONSE_MANAGER_TOKEN, ACTION_EXECUTION_TOKEN, ROOT_EXECUTION_CONTEXT_TOKEN, LOGGER_TOKEN, EXECUTION_CONTEXT_MANAGER_TOKEN, COMMAND_LINE_EXECUTION_CONTEXT_TOKEN, PUBSUB_FACTORY_TOKEN, PUBSUB_TOKEN, ROOT_PUBSUB_TOKEN, INITIAL_APP_STATE_TOKEN, ACTION_REGISTRY_TOKEN, ACTION_CONDITIONALS, CONTEXT_TOKEN, ACTION_PAGE_RUNNER_TOKEN, DISPATCHER_TOKEN, DISPATCHER_CONTEXT_TOKEN, STORE_MIDDLEWARE, CREATE_CACHE_TOKEN, CLEAR_CACHE_TOKEN, REGISTER_CLEAR_CACHE_TOKEN, HOOK_TOKEN, COMPONENT_REGISTRY_TOKEN, BUNDLE_MANAGER_TOKEN, ADDITIONAL_BUNDLE_TOKEN } from '@tramvai/tokens-common';
1
+ export { CommonModule } from './CommonModule.browser.js';
2
+ export { CommandModule } from './command/CommandModule.browser.js';
3
+ export { ActionExecution } from './actions/actionExecution.browser.js';
4
+ export { ExecutionContextManager } from './executionContext/executionContextManager.browser.js';
5
+ import './actions/ActionModule.browser.js';
6
+ export { createConsumerContext } from './createConsumerContext/createConsumerContext.browser.js';
7
+ export { CommonChildAppModule } from './child-app/ChildAppModule.browser.js';
10
8
  export * from '@tramvai/tokens-common';
11
- import isObject from '@tinkoff/utils/is/object';
12
- import isArray from '@tinkoff/utils/is/array';
13
- import { resolveLazyComponent, __lazyErrorHandler } from '@tramvai/react';
14
- import { fileSystemPagesEnabled, getAllFileSystemPages, getAllFileSystemLayouts, getAllFileSystemErrorBoundaries, isFileSystemPageComponent, fileSystemPageToLayoutKey, fileSystemPageToErrorBoundaryKey } from '@tramvai/experiments';
15
- import pathOr from '@tinkoff/utils/object/pathOr';
16
- import flatten from '@tinkoff/utils/array/flatten';
17
- import { FASTIFY_REQUEST, FASTIFY_RESPONSE } from '@tramvai/tokens-server-private';
18
- import { createEvent, createReducer, convertAction, createDispatcher, devTools, Provider } from '@tramvai/state';
19
- import { format, parse } from '@tinkoff/url';
20
- import isEmpty from '@tinkoff/utils/is/empty';
21
- import values from '@tinkoff/utils/object/values';
22
- import { COMMAND_LINE_TIMING_INFO_TOKEN, COMMAND_LINE_EXECUTION_END_TOKEN } from '@tramvai/tokens-core-private';
23
- import { createChildContainer, provide as provide$1, Scope as Scope$1, createToken as createToken$1 } from '@tinkoff/dippy';
24
- import { isSilentError, ConditionFailError, ExecutionAbortError } from '@tinkoff/errors';
25
- import { PubSub } from '@tinkoff/pubsub';
26
- import identity from '@tinkoff/utils/function/identity';
27
- import objectMap from '@tinkoff/utils/object/map';
28
- import uniq from '@tinkoff/utils/array/uniq';
29
- import difference from '@tinkoff/utils/array/difference';
30
- import toArray from '@tinkoff/utils/array/toArray';
31
- import LRU from '@tinkoff/lru-cache-nano';
32
- import { AbortController } from 'node-abort-controller';
33
- import { jsx } from 'react/jsx-runtime';
34
- import { EXTEND_RENDER } from '@tramvai/tokens-render';
35
- import { CHILD_APP_COMMON_INITIAL_STATE_TOKEN, CHILD_APP_INTERNAL_CONFIG_TOKEN, CHILD_APP_INTERNAL_ROOT_DI_BORROW_TOKEN, commandLineListTokens as commandLineListTokens$1 } from '@tramvai/tokens-child-app';
36
-
37
- const FS_PAGES_DEFAULT_BUNDLE = '__default';
38
- class BundleManager {
39
- constructor({ bundleList, componentRegistry, actionRegistry, dispatcher, logger }) {
40
- this.bundles = bundleList;
41
- this.componentRegistry = componentRegistry;
42
- this.actionRegistry = actionRegistry;
43
- this.dispatcher = dispatcher;
44
- if (fileSystemPagesEnabled()) {
45
- const log = logger('file-system-pages:bundle-manager');
46
- const components = getAllFileSystemPages();
47
- const layouts = getAllFileSystemLayouts();
48
- const errorBoundaries = getAllFileSystemErrorBoundaries();
49
- const getComponentsFor = (mapping, getKey) => Object.keys(mapping).reduce((result, key) => {
50
- // eslint-disable-next-line no-param-reassign
51
- result[getKey(key)] = mapping[key];
52
- return result;
53
- }, {});
54
- const componentsDefaultBundle = createBundle({
55
- name: FS_PAGES_DEFAULT_BUNDLE,
56
- components: {
57
- ...getComponentsFor(layouts, fileSystemPageToLayoutKey),
58
- ...getComponentsFor(errorBoundaries, fileSystemPageToErrorBoundaryKey),
59
- ...components,
60
- },
61
- });
62
- this.bundles[FS_PAGES_DEFAULT_BUNDLE] = () => Promise.resolve({
63
- default: componentsDefaultBundle,
64
- });
65
- for (const key in componentsDefaultBundle.components) {
66
- this.componentRegistry.add(key, componentsDefaultBundle.components[key], FS_PAGES_DEFAULT_BUNDLE);
67
- }
68
- log.debug({
69
- event: 'create default bundle with file-system pages',
70
- components: Object.keys(components),
71
- });
72
- }
73
- }
74
- get(name, pageComponent) {
75
- // use fake bundle with file-system pages
76
- if (isFileSystemPageComponent(pageComponent)) {
77
- // eslint-disable-next-line no-param-reassign
78
- name = FS_PAGES_DEFAULT_BUNDLE;
79
- }
80
- return this.loadBundle(name, pageComponent).then((bundle) => this.resolve(bundle.default, pageComponent));
81
- }
82
- has(name, pageComponent) {
83
- // use fake bundle with file-system pages
84
- if (isFileSystemPageComponent(pageComponent)) {
85
- // eslint-disable-next-line no-param-reassign
86
- name = FS_PAGES_DEFAULT_BUNDLE;
87
- }
88
- return !!this.bundles[name];
89
- }
90
- async resolve(bundle, pageComponent) {
91
- // preload `lazy` components then register actions and reducers
92
- if (pageComponent && bundle.components[pageComponent]) {
93
- const componentOrLoader = bundle.components[pageComponent];
94
- const component = await resolveLazyComponent(componentOrLoader);
95
- if (!component) {
96
- return;
97
- }
98
- // allow page components to register any other components
99
- if ('components' in component && isObject(component.components)) {
100
- eachObj((cmp, name) => {
101
- this.componentRegistry.add(name, cmp, pageComponent);
102
- }, component.components);
103
- }
104
- if ('actions' in component && isArray(component.actions)) {
105
- this.actionRegistry.add(pageComponent, component.actions);
106
- }
107
- if ('reducers' in component && isArray(component.reducers)) {
108
- component.reducers.forEach((reducer) => {
109
- this.dispatcher.registerStore(reducer);
110
- });
111
- }
112
- }
113
- eachObj((component, name) => {
114
- this.componentRegistry.add(name, component, bundle.name);
115
- }, bundle.components);
116
- if (bundle.actions) {
117
- this.actionRegistry.add(bundle.name, bundle.actions);
118
- }
119
- if (bundle.reducers) {
120
- bundle.reducers.forEach((reducer) => {
121
- this.dispatcher.registerStore(reducer);
122
- });
123
- }
124
- return bundle;
125
- }
126
- loadBundle(name, pageComponent) {
127
- if (!this.has(name, pageComponent)) {
128
- return Promise.reject(new Error(`Bundle "${name}" not found`));
129
- }
130
- return this.bundles[name]().catch((e) => __lazyErrorHandler(e, this.bundles[name]));
131
- }
132
- }
133
-
134
- const DEFAULT_GROUP = '__default';
135
- class ComponentRegistry {
136
- constructor({ componentList } = {}) {
137
- this.components = {
138
- [DEFAULT_GROUP]: Object.assign({}, ...flatten(componentList !== null && componentList !== void 0 ? componentList : [])),
139
- };
140
- }
141
- add(name, component, group = DEFAULT_GROUP) {
142
- const groupComponents = this.components[group] || {};
143
- groupComponents[name] = component;
144
- this.components[group] = groupComponents;
145
- }
146
- get(name, group = DEFAULT_GROUP) {
147
- const groupComponents = this.components[group] || {};
148
- return groupComponents[name] || this.components[DEFAULT_GROUP][name];
149
- }
150
- getComponentParam(param, defaultValue, component, group) {
151
- return pathOr([param], defaultValue, this.get(component, group));
152
- }
153
- }
154
-
155
- const setRequest = createEvent('setRequest');
156
- const RequestManagerStore = createReducer('requestManager', {}).on(setRequest, (_, state) => {
157
- return state;
158
- });
159
-
160
- class RequestManager {
161
- constructor({ request }) {
162
- this.request = request || {};
163
- if (typeof window === 'undefined') {
164
- this.url = format({
165
- protocol: this.getHeader('x-forwarded-proto') || this.request.protocol,
166
- host: this.getHost(),
167
- path: this.request.url,
168
- });
169
- }
170
- else {
171
- this.url = window.location.href;
172
- }
173
- }
174
- getBody() {
175
- return this.request.body;
176
- }
177
- getUrl() {
178
- return this.url;
179
- }
180
- getParsedUrl() {
181
- if (!this.parsedUrl) {
182
- this.parsedUrl = parse(this.url);
183
- }
184
- return this.parsedUrl;
185
- }
186
- getMethod() {
187
- return this.request.method;
188
- }
189
- getHeader(key) {
190
- var _a;
191
- return (_a = this.request.headers) === null || _a === void 0 ? void 0 : _a[key];
192
- }
193
- getHeaders() {
194
- return this.request.headers;
195
- }
196
- getCookie(key) {
197
- return this.request.cookies[key];
198
- }
199
- getCookies() {
200
- return this.request.cookies;
201
- }
202
- getClientIp() {
203
- var _a, _b;
204
- return this.getHeader('x-real-ip') || ((_b = (_a = this.request) === null || _a === void 0 ? void 0 : _a.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress) || '';
205
- }
206
- getHost() {
207
- if (typeof window === 'undefined') {
208
- return (this.getHeader('x-original-host') || this.getHeader('host'));
209
- }
210
- return window.location.host;
211
- }
212
- }
213
-
214
- const sharedProviders$1 = [
215
- provide({
216
- provide: REQUEST_MANAGER_TOKEN,
217
- scope: Scope.REQUEST,
218
- useClass: RequestManager,
219
- deps: {
220
- request: FASTIFY_REQUEST,
221
- },
222
- }),
223
- provide({
224
- provide: COMBINE_REDUCERS,
225
- multi: true,
226
- useValue: RequestManagerStore,
227
- }),
228
- ];
229
-
230
- let RequestManagerModule = class RequestManagerModule {
231
- };
232
- RequestManagerModule = __decorate([
233
- Module({
234
- providers: [
235
- ...sharedProviders$1,
236
- provide({
237
- provide: FASTIFY_REQUEST,
238
- useFactory: ({ store }) => {
239
- const fromServer = store.getState(RequestManagerStore);
240
- return {
241
- ...fromServer,
242
- headers: {
243
- ...fromServer === null || fromServer === void 0 ? void 0 : fromServer.headers,
244
- 'user-agent': navigator.userAgent,
245
- cookie: document.cookie,
246
- },
247
- // the type is not actually the same and is only partially compatible with actual request object
248
- // but provide it as a backup for some of the isomorphic code
249
- // anyway it is better not to use request/response on client
250
- };
251
- },
252
- deps: {
253
- store: STORE_TOKEN,
254
- },
255
- }),
256
- ],
257
- })
258
- ], RequestManagerModule);
259
-
260
- class ResponseManager {
261
- constructor() {
262
- this.body = '';
263
- this.headers = {};
264
- this.cookies = {};
265
- this.status = 200;
266
- }
267
- getBody() {
268
- return this.body;
269
- }
270
- setBody(value) {
271
- this.body = value;
272
- }
273
- getHeader(key) {
274
- if (key === 'set-cookie') {
275
- return values(this.cookies);
276
- }
277
- return this.headers[key];
278
- }
279
- getHeaders() {
280
- if (isEmpty(this.cookies)) {
281
- return this.headers;
282
- }
283
- return {
284
- ...this.headers,
285
- 'Set-Cookie': values(this.cookies),
286
- };
287
- }
288
- setHeader(key, value) {
289
- this.headers[key] = value;
290
- }
291
- getCookie(key) {
292
- return this.cookies[key];
293
- }
294
- getCookies() {
295
- return this.cookies;
296
- }
297
- setCookie(key, value) {
298
- this.cookies[key] = value;
299
- }
300
- setStatus(status) {
301
- this.status = status;
302
- }
303
- getStatus() {
304
- return this.status;
305
- }
306
- }
307
-
308
- const sharedProviders = [
309
- provide({
310
- provide: RESPONSE_MANAGER_TOKEN,
311
- scope: Scope.REQUEST,
312
- useClass: ResponseManager,
313
- }),
314
- ];
315
-
316
- let ResponseManagerModule = class ResponseManagerModule {
317
- };
318
- ResponseManagerModule = __decorate([
319
- Module({
320
- providers: [
321
- ...sharedProviders,
322
- provide({
323
- provide: FASTIFY_RESPONSE,
324
- // @ts-expect-error
325
- useValue: {},
326
- }),
327
- ],
328
- })
329
- ], ResponseManagerModule);
330
-
331
- class ConsumerContext {
332
- constructor({ di, dispatcherContext, pubsub, store }) {
333
- /* Side Effects */
334
- this.executeAction = (action, payload) => {
335
- return this.di.get(ACTION_EXECUTION_TOKEN).run(action, payload);
336
- };
337
- /* State manager */
338
- this.dispatch = (actionOrNameEvent, payload) => {
339
- return new Promise((resolve, reject) => {
340
- try {
341
- resolve(this.store.dispatch(convertAction(actionOrNameEvent, payload)));
342
- }
343
- catch (err) {
344
- reject(err);
345
- }
346
- });
347
- };
348
- this.dispatchWith = (createActionOrType, options) => {
349
- return typeof createActionOrType === 'function'
350
- ? (...args) => this.dispatch(createActionOrType(...args), options)
351
- : (payload) => this.dispatch(createActionOrType, payload);
352
- };
353
- /**
354
- * @deprecated
355
- */
356
- this.getStore = (store) => {
357
- return this.dispatcher.getStore(store);
358
- };
359
- this.dehydrate = () => ({
360
- dispatcher: this.dispatcher.dehydrate(),
361
- });
362
- this.getState = (...args) => {
363
- return this.store.getState(args[0]);
364
- };
365
- this.subscribe = (...args) => {
366
- return this.store.subscribe(args[0], args[1]);
367
- };
368
- this.hasStore = (store) => this.dispatcher.hasStore(store);
369
- this.registerStore = (store) => this.dispatcher.registerStore(store);
370
- this.unregisterStore = (store) => this.dispatcher.unregisterStore(store);
371
- this.store = store;
372
- // @ts-expect-error
373
- this.dispatcher = dispatcherContext;
374
- // TODO убрать, нужно для некоторых старых сторов на платформе
375
- this.dispatcher.setContext(this);
376
- this.di = di; // кажется этого здесь не должно быть
377
- this.pubsub = pubsub;
378
- }
379
- }
380
- function createConsumerContext({ di, dispatcherContext, pubsub, store }) {
381
- return new ConsumerContext({
382
- di,
383
- dispatcherContext,
384
- pubsub,
385
- store,
386
- });
387
- }
388
-
389
- const resolveDi = (type, status, diContainer, providers) => {
390
- let di = diContainer;
391
- if (status === 'customer' && type !== 'client') {
392
- di = createChildContainer(di);
393
- }
394
- if (providers) {
395
- providers.forEach((item) => {
396
- return di.register(item);
397
- });
398
- }
399
- return di;
400
- };
401
- class CommandLineRunner {
402
- constructor({ lines, rootDi, logger, executionContextManager, executionEndHandlers }) {
403
- this.executionContextByDi = new WeakMap();
404
- this.abortControllerByDi = new WeakMap();
405
- this.lines = lines;
406
- this.rootDi = rootDi;
407
- this.log = logger('command:command-line-runner');
408
- this.executionContextManager = executionContextManager;
409
- this.executionEndHandlers = executionEndHandlers;
410
- }
411
- run(type, status, providers, customDi) {
412
- const di = customDi !== null && customDi !== void 0 ? customDi : resolveDi(type, status, this.rootDi, providers);
413
- const rootExecutionContext = di.get({ token: ROOT_EXECUTION_CONTEXT_TOKEN, optional: true });
414
- this.log.debug({
415
- event: 'command-run',
416
- type,
417
- status,
418
- });
419
- const timingInfo = {};
420
- di.register({ provide: COMMAND_LINE_TIMING_INFO_TOKEN, useValue: timingInfo });
421
- return (this.lines[type][status]
422
- .reduce((chain, line) => {
423
- return chain.then(() => {
424
- const lineName = line.toString();
425
- timingInfo[lineName] = { start: performance.now() };
426
- // eslint-disable-next-line promise/no-nesting
427
- return Promise.resolve()
428
- .then(() => {
429
- return this.executionContextManager.withContext(rootExecutionContext, `command-line:${lineName}`, async (executionContext, abortController) => {
430
- this.executionContextByDi.set(di, executionContext);
431
- this.abortControllerByDi.set(di, abortController);
432
- await this.createLineChain(di, line);
433
- });
434
- })
435
- .finally(() => {
436
- timingInfo[lineName].end = performance.now();
437
- });
438
- });
439
- }, Promise.resolve())
440
- // После завершения цепочки отдаем context выполнения
441
- .finally(() => {
442
- this.executionContextByDi.delete(di);
443
- this.abortControllerByDi.delete(di);
444
- if (this.executionEndHandlers) {
445
- for (const executionEndHandler of this.executionEndHandlers) {
446
- executionEndHandler(di, type, status, timingInfo);
447
- }
448
- }
449
- })
450
- .then(() => di));
451
- }
452
- resolveExecutionContextFromDi(di) {
453
- var _a;
454
- return (_a = this.executionContextByDi.get(di)) !== null && _a !== void 0 ? _a : null;
455
- }
456
- createLineChain(di, line) {
457
- let lineInstance;
458
- try {
459
- lineInstance = di.get({ token: line, optional: true });
460
- // Пропускаем step. Так как нет действий
461
- if (lineInstance === null) {
462
- return Promise.resolve();
463
- }
464
- }
465
- catch (e) {
466
- // Логируем ошибку и дальше падаем
467
- this.log.error(e);
468
- return this.throwError(e, di);
469
- }
470
- if (!Array.isArray(lineInstance)) {
471
- return this.instanceExecute(lineInstance, line, di);
472
- }
473
- return Promise.all(lineInstance.map((instance) => {
474
- return this.instanceExecute(instance, line, di);
475
- }));
476
- }
477
- instanceExecute(instance, line, di) {
478
- if (!(instance instanceof Function)) {
479
- const error = new TypeError(`Expected function in line processing "commandLineListTokens.${line.toString()}", received "${instance}".
480
- Check that all commandLineListTokens subscribers return functions`);
481
- if (process.env.NODE_ENV !== 'production') {
482
- const instances = di.get(line);
483
- const record = di.getRecord(line.toString());
484
- // пробегаемся по всем инстансам и для текущего получаем его запись, из которой можно получить стек
485
- for (let i = 0; i < instances.length; i++) {
486
- if (instances[i] === instance) {
487
- // @ts-expect-error
488
- error.stack = `${error.stack}\n---- caused by: ----\n${record.multi[i].stack || ''}`;
489
- }
490
- }
491
- }
492
- this.log.error({
493
- event: 'line-error',
494
- error,
495
- line: line.toString(),
496
- });
497
- return;
498
- }
499
- const { name = '' } = instance;
500
- this.log.debug({
501
- event: 'line-run',
502
- line: line.toString(),
503
- command: name,
504
- });
505
- return Promise.resolve()
506
- .then(() => instance())
507
- .catch((err) => {
508
- var _a;
509
- this.log[isSilentError(err) ? 'debug' : 'error']({
510
- event: 'line-error',
511
- error: err,
512
- line: line.toString(),
513
- command: name,
514
- });
515
- // in case if any error happens during line execution results from other line handlers will not be used anyway
516
- (_a = this.abortControllerByDi.get(di)) === null || _a === void 0 ? void 0 : _a.abort();
517
- this.throwError(err, di);
518
- });
519
- }
520
- // eslint-disable-next-line class-methods-use-this
521
- throwError(err, di) {
522
- if (typeof err === 'object') {
523
- // eslint-disable-next-line no-param-reassign
524
- err.di = di;
525
- }
526
- throw err;
527
- }
528
- }
529
-
530
- const command$1 = {
531
- init: [commandLineListTokens.init, commandLineListTokens.listen],
532
- close: [commandLineListTokens.close],
533
- customer: [
534
- commandLineListTokens.customerStart,
535
- commandLineListTokens.resolveUserDeps,
536
- commandLineListTokens.resolvePageDeps,
537
- commandLineListTokens.generatePage,
538
- commandLineListTokens.clear,
539
- ],
540
- spa: [
541
- commandLineListTokens.resolveUserDeps,
542
- commandLineListTokens.resolvePageDeps,
543
- commandLineListTokens.spaTransition,
544
- ],
545
- afterSpa: [commandLineListTokens.afterSpaTransition],
546
- };
547
- const lines$1 = {
548
- server: command$1,
549
- client: command$1,
550
- };
551
-
552
- let CommandModule = class CommandModule {
553
- };
554
- CommandModule = __decorate([
555
- Module({
556
- providers: [
557
- provide$1({
558
- // Раннер процессов
559
- provide: COMMAND_LINE_RUNNER_TOKEN,
560
- scope: Scope$1.SINGLETON,
561
- useClass: CommandLineRunner,
562
- deps: {
563
- lines: COMMAND_LINES_TOKEN,
564
- rootDi: DI_TOKEN,
565
- logger: LOGGER_TOKEN,
566
- executionContextManager: EXECUTION_CONTEXT_MANAGER_TOKEN,
567
- executionEndHandlers: {
568
- token: COMMAND_LINE_EXECUTION_END_TOKEN,
569
- optional: true,
570
- },
571
- },
572
- }),
573
- provide$1({
574
- provide: COMMAND_LINE_EXECUTION_CONTEXT_TOKEN,
575
- useFactory: ({ di, commandLineRunner }) => {
576
- return () => {
577
- return commandLineRunner.resolveExecutionContextFromDi(di);
578
- };
579
- },
580
- deps: {
581
- di: DI_TOKEN,
582
- commandLineRunner: COMMAND_LINE_RUNNER_TOKEN,
583
- },
584
- }),
585
- provide$1({
586
- // Дефолтный список команл
587
- provide: COMMAND_LINES_TOKEN,
588
- scope: Scope$1.SINGLETON,
589
- useValue: lines$1,
590
- }),
591
- ],
592
- })
593
- ], CommandModule);
594
-
595
- let PubSubModule = class PubSubModule {
596
- };
597
- PubSubModule = __decorate([
598
- Module({
599
- providers: [
600
- provide({
601
- // Фабрика для создания pubsub
602
- provide: PUBSUB_FACTORY_TOKEN,
603
- scope: Scope.SINGLETON,
604
- useFactory: (deps) => () => {
605
- return new PubSub({
606
- logger: deps.logger('pubsub'),
607
- });
608
- },
609
- deps: {
610
- logger: LOGGER_TOKEN,
611
- },
612
- }),
613
- provide({
614
- provide: PUBSUB_TOKEN,
615
- scope: Scope.REQUEST,
616
- useFactory: ({ createPubsub }) => createPubsub(),
617
- deps: {
618
- createPubsub: PUBSUB_FACTORY_TOKEN,
619
- },
620
- }),
621
- provide({
622
- provide: ROOT_PUBSUB_TOKEN,
623
- scope: Scope.SINGLETON,
624
- useFactory: ({ createPubsub }) => createPubsub(),
625
- deps: {
626
- createPubsub: PUBSUB_FACTORY_TOKEN,
627
- },
628
- }),
629
- ],
630
- })
631
- ], PubSubModule);
632
-
633
- const providers$2 = [
634
- provide({
635
- provide: INITIAL_APP_STATE_TOKEN,
636
- useFactory: () => { var _a, _b; return JSON.parse((_b = (_a = document.getElementById('__TRAMVAI_STATE__')) === null || _a === void 0 ? void 0 : _a.textContent) !== null && _b !== void 0 ? _b : '{}'); },
637
- scope: Scope.REQUEST,
638
- }),
639
- provide({
640
- provide: commandLineListTokens.listen,
641
- useFactory: ({ commandLineRunner, }) => {
642
- return function initClientCommand() {
643
- return commandLineRunner.run('client', 'customer');
644
- };
645
- },
646
- deps: { commandLineRunner: COMMAND_LINE_RUNNER_TOKEN },
647
- multi: true,
648
- }),
649
- ];
650
-
651
- const actionServerStateEvent = createEvent('action state execution in server');
652
- const initalState = { serverState: {} };
653
- const actionTramvaiReducer = createReducer('actionTramvai', initalState).on(actionServerStateEvent, (state, payload) => ({
654
- ...state,
655
- serverState: payload,
656
- }));
657
-
658
- /**
659
- * @deprecated only for compatibility with legacy createAction
660
- */
661
- const actionType = {
662
- global: 'global',
663
- local: 'local',
664
- };
665
-
666
- const DEFAULT_CONDITIONS = {};
667
- class ActionChecker {
668
- // eslint-disable-next-line max-params
669
- constructor(globalConditionals, payload, parameters, executionState, type) {
670
- var _a;
671
- this.globalConditionals = globalConditionals;
672
- this.payload = payload;
673
- this.parameters = parameters;
674
- this.executionState = executionState;
675
- this.type = type;
676
- this.status = true;
677
- this.forbiddenMarker = false;
678
- this.key = null;
679
- // для глобальных экшенов мы должны дедублицировать выполнение и меньше выполнять
680
- if (type === actionType.global) {
681
- // если экшен был уже выполнен, то считаем, что его не нужно больше выполнять
682
- this.status = executionState.status !== 'success';
683
- }
684
- this.conditions = (_a = parameters.conditions) !== null && _a !== void 0 ? _a : DEFAULT_CONDITIONS;
685
- }
686
- check() {
687
- this.globalConditionals.forEach((filter) => {
688
- this.key = filter.key;
689
- filter.fn(this);
690
- });
691
- return this.getStatus();
692
- }
693
- setState(value) {
694
- this.executionState.state[this.key] = value;
695
- }
696
- getState() {
697
- return this.executionState.state[this.key];
698
- }
699
- forbid() {
700
- this.executionState.status = 'forbidden';
701
- this.executionState.forbiddenBy = this.key;
702
- this.forbiddenMarker = true;
703
- }
704
- allow() {
705
- this.status = true;
706
- }
707
- getStatus() {
708
- if (this.forbiddenMarker) {
709
- return false;
710
- }
711
- return this.status;
712
- }
713
- }
714
-
715
- const EMPTY_DEPS = {};
716
- const DEFAULT_PAYLOAD = {};
717
- const getParameters = (action) => action[ACTION_PARAMETERS];
718
- class ActionExecution {
719
- constructor({ store, context, di, executionContextManager, actionConditionals, transformAction, }) {
720
- this.actionConditionals = flatten(actionConditionals !== null && actionConditionals !== void 0 ? actionConditionals : []);
721
- this.context = context;
722
- this.store = store;
723
- this.di = di;
724
- this.executionContextManager = executionContextManager;
725
- this.execution = new Map();
726
- this.transformAction = transformAction || identity;
727
- const initialState = store.getState(actionTramvaiReducer);
728
- if (initialState && initialState.serverState) {
729
- objectMap((value, key) => {
730
- this.execution.set(key, value);
731
- }, initialState.serverState);
732
- }
733
- }
734
- async runInContext(executionContext, action, ...params) {
735
- var _a, _b;
736
- let parameters;
737
- const payload = (_a = params[0]) !== null && _a !== void 0 ? _a : DEFAULT_PAYLOAD;
738
- // TODO: replace type with pure context usage
739
- const type = (executionContext === null || executionContext === void 0 ? void 0 : executionContext.values.pageActions) === true ? actionType.global : actionType.local;
740
- // TODO: remove else branch after migration to new declareAction
741
- if (isTramvaiAction(action)) {
742
- parameters = action;
743
- }
744
- else {
745
- this.transformAction(action);
746
- parameters = getParameters(action);
747
- }
748
- const executionState = this.getExecutionState(parameters.name);
749
- if (!this.canExecuteAction(payload, parameters, executionState, type)) {
750
- switch (parameters.conditionsFailResult) {
751
- case 'reject':
752
- return Promise.reject(new ConditionFailError({
753
- conditionName: (_b = executionState.forbiddenBy) !== null && _b !== void 0 ? _b : 'unknown',
754
- targetName: parameters.name,
755
- }));
756
- default:
757
- return Promise.resolve();
758
- }
759
- }
760
- executionState.status = 'pending';
761
- return this.executionContextManager.withContext(executionContext, {
762
- name: parameters.name,
763
- values: (executionContext === null || executionContext === void 0 ? void 0 : executionContext.values.pageActions) === true ? { pageActions: false } : undefined,
764
- }, (executionActionContext, abortController) => {
765
- const context = this.createActionContext(executionContext, executionActionContext, abortController, parameters);
766
- return Promise.resolve()
767
- .then(() => {
768
- if (isTramvaiAction(action)) {
769
- return action.fn.apply(context, params);
770
- }
771
- return action(this.context, payload, context.deps);
772
- })
773
- .then((data) => {
774
- executionState.status = 'success';
775
- return data;
776
- })
777
- .catch((err) => {
778
- executionState.status = 'failed';
779
- throw err;
780
- });
781
- });
782
- }
783
- async run(action, ...params) {
784
- return this.runInContext(null, action, ...params);
785
- }
786
- getExecutionState(name) {
787
- let executionState = this.execution.get(name);
788
- // TODO: probably do not need to create executionState on client as it is not used
789
- if (!executionState) {
790
- executionState = { status: 'pending', state: {} };
791
- this.execution.set(name, executionState);
792
- }
793
- return executionState;
794
- }
795
- canExecuteAction(payload, parameters, executionState, type) {
796
- const actionChecker = new ActionChecker(this.actionConditionals, payload, parameters, executionState, type);
797
- return actionChecker.check();
798
- }
799
- createActionContext(parentExecutionContext, actionExecutionContext, abortController, parameters) {
800
- return {
801
- abortController,
802
- abortSignal: actionExecutionContext === null || actionExecutionContext === void 0 ? void 0 : actionExecutionContext.abortSignal,
803
- executeAction: this.runInContext.bind(this, actionExecutionContext),
804
- deps: parameters.deps ? this.di.getOfDeps(parameters.deps) : EMPTY_DEPS,
805
- actionType: (parentExecutionContext === null || parentExecutionContext === void 0 ? void 0 : parentExecutionContext.values.pageActions) ? 'page' : 'standalone',
806
- dispatch: this.store.dispatch,
807
- getState: this.store.getState,
808
- };
809
- }
810
- }
811
-
812
- const GLOBAL_PARAMETER = '@@global';
813
- class ActionRegistry {
814
- constructor({ actionsList }) {
815
- this.actions = new Map([[GLOBAL_PARAMETER, flatten(actionsList)]]);
816
- }
817
- add(type, actions) {
818
- const normalized = toArray(actions);
819
- this.actions.set(type, uniq(this.actions.has(type) ? [...this.actions.get(type), ...normalized] : normalized));
820
- }
821
- get(type, addingActions) {
822
- return uniq([...(this.actions.get(type) || []), ...(addingActions || [])]);
823
- }
824
- getGlobal() {
825
- return this.actions.get(GLOBAL_PARAMETER);
826
- }
827
- remove(type, actions) {
828
- if (!actions) {
829
- this.actions.delete(type);
830
- return;
831
- }
832
- const normalized = toArray(actions);
833
- if (this.actions.has(type)) {
834
- this.actions.set(type, difference(this.actions.get(type), normalized));
835
- }
836
- }
837
- }
838
-
839
- class ActionPageRunner {
840
- constructor(deps) {
841
- this.deps = deps;
842
- this.log = deps.logger('action:action-page-runner');
843
- }
844
- runActions(actions, stopRunAtError = () => false) {
845
- return this.deps.executionContextManager.withContext(this.deps.commandLineExecutionContext(), { name: 'pageActions', values: { pageActions: true } }, async (executionContext) => {
846
- const actionMapper = (action) => {
847
- return Promise.resolve()
848
- .then(() => this.deps.actionExecution.runInContext(executionContext, action))
849
- .catch((error) => {
850
- if (!isSilentError(error)) {
851
- const parameters = isTramvaiAction(action) ? action : action[ACTION_PARAMETERS];
852
- this.log.error({
853
- error,
854
- event: `action-execution-error`,
855
- message: `${parameters.name} execution error`,
856
- });
857
- }
858
- if (stopRunAtError(error)) {
859
- throw error;
860
- }
861
- });
862
- };
863
- await Promise.all(actions.map(actionMapper));
864
- });
865
- }
866
- }
867
-
868
- const alwaysCondition = {
869
- key: 'alwaysCondition',
870
- fn: (checker) => {
871
- if (checker.conditions.always) {
872
- checker.allow();
873
- }
874
- },
875
- };
876
-
877
- const isServer = typeof window === 'undefined';
878
- const isBrowser = !isServer;
879
-
880
- const onlyServer = {
881
- key: 'onlyServer',
882
- fn: (checker) => {
883
- if (checker.conditions.onlyServer && isBrowser) {
884
- checker.forbid();
885
- }
886
- },
887
- };
888
-
889
- const onlyBrowser = {
890
- key: 'onlyBrowser',
891
- fn: (checker) => {
892
- if (checker.conditions.onlyBrowser && isServer) {
893
- checker.forbid();
894
- }
895
- },
896
- };
897
-
898
- const pageServer = {
899
- key: 'pageServer',
900
- fn: (checker) => {
901
- if (checker.conditions.pageServer && checker.type === actionType.global && isBrowser) {
902
- checker.forbid();
903
- }
904
- },
905
- };
906
-
907
- const pageBrowser = {
908
- key: 'pageBrowser',
909
- fn: (checker) => {
910
- if (checker.conditions.pageBrowser && checker.type === actionType.global && isServer) {
911
- checker.forbid();
912
- }
913
- },
914
- };
915
-
916
- const LIMIT_ACTION_GLOBAL_TIME_RUN = createToken('limitActionGlobalTimeRun');
917
- let ActionModule = class ActionModule {
918
- };
919
- ActionModule = __decorate([
920
- Module({
921
- providers: [
922
- provide({
923
- provide: COMBINE_REDUCERS,
924
- multi: true,
925
- useValue: actionTramvaiReducer,
926
- }),
927
- provide({
928
- // Регистер глобальных экшенов
929
- provide: ACTION_REGISTRY_TOKEN,
930
- scope: Scope.SINGLETON,
931
- useClass: ActionRegistry,
932
- deps: { actionsList: ACTIONS_LIST_TOKEN },
933
- }),
934
- provide({
935
- provide: ACTION_EXECUTION_TOKEN,
936
- scope: Scope.REQUEST,
937
- useClass: ActionExecution,
938
- deps: {
939
- actionConditionals: { token: ACTION_CONDITIONALS, optional: true },
940
- context: CONTEXT_TOKEN,
941
- store: STORE_TOKEN,
942
- di: DI_TOKEN,
943
- executionContextManager: EXECUTION_CONTEXT_MANAGER_TOKEN,
944
- transformAction: {
945
- token: 'actionTransformAction',
946
- optional: true,
947
- },
948
- },
949
- }),
950
- provide({
951
- provide: ACTION_PAGE_RUNNER_TOKEN,
952
- scope: Scope.REQUEST,
953
- useClass: ActionPageRunner,
954
- deps: {
955
- actionExecution: ACTION_EXECUTION_TOKEN,
956
- executionContextManager: EXECUTION_CONTEXT_MANAGER_TOKEN,
957
- commandLineExecutionContext: COMMAND_LINE_EXECUTION_CONTEXT_TOKEN,
958
- store: STORE_TOKEN,
959
- limitTime: LIMIT_ACTION_GLOBAL_TIME_RUN,
960
- logger: LOGGER_TOKEN,
961
- },
962
- }),
963
- provide({
964
- provide: LIMIT_ACTION_GLOBAL_TIME_RUN,
965
- useValue: 500,
966
- }),
967
- provide({
968
- provide: ACTION_CONDITIONALS,
969
- multi: true,
970
- useValue: [alwaysCondition, onlyServer, onlyBrowser, pageServer, pageBrowser],
971
- }),
972
- ],
973
- })
974
- ], ActionModule);
975
-
976
- let StateModule = class StateModule {
977
- };
978
- StateModule = __decorate([
979
- Module({
980
- providers: [
981
- provide({
982
- provide: DISPATCHER_TOKEN,
983
- scope: Scope.SINGLETON,
984
- useFactory: ({ stores }) => createDispatcher({ stores: stores && flatten(stores) }),
985
- deps: {
986
- stores: {
987
- token: COMBINE_REDUCERS,
988
- optional: true,
989
- },
990
- },
991
- }),
992
- provide({
993
- provide: DISPATCHER_CONTEXT_TOKEN,
994
- scope: Scope.REQUEST,
995
- useFactory: ({ dispatcher, initialState, middlewares }) => {
996
- return dispatcher.createContext({}, initialState, [
997
- devTools.middleware(),
998
- ...flatten(middlewares || []),
999
- ]);
1000
- },
1001
- deps: {
1002
- dispatcher: DISPATCHER_TOKEN,
1003
- middlewares: { token: STORE_MIDDLEWARE, optional: true },
1004
- initialState: { token: INITIAL_APP_STATE_TOKEN, optional: true },
1005
- },
1006
- }),
1007
- provide({
1008
- provide: STORE_TOKEN,
1009
- scope: Scope.REQUEST,
1010
- useFactory: ({ dispatcherContext }) => ({
1011
- getState: dispatcherContext.getState.bind(dispatcherContext),
1012
- dispatch: dispatcherContext.dispatch.bind(dispatcherContext),
1013
- subscribe: dispatcherContext.subscribe.bind(dispatcherContext),
1014
- }),
1015
- deps: {
1016
- dispatcherContext: DISPATCHER_CONTEXT_TOKEN,
1017
- },
1018
- }),
1019
- ],
1020
- })
1021
- ], StateModule);
1022
-
1023
- const cacheFactory = (type, options = { max: 100 }) => {
1024
- return new LRU(options);
1025
- };
1026
-
1027
- const providers$1 = [];
1028
-
1029
- const cachesToken = createToken$1('_cachesList');
1030
- let CacheModule = class CacheModule {
1031
- };
1032
- CacheModule = __decorate([
1033
- Module({
1034
- providers: [
1035
- ...providers$1,
1036
- {
1037
- provide: cachesToken,
1038
- scope: Scope.SINGLETON,
1039
- useValue: [],
1040
- },
1041
- {
1042
- provide: CREATE_CACHE_TOKEN,
1043
- useFactory: ({ caches, isChildDi }) => {
1044
- if (isChildDi) {
1045
- return cacheFactory;
1046
- }
1047
- return (type, ...args) => {
1048
- const cache = cacheFactory(type, ...args);
1049
- caches.push(cache);
1050
- return cache;
1051
- };
1052
- },
1053
- deps: {
1054
- caches: cachesToken,
1055
- isChildDi: { token: IS_DI_CHILD_CONTAINER_TOKEN, optional: true },
1056
- },
1057
- },
1058
- {
1059
- provide: CLEAR_CACHE_TOKEN,
1060
- scope: Scope.SINGLETON,
1061
- useFactory: ({ caches, cachesClear }) => {
1062
- return (type) => {
1063
- caches.forEach((cache) => cache.clear());
1064
- if (cachesClear) {
1065
- return Promise.all(cachesClear.map((clear) => clear(type)));
1066
- }
1067
- return Promise.resolve();
1068
- };
1069
- },
1070
- deps: {
1071
- caches: cachesToken,
1072
- cachesClear: { token: REGISTER_CLEAR_CACHE_TOKEN, optional: true },
1073
- },
1074
- },
1075
- ],
1076
- })
1077
- ], CacheModule);
1078
-
1079
- const EMPTY_VALUES = {};
1080
- const normalizeOptions = (nameOrOptions) => {
1081
- return typeof nameOrOptions === 'string' ? { name: nameOrOptions } : nameOrOptions;
1082
- };
1083
- class ExecutionContextManager {
1084
- async withContext(parentContext, nameOrOptions, cb) {
1085
- const options = normalizeOptions(nameOrOptions);
1086
- const { name, values: selfValues = EMPTY_VALUES } = options;
1087
- const contextName = parentContext ? `${parentContext.name}.${name}` : name;
1088
- if (parentContext === null || parentContext === void 0 ? void 0 : parentContext.abortSignal.aborted) {
1089
- throw new ExecutionAbortError({
1090
- message: `Execution aborted in context "${contextName}"`,
1091
- contextName,
1092
- });
1093
- }
1094
- const abortController = new AbortController();
1095
- let abortListener;
1096
- let values = selfValues;
1097
- if (parentContext) {
1098
- values = {
1099
- ...parentContext.values,
1100
- ...selfValues,
1101
- };
1102
- abortListener = () => {
1103
- abortController.abort();
1104
- };
1105
- // abort child context AbortController if parent AbortController was aborted
1106
- parentContext.abortSignal.addEventListener('abort', abortListener);
1107
- }
1108
- const context = {
1109
- name: contextName,
1110
- abortSignal: abortController.signal,
1111
- values,
1112
- };
1113
- try {
1114
- const result = await cb(context, abortController);
1115
- return result;
1116
- }
1117
- catch (error) {
1118
- if (typeof error === 'object' && !error.executionContextName) {
1119
- error.executionContextName = context.name;
1120
- }
1121
- throw error;
1122
- }
1123
- finally {
1124
- // @ts-expect-error
1125
- if (abortListener && parentContext) {
1126
- parentContext.abortSignal.removeEventListener('abort', abortListener);
1127
- }
1128
- }
1129
- }
1130
- }
1131
-
1132
- let CommonModule = class CommonModule {
1133
- };
1134
- CommonModule = __decorate([
1135
- Module({
1136
- imports: [
1137
- CommandModule,
1138
- EnvironmentModule,
1139
- PubSubModule,
1140
- LogModule,
1141
- CookieModule,
1142
- ActionModule,
1143
- StateModule,
1144
- RequestManagerModule,
1145
- ResponseManagerModule,
1146
- CacheModule,
1147
- ],
1148
- providers: [
1149
- provide({
1150
- // Инстанс хук системы
1151
- provide: HOOK_TOKEN,
1152
- scope: Scope.SINGLETON,
1153
- useClass: Hooks,
1154
- }),
1155
- provide({
1156
- // Регистр ui компонентов
1157
- provide: COMPONENT_REGISTRY_TOKEN,
1158
- scope: Scope.SINGLETON,
1159
- useClass: ComponentRegistry,
1160
- deps: {
1161
- componentList: { token: 'componentDefaultList', optional: true },
1162
- },
1163
- }),
1164
- provide({
1165
- // Управление бандлами, хранение и получение
1166
- provide: BUNDLE_MANAGER_TOKEN,
1167
- scope: Scope.SINGLETON,
1168
- useFactory: ({ additionalBundleList, ...bundleManagerDeps }) => {
1169
- additionalBundleList === null || additionalBundleList === void 0 ? void 0 : additionalBundleList.forEach((bundles) => {
1170
- eachObj((bundle, name) => {
1171
- const bundleAlreadyExists = name in bundleManagerDeps.bundleList;
1172
- if (!bundleAlreadyExists) {
1173
- // eslint-disable-next-line no-param-reassign
1174
- bundleManagerDeps.bundleList[name] = () => Promise.resolve({ default: bundle });
1175
- }
1176
- }, bundles);
1177
- });
1178
- return new BundleManager(bundleManagerDeps);
1179
- },
1180
- deps: {
1181
- bundleList: BUNDLE_LIST_TOKEN,
1182
- additionalBundleList: { token: ADDITIONAL_BUNDLE_TOKEN, optional: true },
1183
- componentRegistry: COMPONENT_REGISTRY_TOKEN,
1184
- actionRegistry: ACTION_REGISTRY_TOKEN,
1185
- dispatcher: DISPATCHER_TOKEN,
1186
- logger: LOGGER_TOKEN,
1187
- },
1188
- }),
1189
- provide({
1190
- // Клиентский контекст исполнения
1191
- provide: CONTEXT_TOKEN,
1192
- scope: Scope.REQUEST,
1193
- useFactory: createConsumerContext,
1194
- deps: {
1195
- di: DI_TOKEN,
1196
- pubsub: PUBSUB_TOKEN,
1197
- dispatcherContext: DISPATCHER_CONTEXT_TOKEN,
1198
- store: STORE_TOKEN,
1199
- },
1200
- }),
1201
- provide({
1202
- provide: EXECUTION_CONTEXT_MANAGER_TOKEN,
1203
- useClass: ExecutionContextManager,
1204
- }),
1205
- ...providers$2,
1206
- ],
1207
- })
1208
- ], CommonModule);
1209
-
1210
- const providers = [
1211
- provide({
1212
- provide: INITIAL_APP_STATE_TOKEN,
1213
- useFactory: ({ commonState, config }) => {
1214
- return commonState[`${config.key}`];
1215
- },
1216
- deps: {
1217
- commonState: CHILD_APP_COMMON_INITIAL_STATE_TOKEN,
1218
- config: CHILD_APP_INTERNAL_CONFIG_TOKEN,
1219
- },
1220
- }),
1221
- ];
1222
-
1223
- const stateProviders = [
1224
- provide({
1225
- provide: CHILD_APP_INTERNAL_ROOT_DI_BORROW_TOKEN,
1226
- multi: true,
1227
- useValue: [DISPATCHER_TOKEN, STORE_TOKEN, CONTEXT_TOKEN],
1228
- }),
1229
- ];
1230
-
1231
- const command = {
1232
- customer: [
1233
- commandLineListTokens$1.customerStart,
1234
- commandLineListTokens$1.resolveUserDeps,
1235
- commandLineListTokens$1.resolvePageDeps,
1236
- ],
1237
- clear: [commandLineListTokens$1.clear],
1238
- spa: [
1239
- commandLineListTokens$1.resolveUserDeps,
1240
- commandLineListTokens$1.resolvePageDeps,
1241
- commandLineListTokens$1.spaTransition,
1242
- ],
1243
- afterSpa: [commandLineListTokens$1.afterSpaTransition],
1244
- };
1245
- const lines = {
1246
- server: command,
1247
- client: command,
1248
- };
1249
- const commandProviders = [
1250
- provide({
1251
- provide: CHILD_APP_INTERNAL_ROOT_DI_BORROW_TOKEN,
1252
- multi: true,
1253
- useValue: COMMAND_LINE_RUNNER_TOKEN,
1254
- }),
1255
- provide({
1256
- provide: COMMAND_LINES_TOKEN,
1257
- scope: Scope.SINGLETON,
1258
- useValue: lines,
1259
- }),
1260
- ];
1261
-
1262
- const actionsProviders = [
1263
- provide({
1264
- provide: CHILD_APP_INTERNAL_ROOT_DI_BORROW_TOKEN,
1265
- multi: true,
1266
- useValue: [ACTION_EXECUTION_TOKEN, ACTION_PAGE_RUNNER_TOKEN],
1267
- }),
1268
- provide({
1269
- provide: COMBINE_REDUCERS,
1270
- multi: true,
1271
- useValue: actionTramvaiReducer,
1272
- }),
1273
- ];
1274
-
1275
- let CommonChildAppModule = class CommonChildAppModule {
1276
- };
1277
- CommonChildAppModule = __decorate([
1278
- Module({
1279
- providers: [
1280
- ...providers,
1281
- ...stateProviders,
1282
- ...commandProviders,
1283
- ...actionsProviders,
1284
- provide({
1285
- provide: EXTEND_RENDER,
1286
- multi: true,
1287
- useFactory: ({ context }) => {
1288
- const serverState = typeof window !== 'undefined' ? context.getState() : undefined;
1289
- return (render) => {
1290
- return (jsx(Provider, { context: context, serverState: serverState, children: render }));
1291
- };
1292
- },
1293
- deps: {
1294
- context: CONTEXT_TOKEN,
1295
- },
1296
- }),
1297
- ],
1298
- })
1299
- ], CommonChildAppModule);
1300
-
1301
- export { ActionExecution, CommandModule, CommonChildAppModule, CommonModule, ExecutionContextManager, alwaysCondition, createConsumerContext, onlyBrowser, onlyServer, pageBrowser, pageServer };
9
+ export { COOKIE_MANAGER_TOKEN } from '@tramvai/module-cookie';
10
+ export { alwaysCondition } from './actions/conditions/always.browser.js';
11
+ export { onlyServer } from './actions/conditions/onlyServer.browser.js';
12
+ export { onlyBrowser } from './actions/conditions/onlyBrowser.browser.js';
13
+ export { pageServer } from './actions/conditions/pageServer.browser.js';
14
+ export { pageBrowser } from './actions/conditions/pageBrowser.browser.js';