@edx/frontend-platform 4.6.0 → 4.6.2

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 (229) hide show
  1. package/.env.development +30 -0
  2. package/.env.test +30 -0
  3. package/.eslintignore +6 -0
  4. package/.eslintrc.js +28 -0
  5. package/.github/PULL_REQUEST_TEMPLATE.md +13 -0
  6. package/.github/workflows/add-depr-ticket-to-depr-board.yml +19 -0
  7. package/.github/workflows/add-remove-label-on-comment.yml +20 -0
  8. package/.github/workflows/ci.yml +42 -0
  9. package/.github/workflows/commitlint.yml +10 -0
  10. package/.github/workflows/lockfileversion-check.yml +13 -0
  11. package/.github/workflows/manual-publish.yml +43 -0
  12. package/.github/workflows/npm-deprecate.yml +22 -0
  13. package/.github/workflows/release.yml +45 -0
  14. package/.github/workflows/self-assign-issue.yml +12 -0
  15. package/.github/workflows/update-browserslist-db.yml +12 -0
  16. package/.nvmrc +1 -0
  17. package/.releaserc +32 -0
  18. package/catalog-info.yaml +21 -0
  19. package/dist/LICENSE +661 -0
  20. package/dist/README.md +155 -0
  21. package/dist/package.json +86 -0
  22. package/docs/addTagsPlugin.js +10 -0
  23. package/docs/auth-API.md +114 -0
  24. package/docs/decisions/0001-record-architecture-decisions.rst +32 -0
  25. package/docs/decisions/0002-frontend-base-design-goals.rst +222 -0
  26. package/docs/decisions/0003-consolidation-into-frontend-platform.rst +71 -0
  27. package/docs/decisions/0004-axios-caching-implementation.rst +88 -0
  28. package/docs/decisions/0005-token-null-after-successful-refresh.rst +69 -0
  29. package/docs/decisions/0006-middleware-support-for-http-clients.rst +44 -0
  30. package/docs/decisions/0007-javascript-file-configuration.rst +143 -0
  31. package/docs/how_tos/automatic-case-conversion.rst +58 -0
  32. package/docs/how_tos/caching.rst +93 -0
  33. package/docs/how_tos/i18n.rst +305 -0
  34. package/docs/removeExport.js +24 -0
  35. package/docs/template/edx/README.md +12 -0
  36. package/docs/template/edx/publish.js +713 -0
  37. package/docs/template/edx/static/fonts/OpenSans-Bold-webfont.eot +0 -0
  38. package/docs/template/edx/static/fonts/OpenSans-Bold-webfont.svg +1830 -0
  39. package/docs/template/edx/static/fonts/OpenSans-Bold-webfont.woff +0 -0
  40. package/docs/template/edx/static/fonts/OpenSans-BoldItalic-webfont.eot +0 -0
  41. package/docs/template/edx/static/fonts/OpenSans-BoldItalic-webfont.svg +1830 -0
  42. package/docs/template/edx/static/fonts/OpenSans-BoldItalic-webfont.woff +0 -0
  43. package/docs/template/edx/static/fonts/OpenSans-Italic-webfont.eot +0 -0
  44. package/docs/template/edx/static/fonts/OpenSans-Italic-webfont.svg +1830 -0
  45. package/docs/template/edx/static/fonts/OpenSans-Italic-webfont.woff +0 -0
  46. package/docs/template/edx/static/fonts/OpenSans-Light-webfont.eot +0 -0
  47. package/docs/template/edx/static/fonts/OpenSans-Light-webfont.svg +1831 -0
  48. package/docs/template/edx/static/fonts/OpenSans-Light-webfont.woff +0 -0
  49. package/docs/template/edx/static/fonts/OpenSans-LightItalic-webfont.eot +0 -0
  50. package/docs/template/edx/static/fonts/OpenSans-LightItalic-webfont.svg +1835 -0
  51. package/docs/template/edx/static/fonts/OpenSans-LightItalic-webfont.woff +0 -0
  52. package/docs/template/edx/static/fonts/OpenSans-Regular-webfont.eot +0 -0
  53. package/docs/template/edx/static/fonts/OpenSans-Regular-webfont.svg +1831 -0
  54. package/docs/template/edx/static/fonts/OpenSans-Regular-webfont.woff +0 -0
  55. package/docs/template/edx/static/scripts/linenumber.js +25 -0
  56. package/docs/template/edx/static/scripts/prettify/Apache-License-2.0.txt +202 -0
  57. package/docs/template/edx/static/scripts/prettify/lang-css.js +2 -0
  58. package/docs/template/edx/static/scripts/prettify/prettify.js +28 -0
  59. package/docs/template/edx/static/styles/jsdoc-default.css +356 -0
  60. package/docs/template/edx/static/styles/prettify-jsdoc.css +111 -0
  61. package/docs/template/edx/static/styles/prettify-tomorrow.css +132 -0
  62. package/docs/template/edx/tmpl/augments.tmpl +10 -0
  63. package/docs/template/edx/tmpl/container.tmpl +196 -0
  64. package/docs/template/edx/tmpl/details.tmpl +143 -0
  65. package/docs/template/edx/tmpl/example.tmpl +2 -0
  66. package/docs/template/edx/tmpl/examples.tmpl +13 -0
  67. package/docs/template/edx/tmpl/exceptions.tmpl +32 -0
  68. package/docs/template/edx/tmpl/layout.tmpl +39 -0
  69. package/docs/template/edx/tmpl/mainpage.tmpl +10 -0
  70. package/docs/template/edx/tmpl/members.tmpl +38 -0
  71. package/docs/template/edx/tmpl/method.tmpl +131 -0
  72. package/docs/template/edx/tmpl/modifies.tmpl +14 -0
  73. package/docs/template/edx/tmpl/params.tmpl +131 -0
  74. package/docs/template/edx/tmpl/properties.tmpl +108 -0
  75. package/docs/template/edx/tmpl/returns.tmpl +19 -0
  76. package/docs/template/edx/tmpl/source.tmpl +8 -0
  77. package/docs/template/edx/tmpl/tutorial.tmpl +19 -0
  78. package/docs/template/edx/tmpl/type.tmpl +7 -0
  79. package/env.config.js +8 -0
  80. package/jsdoc.json +36 -0
  81. package/openedx.yaml +12 -0
  82. package/package.json +6 -6
  83. package/service-interface.png +0 -0
  84. package/src/analytics/MockAnalyticsService.js +71 -0
  85. package/src/analytics/SegmentAnalyticsService.js +243 -0
  86. package/src/analytics/index.js +12 -0
  87. package/src/analytics/interface.js +142 -0
  88. package/src/auth/AxiosCsrfTokenService.js +60 -0
  89. package/src/auth/AxiosJwtAuthService.js +364 -0
  90. package/src/auth/AxiosJwtTokenService.js +134 -0
  91. package/src/auth/LocalForageCache.js +78 -0
  92. package/src/auth/MockAuthService.js +285 -0
  93. package/src/auth/index.js +19 -0
  94. package/src/auth/interceptors/createCsrfTokenProviderInterceptor.js +37 -0
  95. package/src/auth/interceptors/createJwtTokenProviderInterceptor.js +38 -0
  96. package/src/auth/interceptors/createProcessAxiosRequestErrorInterceptor.js +20 -0
  97. package/src/auth/interceptors/createRetryInterceptor.js +72 -0
  98. package/src/auth/interface.js +309 -0
  99. package/src/auth/utils.js +105 -0
  100. package/src/config.js +327 -0
  101. package/src/constants.js +66 -0
  102. package/src/i18n/countries.js +57 -0
  103. package/src/i18n/index.js +123 -0
  104. package/src/i18n/injectIntlWithShim.jsx +45 -0
  105. package/src/i18n/languages.js +60 -0
  106. package/src/i18n/lib.js +282 -0
  107. package/src/i18n/scripts/README.md +29 -0
  108. package/src/i18n/scripts/intl-imports.js +259 -0
  109. package/src/i18n/scripts/transifex-utils.js +75 -0
  110. package/src/index.js +42 -0
  111. package/src/initialize.js +357 -0
  112. package/src/logging/MockLoggingService.js +31 -0
  113. package/src/logging/NewRelicLoggingService.js +181 -0
  114. package/src/logging/index.js +9 -0
  115. package/src/logging/interface.js +110 -0
  116. package/src/pubSub.js +47 -0
  117. package/src/react/AppContext.jsx +24 -0
  118. package/src/react/AppProvider.jsx +93 -0
  119. package/src/react/AuthenticatedPageRoute.jsx +60 -0
  120. package/src/react/ErrorBoundary.jsx +44 -0
  121. package/src/react/ErrorPage.jsx +76 -0
  122. package/src/react/LoginRedirect.jsx +16 -0
  123. package/src/react/OptionalReduxProvider.jsx +28 -0
  124. package/src/react/PageRoute.jsx +31 -0
  125. package/src/react/hooks.js +50 -0
  126. package/src/react/index.js +16 -0
  127. package/src/scripts/GoogleAnalyticsLoader.js +53 -0
  128. package/src/scripts/index.js +2 -0
  129. package/src/testing/index.js +9 -0
  130. package/src/testing/initializeMockApp.js +77 -0
  131. package/src/testing/mockMessages.js +21 -0
  132. package/src/utils.js +167 -0
  133. /package/{analytics → dist/analytics}/MockAnalyticsService.js +0 -0
  134. /package/{analytics → dist/analytics}/MockAnalyticsService.js.map +0 -0
  135. /package/{analytics → dist/analytics}/SegmentAnalyticsService.js +0 -0
  136. /package/{analytics → dist/analytics}/SegmentAnalyticsService.js.map +0 -0
  137. /package/{analytics → dist/analytics}/index.js +0 -0
  138. /package/{analytics → dist/analytics}/index.js.map +0 -0
  139. /package/{analytics → dist/analytics}/interface.js +0 -0
  140. /package/{analytics → dist/analytics}/interface.js.map +0 -0
  141. /package/{auth → dist/auth}/AxiosCsrfTokenService.js +0 -0
  142. /package/{auth → dist/auth}/AxiosCsrfTokenService.js.map +0 -0
  143. /package/{auth → dist/auth}/AxiosJwtAuthService.js +0 -0
  144. /package/{auth → dist/auth}/AxiosJwtAuthService.js.map +0 -0
  145. /package/{auth → dist/auth}/AxiosJwtTokenService.js +0 -0
  146. /package/{auth → dist/auth}/AxiosJwtTokenService.js.map +0 -0
  147. /package/{auth → dist/auth}/LocalForageCache.js +0 -0
  148. /package/{auth → dist/auth}/LocalForageCache.js.map +0 -0
  149. /package/{auth → dist/auth}/MockAuthService.js +0 -0
  150. /package/{auth → dist/auth}/MockAuthService.js.map +0 -0
  151. /package/{auth → dist/auth}/index.js +0 -0
  152. /package/{auth → dist/auth}/index.js.map +0 -0
  153. /package/{auth → dist/auth}/interceptors/createCsrfTokenProviderInterceptor.js +0 -0
  154. /package/{auth → dist/auth}/interceptors/createCsrfTokenProviderInterceptor.js.map +0 -0
  155. /package/{auth → dist/auth}/interceptors/createJwtTokenProviderInterceptor.js +0 -0
  156. /package/{auth → dist/auth}/interceptors/createJwtTokenProviderInterceptor.js.map +0 -0
  157. /package/{auth → dist/auth}/interceptors/createProcessAxiosRequestErrorInterceptor.js +0 -0
  158. /package/{auth → dist/auth}/interceptors/createProcessAxiosRequestErrorInterceptor.js.map +0 -0
  159. /package/{auth → dist/auth}/interceptors/createRetryInterceptor.js +0 -0
  160. /package/{auth → dist/auth}/interceptors/createRetryInterceptor.js.map +0 -0
  161. /package/{auth → dist/auth}/interface.js +0 -0
  162. /package/{auth → dist/auth}/interface.js.map +0 -0
  163. /package/{auth → dist/auth}/utils.js +0 -0
  164. /package/{auth → dist/auth}/utils.js.map +0 -0
  165. /package/{config.js → dist/config.js} +0 -0
  166. /package/{config.js.map → dist/config.js.map} +0 -0
  167. /package/{constants.js → dist/constants.js} +0 -0
  168. /package/{constants.js.map → dist/constants.js.map} +0 -0
  169. /package/{i18n → dist/i18n}/countries.js +0 -0
  170. /package/{i18n → dist/i18n}/countries.js.map +0 -0
  171. /package/{i18n → dist/i18n}/index.js +0 -0
  172. /package/{i18n → dist/i18n}/index.js.map +0 -0
  173. /package/{i18n → dist/i18n}/injectIntlWithShim.js +0 -0
  174. /package/{i18n → dist/i18n}/injectIntlWithShim.js.map +0 -0
  175. /package/{i18n → dist/i18n}/languages.js +0 -0
  176. /package/{i18n → dist/i18n}/languages.js.map +0 -0
  177. /package/{i18n → dist/i18n}/lib.js +0 -0
  178. /package/{i18n → dist/i18n}/lib.js.map +0 -0
  179. /package/{i18n → dist/i18n}/scripts/README.md +0 -0
  180. /package/{i18n → dist/i18n}/scripts/intl-imports.js +0 -0
  181. /package/{i18n → dist/i18n}/scripts/intl-imports.js.map +0 -0
  182. /package/{i18n → dist/i18n}/scripts/transifex-utils.js +0 -0
  183. /package/{i18n → dist/i18n}/scripts/transifex-utils.js.map +0 -0
  184. /package/{index.js → dist/index.js} +0 -0
  185. /package/{index.js.map → dist/index.js.map} +0 -0
  186. /package/{initialize.js → dist/initialize.js} +0 -0
  187. /package/{initialize.js.map → dist/initialize.js.map} +0 -0
  188. /package/{logging → dist/logging}/MockLoggingService.js +0 -0
  189. /package/{logging → dist/logging}/MockLoggingService.js.map +0 -0
  190. /package/{logging → dist/logging}/NewRelicLoggingService.js +0 -0
  191. /package/{logging → dist/logging}/NewRelicLoggingService.js.map +0 -0
  192. /package/{logging → dist/logging}/index.js +0 -0
  193. /package/{logging → dist/logging}/index.js.map +0 -0
  194. /package/{logging → dist/logging}/interface.js +0 -0
  195. /package/{logging → dist/logging}/interface.js.map +0 -0
  196. /package/{pubSub.js → dist/pubSub.js} +0 -0
  197. /package/{pubSub.js.map → dist/pubSub.js.map} +0 -0
  198. /package/{react → dist/react}/AppContext.js +0 -0
  199. /package/{react → dist/react}/AppContext.js.map +0 -0
  200. /package/{react → dist/react}/AppProvider.js +0 -0
  201. /package/{react → dist/react}/AppProvider.js.map +0 -0
  202. /package/{react → dist/react}/AuthenticatedPageRoute.js +0 -0
  203. /package/{react → dist/react}/AuthenticatedPageRoute.js.map +0 -0
  204. /package/{react → dist/react}/ErrorBoundary.js +0 -0
  205. /package/{react → dist/react}/ErrorBoundary.js.map +0 -0
  206. /package/{react → dist/react}/ErrorPage.js +0 -0
  207. /package/{react → dist/react}/ErrorPage.js.map +0 -0
  208. /package/{react → dist/react}/LoginRedirect.js +0 -0
  209. /package/{react → dist/react}/LoginRedirect.js.map +0 -0
  210. /package/{react → dist/react}/OptionalReduxProvider.js +0 -0
  211. /package/{react → dist/react}/OptionalReduxProvider.js.map +0 -0
  212. /package/{react → dist/react}/PageRoute.js +0 -0
  213. /package/{react → dist/react}/PageRoute.js.map +0 -0
  214. /package/{react → dist/react}/hooks.js +0 -0
  215. /package/{react → dist/react}/hooks.js.map +0 -0
  216. /package/{react → dist/react}/index.js +0 -0
  217. /package/{react → dist/react}/index.js.map +0 -0
  218. /package/{scripts → dist/scripts}/GoogleAnalyticsLoader.js +0 -0
  219. /package/{scripts → dist/scripts}/GoogleAnalyticsLoader.js.map +0 -0
  220. /package/{scripts → dist/scripts}/index.js +0 -0
  221. /package/{scripts → dist/scripts}/index.js.map +0 -0
  222. /package/{testing → dist/testing}/index.js +0 -0
  223. /package/{testing → dist/testing}/index.js.map +0 -0
  224. /package/{testing → dist/testing}/initializeMockApp.js +0 -0
  225. /package/{testing → dist/testing}/initializeMockApp.js.map +0 -0
  226. /package/{testing → dist/testing}/mockMessages.js +0 -0
  227. /package/{testing → dist/testing}/mockMessages.js.map +0 -0
  228. /package/{utils.js → dist/utils.js} +0 -0
  229. /package/{utils.js.map → dist/utils.js.map} +0 -0
@@ -0,0 +1,357 @@
1
+ /**
2
+ * #### Import members from **@edx/frontend-platform**
3
+ *
4
+ * The initialization module provides a function for managing an application's initialization
5
+ * lifecycle. It also provides constants and default handler implementations.
6
+ *
7
+ * ```
8
+ * import {
9
+ * initialize,
10
+ * APP_INIT_ERROR,
11
+ * APP_READY,
12
+ * subscribe,
13
+ * } from '@edx/frontend-platform';
14
+ * import { AppProvider, ErrorPage, PageRoute } from '@edx/frontend-platform/react';
15
+ * import React from 'react';
16
+ * import ReactDOM from 'react-dom';
17
+ * import { Switch } from 'react-router-dom';
18
+ *
19
+ * subscribe(APP_READY, () => {
20
+ * ReactDOM.render(
21
+ * <AppProvider store={configureStore()}>
22
+ * <Header />
23
+ * <main>
24
+ * <Switch>
25
+ * <PageRoute exact path="/" component={PaymentPage} />
26
+ * </Switch>
27
+ * </main>
28
+ * <Footer />
29
+ * </AppProvider>,
30
+ * document.getElementById('root'),
31
+ * );
32
+ * });
33
+ *
34
+ * subscribe(APP_INIT_ERROR, (error) => {
35
+ * ReactDOM.render(<ErrorPage message={error.message} />, document.getElementById('root'));
36
+ * });
37
+ *
38
+ * initialize({
39
+ * messages: [appMessages],
40
+ * requireAuthenticatedUser: true,
41
+ * hydrateAuthenticatedUser: true,
42
+ * });
43
+
44
+ ```
45
+ * @module Initialization
46
+ */
47
+
48
+ import { createBrowserHistory, createMemoryHistory } from 'history';
49
+ /*
50
+ This 'env.config' package is a special 'magic' alias in our webpack configuration in frontend-build.
51
+ It points at an `env.config.js` file in the root of an MFE's repository if it exists and falls back
52
+ to an empty object `{}` if the file doesn't exist. This acts like an 'optional' import, in a sense.
53
+ Note that the env.config.js file in frontend-platform's root directory is NOT used by the actual
54
+ initialization code, it's just there for the test suite and example application.
55
+ */
56
+ import envConfig from 'env.config'; // eslint-disable-line import/no-unresolved
57
+
58
+ import {
59
+ publish,
60
+ } from './pubSub';
61
+ // eslint-disable-next-line import/no-cycle
62
+ import {
63
+ getConfig, mergeConfig,
64
+ } from './config';
65
+ import {
66
+ configure as configureLogging, getLoggingService, NewRelicLoggingService, logError,
67
+ } from './logging';
68
+ import {
69
+ configure as configureAnalytics, SegmentAnalyticsService, identifyAnonymousUser, identifyAuthenticatedUser,
70
+ } from './analytics';
71
+ import { GoogleAnalyticsLoader } from './scripts';
72
+ import {
73
+ getAuthenticatedHttpClient,
74
+ configure as configureAuth,
75
+ ensureAuthenticatedUser,
76
+ fetchAuthenticatedUser,
77
+ hydrateAuthenticatedUser,
78
+ getAuthenticatedUser,
79
+ AxiosJwtAuthService,
80
+ } from './auth';
81
+ import { configure as configureI18n } from './i18n';
82
+ import {
83
+ APP_PUBSUB_INITIALIZED,
84
+ APP_CONFIG_INITIALIZED,
85
+ APP_AUTH_INITIALIZED,
86
+ APP_I18N_INITIALIZED,
87
+ APP_LOGGING_INITIALIZED,
88
+ APP_ANALYTICS_INITIALIZED,
89
+ APP_READY, APP_INIT_ERROR,
90
+ } from './constants';
91
+ import configureCache from './auth/LocalForageCache';
92
+
93
+ /**
94
+ * A browser history or memory history object created by the [history](https://github.com/ReactTraining/history)
95
+ * package. Applications are encouraged to use this history object, rather than creating their own,
96
+ * as behavior may be undefined when managing history via multiple mechanisms/instances. Note that
97
+ * in environments where browser history may be inaccessible due to `window` being undefined, this
98
+ * falls back to memory history.
99
+ */
100
+ export const history = (typeof window !== 'undefined')
101
+ ? createBrowserHistory({
102
+ basename: getConfig().PUBLIC_PATH,
103
+ }) : createMemoryHistory();
104
+
105
+ /**
106
+ * The default handler for the initialization lifecycle's `initError` phase. Logs the error to the
107
+ * LoggingService using `logError`
108
+ *
109
+ * @see {@link module:frontend-platform/logging~logError}
110
+ * @param {*} error
111
+ */
112
+ export async function initError(error) {
113
+ logError(error);
114
+ }
115
+
116
+ /**
117
+ * The default handler for the initialization lifecycle's `auth` phase.
118
+ *
119
+ * The handler has several responsibilities:
120
+ * - Determining the user's authentication state (authenticated or anonymous)
121
+ * - Optionally redirecting to login if the application requires an authenticated user.
122
+ * - Optionally loading additional user information via the application's user account data
123
+ * endpoint.
124
+ *
125
+ * @param {boolean} requireUser Whether or not we should redirect to login if a user is not
126
+ * authenticated.
127
+ * @param {boolean} hydrateUser Whether or not we should fetch additional user account data.
128
+ */
129
+ export async function auth(requireUser, hydrateUser) {
130
+ if (requireUser) {
131
+ await ensureAuthenticatedUser(global.location.href);
132
+ } else {
133
+ await fetchAuthenticatedUser();
134
+ }
135
+
136
+ if (hydrateUser && getAuthenticatedUser() !== null) {
137
+ // We intentionally do not await the promise returned by hydrateAuthenticatedUser. All the
138
+ // critical data is returned as part of fetch/ensureAuthenticatedUser above, and anything else
139
+ // is a nice-to-have for application code.
140
+ hydrateAuthenticatedUser();
141
+ }
142
+ }
143
+
144
+ /**
145
+ * Set or overrides configuration via an env.config.js file in the consuming application.
146
+ * This env.config.js is loaded at runtime and must export one of two things:
147
+ *
148
+ * - An object which will be merged into the application config via `mergeConfig`.
149
+ * - A function which returns an object which will be merged into the application config via
150
+ * `mergeConfig`. This function can return a promise.
151
+ */
152
+ async function jsFileConfig() {
153
+ let config = {};
154
+ if (typeof envConfig === 'function') {
155
+ config = await envConfig();
156
+ } else {
157
+ config = envConfig;
158
+ }
159
+
160
+ mergeConfig(config);
161
+ }
162
+
163
+ /*
164
+ * Set or overrides configuration through an API.
165
+ * This method allows runtime configuration.
166
+ * Set a basic configuration when an error happen and allow initError and display the ErrorPage.
167
+ */
168
+ async function runtimeConfig() {
169
+ try {
170
+ const { MFE_CONFIG_API_URL, APP_ID } = getConfig();
171
+
172
+ if (MFE_CONFIG_API_URL) {
173
+ const apiConfig = { headers: { accept: 'application/json' } };
174
+ const apiService = await configureCache();
175
+
176
+ const params = new URLSearchParams();
177
+ params.append('mfe', APP_ID);
178
+ const url = `${MFE_CONFIG_API_URL}?${params.toString()}`;
179
+
180
+ const { data } = await apiService.get(url, apiConfig);
181
+ mergeConfig(data);
182
+ }
183
+ } catch (error) {
184
+ // eslint-disable-next-line no-console
185
+ console.error('Error with config API', error.message);
186
+ }
187
+ }
188
+
189
+ export function loadExternalScripts(externalScripts, data) {
190
+ externalScripts.forEach(ExternalScript => {
191
+ const script = new ExternalScript(data);
192
+ script.loadScript();
193
+ });
194
+ }
195
+
196
+ /**
197
+ * The default handler for the initialization lifecycle's `analytics` phase.
198
+ *
199
+ * The handler is responsible for identifying authenticated and anonymous users with the analytics
200
+ * service. This is a pre-requisite for sending analytics events, thus, we do it during the
201
+ * initialization sequence so that analytics is ready once the application's UI code starts to load.
202
+ *
203
+ */
204
+ export async function analytics() {
205
+ const authenticatedUser = getAuthenticatedUser();
206
+ if (authenticatedUser && authenticatedUser.userId) {
207
+ identifyAuthenticatedUser(authenticatedUser.userId);
208
+ } else {
209
+ await identifyAnonymousUser();
210
+ }
211
+ }
212
+
213
+ function applyOverrideHandlers(overrides) {
214
+ const noOp = async () => { };
215
+ return {
216
+ pubSub: noOp,
217
+ config: noOp,
218
+ logging: noOp,
219
+ auth,
220
+ analytics,
221
+ i18n: noOp,
222
+ ready: noOp,
223
+ initError,
224
+ ...overrides, // This will override any same-keyed handlers from above.
225
+ };
226
+ }
227
+
228
+ /**
229
+ * Invokes the application initialization sequence.
230
+ *
231
+ * The sequence proceeds through a number of lifecycle phases, during which pertinent services are
232
+ * configured.
233
+ *
234
+ * Using the `handlers` option, lifecycle phase handlers can be overridden to perform custom
235
+ * functionality. Note that while these override handlers _do_ replace the default handler
236
+ * functionality for analytics, auth, and initError (the other phases have no default
237
+ * functionality), they do _not_ override the configuration of the actual services that those
238
+ * handlers leverage.
239
+ *
240
+ * Some services can be overridden via the loggingService and analyticsService options. The other
241
+ * services (auth and i18n) cannot currently be overridden.
242
+ *
243
+ * The following lifecycle phases exist:
244
+ *
245
+ * - pubSub: A no-op by default.
246
+ * - config: A no-op by default.
247
+ * - logging: A no-op by default.
248
+ * - auth: Uses the 'auth' handler defined above.
249
+ * - analytics: Uses the 'analytics' handler defined above.
250
+ * - i18n: A no-op by default.
251
+ * - ready: A no-op by default.
252
+ * - initError: Uses the 'initError' handler defined above.
253
+ *
254
+ * @param {Object} [options]
255
+ * @param {*} [options.loggingService=NewRelicLoggingService] The `LoggingService` implementation
256
+ * to use.
257
+ * @param {*} [options.analyticsService=SegmentAnalyticsService] The `AnalyticsService`
258
+ * implementation to use.
259
+ * @param {*} [options.authMiddleware=[]] An array of middleware to apply to http clients in the auth service.
260
+ * @param {*} [options.externalScripts=[GoogleAnalyticsLoader]] An array of externalScripts.
261
+ * By default added GoogleAnalyticsLoader.
262
+ * @param {*} [options.requireAuthenticatedUser=false] If true, turns on automatic login
263
+ * redirection for unauthenticated users. Defaults to false, meaning that by default the
264
+ * application will allow anonymous/unauthenticated sessions.
265
+ * @param {*} [options.hydrateAuthenticatedUser=false] If true, makes an API call to the user
266
+ * account endpoint (`${App.config.LMS_BASE_URL}/api/user/v1/accounts/${username}`) to fetch
267
+ * detailed account information for the authenticated user. This data is merged into the return
268
+ * value of `getAuthenticatedUser`, overriding any duplicate keys that already exist. Defaults to
269
+ * false, meaning that no additional account information will be loaded.
270
+ * @param {*} [options.messages] A i18n-compatible messages object, or an array of such objects. If
271
+ * an array is provided, duplicate keys are resolved with the last-one-in winning.
272
+ * @param {*} [options.handlers={}] An optional object of handlers which can be used to replace the
273
+ * default behavior of any part of the startup sequence. It can also be used to add additional
274
+ * initialization behavior before or after the rest of the sequence.
275
+ */
276
+ export async function initialize({
277
+ loggingService = NewRelicLoggingService,
278
+ analyticsService = SegmentAnalyticsService,
279
+ authService = AxiosJwtAuthService,
280
+ authMiddleware = [],
281
+ externalScripts = [GoogleAnalyticsLoader],
282
+ requireAuthenticatedUser: requireUser = false,
283
+ hydrateAuthenticatedUser: hydrateUser = false,
284
+ messages,
285
+ handlers: overrideHandlers = {},
286
+ }) {
287
+ const handlers = applyOverrideHandlers(overrideHandlers);
288
+ try {
289
+ // Pub/Sub
290
+ await handlers.pubSub();
291
+ publish(APP_PUBSUB_INITIALIZED);
292
+
293
+ // Configuration
294
+ await handlers.config();
295
+ await jsFileConfig();
296
+ await runtimeConfig();
297
+ publish(APP_CONFIG_INITIALIZED);
298
+
299
+ loadExternalScripts(externalScripts, {
300
+ config: getConfig(),
301
+ });
302
+
303
+ // This allows us to replace the implementations of the logging, analytics, and auth services
304
+ // based on keys in the ConfigDocument. The JavaScript File Configuration method is the only
305
+ // one capable of supplying an alternate implementation since it can import other modules.
306
+ // If a service wasn't supplied we fall back to the default parameters on the initialize
307
+ // function signature.
308
+ const loggingServiceImpl = getConfig().loggingService || loggingService;
309
+ const analyticsServiceImpl = getConfig().analyticsService || analyticsService;
310
+ const authServiceImpl = getConfig().authService || authService;
311
+
312
+ // Logging
313
+ configureLogging(loggingServiceImpl, {
314
+ config: getConfig(),
315
+ });
316
+ await handlers.logging();
317
+ publish(APP_LOGGING_INITIALIZED);
318
+
319
+ // Authentication
320
+ configureAuth(authServiceImpl, {
321
+ loggingService: getLoggingService(),
322
+ config: getConfig(),
323
+ middleware: authMiddleware,
324
+ });
325
+
326
+ await handlers.auth(requireUser, hydrateUser);
327
+ publish(APP_AUTH_INITIALIZED);
328
+
329
+ // Analytics
330
+ configureAnalytics(analyticsServiceImpl, {
331
+ config: getConfig(),
332
+ loggingService: getLoggingService(),
333
+ httpClient: getAuthenticatedHttpClient(),
334
+ });
335
+ await handlers.analytics();
336
+ publish(APP_ANALYTICS_INITIALIZED);
337
+
338
+ // Internationalization
339
+ configureI18n({
340
+ messages,
341
+ config: getConfig(),
342
+ loggingService: getLoggingService(),
343
+ });
344
+ await handlers.i18n();
345
+ publish(APP_I18N_INITIALIZED);
346
+
347
+ // Application Ready
348
+ await handlers.ready();
349
+ publish(APP_READY);
350
+ } catch (error) {
351
+ if (!error.isRedirecting) {
352
+ // Initialization Error
353
+ await handlers.initError(error);
354
+ publish(APP_INIT_ERROR, error);
355
+ }
356
+ }
357
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The MockLoggingService implements both logInfo and logError as jest mock functions via
3
+ * jest.fn(). It has no other functionality.
4
+ *
5
+ * @implements {LoggingService}
6
+ * @memberof module:Logging
7
+ */
8
+ class MockLoggingService {
9
+ /**
10
+ * Implemented as a jest.fn()
11
+ *
12
+ * @memberof MockLoggingService
13
+ */
14
+ logInfo = jest.fn();
15
+
16
+ /**
17
+ * Implemented as a jest.fn()
18
+ *
19
+ * @memberof MockLoggingService
20
+ */
21
+ logError = jest.fn();
22
+
23
+ /**
24
+ * Implemented as a jest.fn()
25
+ *
26
+ * @memberof MockLoggingService
27
+ */
28
+ setCustomAttribute = jest.fn();
29
+ }
30
+
31
+ export default MockLoggingService;
@@ -0,0 +1,181 @@
1
+ /**
2
+ * NewRelic will not log an error if it is too long.
3
+ *
4
+ * @ignore
5
+ */
6
+ export const MAX_ERROR_LENGTH = 4000;
7
+
8
+ function fixErrorLength(error) {
9
+ if (error.message && error.message.length > MAX_ERROR_LENGTH) {
10
+ const processedError = Object.create(error);
11
+ processedError.message = processedError.message.substring(0, MAX_ERROR_LENGTH);
12
+ return processedError;
13
+ }
14
+ if (typeof error === 'string' && error.length > MAX_ERROR_LENGTH) {
15
+ return error.substring(0, MAX_ERROR_LENGTH);
16
+ }
17
+ return error;
18
+ }
19
+
20
+ /* Constants used as New Relic page action names. */
21
+ const pageActionNameInfo = 'INFO';
22
+ const pageActionNameIgnoredError = 'IGNORED_ERROR';
23
+
24
+ function sendPageAction(actionName, message, customAttributes) {
25
+ if (process.env.NODE_ENV === 'development') {
26
+ console.log(actionName, message, customAttributes); // eslint-disable-line
27
+ }
28
+ if (window && typeof window.newrelic !== 'undefined') {
29
+ // https://docs.newrelic.com/docs/browser/new-relic-browser/browser-apis/addpageaction/
30
+ window.newrelic.addPageAction(actionName, { message, ...customAttributes });
31
+ }
32
+ }
33
+
34
+ function sendError(error, customAttributes) {
35
+ if (process.env.NODE_ENV === 'development') {
36
+ console.error(error, customAttributes); // eslint-disable-line
37
+ }
38
+ if (window && typeof window.newrelic !== 'undefined') {
39
+ // https://docs.newrelic.com/docs/browser/new-relic-browser/browser-apis/noticeerror/
40
+ window.newrelic.noticeError(fixErrorLength(error), customAttributes);
41
+ }
42
+ }
43
+
44
+ function setCustomAttribute(name, value) {
45
+ if (process.env.NODE_ENV === 'development') {
46
+ console.log(name, value); // eslint-disable-line
47
+ }
48
+ if (window && typeof window.newrelic !== 'undefined') {
49
+ // https://docs.newrelic.com/docs/browser/new-relic-browser/browser-apis/setcustomattribute/
50
+ window.newrelic.setCustomAttribute(name, value);
51
+ }
52
+ }
53
+
54
+ /**
55
+ * The NewRelicLoggingService is a concrete implementation of the logging service interface that
56
+ * sends messages to NewRelic that can be seen in NewRelic Browser and NewRelic Insights. When in
57
+ * development mode, all messages will instead be sent to the console.
58
+ *
59
+ * When you use `logError`, your errors will be checked to see if they're ignored *or* not.
60
+ * Not-ignored errors will appear under "JS errors" for your Browser application.
61
+ *
62
+ * ```
63
+ * SELECT * from JavaScriptError WHERE errorStatus is not null SINCE 10 days ago
64
+ * ```
65
+ *
66
+ * Ignored errors will appear in New Relic Insights as page actions, which can be queried:
67
+ *
68
+ * ```
69
+ * SELECT * from PageAction WHERE actionName = 'IGNORED_ERROR' SINCE 1 hour ago
70
+ * ```
71
+ *
72
+ * When using `logInfo`, these only appear in New Relic Insights when querying for page actions as
73
+ * follows:
74
+ *
75
+ * ```
76
+ * SELECT * from PageAction WHERE actionName = 'INFO' SINCE 1 hour ago
77
+ * ```
78
+ *
79
+ * You can also add your own custom metrics as an additional argument, or see the code to find
80
+ * other standard custom attributes. By default, userId is added (via setCustomAttribute) for logged
81
+ * in users via the auth service (AuthAxiosJwtService).
82
+ *
83
+ * Requires the NewRelic Browser JavaScript snippet.
84
+ *
85
+ * @implements {LoggingService}
86
+ * @memberof module:Logging
87
+ */
88
+ export default class NewRelicLoggingService {
89
+ constructor(options) {
90
+ const config = options ? options.config : undefined;
91
+ /*
92
+ String which is an explicit error message regex. If an error message matches the regex, the error
93
+ is considered an *ignored* error and submitted to New Relic as a page action - not an error.
94
+
95
+ Ignored error regexes are configured per frontend application (MFE).
96
+
97
+ The regex for all ignored errors are represented in the .env files as a single string. If you need to
98
+ ignore multiple errors, use the standard `|` regex syntax.
99
+
100
+ For example, here's a .env line which ignores two specific errors:
101
+
102
+ IGNORED_ERROR_REGEX='^\\[frontend-auth\\] Unimportant Error|Specific non-critical error #[\\d]+'
103
+
104
+ This example would ignore errors with the following messages:
105
+
106
+ [frontend-app-generic] - Specific non-critical error #45678 happened.
107
+ [frontend-app-generic] - Specific non-critical error #93475 happened.
108
+ [frontend-auth] Unimportant Error: Browser strangeness occurred.
109
+
110
+ To test your regex additions, use a JS CLI environment (such as node) and run code like this:
111
+
112
+ x = new RegExp('^\\[frontend-auth\\] Unimportant Error|Specific non-critical error #[\\d]+');
113
+ '[frontend-app-generic] - Specific non-critical error #45678 happened.'.match(x);
114
+ '[frontend-auth] Unimportant Error: Browser strangeness occurred.'.match(x);
115
+ 'This error should not match anything!'.match(x);
116
+
117
+ For edx.org, add new error message regexes in edx-internal YAML as needed.
118
+ */
119
+ this.ignoredErrorRegexes = config ? config.IGNORED_ERROR_REGEX : undefined;
120
+ }
121
+
122
+ /**
123
+ *
124
+ *
125
+ * @param {*} infoStringOrErrorObject
126
+ * @param {*} [customAttributes={}]
127
+ * @memberof NewRelicLoggingService
128
+ */
129
+ logInfo(infoStringOrErrorObject, customAttributes = {}) {
130
+ let message = infoStringOrErrorObject;
131
+ let customAttrs = customAttributes;
132
+ if (typeof infoStringOrErrorObject === 'object' && 'message' in infoStringOrErrorObject) {
133
+ /* Caller has passed in an error object to be logged as a page action. */
134
+ /* Extract the attributes and the message. */
135
+ const infoCustomAttributes = infoStringOrErrorObject.customAttributes || {};
136
+ customAttrs = { ...infoCustomAttributes, ...customAttributes };
137
+ message = infoStringOrErrorObject.message;
138
+ }
139
+ sendPageAction(pageActionNameInfo, message, customAttrs);
140
+ }
141
+
142
+ /**
143
+ *
144
+ *
145
+ * @param {*} errorStringOrObject
146
+ * @param {*} [customAttributes={}]
147
+ * @memberof NewRelicLoggingService
148
+ */
149
+ logError(errorStringOrObject, customAttributes = {}) {
150
+ const errorCustomAttributes = errorStringOrObject.customAttributes || {};
151
+ let allCustomAttributes = { ...errorCustomAttributes, ...customAttributes };
152
+ if (Object.keys(allCustomAttributes).length === 0) {
153
+ // noticeError expects undefined if there are no custom attributes.
154
+ allCustomAttributes = undefined;
155
+ }
156
+
157
+ /*
158
+ Separate the errors into ignored errors and other errors.
159
+ Ignored errors are logged via adding a page action.
160
+ Other errors are logged via noticeError and count as "JS Errors" for the application.
161
+ */
162
+ const errorMessage = errorStringOrObject.message || (typeof errorStringOrObject === 'string' ? errorStringOrObject : '');
163
+ if (this.ignoredErrorRegexes && errorMessage.match(this.ignoredErrorRegexes)) {
164
+ /* ignored error */
165
+ sendPageAction(pageActionNameIgnoredError, errorMessage, allCustomAttributes);
166
+ } else {
167
+ /* error! */
168
+ sendError(errorStringOrObject, allCustomAttributes);
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Sets a custom attribute that will be included with all subsequent log messages.
174
+ *
175
+ * @param {string} name
176
+ * @param {string|number|null} value
177
+ */
178
+ setCustomAttribute(name, value) {
179
+ setCustomAttribute(name, value);
180
+ }
181
+ }
@@ -0,0 +1,9 @@
1
+ export {
2
+ getLoggingService,
3
+ resetLoggingService,
4
+ configure,
5
+ logInfo,
6
+ logError,
7
+ } from './interface';
8
+ export { default as NewRelicLoggingService } from './NewRelicLoggingService';
9
+ export { default as MockLoggingService } from './MockLoggingService';
@@ -0,0 +1,110 @@
1
+ /**
2
+ * #### Import members from **@edx/frontend-platform/logging**
3
+ *
4
+ * Contains a shared interface for logging information. (The default implementation is in
5
+ * NewRelicLoggingService.js.) When in development mode, all messages will instead be sent to the console.
6
+ *
7
+ * The `initialize` function performs much of the logging configuration for you. If, however,
8
+ * you're not using the `initialize` function, logging (via New Relic) can be configured via:
9
+ *
10
+ * ```
11
+ * import { configure, NewRelicLoggingService, logInfo, logError } from '@edx/frontend-platform/logging';
12
+ * import { geConfig } from '@edx/frontend-platform';
13
+ *
14
+ * configureLogging(NewRelicLoggingService, {
15
+ * config: getConfig(),
16
+ * });
17
+ *
18
+ * logInfo('Just so you know...');
19
+ * logInfo(new Error('Unimportant error'), { type: 'unimportant' });
20
+ * logError('Uhoh!');
21
+ * logError(new Error('Uhoh error!'));
22
+ * ```
23
+ *
24
+ * As shown in this example, logging depends on the configuration document.
25
+ *
26
+ * @module Logging
27
+ */
28
+
29
+ import PropTypes from 'prop-types';
30
+
31
+ const optionsShape = {
32
+ config: PropTypes.object.isRequired,
33
+ };
34
+
35
+ const serviceShape = {
36
+ logInfo: PropTypes.func.isRequired,
37
+ logError: PropTypes.func.isRequired,
38
+ };
39
+
40
+ let service = null;
41
+
42
+ /**
43
+ *
44
+ */
45
+ export function configure(LoggingService, options) {
46
+ PropTypes.checkPropTypes(optionsShape, options, 'property', 'Logging');
47
+ service = new LoggingService(options);
48
+ PropTypes.checkPropTypes(serviceShape, service, 'property', 'LoggingService');
49
+ return service;
50
+ }
51
+
52
+ /**
53
+ * Logs a message to the 'info' log level. Can accept custom attributes as a property of the error
54
+ * object, or as an optional second parameter.
55
+ *
56
+ * @param {string|Error} infoStringOrErrorObject
57
+ * @param {Object} [customAttributes={}]
58
+ */
59
+ export function logInfo(infoStringOrErrorObject, customAttributes) {
60
+ return service.logInfo(infoStringOrErrorObject, customAttributes);
61
+ }
62
+
63
+ /**
64
+ * Logs a message to the 'error' log level. Can accept custom attributes as a property of the error
65
+ * object, or as an optional second parameter.
66
+ *
67
+ * @param {string|Error} errorStringOrObject
68
+ * @param {Object} [customAttributes={}]
69
+ */
70
+ export function logError(errorStringOrObject, customAttributes) {
71
+ return service.logError(errorStringOrObject, customAttributes);
72
+ }
73
+
74
+ /**
75
+ * Sets a custom attribute that will be included with all subsequent log messages.
76
+ *
77
+ * @param {string} name
78
+ * @param {string|number|null} value
79
+ */
80
+ export function setCustomAttribute(name, value) {
81
+ return service.setCustomAttribute(name, value);
82
+ }
83
+
84
+ /**
85
+ *
86
+ * @throws {Error} Thrown if the logging service has not yet been configured via {@link configure}.
87
+ * @returns {LoggingService}
88
+ */
89
+ export function getLoggingService() {
90
+ if (!service) {
91
+ throw Error('You must first configure the logging service.');
92
+ }
93
+ return service;
94
+ }
95
+
96
+ /**
97
+ * Sets the configured logging service back to null.
98
+ *
99
+ */
100
+ export function resetLoggingService() {
101
+ service = null;
102
+ }
103
+
104
+ /**
105
+ * @name LoggingService
106
+ * @interface
107
+ * @memberof module:Logging
108
+ * @property {function} logError
109
+ * @property {function} logInfo
110
+ */