@embeddable.com/sdk-react 0.1.2 → 1.0.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.
@@ -0,0 +1,3 @@
1
+ import * as React from "react";
2
+ export declare const EmbeddableStateContext: React.Context<{}>;
3
+ export declare const useEmbeddableState: <S>(initialState?: S) => {};
@@ -1,13 +1,12 @@
1
- import * as React from 'react';
1
+ import * as React from "react";
2
2
  import { LoadDataParams } from "@embeddable.com/sdk-core";
3
3
  type WrapperProps = {
4
4
  propsUpdateListener: HTMLElement;
5
5
  componentId: string;
6
6
  };
7
- export type Config = {
8
- extendedProps?: (props: any) => any;
9
- events: Record<string, EmbeddableEventHandler>;
10
- dataLoaders: (props: any) => Record<string, LoadDataParams>;
7
+ export type Config<ES> = {
8
+ props?: <P>(ownProps: P, embeddableState: [ES, React.Dispatch<React.SetStateAction<ES>>]) => Record<string, unknown | LoadDataParams>;
9
+ events?: Record<string, EmbeddableEventHandler>;
11
10
  };
12
11
  export type EmbeddableEventHandler = (value: any) => any;
13
12
  export type DataResponse = {
@@ -15,7 +14,7 @@ export type DataResponse = {
15
14
  data?: any;
16
15
  error?: string;
17
16
  };
18
- export declare function embedComponent(InnerComponent: React.ComponentType, config: Config): {
17
+ export declare function embedComponent<ES>(InnerComponent: React.ComponentType<any>, config?: Config<ES>): {
19
18
  ({ propsUpdateListener, ...props }: WrapperProps): React.JSX.Element;
20
19
  displayName: string;
21
20
  };
@@ -1,4 +1,4 @@
1
- import * as React from 'react';
1
+ import * as React from "react";
2
2
  export type Config<T> = {
3
3
  inputs: (value: any, setter: Setter<T>) => any;
4
4
  events: Record<string, EmbeddableEventHandler<T>>;
package/lib/index.cjs.js CHANGED
@@ -67,61 +67,106 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
67
67
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
68
68
  };
69
69
 
70
- var UPDATE_PROPS_EVENT_NAME = 'embeddable-event:update-props';
71
- var RELOAD_DATASET_EVENT_NAME = 'embeddable-event:reload-dataset';
70
+ var EmbeddableStateContext = React__namespace.createContext({});
71
+ var useEmbeddableState = function (initialState) {
72
+ if (initialState === void 0) { initialState = {}; }
73
+ var ctx = React__namespace.useContext(EmbeddableStateContext);
74
+ React__namespace.useEffect(function () {
75
+ ctx[1](initialState);
76
+ }, [initialState]);
77
+ return ctx;
78
+ };
79
+
80
+ var UPDATE_PROPS_EVENT_NAME = "embeddable-event:update-props";
81
+ var RELOAD_DATASET_EVENT_NAME = "embeddable-event:reload-dataset";
82
+ var LOAD_DATA_RESULT_EVENT_NAME = "embeddable-event:load-data-result";
72
83
  var ReducerActionTypes = {
73
- loading: 'loading',
74
- error: 'error',
75
- data: 'data',
84
+ loading: "loading",
85
+ error: "error",
86
+ data: "data",
76
87
  };
77
88
  var reducer = function (state, action) {
78
89
  var _a, _b, _c;
79
90
  switch (action.type) {
80
- case (ReducerActionTypes.loading): {
81
- return __assign(__assign({}, state), (_a = {}, _a[action.inputName] = { isLoading: true }, _a));
91
+ case ReducerActionTypes.loading: {
92
+ return __assign(__assign({}, state), (_a = {}, _a[action.inputName] = {
93
+ data: state[action.inputName].data,
94
+ isLoading: true,
95
+ }, _a));
82
96
  }
83
- case (ReducerActionTypes.data): {
84
- return __assign(__assign({}, state), (_b = {}, _b[action.inputName] = { isLoading: false, data: action.payload.data }, _b));
97
+ case ReducerActionTypes.data: {
98
+ return __assign(__assign({}, state), (_b = {}, _b[action.inputName] = { isLoading: false, data: action.payload }, _b));
85
99
  }
86
- case (ReducerActionTypes.error): {
87
- return __assign(__assign({}, state), (_c = {}, _c[action.inputName] = { isLoading: false, error: action.payload.message || action.payload }, _c));
100
+ case ReducerActionTypes.error: {
101
+ return __assign(__assign({}, state), (_c = {}, _c[action.inputName] = {
102
+ isLoading: false,
103
+ error: action.payload.message || action.payload,
104
+ }, _c));
88
105
  }
89
106
  }
90
107
  return state;
91
108
  };
92
- var createInitialLoadersState = function (dataLoaders) { return Object.keys(dataLoaders).reduce(function (loaderState, loaderKey) {
93
- var _a;
94
- return (__assign(__assign({}, loaderState), (_a = {}, _a[loaderKey] = { isLoading: false }, _a)));
95
- }, {}); };
96
- var latestVariables = {};
109
+ var createInitialLoadersState = function (dataLoaders) {
110
+ return Object.keys(dataLoaders).reduce(function (loaderState, loaderKey) {
111
+ var _a;
112
+ return (__assign(__assign({}, loaderState), (_a = {}, _a[loaderKey] = { isLoading: false }, _a)));
113
+ }, {});
114
+ };
97
115
  function embedComponent(InnerComponent, config) {
98
116
  var _a;
117
+ if (config === void 0) { config = {}; }
99
118
  function EmbeddableWrapper(_a) {
100
119
  var propsUpdateListener = _a.propsUpdateListener, props = __rest(_a, ["propsUpdateListener"]);
101
120
  var _b = React__namespace.useState(props), propsProxy = _b[0], setProps = _b[1];
121
+ var embeddableState = React__namespace.useState();
102
122
  var componentId = props.componentId;
123
+ var loadDataResultEventName = "".concat(LOAD_DATA_RESULT_EVENT_NAME, ":").concat(componentId);
103
124
  var propsUpdateEventHandler = function (_a) {
104
125
  var detail = _a.detail;
105
126
  return setProps(detail);
106
127
  };
107
128
  React__namespace.useEffect(function () {
108
129
  propsUpdateListener.addEventListener(UPDATE_PROPS_EVENT_NAME, propsUpdateEventHandler);
109
- return function () { return propsUpdateListener.removeEventListener(UPDATE_PROPS_EVENT_NAME, propsUpdateEventHandler); };
130
+ return function () {
131
+ return propsUpdateListener.removeEventListener(UPDATE_PROPS_EVENT_NAME, propsUpdateEventHandler);
132
+ };
110
133
  }, []);
111
- var extendedProps = React__namespace.useMemo(function () { var _a; return (_a = config === null || config === void 0 ? void 0 : config.extendedProps) === null || _a === void 0 ? void 0 : _a.call(config, propsProxy); }, [propsProxy, config === null || config === void 0 ? void 0 : config.extendedProps]);
112
- var dataLoaders = React__namespace.useMemo(function () { var _a, _b; return (_b = (_a = config === null || config === void 0 ? void 0 : config.dataLoaders) === null || _a === void 0 ? void 0 : _a.call(config, propsProxy)) !== null && _b !== void 0 ? _b : {}; }, [propsProxy, config === null || config === void 0 ? void 0 : config.dataLoaders]);
113
- var _c = React__namespace.useReducer(reducer, dataLoaders, createInitialLoadersState), loadersState = _c[0], dispatch = _c[1];
114
- var handleDataLoaded = function (inputName) { return function (res) { return dispatch({ type: ReducerActionTypes.data, inputName: inputName, payload: res.data }); }; };
115
- var handleError = function (inputName) { return function (error) { return dispatch({ type: ReducerActionTypes.error, inputName: inputName, payload: error }); }; };
134
+ var _c = React__namespace.useMemo(function () {
135
+ var _a, _b;
136
+ return Object.entries((_b = (_a = config === null || config === void 0 ? void 0 : config.props) === null || _a === void 0 ? void 0 : _a.call(config, propsProxy, embeddableState)) !== null && _b !== void 0 ? _b : {}).reduce(function (acc, _a) {
137
+ var key = _a[0], value = _a[1];
138
+ if (sdkCore.isLoadDataParams(value)) {
139
+ acc.dataLoaders[key] = value;
140
+ }
141
+ else {
142
+ acc.extendedProps[key] = value;
143
+ }
144
+ return acc;
145
+ }, { extendedProps: {}, dataLoaders: {} });
146
+ }, [propsProxy, config === null || config === void 0 ? void 0 : config.props, embeddableState[0]]), extendedProps = _c.extendedProps, dataLoaders = _c.dataLoaders;
147
+ var _d = React__namespace.useReducer(reducer, dataLoaders, createInitialLoadersState), loadersState = _d[0], dispatch = _d[1];
148
+ var handleDataLoaded = function (inputName, data) {
149
+ return dispatch({ type: ReducerActionTypes.data, inputName: inputName, payload: data });
150
+ };
151
+ var handleError = function (inputName, error) {
152
+ return dispatch({ type: ReducerActionTypes.error, inputName: inputName, payload: error });
153
+ };
116
154
  var reloadDataset = function (inputName, params) {
117
155
  dispatch({ type: ReducerActionTypes.loading, inputName: inputName });
118
- params.dataLoader(params.requestParams, latestVariables)
119
- .then(handleDataLoaded(inputName))
120
- .catch(handleError(inputName));
156
+ var error = params.dataLoader(params.requestParams, componentId, inputName);
157
+ if (error)
158
+ handleError(inputName, error);
159
+ };
160
+ var handleLoadDataResult = function (ev) {
161
+ if (ev.detail.isSuccess) {
162
+ handleDataLoaded(ev.detail.propertyName, ev.detail.data);
163
+ }
164
+ else {
165
+ handleError(ev.detail.propertyName, ev.detail.error);
166
+ }
121
167
  };
122
168
  var variableChangedEventHandler = function (_a) {
123
169
  var detail = _a.detail;
124
- latestVariables = detail.variableValues;
125
170
  Object.entries(dataLoaders)
126
171
  .filter(function (_a) {
127
172
  _a[0]; var params = _a[1];
@@ -138,25 +183,36 @@ function embedComponent(InnerComponent, config) {
138
183
  return reloadDataset(inputName, params);
139
184
  });
140
185
  window.addEventListener(RELOAD_DATASET_EVENT_NAME, variableChangedEventHandler);
141
- return function () { return window.removeEventListener(RELOAD_DATASET_EVENT_NAME, variableChangedEventHandler); };
142
- }, [JSON.stringify(Object.values(dataLoaders).map(function (loader) { return loader.requestParams; }))]);
143
- var createEvent = function (value, eventName) { return sdkCore.setValue(value, componentId, eventName); };
186
+ window.addEventListener(loadDataResultEventName, handleLoadDataResult);
187
+ return function () {
188
+ window.removeEventListener(RELOAD_DATASET_EVENT_NAME, variableChangedEventHandler);
189
+ window.removeEventListener(loadDataResultEventName, handleLoadDataResult);
190
+ };
191
+ }, [
192
+ JSON.stringify(Object.values(dataLoaders).map(function (loader) { return loader.requestParams; })),
193
+ ]);
194
+ var createEvent = function (value, eventName) {
195
+ return sdkCore.setValue(value, componentId, eventName);
196
+ };
144
197
  var events = config === null || config === void 0 ? void 0 : config.events;
145
198
  var eventProps = {};
146
199
  if (events) {
147
200
  var _loop_1 = function (event_1) {
148
201
  if (events.hasOwnProperty(event_1)) {
149
202
  var eventFunction_1 = events[event_1];
150
- eventProps[event_1] = function (value) { return createEvent(eventFunction_1(value), event_1); };
203
+ eventProps[event_1] = function (value) {
204
+ return createEvent(eventFunction_1(value), event_1);
205
+ };
151
206
  }
152
207
  };
153
208
  for (var event_1 in events) {
154
209
  _loop_1(event_1);
155
210
  }
156
211
  }
157
- return React__namespace.createElement(InnerComponent, __assign({}, propsProxy, extendedProps, eventProps, loadersState));
212
+ return (React__namespace.createElement(EmbeddableStateContext.Provider, { value: embeddableState },
213
+ React__namespace.createElement(InnerComponent, __assign({}, extendedProps, eventProps, loadersState))));
158
214
  }
159
- EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : 'Component', ")");
215
+ EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : "Component", ")");
160
216
  return EmbeddableWrapper;
161
217
  }
162
218
 
@@ -170,11 +226,12 @@ function embedControl(InnerComponent, config) {
170
226
  setComponentState(value);
171
227
  sdkCore.setValue(value, componentId);
172
228
  };
173
- return React__namespace.createElement(InnerComponent, __assign({}, config.inputs(componentState, setter), ((_b = (_a = config.mapProps) === null || _a === void 0 ? void 0 : _a.call(config, props)) !== null && _b !== void 0 ? _b : {})));
229
+ return (React__namespace.createElement(InnerComponent, __assign({}, config.inputs(componentState, setter), ((_b = (_a = config.mapProps) === null || _a === void 0 ? void 0 : _a.call(config, props)) !== null && _b !== void 0 ? _b : {}))));
174
230
  }
175
- EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : 'Editor', ")");
231
+ EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : "Editor", ")");
176
232
  return EmbeddableWrapper;
177
233
  }
178
234
 
179
235
  exports.embedComponent = embedComponent;
180
236
  exports.embedControl = embedControl;
237
+ exports.useEmbeddableState = useEmbeddableState;
package/lib/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
- export { embedComponent } from './embedComponent';
2
- export { embedControl } from './embedControl';
1
+ export { embedComponent } from "./embedComponent";
2
+ export { embedControl } from "./embedControl";
3
+ export { useEmbeddableState } from "./EmbeddableStateContext";
package/lib/index.esm.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as React from 'react';
2
- import { setValue } from '@embeddable.com/sdk-core';
2
+ import { isLoadDataParams, setValue } from '@embeddable.com/sdk-core';
3
3
 
4
4
  /******************************************************************************
5
5
  Copyright (c) Microsoft Corporation.
@@ -46,61 +46,106 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
46
46
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
47
47
  };
48
48
 
49
- var UPDATE_PROPS_EVENT_NAME = 'embeddable-event:update-props';
50
- var RELOAD_DATASET_EVENT_NAME = 'embeddable-event:reload-dataset';
49
+ var EmbeddableStateContext = React.createContext({});
50
+ var useEmbeddableState = function (initialState) {
51
+ if (initialState === void 0) { initialState = {}; }
52
+ var ctx = React.useContext(EmbeddableStateContext);
53
+ React.useEffect(function () {
54
+ ctx[1](initialState);
55
+ }, [initialState]);
56
+ return ctx;
57
+ };
58
+
59
+ var UPDATE_PROPS_EVENT_NAME = "embeddable-event:update-props";
60
+ var RELOAD_DATASET_EVENT_NAME = "embeddable-event:reload-dataset";
61
+ var LOAD_DATA_RESULT_EVENT_NAME = "embeddable-event:load-data-result";
51
62
  var ReducerActionTypes = {
52
- loading: 'loading',
53
- error: 'error',
54
- data: 'data',
63
+ loading: "loading",
64
+ error: "error",
65
+ data: "data",
55
66
  };
56
67
  var reducer = function (state, action) {
57
68
  var _a, _b, _c;
58
69
  switch (action.type) {
59
- case (ReducerActionTypes.loading): {
60
- return __assign(__assign({}, state), (_a = {}, _a[action.inputName] = { isLoading: true }, _a));
70
+ case ReducerActionTypes.loading: {
71
+ return __assign(__assign({}, state), (_a = {}, _a[action.inputName] = {
72
+ data: state[action.inputName].data,
73
+ isLoading: true,
74
+ }, _a));
61
75
  }
62
- case (ReducerActionTypes.data): {
63
- return __assign(__assign({}, state), (_b = {}, _b[action.inputName] = { isLoading: false, data: action.payload.data }, _b));
76
+ case ReducerActionTypes.data: {
77
+ return __assign(__assign({}, state), (_b = {}, _b[action.inputName] = { isLoading: false, data: action.payload }, _b));
64
78
  }
65
- case (ReducerActionTypes.error): {
66
- return __assign(__assign({}, state), (_c = {}, _c[action.inputName] = { isLoading: false, error: action.payload.message || action.payload }, _c));
79
+ case ReducerActionTypes.error: {
80
+ return __assign(__assign({}, state), (_c = {}, _c[action.inputName] = {
81
+ isLoading: false,
82
+ error: action.payload.message || action.payload,
83
+ }, _c));
67
84
  }
68
85
  }
69
86
  return state;
70
87
  };
71
- var createInitialLoadersState = function (dataLoaders) { return Object.keys(dataLoaders).reduce(function (loaderState, loaderKey) {
72
- var _a;
73
- return (__assign(__assign({}, loaderState), (_a = {}, _a[loaderKey] = { isLoading: false }, _a)));
74
- }, {}); };
75
- var latestVariables = {};
88
+ var createInitialLoadersState = function (dataLoaders) {
89
+ return Object.keys(dataLoaders).reduce(function (loaderState, loaderKey) {
90
+ var _a;
91
+ return (__assign(__assign({}, loaderState), (_a = {}, _a[loaderKey] = { isLoading: false }, _a)));
92
+ }, {});
93
+ };
76
94
  function embedComponent(InnerComponent, config) {
77
95
  var _a;
96
+ if (config === void 0) { config = {}; }
78
97
  function EmbeddableWrapper(_a) {
79
98
  var propsUpdateListener = _a.propsUpdateListener, props = __rest(_a, ["propsUpdateListener"]);
80
99
  var _b = React.useState(props), propsProxy = _b[0], setProps = _b[1];
100
+ var embeddableState = React.useState();
81
101
  var componentId = props.componentId;
102
+ var loadDataResultEventName = "".concat(LOAD_DATA_RESULT_EVENT_NAME, ":").concat(componentId);
82
103
  var propsUpdateEventHandler = function (_a) {
83
104
  var detail = _a.detail;
84
105
  return setProps(detail);
85
106
  };
86
107
  React.useEffect(function () {
87
108
  propsUpdateListener.addEventListener(UPDATE_PROPS_EVENT_NAME, propsUpdateEventHandler);
88
- return function () { return propsUpdateListener.removeEventListener(UPDATE_PROPS_EVENT_NAME, propsUpdateEventHandler); };
109
+ return function () {
110
+ return propsUpdateListener.removeEventListener(UPDATE_PROPS_EVENT_NAME, propsUpdateEventHandler);
111
+ };
89
112
  }, []);
90
- var extendedProps = React.useMemo(function () { var _a; return (_a = config === null || config === void 0 ? void 0 : config.extendedProps) === null || _a === void 0 ? void 0 : _a.call(config, propsProxy); }, [propsProxy, config === null || config === void 0 ? void 0 : config.extendedProps]);
91
- var dataLoaders = React.useMemo(function () { var _a, _b; return (_b = (_a = config === null || config === void 0 ? void 0 : config.dataLoaders) === null || _a === void 0 ? void 0 : _a.call(config, propsProxy)) !== null && _b !== void 0 ? _b : {}; }, [propsProxy, config === null || config === void 0 ? void 0 : config.dataLoaders]);
92
- var _c = React.useReducer(reducer, dataLoaders, createInitialLoadersState), loadersState = _c[0], dispatch = _c[1];
93
- var handleDataLoaded = function (inputName) { return function (res) { return dispatch({ type: ReducerActionTypes.data, inputName: inputName, payload: res.data }); }; };
94
- var handleError = function (inputName) { return function (error) { return dispatch({ type: ReducerActionTypes.error, inputName: inputName, payload: error }); }; };
113
+ var _c = React.useMemo(function () {
114
+ var _a, _b;
115
+ return Object.entries((_b = (_a = config === null || config === void 0 ? void 0 : config.props) === null || _a === void 0 ? void 0 : _a.call(config, propsProxy, embeddableState)) !== null && _b !== void 0 ? _b : {}).reduce(function (acc, _a) {
116
+ var key = _a[0], value = _a[1];
117
+ if (isLoadDataParams(value)) {
118
+ acc.dataLoaders[key] = value;
119
+ }
120
+ else {
121
+ acc.extendedProps[key] = value;
122
+ }
123
+ return acc;
124
+ }, { extendedProps: {}, dataLoaders: {} });
125
+ }, [propsProxy, config === null || config === void 0 ? void 0 : config.props, embeddableState[0]]), extendedProps = _c.extendedProps, dataLoaders = _c.dataLoaders;
126
+ var _d = React.useReducer(reducer, dataLoaders, createInitialLoadersState), loadersState = _d[0], dispatch = _d[1];
127
+ var handleDataLoaded = function (inputName, data) {
128
+ return dispatch({ type: ReducerActionTypes.data, inputName: inputName, payload: data });
129
+ };
130
+ var handleError = function (inputName, error) {
131
+ return dispatch({ type: ReducerActionTypes.error, inputName: inputName, payload: error });
132
+ };
95
133
  var reloadDataset = function (inputName, params) {
96
134
  dispatch({ type: ReducerActionTypes.loading, inputName: inputName });
97
- params.dataLoader(params.requestParams, latestVariables)
98
- .then(handleDataLoaded(inputName))
99
- .catch(handleError(inputName));
135
+ var error = params.dataLoader(params.requestParams, componentId, inputName);
136
+ if (error)
137
+ handleError(inputName, error);
138
+ };
139
+ var handleLoadDataResult = function (ev) {
140
+ if (ev.detail.isSuccess) {
141
+ handleDataLoaded(ev.detail.propertyName, ev.detail.data);
142
+ }
143
+ else {
144
+ handleError(ev.detail.propertyName, ev.detail.error);
145
+ }
100
146
  };
101
147
  var variableChangedEventHandler = function (_a) {
102
148
  var detail = _a.detail;
103
- latestVariables = detail.variableValues;
104
149
  Object.entries(dataLoaders)
105
150
  .filter(function (_a) {
106
151
  _a[0]; var params = _a[1];
@@ -117,25 +162,36 @@ function embedComponent(InnerComponent, config) {
117
162
  return reloadDataset(inputName, params);
118
163
  });
119
164
  window.addEventListener(RELOAD_DATASET_EVENT_NAME, variableChangedEventHandler);
120
- return function () { return window.removeEventListener(RELOAD_DATASET_EVENT_NAME, variableChangedEventHandler); };
121
- }, [JSON.stringify(Object.values(dataLoaders).map(function (loader) { return loader.requestParams; }))]);
122
- var createEvent = function (value, eventName) { return setValue(value, componentId, eventName); };
165
+ window.addEventListener(loadDataResultEventName, handleLoadDataResult);
166
+ return function () {
167
+ window.removeEventListener(RELOAD_DATASET_EVENT_NAME, variableChangedEventHandler);
168
+ window.removeEventListener(loadDataResultEventName, handleLoadDataResult);
169
+ };
170
+ }, [
171
+ JSON.stringify(Object.values(dataLoaders).map(function (loader) { return loader.requestParams; })),
172
+ ]);
173
+ var createEvent = function (value, eventName) {
174
+ return setValue(value, componentId, eventName);
175
+ };
123
176
  var events = config === null || config === void 0 ? void 0 : config.events;
124
177
  var eventProps = {};
125
178
  if (events) {
126
179
  var _loop_1 = function (event_1) {
127
180
  if (events.hasOwnProperty(event_1)) {
128
181
  var eventFunction_1 = events[event_1];
129
- eventProps[event_1] = function (value) { return createEvent(eventFunction_1(value), event_1); };
182
+ eventProps[event_1] = function (value) {
183
+ return createEvent(eventFunction_1(value), event_1);
184
+ };
130
185
  }
131
186
  };
132
187
  for (var event_1 in events) {
133
188
  _loop_1(event_1);
134
189
  }
135
190
  }
136
- return React.createElement(InnerComponent, __assign({}, propsProxy, extendedProps, eventProps, loadersState));
191
+ return (React.createElement(EmbeddableStateContext.Provider, { value: embeddableState },
192
+ React.createElement(InnerComponent, __assign({}, extendedProps, eventProps, loadersState))));
137
193
  }
138
- EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : 'Component', ")");
194
+ EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : "Component", ")");
139
195
  return EmbeddableWrapper;
140
196
  }
141
197
 
@@ -149,10 +205,10 @@ function embedControl(InnerComponent, config) {
149
205
  setComponentState(value);
150
206
  setValue(value, componentId);
151
207
  };
152
- return React.createElement(InnerComponent, __assign({}, config.inputs(componentState, setter), ((_b = (_a = config.mapProps) === null || _a === void 0 ? void 0 : _a.call(config, props)) !== null && _b !== void 0 ? _b : {})));
208
+ return (React.createElement(InnerComponent, __assign({}, config.inputs(componentState, setter), ((_b = (_a = config.mapProps) === null || _a === void 0 ? void 0 : _a.call(config, props)) !== null && _b !== void 0 ? _b : {}))));
153
209
  }
154
- EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : 'Editor', ")");
210
+ EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : "Editor", ")");
155
211
  return EmbeddableWrapper;
156
212
  }
157
213
 
158
- export { embedComponent, embedControl };
214
+ export { embedComponent, embedControl, useEmbeddableState };
package/lib/index.umd.js CHANGED
@@ -86,6 +86,10 @@
86
86
 
87
87
  var reactExports = react.exports;
88
88
 
89
+ var isLoadDataParams = function (ldp) {
90
+ return typeof ldp === "object" && "requestParams" in ldp && "dataLoader" in ldp;
91
+ };
92
+
89
93
  var UPDATE_VALUE_EVENT = "embeddable:value:changed";
90
94
  var setValue = function (value, componentId, eventName) {
91
95
  var event = new CustomEvent(UPDATE_VALUE_EVENT, {
@@ -93,7 +97,7 @@
93
97
  detail: {
94
98
  componentId: componentId,
95
99
  value: value,
96
- eventName: eventName
100
+ eventName: eventName,
97
101
  },
98
102
  });
99
103
  window.dispatchEvent(event);
@@ -104,61 +108,106 @@
104
108
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
105
109
  };
106
110
 
107
- var UPDATE_PROPS_EVENT_NAME = 'embeddable-event:update-props';
108
- var RELOAD_DATASET_EVENT_NAME = 'embeddable-event:reload-dataset';
111
+ var EmbeddableStateContext = reactExports.createContext({});
112
+ var useEmbeddableState = function (initialState) {
113
+ if (initialState === void 0) { initialState = {}; }
114
+ var ctx = reactExports.useContext(EmbeddableStateContext);
115
+ reactExports.useEffect(function () {
116
+ ctx[1](initialState);
117
+ }, [initialState]);
118
+ return ctx;
119
+ };
120
+
121
+ var UPDATE_PROPS_EVENT_NAME = "embeddable-event:update-props";
122
+ var RELOAD_DATASET_EVENT_NAME = "embeddable-event:reload-dataset";
123
+ var LOAD_DATA_RESULT_EVENT_NAME = "embeddable-event:load-data-result";
109
124
  var ReducerActionTypes = {
110
- loading: 'loading',
111
- error: 'error',
112
- data: 'data',
125
+ loading: "loading",
126
+ error: "error",
127
+ data: "data",
113
128
  };
114
129
  var reducer = function (state, action) {
115
130
  var _a, _b, _c;
116
131
  switch (action.type) {
117
- case (ReducerActionTypes.loading): {
118
- return __assign(__assign({}, state), (_a = {}, _a[action.inputName] = { isLoading: true }, _a));
132
+ case ReducerActionTypes.loading: {
133
+ return __assign(__assign({}, state), (_a = {}, _a[action.inputName] = {
134
+ data: state[action.inputName].data,
135
+ isLoading: true,
136
+ }, _a));
119
137
  }
120
- case (ReducerActionTypes.data): {
121
- return __assign(__assign({}, state), (_b = {}, _b[action.inputName] = { isLoading: false, data: action.payload.data }, _b));
138
+ case ReducerActionTypes.data: {
139
+ return __assign(__assign({}, state), (_b = {}, _b[action.inputName] = { isLoading: false, data: action.payload }, _b));
122
140
  }
123
- case (ReducerActionTypes.error): {
124
- return __assign(__assign({}, state), (_c = {}, _c[action.inputName] = { isLoading: false, error: action.payload.message || action.payload }, _c));
141
+ case ReducerActionTypes.error: {
142
+ return __assign(__assign({}, state), (_c = {}, _c[action.inputName] = {
143
+ isLoading: false,
144
+ error: action.payload.message || action.payload,
145
+ }, _c));
125
146
  }
126
147
  }
127
148
  return state;
128
149
  };
129
- var createInitialLoadersState = function (dataLoaders) { return Object.keys(dataLoaders).reduce(function (loaderState, loaderKey) {
130
- var _a;
131
- return (__assign(__assign({}, loaderState), (_a = {}, _a[loaderKey] = { isLoading: false }, _a)));
132
- }, {}); };
133
- var latestVariables = {};
150
+ var createInitialLoadersState = function (dataLoaders) {
151
+ return Object.keys(dataLoaders).reduce(function (loaderState, loaderKey) {
152
+ var _a;
153
+ return (__assign(__assign({}, loaderState), (_a = {}, _a[loaderKey] = { isLoading: false }, _a)));
154
+ }, {});
155
+ };
134
156
  function embedComponent(InnerComponent, config) {
135
157
  var _a;
158
+ if (config === void 0) { config = {}; }
136
159
  function EmbeddableWrapper(_a) {
137
160
  var propsUpdateListener = _a.propsUpdateListener, props = __rest(_a, ["propsUpdateListener"]);
138
161
  var _b = reactExports.useState(props), propsProxy = _b[0], setProps = _b[1];
162
+ var embeddableState = reactExports.useState();
139
163
  var componentId = props.componentId;
164
+ var loadDataResultEventName = "".concat(LOAD_DATA_RESULT_EVENT_NAME, ":").concat(componentId);
140
165
  var propsUpdateEventHandler = function (_a) {
141
166
  var detail = _a.detail;
142
167
  return setProps(detail);
143
168
  };
144
169
  reactExports.useEffect(function () {
145
170
  propsUpdateListener.addEventListener(UPDATE_PROPS_EVENT_NAME, propsUpdateEventHandler);
146
- return function () { return propsUpdateListener.removeEventListener(UPDATE_PROPS_EVENT_NAME, propsUpdateEventHandler); };
171
+ return function () {
172
+ return propsUpdateListener.removeEventListener(UPDATE_PROPS_EVENT_NAME, propsUpdateEventHandler);
173
+ };
147
174
  }, []);
148
- var extendedProps = reactExports.useMemo(function () { var _a; return (_a = config === null || config === void 0 ? void 0 : config.extendedProps) === null || _a === void 0 ? void 0 : _a.call(config, propsProxy); }, [propsProxy, config === null || config === void 0 ? void 0 : config.extendedProps]);
149
- var dataLoaders = reactExports.useMemo(function () { var _a, _b; return (_b = (_a = config === null || config === void 0 ? void 0 : config.dataLoaders) === null || _a === void 0 ? void 0 : _a.call(config, propsProxy)) !== null && _b !== void 0 ? _b : {}; }, [propsProxy, config === null || config === void 0 ? void 0 : config.dataLoaders]);
150
- var _c = reactExports.useReducer(reducer, dataLoaders, createInitialLoadersState), loadersState = _c[0], dispatch = _c[1];
151
- var handleDataLoaded = function (inputName) { return function (res) { return dispatch({ type: ReducerActionTypes.data, inputName: inputName, payload: res.data }); }; };
152
- var handleError = function (inputName) { return function (error) { return dispatch({ type: ReducerActionTypes.error, inputName: inputName, payload: error }); }; };
175
+ var _c = reactExports.useMemo(function () {
176
+ var _a, _b;
177
+ return Object.entries((_b = (_a = config === null || config === void 0 ? void 0 : config.props) === null || _a === void 0 ? void 0 : _a.call(config, propsProxy, embeddableState)) !== null && _b !== void 0 ? _b : {}).reduce(function (acc, _a) {
178
+ var key = _a[0], value = _a[1];
179
+ if (isLoadDataParams(value)) {
180
+ acc.dataLoaders[key] = value;
181
+ }
182
+ else {
183
+ acc.extendedProps[key] = value;
184
+ }
185
+ return acc;
186
+ }, { extendedProps: {}, dataLoaders: {} });
187
+ }, [propsProxy, config === null || config === void 0 ? void 0 : config.props, embeddableState[0]]), extendedProps = _c.extendedProps, dataLoaders = _c.dataLoaders;
188
+ var _d = reactExports.useReducer(reducer, dataLoaders, createInitialLoadersState), loadersState = _d[0], dispatch = _d[1];
189
+ var handleDataLoaded = function (inputName, data) {
190
+ return dispatch({ type: ReducerActionTypes.data, inputName: inputName, payload: data });
191
+ };
192
+ var handleError = function (inputName, error) {
193
+ return dispatch({ type: ReducerActionTypes.error, inputName: inputName, payload: error });
194
+ };
153
195
  var reloadDataset = function (inputName, params) {
154
196
  dispatch({ type: ReducerActionTypes.loading, inputName: inputName });
155
- params.dataLoader(params.requestParams, latestVariables)
156
- .then(handleDataLoaded(inputName))
157
- .catch(handleError(inputName));
197
+ var error = params.dataLoader(params.requestParams, componentId, inputName);
198
+ if (error)
199
+ handleError(inputName, error);
200
+ };
201
+ var handleLoadDataResult = function (ev) {
202
+ if (ev.detail.isSuccess) {
203
+ handleDataLoaded(ev.detail.propertyName, ev.detail.data);
204
+ }
205
+ else {
206
+ handleError(ev.detail.propertyName, ev.detail.error);
207
+ }
158
208
  };
159
209
  var variableChangedEventHandler = function (_a) {
160
210
  var detail = _a.detail;
161
- latestVariables = detail.variableValues;
162
211
  Object.entries(dataLoaders)
163
212
  .filter(function (_a) {
164
213
  _a[0]; var params = _a[1];
@@ -175,25 +224,36 @@
175
224
  return reloadDataset(inputName, params);
176
225
  });
177
226
  window.addEventListener(RELOAD_DATASET_EVENT_NAME, variableChangedEventHandler);
178
- return function () { return window.removeEventListener(RELOAD_DATASET_EVENT_NAME, variableChangedEventHandler); };
179
- }, [JSON.stringify(Object.values(dataLoaders).map(function (loader) { return loader.requestParams; }))]);
180
- var createEvent = function (value, eventName) { return setValue(value, componentId, eventName); };
227
+ window.addEventListener(loadDataResultEventName, handleLoadDataResult);
228
+ return function () {
229
+ window.removeEventListener(RELOAD_DATASET_EVENT_NAME, variableChangedEventHandler);
230
+ window.removeEventListener(loadDataResultEventName, handleLoadDataResult);
231
+ };
232
+ }, [
233
+ JSON.stringify(Object.values(dataLoaders).map(function (loader) { return loader.requestParams; })),
234
+ ]);
235
+ var createEvent = function (value, eventName) {
236
+ return setValue(value, componentId, eventName);
237
+ };
181
238
  var events = config === null || config === void 0 ? void 0 : config.events;
182
239
  var eventProps = {};
183
240
  if (events) {
184
241
  var _loop_1 = function (event_1) {
185
242
  if (events.hasOwnProperty(event_1)) {
186
243
  var eventFunction_1 = events[event_1];
187
- eventProps[event_1] = function (value) { return createEvent(eventFunction_1(value), event_1); };
244
+ eventProps[event_1] = function (value) {
245
+ return createEvent(eventFunction_1(value), event_1);
246
+ };
188
247
  }
189
248
  };
190
249
  for (var event_1 in events) {
191
250
  _loop_1(event_1);
192
251
  }
193
252
  }
194
- return reactExports.createElement(InnerComponent, __assign({}, propsProxy, extendedProps, eventProps, loadersState));
253
+ return (reactExports.createElement(EmbeddableStateContext.Provider, { value: embeddableState },
254
+ reactExports.createElement(InnerComponent, __assign({}, extendedProps, eventProps, loadersState))));
195
255
  }
196
- EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : 'Component', ")");
256
+ EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : "Component", ")");
197
257
  return EmbeddableWrapper;
198
258
  }
199
259
 
@@ -207,13 +267,14 @@
207
267
  setComponentState(value);
208
268
  setValue(value, componentId);
209
269
  };
210
- return reactExports.createElement(InnerComponent, __assign({}, config.inputs(componentState, setter), ((_b = (_a = config.mapProps) === null || _a === void 0 ? void 0 : _a.call(config, props)) !== null && _b !== void 0 ? _b : {})));
270
+ return (reactExports.createElement(InnerComponent, __assign({}, config.inputs(componentState, setter), ((_b = (_a = config.mapProps) === null || _a === void 0 ? void 0 : _a.call(config, props)) !== null && _b !== void 0 ? _b : {}))));
211
271
  }
212
- EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : 'Editor', ")");
272
+ EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : "Editor", ")");
213
273
  return EmbeddableWrapper;
214
274
  }
215
275
 
216
276
  exports.embedComponent = embedComponent;
217
277
  exports.embedControl = embedControl;
278
+ exports.useEmbeddableState = useEmbeddableState;
218
279
 
219
280
  }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@embeddable.com/sdk-react",
3
- "version": "0.1.2",
3
+ "version": "1.0.0",
4
4
  "description": "Embeddable SDK React plugin/module responsible for React components bundling.",
5
5
  "keywords": [
6
6
  "embeddable",
@@ -41,5 +41,10 @@
41
41
  "@vitejs/plugin-react": "^4.0.2",
42
42
  "vite": "^4.4.2",
43
43
  "ora": "^6.3.1"
44
+ },
45
+ "lint-staged": {
46
+ "*.{js,ts,jsx,tsx,json}": [
47
+ "prettier --write"
48
+ ]
44
49
  }
45
50
  }
package/scripts/build.js CHANGED
@@ -1,47 +1,79 @@
1
1
  const path = require("path");
2
- const { fork } = require('child_process');
3
- const oraP = import('ora');
2
+ const { fork } = require("child_process");
3
+ const oraP = import("ora");
4
4
  const core = require("@embeddable.com/sdk-core/scripts");
5
5
 
6
- const {createContext} = require("./createContext");
7
- const {prepare} = require("./prepare");
8
- const {cleanup} = require("./cleanup");
6
+ const { createContext } = require("./createContext");
7
+ const { prepare } = require("./prepare");
9
8
 
10
- const generateFork = fork(
11
- path.resolve(__dirname, 'generate.js'),
12
- [],
13
- process.env.NODE_ENV === 'dev' ? undefined : { silent: true }
14
- );
9
+ let ora;
15
10
 
16
11
  async function build() {
17
- const ora = (await oraP).default;
12
+ ora = (await oraP).default;
18
13
 
19
- const spinnerPrepare = ora("preparing...").start();
14
+ const spinnerPrepare = ora("preparing...").start();
20
15
 
21
- const ctx = createContext(path.resolve(__dirname, '..'), process.cwd());
16
+ const ctx = createContext(path.resolve(__dirname, ".."), process.cwd());
22
17
 
23
- await validationEmulation();
24
- await prepare(ctx);
25
- spinnerPrepare.succeed("preparation competed");
18
+ await core.validate(ctx);
26
19
 
27
- const spinnerBuild = ora("building...").start();
20
+ await prepare(ctx);
21
+ spinnerPrepare.succeed("preparation competed");
28
22
 
29
- generateFork.send({ ctx });
23
+ await runProcess({
24
+ ctx,
25
+ processFile: "generateProcess.js",
26
+ initMessage: "building components...",
27
+ successMessage: "components built completed",
28
+ failMessage: "components built failed",
29
+ });
30
30
 
31
- generateFork.on('exit', async () => {
32
- await cleanup(ctx);
33
- spinnerBuild.succeed("build completed");
31
+ await runProcess({
32
+ ctx,
33
+ processFile: "buildTypesProcess.js",
34
+ initMessage: "building types...",
35
+ successMessage: "types built completed",
36
+ failMessage: "types built failed",
37
+ });
38
+ }
34
39
 
35
- await core.buildTypes(ctx);
36
- })
37
40
 
41
+ module.exports = { build };
42
+
43
+ async function runProcess({ processFile, ctx, initMessage, successMessage, failMessage }) {
44
+ const spinner = ora(initMessage).start();
45
+ try {
46
+ await promisifyForkedProcess(processFile, ctx);
47
+ spinner.succeed(successMessage);
48
+ } catch ({ watchFiles, ...info }) {
49
+ spinner.fail(failMessage);
50
+ console.log(info);
51
+ await core.globalCleanup(ctx);
52
+ process.exit(1);
53
+ }
38
54
  }
39
55
 
40
- module.exports = { build };
56
+ function promisifyForkedProcess (fileName, ctx) {
57
+ const forkedProcess = fork(
58
+ path.resolve(__dirname, fileName),
59
+ [],
60
+ process.env.NODE_ENV === "dev" ? undefined : { silent: true },
61
+ );
62
+
63
+ forkedProcess.send({ ctx });
41
64
 
42
- // TODO: later we will validate configs e.g. yaml files with this function.
43
- function validationEmulation() {
44
- return new Promise((res, _rej) => {
45
- setTimeout(res, 4000);
65
+ return new Promise((resolve, reject) => {
66
+ forkedProcess.on("exit", (code) => {
67
+ if (code === 0) resolve();
68
+ });
69
+
70
+ forkedProcess.on("message", ({ error }) => {
71
+ if (!error) return;
72
+
73
+ reject(error);
46
74
  })
75
+ });
47
76
  }
77
+
78
+
79
+
@@ -0,0 +1,12 @@
1
+ const core = require("@embeddable.com/sdk-core/scripts");
2
+
3
+ process.on("message", async ({ ctx }) => {
4
+ try {
5
+ await core.buildTypes(ctx);
6
+ } catch (error) {
7
+ process.send({ error });
8
+ process.exit(1);
9
+ }
10
+
11
+ process.exit();
12
+ });
@@ -2,7 +2,7 @@ const fs = require("fs/promises");
2
2
  const path = require("path");
3
3
 
4
4
  async function cleanup(ctx) {
5
- await fs.rm(path.resolve(ctx.client.rootDir, 'embeddable-entry-point.jsx'));
5
+ await fs.rm(path.resolve(ctx.client.rootDir, ctx.outputOptions.componentsEntryPointFilename));
6
6
  }
7
7
 
8
- module.exports = { cleanup };
8
+ module.exports = { cleanup };
@@ -1,22 +1,24 @@
1
- const path = require('path');
1
+ const path = require("path");
2
2
 
3
- function createContext (pluginRoot, clientRoot) {
4
- return {
5
- plugin: {
6
- rootDir: pluginRoot,
7
- templatesDir: path.resolve(pluginRoot, 'templates'),
8
- },
9
- client: {
10
- rootDir: clientRoot,
11
- srcDir: path.resolve(clientRoot, 'src'), // TODO: should be specified via command parameters or from rc file.
12
- buildDir: path.resolve(clientRoot, '.embeddable-build'),
13
- },
14
- outputOptions: { // TODO: should be specified via command parameters or from rc file.
15
- fileName: 'embeddable-prepared',
16
- buildName: 'embeddable-prepared-build',
17
- typesEntryPointFilename: 'embeddable-types-entry-point.js',
18
- },
19
- };
3
+ function createContext(pluginRoot, clientRoot) {
4
+ return {
5
+ plugin: {
6
+ rootDir: pluginRoot,
7
+ templatesDir: path.resolve(pluginRoot, "templates"),
8
+ },
9
+ client: {
10
+ rootDir: clientRoot,
11
+ srcDir: path.resolve(clientRoot, "src"), // TODO: should be specified via command parameters or from rc file.
12
+ buildDir: path.resolve(clientRoot, ".embeddable-build"),
13
+ },
14
+ outputOptions: {
15
+ // TODO: should be specified via command parameters or from rc file.
16
+ fileName: "embeddable-prepared",
17
+ buildName: "embeddable-prepared-build",
18
+ componentsEntryPointFilename: "embeddable-entry-point.jsx",
19
+ typesEntryPointFilename: "embeddable-types-entry-point.js",
20
+ },
21
+ };
20
22
  }
21
23
 
22
24
  module.exports = { createContext };
@@ -1,69 +1,70 @@
1
1
  const fs = require("fs/promises");
2
2
  const path = require("path");
3
3
  const vite = require("vite");
4
- const viteReactPlugin = require('@vitejs/plugin-react');
4
+ const viteReactPlugin = require("@vitejs/plugin-react");
5
5
  const core = require("@embeddable.com/sdk-core/scripts");
6
6
 
7
- process.on('message', async ({ ctx }) => {
8
- await generate(ctx);
9
-
10
- process.exit();
11
- });
12
-
13
7
  const EMB_FILE_REGEX = /^(.*)(?<!\.type|\.options)\.emb\.[jt]s$/;
14
8
 
15
9
  async function generate(ctx) {
16
- const filesList = await core.findEmbFiles(ctx.client.srcDir, EMB_FILE_REGEX);
10
+ const filesList = await core.findEmbFiles(ctx.client.srcDir, EMB_FILE_REGEX);
17
11
 
18
- await injectImports(ctx, filesList);
12
+ await injectImports(ctx, filesList);
19
13
 
20
- await runViteBuild(ctx);
14
+ await runViteBuild(ctx);
21
15
 
22
- await runCoreBuild(ctx);
16
+ await runCoreBuild(ctx);
23
17
  }
24
18
 
25
19
  module.exports = { generate };
26
20
 
27
-
28
21
  async function runCoreBuild(ctx) {
29
- await core.build({
30
- outDir: ctx.outputOptions.buildName,
31
- renderFunctionFileName: ctx.outputOptions.fileName
32
- });
22
+ await core.build({
23
+ outDir: ctx.outputOptions.buildName,
24
+ renderFunctionFileName: ctx.outputOptions.fileName,
25
+ });
33
26
  }
34
27
 
35
28
  async function runViteBuild(ctx) {
36
- process.chdir(ctx.client.rootDir);
37
-
38
- await vite.build({
39
- plugins: [viteReactPlugin()],
40
- build: {
41
- lib: {
42
- entry: './embeddable-entry-point.jsx',
43
- formats: ['es'],
44
- fileName: ctx.outputOptions.fileName
45
- },
46
- outDir: `.embeddable-build/${ctx.outputOptions.buildName}`
47
- },
48
- define: { 'process.env.NODE_ENV': '"production"' }
49
- });
29
+ process.chdir(ctx.client.rootDir);
30
+
31
+ await vite.build({
32
+ plugins: [viteReactPlugin()],
33
+ build: {
34
+ lib: {
35
+ entry: `./${ctx.outputOptions.componentsEntryPointFilename}`,
36
+ formats: ["es"],
37
+ fileName: ctx.outputOptions.fileName,
38
+ },
39
+ outDir: `.embeddable-build/${ctx.outputOptions.buildName}`,
40
+ },
41
+ define: { "process.env.NODE_ENV": '"production"' },
42
+ });
50
43
  }
51
44
 
52
-
53
- const REPLACE_TOKEN = '{{LAZY_IMPORTS}}';
45
+ const REPLACE_TOKEN = "{{LAZY_IMPORTS}}";
54
46
 
55
47
  async function injectImports(ctx, filesList) {
56
- const imports = filesList.map(([fileName, filePath]) =>
57
- `\t${fileName}: React.lazy(() => import('./${path.relative(ctx.client.rootDir, filePath)}'))`
58
- ).join(',\n');
59
-
60
- const content = await fs.readFile(
61
- path.resolve(ctx.plugin.templatesDir, 'embeddable-entry-point.jsx.template'),
62
- 'utf8'
63
- );
64
-
65
- await fs.writeFile(
66
- path.resolve(ctx.client.rootDir, 'embeddable-entry-point.jsx'),
67
- content.replace(REPLACE_TOKEN, imports)
68
- );
48
+ const imports = filesList
49
+ .map(
50
+ ([fileName, filePath]) =>
51
+ `\t${fileName}: React.lazy(() => import('./${path.relative(
52
+ ctx.client.rootDir,
53
+ filePath,
54
+ )}'))`,
55
+ )
56
+ .join(",\n");
57
+
58
+ const content = await fs.readFile(
59
+ path.resolve(
60
+ ctx.plugin.templatesDir,
61
+ `${ctx.outputOptions.componentsEntryPointFilename}.template`,
62
+ ),
63
+ "utf8",
64
+ );
65
+
66
+ await fs.writeFile(
67
+ path.resolve(ctx.client.rootDir, ctx.outputOptions.componentsEntryPointFilename),
68
+ content.replace(REPLACE_TOKEN, imports),
69
+ );
69
70
  }
@@ -0,0 +1,14 @@
1
+ const { generate } = require("./generate");
2
+ const { cleanup } = require("./cleanup");
3
+
4
+ process.on("message", async ({ ctx }) => {
5
+ try {
6
+ await generate(ctx);
7
+ await cleanup(ctx);
8
+ } catch (error) {
9
+ process.send({ error });
10
+ process.exit(1);
11
+ }
12
+
13
+ process.exit();
14
+ });
@@ -1,13 +1,12 @@
1
1
  const fsSync = require("fs");
2
2
  const fs = require("fs/promises");
3
3
 
4
- async function prepare (ctx) {
5
- await removeIfExists(ctx.client.buildDir);
4
+ async function prepare(ctx) {
5
+ await removeIfExists(ctx.client.buildDir);
6
6
  }
7
7
 
8
- module.exports = { prepare }
8
+ module.exports = { prepare };
9
9
 
10
10
  async function removeIfExists(buildDir) {
11
- if (fsSync.existsSync(buildDir)) await fs.rm(buildDir, { recursive: true });
11
+ if (fsSync.existsSync(buildDir)) await fs.rm(buildDir, { recursive: true });
12
12
  }
13
-