@embeddable.com/sdk-react 1.0.0 → 2.0.1

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.
package/lib/index.umd.js DELETED
@@ -1,280 +0,0 @@
1
- (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.embeddableSdkReact = {}));
5
- })(this, (function (exports) { 'use strict';
6
-
7
- /******************************************************************************
8
- Copyright (c) Microsoft Corporation.
9
-
10
- Permission to use, copy, modify, and/or distribute this software for any
11
- purpose with or without fee is hereby granted.
12
-
13
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
14
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
15
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
16
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
17
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
18
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
19
- PERFORMANCE OF THIS SOFTWARE.
20
- ***************************************************************************** */
21
- /* global Reflect, Promise, SuppressedError, Symbol */
22
-
23
-
24
- var __assign = function() {
25
- __assign = Object.assign || function __assign(t) {
26
- for (var s, i = 1, n = arguments.length; i < n; i++) {
27
- s = arguments[i];
28
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
29
- }
30
- return t;
31
- };
32
- return __assign.apply(this, arguments);
33
- };
34
-
35
- function __rest(s, e) {
36
- var t = {};
37
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
38
- t[p] = s[p];
39
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
40
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
41
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
42
- t[p[i]] = s[p[i]];
43
- }
44
- return t;
45
- }
46
-
47
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
48
- var e = new Error(message);
49
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
50
- };
51
-
52
- var react = {exports: {}};
53
-
54
- var react_production_min = {};
55
-
56
- /**
57
- * @license React
58
- * react.production.min.js
59
- *
60
- * Copyright (c) Facebook, Inc. and its affiliates.
61
- *
62
- * This source code is licensed under the MIT license found in the
63
- * LICENSE file in the root directory of this source tree.
64
- */
65
- var l=Symbol.for("react.element"),n=Symbol.for("react.portal"),p=Symbol.for("react.fragment"),q=Symbol.for("react.strict_mode"),r=Symbol.for("react.profiler"),t=Symbol.for("react.provider"),u=Symbol.for("react.context"),v=Symbol.for("react.forward_ref"),w=Symbol.for("react.suspense"),x=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),z=Symbol.iterator;function A(a){if(null===a||"object"!==typeof a)return null;a=z&&a[z]||a["@@iterator"];return "function"===typeof a?a:null}
66
- var B={isMounted:function(){return !1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,D={};function E(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B;}E.prototype.isReactComponent={};
67
- E.prototype.setState=function(a,b){if("object"!==typeof a&&"function"!==typeof a&&null!=a)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,a,b,"setState");};E.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate");};function F(){}F.prototype=E.prototype;function G(a,b,e){this.props=a;this.context=b;this.refs=D;this.updater=e||B;}var H=G.prototype=new F;
68
- H.constructor=G;C(H,E.prototype);H.isPureReactComponent=!0;var I=Array.isArray,J=Object.prototype.hasOwnProperty,K={current:null},L={key:!0,ref:!0,__self:!0,__source:!0};
69
- function M(a,b,e){var d,c={},k=null,h=null;if(null!=b)for(d in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=""+b.key),b)J.call(b,d)&&!L.hasOwnProperty(d)&&(c[d]=b[d]);var g=arguments.length-2;if(1===g)c.children=e;else if(1<g){for(var f=Array(g),m=0;m<g;m++)f[m]=arguments[m+2];c.children=f;}if(a&&a.defaultProps)for(d in g=a.defaultProps,g)void 0===c[d]&&(c[d]=g[d]);return {$$typeof:l,type:a,key:k,ref:h,props:c,_owner:K.current}}
70
- function N(a,b){return {$$typeof:l,type:a.type,key:b,ref:a.ref,props:a.props,_owner:a._owner}}function O(a){return "object"===typeof a&&null!==a&&a.$$typeof===l}function escape(a){var b={"=":"=0",":":"=2"};return "$"+a.replace(/[=:]/g,function(a){return b[a]})}var P=/\/+/g;function Q(a,b){return "object"===typeof a&&null!==a&&null!=a.key?escape(""+a.key):b.toString(36)}
71
- function R(a,b,e,d,c){var k=typeof a;if("undefined"===k||"boolean"===k)a=null;var h=!1;if(null===a)h=!0;else switch(k){case "string":case "number":h=!0;break;case "object":switch(a.$$typeof){case l:case n:h=!0;}}if(h)return h=a,c=c(h),a=""===d?"."+Q(h,0):d,I(c)?(e="",null!=a&&(e=a.replace(P,"$&/")+"/"),R(c,b,e,"",function(a){return a})):null!=c&&(O(c)&&(c=N(c,e+(!c.key||h&&h.key===c.key?"":(""+c.key).replace(P,"$&/")+"/")+a)),b.push(c)),1;h=0;d=""===d?".":d+":";if(I(a))for(var g=0;g<a.length;g++){k=
72
- a[g];var f=d+Q(k,g);h+=R(k,b,e,f,c);}else if(f=A(a),"function"===typeof f)for(a=f.call(a),g=0;!(k=a.next()).done;)k=k.value,f=d+Q(k,g++),h+=R(k,b,e,f,c);else if("object"===k)throw b=String(a),Error("Objects are not valid as a React child (found: "+("[object Object]"===b?"object with keys {"+Object.keys(a).join(", ")+"}":b)+"). If you meant to render a collection of children, use an array instead.");return h}
73
- function S(a,b,e){if(null==a)return a;var d=[],c=0;R(a,d,"","",function(a){return b.call(e,a,c++)});return d}function T(a){if(-1===a._status){var b=a._result;b=b();b.then(function(b){if(0===a._status||-1===a._status)a._status=1,a._result=b;},function(b){if(0===a._status||-1===a._status)a._status=2,a._result=b;});-1===a._status&&(a._status=0,a._result=b);}if(1===a._status)return a._result.default;throw a._result;}
74
- var U={current:null},V={transition:null},W={ReactCurrentDispatcher:U,ReactCurrentBatchConfig:V,ReactCurrentOwner:K};react_production_min.Children={map:S,forEach:function(a,b,e){S(a,function(){b.apply(this,arguments);},e);},count:function(a){var b=0;S(a,function(){b++;});return b},toArray:function(a){return S(a,function(a){return a})||[]},only:function(a){if(!O(a))throw Error("React.Children.only expected to receive a single React element child.");return a}};react_production_min.Component=E;react_production_min.Fragment=p;
75
- react_production_min.Profiler=r;react_production_min.PureComponent=G;react_production_min.StrictMode=q;react_production_min.Suspense=w;react_production_min.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=W;
76
- react_production_min.cloneElement=function(a,b,e){if(null===a||void 0===a)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+a+".");var d=C({},a.props),c=a.key,k=a.ref,h=a._owner;if(null!=b){void 0!==b.ref&&(k=b.ref,h=K.current);void 0!==b.key&&(c=""+b.key);if(a.type&&a.type.defaultProps)var g=a.type.defaultProps;for(f in b)J.call(b,f)&&!L.hasOwnProperty(f)&&(d[f]=void 0===b[f]&&void 0!==g?g[f]:b[f]);}var f=arguments.length-2;if(1===f)d.children=e;else if(1<f){g=Array(f);
77
- for(var m=0;m<f;m++)g[m]=arguments[m+2];d.children=g;}return {$$typeof:l,type:a.type,key:c,ref:k,props:d,_owner:h}};react_production_min.createContext=function(a){a={$$typeof:u,_currentValue:a,_currentValue2:a,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null};a.Provider={$$typeof:t,_context:a};return a.Consumer=a};react_production_min.createElement=M;react_production_min.createFactory=function(a){var b=M.bind(null,a);b.type=a;return b};react_production_min.createRef=function(){return {current:null}};
78
- react_production_min.forwardRef=function(a){return {$$typeof:v,render:a}};react_production_min.isValidElement=O;react_production_min.lazy=function(a){return {$$typeof:y,_payload:{_status:-1,_result:a},_init:T}};react_production_min.memo=function(a,b){return {$$typeof:x,type:a,compare:void 0===b?null:b}};react_production_min.startTransition=function(a){var b=V.transition;V.transition={};try{a();}finally{V.transition=b;}};react_production_min.unstable_act=function(){throw Error("act(...) is not supported in production builds of React.");};
79
- react_production_min.useCallback=function(a,b){return U.current.useCallback(a,b)};react_production_min.useContext=function(a){return U.current.useContext(a)};react_production_min.useDebugValue=function(){};react_production_min.useDeferredValue=function(a){return U.current.useDeferredValue(a)};react_production_min.useEffect=function(a,b){return U.current.useEffect(a,b)};react_production_min.useId=function(){return U.current.useId()};react_production_min.useImperativeHandle=function(a,b,e){return U.current.useImperativeHandle(a,b,e)};
80
- react_production_min.useInsertionEffect=function(a,b){return U.current.useInsertionEffect(a,b)};react_production_min.useLayoutEffect=function(a,b){return U.current.useLayoutEffect(a,b)};react_production_min.useMemo=function(a,b){return U.current.useMemo(a,b)};react_production_min.useReducer=function(a,b,e){return U.current.useReducer(a,b,e)};react_production_min.useRef=function(a){return U.current.useRef(a)};react_production_min.useState=function(a){return U.current.useState(a)};react_production_min.useSyncExternalStore=function(a,b,e){return U.current.useSyncExternalStore(a,b,e)};
81
- react_production_min.useTransition=function(){return U.current.useTransition()};react_production_min.version="18.2.0";
82
-
83
- {
84
- react.exports = react_production_min;
85
- }
86
-
87
- var reactExports = react.exports;
88
-
89
- var isLoadDataParams = function (ldp) {
90
- return typeof ldp === "object" && "requestParams" in ldp && "dataLoader" in ldp;
91
- };
92
-
93
- var UPDATE_VALUE_EVENT = "embeddable:value:changed";
94
- var setValue = function (value, componentId, eventName) {
95
- var event = new CustomEvent(UPDATE_VALUE_EVENT, {
96
- bubbles: false,
97
- detail: {
98
- componentId: componentId,
99
- value: value,
100
- eventName: eventName,
101
- },
102
- });
103
- window.dispatchEvent(event);
104
- };
105
-
106
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
107
- var e = new Error(message);
108
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
109
- };
110
-
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";
124
- var ReducerActionTypes = {
125
- loading: "loading",
126
- error: "error",
127
- data: "data",
128
- };
129
- var reducer = function (state, action) {
130
- var _a, _b, _c;
131
- switch (action.type) {
132
- case ReducerActionTypes.loading: {
133
- return __assign(__assign({}, state), (_a = {}, _a[action.inputName] = {
134
- data: state[action.inputName].data,
135
- isLoading: true,
136
- }, _a));
137
- }
138
- case ReducerActionTypes.data: {
139
- return __assign(__assign({}, state), (_b = {}, _b[action.inputName] = { isLoading: false, data: action.payload }, _b));
140
- }
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));
146
- }
147
- }
148
- return state;
149
- };
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
- };
156
- function embedComponent(InnerComponent, config) {
157
- var _a;
158
- if (config === void 0) { config = {}; }
159
- function EmbeddableWrapper(_a) {
160
- var propsUpdateListener = _a.propsUpdateListener, props = __rest(_a, ["propsUpdateListener"]);
161
- var _b = reactExports.useState(props), propsProxy = _b[0], setProps = _b[1];
162
- var embeddableState = reactExports.useState();
163
- var componentId = props.componentId;
164
- var loadDataResultEventName = "".concat(LOAD_DATA_RESULT_EVENT_NAME, ":").concat(componentId);
165
- var propsUpdateEventHandler = function (_a) {
166
- var detail = _a.detail;
167
- return setProps(detail);
168
- };
169
- reactExports.useEffect(function () {
170
- propsUpdateListener.addEventListener(UPDATE_PROPS_EVENT_NAME, propsUpdateEventHandler);
171
- return function () {
172
- return propsUpdateListener.removeEventListener(UPDATE_PROPS_EVENT_NAME, propsUpdateEventHandler);
173
- };
174
- }, []);
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
- };
195
- var reloadDataset = function (inputName, params) {
196
- dispatch({ type: ReducerActionTypes.loading, inputName: 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
- }
208
- };
209
- var variableChangedEventHandler = function (_a) {
210
- var detail = _a.detail;
211
- Object.entries(dataLoaders)
212
- .filter(function (_a) {
213
- _a[0]; var params = _a[1];
214
- return params.requestParams.from.datasetId === detail.datasetId;
215
- })
216
- .forEach(function (_a) {
217
- var inputName = _a[0], params = _a[1];
218
- return reloadDataset(inputName, params);
219
- });
220
- };
221
- reactExports.useEffect(function () {
222
- Object.entries(dataLoaders).forEach(function (_a) {
223
- var inputName = _a[0], params = _a[1];
224
- return reloadDataset(inputName, params);
225
- });
226
- window.addEventListener(RELOAD_DATASET_EVENT_NAME, variableChangedEventHandler);
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
- };
238
- var events = config === null || config === void 0 ? void 0 : config.events;
239
- var eventProps = {};
240
- if (events) {
241
- var _loop_1 = function (event_1) {
242
- if (events.hasOwnProperty(event_1)) {
243
- var eventFunction_1 = events[event_1];
244
- eventProps[event_1] = function (value) {
245
- return createEvent(eventFunction_1(value), event_1);
246
- };
247
- }
248
- };
249
- for (var event_1 in events) {
250
- _loop_1(event_1);
251
- }
252
- }
253
- return (reactExports.createElement(EmbeddableStateContext.Provider, { value: embeddableState },
254
- reactExports.createElement(InnerComponent, __assign({}, extendedProps, eventProps, loadersState))));
255
- }
256
- EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : "Component", ")");
257
- return EmbeddableWrapper;
258
- }
259
-
260
- function embedControl(InnerComponent, config) {
261
- var _a;
262
- function EmbeddableWrapper(props) {
263
- var _a, _b;
264
- var componentId = props.componentId, initialValue = props.initialValue;
265
- var _c = reactExports.useState(initialValue), componentState = _c[0], setComponentState = _c[1];
266
- var setter = function (value) {
267
- setComponentState(value);
268
- setValue(value, componentId);
269
- };
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 : {}))));
271
- }
272
- EmbeddableWrapper.displayName = "embedded(".concat((_a = InnerComponent.displayName) !== null && _a !== void 0 ? _a : "Editor", ")");
273
- return EmbeddableWrapper;
274
- }
275
-
276
- exports.embedComponent = embedComponent;
277
- exports.embedControl = embedControl;
278
- exports.useEmbeddableState = useEmbeddableState;
279
-
280
- }));
package/scripts/build.js DELETED
@@ -1,79 +0,0 @@
1
- const path = require("path");
2
- const { fork } = require("child_process");
3
- const oraP = import("ora");
4
- const core = require("@embeddable.com/sdk-core/scripts");
5
-
6
- const { createContext } = require("./createContext");
7
- const { prepare } = require("./prepare");
8
-
9
- let ora;
10
-
11
- async function build() {
12
- ora = (await oraP).default;
13
-
14
- const spinnerPrepare = ora("preparing...").start();
15
-
16
- const ctx = createContext(path.resolve(__dirname, ".."), process.cwd());
17
-
18
- await core.validate(ctx);
19
-
20
- await prepare(ctx);
21
- spinnerPrepare.succeed("preparation competed");
22
-
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
-
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
- }
39
-
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
- }
54
- }
55
-
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 });
64
-
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);
74
- })
75
- });
76
- }
77
-
78
-
79
-
@@ -1,12 +0,0 @@
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
- });
@@ -1,8 +0,0 @@
1
- const fs = require("fs/promises");
2
- const path = require("path");
3
-
4
- async function cleanup(ctx) {
5
- await fs.rm(path.resolve(ctx.client.rootDir, ctx.outputOptions.componentsEntryPointFilename));
6
- }
7
-
8
- module.exports = { cleanup };
@@ -1,24 +0,0 @@
1
- const path = require("path");
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: {
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
- };
22
- }
23
-
24
- module.exports = { createContext };
@@ -1,70 +0,0 @@
1
- const fs = require("fs/promises");
2
- const path = require("path");
3
- const vite = require("vite");
4
- const viteReactPlugin = require("@vitejs/plugin-react");
5
- const core = require("@embeddable.com/sdk-core/scripts");
6
-
7
- const EMB_FILE_REGEX = /^(.*)(?<!\.type|\.options)\.emb\.[jt]s$/;
8
-
9
- async function generate(ctx) {
10
- const filesList = await core.findEmbFiles(ctx.client.srcDir, EMB_FILE_REGEX);
11
-
12
- await injectImports(ctx, filesList);
13
-
14
- await runViteBuild(ctx);
15
-
16
- await runCoreBuild(ctx);
17
- }
18
-
19
- module.exports = { generate };
20
-
21
- async function runCoreBuild(ctx) {
22
- await core.build({
23
- outDir: ctx.outputOptions.buildName,
24
- renderFunctionFileName: ctx.outputOptions.fileName,
25
- });
26
- }
27
-
28
- async function runViteBuild(ctx) {
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
- });
43
- }
44
-
45
- const REPLACE_TOKEN = "{{LAZY_IMPORTS}}";
46
-
47
- async function injectImports(ctx, filesList) {
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
- );
70
- }
@@ -1,14 +0,0 @@
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,12 +0,0 @@
1
- const fsSync = require("fs");
2
- const fs = require("fs/promises");
3
-
4
- async function prepare(ctx) {
5
- await removeIfExists(ctx.client.buildDir);
6
- }
7
-
8
- module.exports = { prepare };
9
-
10
- async function removeIfExists(buildDir) {
11
- if (fsSync.existsSync(buildDir)) await fs.rm(buildDir, { recursive: true });
12
- }