@embeddable.com/sdk-react 4.0.4 → 4.0.5-next.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.
package/lib/index.js DELETED
@@ -1,1215 +0,0 @@
1
- 'use strict';
2
-
3
- var path = require('node:path');
4
- var fs$2 = require('fs/promises');
5
- var path$1 = require('path');
6
- var vite = require('vite');
7
- var ora = require('ora');
8
- var viteReactPlugin = require('@vitejs/plugin-react');
9
- var fs = require('node:fs/promises');
10
- var url = require('node:url');
11
- var globalRegistrator = require('@happy-dom/global-registrator');
12
- require('node:child_process');
13
- var crypto = require('node:crypto');
14
- var zod = require('zod');
15
- var parser = require('@babel/parser');
16
- var traverse = require('@babel/traverse');
17
- var fs$1 = require('fs');
18
-
19
- function _interopNamespaceDefault(e) {
20
- var n = Object.create(null);
21
- if (e) {
22
- Object.keys(e).forEach(function (k) {
23
- if (k !== 'default') {
24
- var d = Object.getOwnPropertyDescriptor(e, k);
25
- Object.defineProperty(n, k, d.get ? d : {
26
- enumerable: true,
27
- get: function () { return e[k]; }
28
- });
29
- }
30
- });
31
- }
32
- n.default = e;
33
- return Object.freeze(n);
34
- }
35
-
36
- var path__namespace$1 = /*#__PURE__*/_interopNamespaceDefault(path);
37
- var fs__namespace$2 = /*#__PURE__*/_interopNamespaceDefault(fs$2);
38
- var path__namespace = /*#__PURE__*/_interopNamespaceDefault(path$1);
39
- var vite__namespace = /*#__PURE__*/_interopNamespaceDefault(vite);
40
- var fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs);
41
- var url__namespace = /*#__PURE__*/_interopNamespaceDefault(url);
42
- var crypto__namespace = /*#__PURE__*/_interopNamespaceDefault(crypto);
43
- var fs__namespace$1 = /*#__PURE__*/_interopNamespaceDefault(fs$1);
44
-
45
- var createContext = (pluginRoot, coreCtx) => {
46
- coreCtx["sdk-react"] = {
47
- rootDir: pluginRoot,
48
- templatesDir: path.resolve(pluginRoot, "templates"),
49
- outputOptions: {
50
- fileName: "embeddable-prepared",
51
- buildName: "embeddable-prepared-build",
52
- componentsEntryPointFilename: "embeddable-entry-point.jsx",
53
- },
54
- };
55
- };
56
-
57
- globalRegistrator.GlobalRegistrator.register({
58
- url: "http://localhost:3000",
59
- width: 1920,
60
- height: 1080,
61
- });
62
- const loadComponentMeta = async (moduleId) => {
63
- const module = await import(url__namespace.pathToFileURL(moduleId).href);
64
- return module.meta;
65
- };
66
-
67
- var findFiles = async (initialSrcDir, regex) => {
68
- const filesList = [];
69
- async function findFilesRec(srcDir) {
70
- const allFiles = await fs.readdir(srcDir);
71
- for (const file of allFiles) {
72
- const filePath = path.join(srcDir, file);
73
- const status = await fs.lstat(filePath);
74
- if (status.isDirectory()) {
75
- await findFilesRec(filePath);
76
- }
77
- const fileName = file.match(regex);
78
- if (fileName) {
79
- filesList.push([fileName[1], filePath]);
80
- }
81
- }
82
- }
83
- await findFilesRec(initialSrcDir);
84
- return filesList;
85
- };
86
-
87
- var util;
88
- (function (util) {
89
- util.assertEqual = (val) => val;
90
- function assertIs(_arg) { }
91
- util.assertIs = assertIs;
92
- function assertNever(_x) {
93
- throw new Error();
94
- }
95
- util.assertNever = assertNever;
96
- util.arrayToEnum = (items) => {
97
- const obj = {};
98
- for (const item of items) {
99
- obj[item] = item;
100
- }
101
- return obj;
102
- };
103
- util.getValidEnumValues = (obj) => {
104
- const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number");
105
- const filtered = {};
106
- for (const k of validKeys) {
107
- filtered[k] = obj[k];
108
- }
109
- return util.objectValues(filtered);
110
- };
111
- util.objectValues = (obj) => {
112
- return util.objectKeys(obj).map(function (e) {
113
- return obj[e];
114
- });
115
- };
116
- util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban
117
- ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban
118
- : (object) => {
119
- const keys = [];
120
- for (const key in object) {
121
- if (Object.prototype.hasOwnProperty.call(object, key)) {
122
- keys.push(key);
123
- }
124
- }
125
- return keys;
126
- };
127
- util.find = (arr, checker) => {
128
- for (const item of arr) {
129
- if (checker(item))
130
- return item;
131
- }
132
- return undefined;
133
- };
134
- util.isInteger = typeof Number.isInteger === "function"
135
- ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban
136
- : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val;
137
- function joinValues(array, separator = " | ") {
138
- return array
139
- .map((val) => (typeof val === "string" ? `'${val}'` : val))
140
- .join(separator);
141
- }
142
- util.joinValues = joinValues;
143
- util.jsonStringifyReplacer = (_, value) => {
144
- if (typeof value === "bigint") {
145
- return value.toString();
146
- }
147
- return value;
148
- };
149
- })(util || (util = {}));
150
- var objectUtil;
151
- (function (objectUtil) {
152
- objectUtil.mergeShapes = (first, second) => {
153
- return {
154
- ...first,
155
- ...second, // second overwrites first
156
- };
157
- };
158
- })(objectUtil || (objectUtil = {}));
159
- util.arrayToEnum([
160
- "string",
161
- "nan",
162
- "number",
163
- "integer",
164
- "float",
165
- "boolean",
166
- "date",
167
- "bigint",
168
- "symbol",
169
- "function",
170
- "undefined",
171
- "null",
172
- "array",
173
- "object",
174
- "unknown",
175
- "promise",
176
- "void",
177
- "never",
178
- "map",
179
- "set",
180
- ]);
181
-
182
- const ZodIssueCode = util.arrayToEnum([
183
- "invalid_type",
184
- "invalid_literal",
185
- "custom",
186
- "invalid_union",
187
- "invalid_union_discriminator",
188
- "invalid_enum_value",
189
- "unrecognized_keys",
190
- "invalid_arguments",
191
- "invalid_return_type",
192
- "invalid_date",
193
- "invalid_string",
194
- "too_small",
195
- "too_big",
196
- "invalid_intersection_types",
197
- "not_multiple_of",
198
- "not_finite",
199
- ]);
200
- class ZodError extends Error {
201
- constructor(issues) {
202
- super();
203
- this.issues = [];
204
- this.addIssue = (sub) => {
205
- this.issues = [...this.issues, sub];
206
- };
207
- this.addIssues = (subs = []) => {
208
- this.issues = [...this.issues, ...subs];
209
- };
210
- const actualProto = new.target.prototype;
211
- if (Object.setPrototypeOf) {
212
- // eslint-disable-next-line ban/ban
213
- Object.setPrototypeOf(this, actualProto);
214
- }
215
- else {
216
- this.__proto__ = actualProto;
217
- }
218
- this.name = "ZodError";
219
- this.issues = issues;
220
- }
221
- get errors() {
222
- return this.issues;
223
- }
224
- format(_mapper) {
225
- const mapper = _mapper ||
226
- function (issue) {
227
- return issue.message;
228
- };
229
- const fieldErrors = { _errors: [] };
230
- const processError = (error) => {
231
- for (const issue of error.issues) {
232
- if (issue.code === "invalid_union") {
233
- issue.unionErrors.map(processError);
234
- }
235
- else if (issue.code === "invalid_return_type") {
236
- processError(issue.returnTypeError);
237
- }
238
- else if (issue.code === "invalid_arguments") {
239
- processError(issue.argumentsError);
240
- }
241
- else if (issue.path.length === 0) {
242
- fieldErrors._errors.push(mapper(issue));
243
- }
244
- else {
245
- let curr = fieldErrors;
246
- let i = 0;
247
- while (i < issue.path.length) {
248
- const el = issue.path[i];
249
- const terminal = i === issue.path.length - 1;
250
- if (!terminal) {
251
- curr[el] = curr[el] || { _errors: [] };
252
- // if (typeof el === "string") {
253
- // curr[el] = curr[el] || { _errors: [] };
254
- // } else if (typeof el === "number") {
255
- // const errorArray: any = [];
256
- // errorArray._errors = [];
257
- // curr[el] = curr[el] || errorArray;
258
- // }
259
- }
260
- else {
261
- curr[el] = curr[el] || { _errors: [] };
262
- curr[el]._errors.push(mapper(issue));
263
- }
264
- curr = curr[el];
265
- i++;
266
- }
267
- }
268
- }
269
- };
270
- processError(this);
271
- return fieldErrors;
272
- }
273
- static assert(value) {
274
- if (!(value instanceof ZodError)) {
275
- throw new Error(`Not a ZodError: ${value}`);
276
- }
277
- }
278
- toString() {
279
- return this.message;
280
- }
281
- get message() {
282
- return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
283
- }
284
- get isEmpty() {
285
- return this.issues.length === 0;
286
- }
287
- flatten(mapper = (issue) => issue.message) {
288
- const fieldErrors = {};
289
- const formErrors = [];
290
- for (const sub of this.issues) {
291
- if (sub.path.length > 0) {
292
- fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
293
- fieldErrors[sub.path[0]].push(mapper(sub));
294
- }
295
- else {
296
- formErrors.push(mapper(sub));
297
- }
298
- }
299
- return { formErrors, fieldErrors };
300
- }
301
- get formErrors() {
302
- return this.flatten();
303
- }
304
- }
305
- ZodError.create = (issues) => {
306
- const error = new ZodError(issues);
307
- return error;
308
- };
309
-
310
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
311
- var e = new Error(message);
312
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
313
- };
314
-
315
- var errorUtil;
316
- (function (errorUtil) {
317
- errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
318
- errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === undefined ? undefined : message.message;
319
- })(errorUtil || (errorUtil = {}));
320
- var ZodFirstPartyTypeKind;
321
- (function (ZodFirstPartyTypeKind) {
322
- ZodFirstPartyTypeKind["ZodString"] = "ZodString";
323
- ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
324
- ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
325
- ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
326
- ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
327
- ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
328
- ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
329
- ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
330
- ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
331
- ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
332
- ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
333
- ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
334
- ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
335
- ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
336
- ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
337
- ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
338
- ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
339
- ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
340
- ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
341
- ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
342
- ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
343
- ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
344
- ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
345
- ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
346
- ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
347
- ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
348
- ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
349
- ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
350
- ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
351
- ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
352
- ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
353
- ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
354
- ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
355
- ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
356
- ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
357
- ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
358
- })(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
359
-
360
- const errorFormatter = (issues) => {
361
- const errors = [];
362
- for (let issue of issues) {
363
- if (issue.code === ZodIssueCode.invalid_union && issue.unionErrors.length) {
364
- const error = issue.unionErrors[issue.unionErrors.length - 1];
365
- issue = error.issues[error.issues.length - 1];
366
- }
367
- const path = formatErrorPath(issue.path);
368
- const message = issue.message;
369
- errors.push(`"${path}": ${message}`);
370
- }
371
- return errors;
372
- };
373
- const formatErrorPath = (path) => {
374
- let formatted = "";
375
- for (const pathElement of path) {
376
- if (formatted.length === 0) {
377
- formatted = `${pathElement}`;
378
- }
379
- else {
380
- formatted +=
381
- typeof pathElement === "number"
382
- ? `[${pathElement}]`
383
- : `.${pathElement}`;
384
- }
385
- }
386
- return formatted;
387
- };
388
-
389
- /**
390
- * Get the hash of the content string. It returns the first 5 characters of the hash
391
- * Example: getContentHash("Hello World")
392
- * @param contentString The content string to hash
393
- * @returns
394
- */
395
- const getContentHash = (contentString) => {
396
- return crypto__namespace
397
- .createHash("md5")
398
- .update(contentString)
399
- .digest("hex")
400
- .substring(0, 5);
401
- };
402
-
403
- /**
404
- * TODO: for some reason code from @embeddable.com/extract-components-config
405
- * is being cached. Thus we use this code duplication in place. Please investigate and fix.
406
- */
407
- var extractComponentsConfigPlugin = ({ globalKey, outputDir, fileName, componentFileRegex, isDev = false, searchEntry = "", }) => {
408
- let configs = [];
409
- return {
410
- name: "extract-components-config",
411
- moduleParsed: async (moduleInfo) => {
412
- var _a;
413
- if (componentFileRegex.test(moduleInfo.id) &&
414
- ((_a = moduleInfo.code) === null || _a === undefined ? undefined : _a.includes(searchEntry))) {
415
- try {
416
- const meta = await loadComponentMeta(moduleInfo.id);
417
- const configJSON = JSON.stringify(meta, (_key, value) => typeof value === "object" &&
418
- value !== null &&
419
- "__embeddableType" in value
420
- ? value.toString()
421
- : value);
422
- configs.push(configJSON);
423
- }
424
- catch (error) {
425
- console.log("Error parsing component meta: ", moduleInfo.id);
426
- console.error(error);
427
- }
428
- }
429
- },
430
- buildEnd: async () => {
431
- const template = `
432
- globalThis.__EMBEDDABLE__ = globalThis.__EMBEDDABLE__ || {};
433
- globalThis.__EMBEDDABLE__.${globalKey} = globalThis.__EMBEDDABLE__.${globalKey} || [
434
- __PLACEHOLDER__
435
- ];
436
- `;
437
- // sort to make sure the hash is consistent
438
- configs.sort((a, b) => a.localeCompare(b));
439
- const contentString = configs.filter(Boolean).join(",\n");
440
- let newFileName = fileName;
441
- if (!isDev) {
442
- const fileHash = getContentHash(contentString);
443
- const fileHashExtention = `-${fileHash}.js`;
444
- newFileName = `${fileName.replace(".js", fileHashExtention)}`;
445
- }
446
- await fs__namespace.writeFile(`${outputDir}/${newFileName}`, template.replace("__PLACEHOLDER__", contentString));
447
- configs = [];
448
- },
449
- };
450
- };
451
-
452
- /******************************************************************************
453
- Copyright (c) Microsoft Corporation.
454
-
455
- Permission to use, copy, modify, and/or distribute this software for any
456
- purpose with or without fee is hereby granted.
457
-
458
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
459
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
460
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
461
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
462
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
463
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
464
- PERFORMANCE OF THIS SOFTWARE.
465
- ***************************************************************************** */
466
- /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
467
-
468
-
469
- var __assign = function() {
470
- __assign = Object.assign || function __assign(t) {
471
- for (var s, i = 1, n = arguments.length; i < n; i++) {
472
- s = arguments[i];
473
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
474
- }
475
- return t;
476
- };
477
- return __assign.apply(this, arguments);
478
- };
479
-
480
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
481
- var e = new Error(message);
482
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
483
- };
484
-
485
- var DEFAULT_LOCALE = "en-US";
486
- var createBuiltInType = function (name, typeConfig) {
487
- if (typeConfig === undefined) { typeConfig = {}; }
488
- return ({
489
- __embeddableType: "built-in",
490
- toString: function () { return name; },
491
- typeConfig: __assign({ label: name, optionLabel: function () { return name; } }, typeConfig),
492
- });
493
- };
494
- var STRING = "string";
495
- var NUMBER = "number";
496
- var BOOLEAN = "boolean";
497
- var TIME = "time";
498
- var TIME_RANGE = "timeRange";
499
- var GRANULARITY = "granularity";
500
- var DATASET = "dataset";
501
- var MEASURE = "measure";
502
- var DIMENSION = "dimension";
503
- var DIMENSION_OR_MEASURE = "dimensionOrMeasure";
504
- var ALL_NATIVE_TYPES = [
505
- STRING,
506
- NUMBER,
507
- BOOLEAN,
508
- TIME,
509
- TIME_RANGE,
510
- GRANULARITY,
511
- DATASET,
512
- MEASURE,
513
- DIMENSION,
514
- DIMENSION_OR_MEASURE,
515
- ];
516
-
517
- createBuiltInType("string", {
518
- transform: function (value) { return value; },
519
- optionLabel: function (value) {
520
- return Array.isArray(value)
521
- ? "[".concat(value.map(function (v) { return "\"".concat(v, "\""); }).join(","), "]")
522
- : "\"".concat(value, "\"");
523
- },
524
- });
525
- createBuiltInType("number", {
526
- transform: function (value) {
527
- return Array.isArray(value) ? value : value ? Number(value) : value;
528
- },
529
- optionLabel: function (value) {
530
- var _a;
531
- return Array.isArray(value)
532
- ? "[".concat(value.join(","), "]")
533
- : ((_a = value === null || value === undefined ? undefined : value.toLocaleString(DEFAULT_LOCALE)) !== null && _a !== undefined ? _a : "");
534
- },
535
- });
536
- createBuiltInType("boolean", {
537
- transform: function (value) { return value === "true" || value === true; },
538
- optionLabel: function (value) { return (value ? "true" : "false"); },
539
- });
540
- createBuiltInType("time", {
541
- transform: function (value) {
542
- var date = (value === null || value === undefined ? undefined : value.date) ? new Date(value.date) : undefined;
543
- var isValid = date && date.toString() !== "Invalid Date";
544
- return {
545
- date: isValid ? date : undefined,
546
- relativeTimeString: value === null || value === undefined ? undefined : value.relativeTimeString,
547
- };
548
- },
549
- optionLabel: function (value) {
550
- var _a, _b;
551
- if (!value)
552
- return "";
553
- if (value === null || value === undefined ? undefined : value.date) {
554
- return ((_b = (_a = value.date) === null || _a === undefined ? undefined : _a.toLocaleDateString(DEFAULT_LOCALE)) !== null && _b !== undefined ? _b : value.date.toLocaleString());
555
- }
556
- return value.relativeTimeString;
557
- },
558
- });
559
- createBuiltInType("timeRange", {
560
- transform: function (value) {
561
- // Return undefined instead of a null populated object
562
- if (!value)
563
- return undefined;
564
- var _a = [value === null || value === undefined ? undefined : value.from, value === null || value === undefined ? undefined : value.to], from = _a[0], to = _a[1];
565
- var fromDate = new Date(from);
566
- var toDate = new Date(to);
567
- return {
568
- from: fromDate.toString() !== "Invalid Date" ? fromDate : undefined,
569
- to: toDate.toString() !== "Invalid Date" ? toDate : undefined,
570
- relativeTimeString: value === null || value === undefined ? undefined : value.relativeTimeString,
571
- };
572
- },
573
- optionLabel: function (value) {
574
- var _a, _b, _c, _d, _e, _f;
575
- if (!value)
576
- return "";
577
- if ((value === null || value === undefined ? undefined : value.from) && (value === null || value === undefined ? undefined : value.to)) {
578
- return "".concat((_b = (_a = value.from) === null || _a === undefined ? undefined : _a.toLocaleDateString(DEFAULT_LOCALE)) !== null && _b !== undefined ? _b : (_c = value.from) === null || _c === undefined ? undefined : _c.toLocaleString(), ",").concat((_e = (_d = value.to) === null || _d === undefined ? undefined : _d.toLocaleDateString(DEFAULT_LOCALE)) !== null && _e !== undefined ? _e : (_f = value.to) === null || _f === undefined ? undefined : _f.toLocaleString());
579
- }
580
- return value === null || value === undefined ? undefined : value.relativeTimeString;
581
- },
582
- });
583
- createBuiltInType("granularity", {
584
- transform: function (value) { return value; },
585
- optionLabel: function (value) { return value; },
586
- });
587
- createBuiltInType("dataset");
588
- createBuiltInType("measure");
589
- createBuiltInType("dimension");
590
- createBuiltInType("dimensionOrMeasure");
591
-
592
- const embeddableTypeSchema = zod.z
593
- .object({
594
- typeConfig: zod.z.object({
595
- label: zod.z.string(),
596
- toString: zod.z.function(),
597
- }),
598
- })
599
- .or(zod.z.enum(ALL_NATIVE_TYPES));
600
-
601
- const editorMetaSchema = zod.z
602
- .object({
603
- name: zod.z.string(),
604
- label: zod.z.string(),
605
- type: embeddableTypeSchema,
606
- config: zod.z.object({}).optional(),
607
- })
608
- .strict();
609
-
610
- const editorMetaValidator = (metaInfo) => {
611
- const result = editorMetaSchema.safeParse(metaInfo.meta);
612
- if (result.success)
613
- return [];
614
- return errorFormatter(result.error.issues);
615
- };
616
-
617
- const componentMetaSchema = zod.z
618
- .object({
619
- name: zod.z.string(),
620
- label: zod.z.string(),
621
- category: zod.z.string().optional(),
622
- classNames: zod.z.string().array().min(1).optional(),
623
- defaultWidth: zod.z.number().optional(),
624
- defaultHeight: zod.z.number().optional(),
625
- inputs: zod.z
626
- .object({
627
- name: zod.z.string(),
628
- label: zod.z.string(),
629
- description: zod.z.string().optional(),
630
- defaultValue: zod.z.any().optional(),
631
- config: zod.z.record(zod.z.string(), zod.z.any()).optional(),
632
- type: embeddableTypeSchema,
633
- array: zod.z.boolean().optional(),
634
- category: zod.z.string().optional(),
635
- required: zod.z.boolean().optional(),
636
- })
637
- .strict()
638
- .array()
639
- .superRefine((inputs, refinementContext) => {
640
- const inputNames = inputs.map((input) => input.name);
641
- if (new Set(inputNames).size !== inputNames.length) {
642
- const duplicateInputNames = inputNames.filter((name, index) => inputNames.indexOf(name) !== index);
643
- return refinementContext.addIssue({
644
- code: zod.z.ZodIssueCode.custom,
645
- message: `Input names must be unique. Duplicate names: ${duplicateInputNames.join(", ")}`,
646
- });
647
- }
648
- })
649
- .optional(),
650
- events: zod.z
651
- .object({
652
- name: zod.z.string(),
653
- label: zod.z.string(),
654
- properties: zod.z
655
- .object({
656
- name: zod.z.string(),
657
- type: embeddableTypeSchema,
658
- array: zod.z.boolean().optional(),
659
- label: zod.z.string().optional(),
660
- })
661
- .array()
662
- .optional(),
663
- })
664
- .strict()
665
- .array()
666
- .optional(),
667
- variables: zod.z
668
- .object({
669
- name: zod.z.string(),
670
- type: embeddableTypeSchema,
671
- array: zod.z.boolean().optional(),
672
- defaultValue: zod.z.any().optional(),
673
- inputs: zod.z.array(zod.z.string()).optional(),
674
- events: zod.z
675
- .array(zod.z.object({
676
- name: zod.z.string(),
677
- property: zod.z.string(),
678
- }))
679
- .optional(),
680
- })
681
- .strict()
682
- .array()
683
- .optional(),
684
- })
685
- .strict()
686
- .superRefine(({ defaultWidth, defaultHeight }, refinementContext) => {
687
- const widthAndHeight = [defaultHeight, defaultWidth].filter(Boolean);
688
- if (widthAndHeight.length === 1) {
689
- return refinementContext.addIssue({
690
- code: zod.z.ZodIssueCode.custom,
691
- message: "both defaultWidth and defaultHeight must be set",
692
- path: ["defaultWidth | defaultHeight"],
693
- });
694
- }
695
- });
696
-
697
- // @ts-ignore
698
- const babelTraverse = traverse.default;
699
- const parseAndTraverse = (code, visitor) => {
700
- const ast = parser.parse(code || "", {
701
- sourceType: "module",
702
- });
703
- babelTraverse(ast, visitor);
704
- };
705
- const componentMetaValidator = (metaInfo) => {
706
- const result = componentMetaSchema.safeParse(metaInfo.meta);
707
- if (!result.success)
708
- return errorFormatter(result.error.issues);
709
- let moduleNameErrors = validateModuleName(metaInfo);
710
- const variableErrors = validateVariables(metaInfo.meta);
711
- const eventErrors = validateComponentEvents(metaInfo);
712
- const loadDataErrors = validateComponentProps(metaInfo);
713
- return [
714
- ...moduleNameErrors,
715
- ...variableErrors,
716
- ...eventErrors,
717
- ...loadDataErrors,
718
- ];
719
- };
720
- const validateComponentProps = (metaInfo) => {
721
- const errors = [];
722
- parseAndTraverse(metaInfo.moduleInfo.code, {
723
- ExportDefaultDeclaration: (path) => {
724
- var _a;
725
- const componentConfig = path.node.declaration
726
- .arguments[2];
727
- const propsNode = (_a = componentConfig.properties) === null || _a === undefined ? undefined : _a.find((x) => { var _a; return ((_a = x.key) === null || _a === undefined ? undefined : _a.name) === "props"; });
728
- // There is no props defined
729
- if (!propsNode)
730
- return;
731
- // if propsNode is a function defined elsewhere
732
- if (propsNode.value.type === "Identifier") {
733
- const functionName = propsNode.value.name;
734
- path
735
- .findParent((path) => path.isProgram())
736
- .traverse({
737
- VariableDeclarator(path) {
738
- if (path.node.id.name === functionName &&
739
- (path.node.init.type === "FunctionExpression" ||
740
- path.node.init.type === "ArrowFunctionExpression")) {
741
- path.node.init.body.body;
742
- }
743
- },
744
- });
745
- }
746
- else {
747
- // assume that propsNode is anonymous function
748
- propsNode.value.body.body;
749
- }
750
- },
751
- });
752
- return errors;
753
- };
754
- const validateComponentEvents = (metaInfo) => {
755
- var _a, _b;
756
- const definedEvents = (_b = (_a = metaInfo.meta.events) === null || _a === undefined ? undefined : _a.map((e) => e.name)) !== null && _b !== undefined ? _b : [];
757
- let implementedEvents = [];
758
- const errors = [];
759
- parseAndTraverse(metaInfo.moduleInfo.code, {
760
- ExportDefaultDeclaration: (path) => {
761
- var _a, _b, _c, _d;
762
- const componentConfig = path.node.declaration
763
- .arguments[2];
764
- const eventsNode = (_a = componentConfig.properties) === null || _a === undefined ? undefined : _a.find((p) => { var _a; return ((_a = p.key) === null || _a === undefined ? undefined : _a.name) === "events"; });
765
- implementedEvents =
766
- (_d = (_c = (_b = eventsNode === null || eventsNode === undefined ? undefined : eventsNode.value) === null || _b === undefined ? undefined : _b.properties) === null || _c === undefined ? undefined : _c.map((p) => p.key.name)) !== null && _d !== undefined ? _d : [];
767
- },
768
- });
769
- const definedEventsSet = new Set(definedEvents);
770
- const implementedEventsSet = new Set(implementedEvents);
771
- const notImplementedEvents = definedEvents.filter((e) => !implementedEventsSet.has(e));
772
- const notDefinedEvents = implementedEvents.filter((e) => !definedEventsSet.has(e));
773
- for (const notDefinedEvent of notDefinedEvents) {
774
- errors.push(`event '${notDefinedEvent}' is not defined in the component's meta`);
775
- }
776
- for (const notImplementedEvent of notImplementedEvents) {
777
- errors.push(`event '${notImplementedEvent}' is defined but not implemented`);
778
- }
779
- return errors;
780
- };
781
- const validateModuleName = (metaInfo) => {
782
- const basename = path__namespace.basename(metaInfo.moduleId);
783
- const fileName = basename.split(".")[0];
784
- if (fileName !== metaInfo.meta.name) {
785
- return [
786
- `meta.name: The name of the .emb.* file and [meta.name]'s value must match. In this case, [meta.name] must be ${fileName}`,
787
- ];
788
- }
789
- return [];
790
- };
791
- const validateVariables = (meta) => {
792
- const variables = meta.variables;
793
- if (!variables)
794
- return [];
795
- const errors = [];
796
- // all inputs should be defined
797
- errors.push(...validateVariableInputs(meta));
798
- // all events and properties should be valid
799
- errors.push(...validateVariableEvents(meta));
800
- return errors;
801
- };
802
- const validateVariableInputs = (meta) => {
803
- const variables = meta.variables;
804
- const definedInputs = meta.inputs;
805
- if (!variables)
806
- return [];
807
- const errors = [];
808
- // all inputs should be defined
809
- variables.forEach((variableConfig, idx) => {
810
- const inputs = variableConfig.inputs;
811
- if (inputs) {
812
- inputs.forEach((input, inputIdx) => {
813
- const definedInput = definedInputs === null || definedInputs === undefined ? undefined : definedInputs.find((d) => d.name === input);
814
- if (!definedInput) {
815
- const path = formatErrorPath(["variables", idx, "inputs", inputIdx]);
816
- errors.push(`${path}: input "${input}" is not defined`);
817
- }
818
- });
819
- }
820
- });
821
- return errors;
822
- };
823
- const validateVariableEvents = (meta) => {
824
- const variables = meta.variables;
825
- const definedEvents = meta.events;
826
- if (!variables)
827
- return [];
828
- const errors = [];
829
- variables.forEach((variableConfig, idx) => {
830
- const events = variableConfig.events;
831
- if (events) {
832
- events.forEach((event, eventIdx) => {
833
- const definedEvent = definedEvents === null || definedEvents === undefined ? undefined : definedEvents.find((d) => d.name === event.name);
834
- if (!definedEvent) {
835
- const path = formatErrorPath([
836
- "variables",
837
- idx,
838
- "events",
839
- eventIdx,
840
- "name",
841
- ]);
842
- errors.push(`${path}: event "${event.name}" is not defined`);
843
- return;
844
- }
845
- const definedProperties = definedEvent.properties;
846
- const definedProperty = definedProperties === null || definedProperties === undefined ? undefined : definedProperties.find((p) => p.name === event.property);
847
- if (!definedProperty) {
848
- const path = formatErrorPath([
849
- "variables",
850
- idx,
851
- "events",
852
- eventIdx,
853
- "property",
854
- ]);
855
- errors.push(`${path}: property "${event.property}" is not defined`);
856
- return;
857
- }
858
- const path = formatErrorPath(["variables", idx]);
859
- if (definedProperty.type !== variableConfig.type) {
860
- errors.push(`${path}: the type of the variable "${variableConfig.name}" and the type of the property "${event.property}" do not match`);
861
- }
862
- if (Boolean(definedProperty.array) !== Boolean(variableConfig.array)) {
863
- errors.push(`${path}: the array of the variable "${variableConfig.name}" and the array of the property "${event.property}" do not match`);
864
- }
865
- });
866
- }
867
- });
868
- return errors;
869
- };
870
-
871
- const EDITOR = "editor";
872
- const COMPONENT = "component";
873
- const validators = {
874
- [EDITOR]: editorMetaValidator,
875
- [COMPONENT]: componentMetaValidator,
876
- };
877
- const getModuleType = (moduleInfo) => {
878
- var _a, _b;
879
- if ((_a = moduleInfo.code) === null || _a === undefined ? undefined : _a.includes("defineComponent")) {
880
- return COMPONENT;
881
- }
882
- else if ((_b = moduleInfo.code) === null || _b === undefined ? undefined : _b.includes("defineEditor")) {
883
- return EDITOR;
884
- }
885
- else {
886
- return null;
887
- }
888
- };
889
- var validateComponentMetaPlugin = (componentFileRegex) => {
890
- let metaConfigs = [];
891
- return {
892
- name: "validate-component-meta",
893
- moduleParsed: async (moduleInfo) => {
894
- const moduleType = componentFileRegex.test(moduleInfo.id)
895
- ? getModuleType(moduleInfo)
896
- : null;
897
- if (moduleType) {
898
- const meta = await loadComponentMeta(moduleInfo.id);
899
- metaConfigs.push({
900
- moduleId: moduleInfo.id,
901
- meta,
902
- moduleType,
903
- moduleInfo,
904
- });
905
- }
906
- },
907
- buildEnd: function () {
908
- const errors = [];
909
- for (const metaConfig of metaConfigs) {
910
- const validator = validators[metaConfig.moduleType];
911
- const validationResult = validator(metaConfig);
912
- if (validationResult && validationResult.length) {
913
- errors.push(`\nComponent meta is not valid ${metaConfig.moduleId}:\n${validationResult.join("\n")}`);
914
- }
915
- }
916
- metaConfigs = [];
917
- if (errors.length) {
918
- // @ts-ignore
919
- this.error(errors.join("\n"));
920
- }
921
- },
922
- };
923
- };
924
-
925
- /**
926
- * Modifies entry point only if there is 'styled-components' in the client's package.json.
927
- * Imports StyleSheetManager from styled-components and adds shadow root as "target".
928
- * That will force styled-components to add classes to the customers web-component
929
- * see https://styled-components.com/docs/api#stylesheetmanager
930
- */
931
- const styledComponentsEntrypointModifier = {
932
- getContentBegin() {
933
- return "<StyleSheetManager target={rootEl.getRootNode()}>";
934
- },
935
- getContentEnd() {
936
- return "</StyleSheetManager>";
937
- },
938
- getImports() {
939
- return "import {StyleSheetManager} from 'styled-components'";
940
- },
941
- needToModify(ctx) {
942
- var _a;
943
- const packageJsonFilePath = path__namespace.resolve(ctx.client.rootDir, "package.json");
944
- const packageJson = require(packageJsonFilePath);
945
- return !!((_a = packageJson.dependencies) === null || _a === undefined ? undefined : _a["styled-components"]);
946
- },
947
- };
948
-
949
- const entrypointModifiers = [
950
- styledComponentsEntrypointModifier,
951
- ];
952
-
953
- function findFilesWithWrongUsage(directory, pattern, mustEndWith = []) {
954
- const files = fs__namespace$1.readdirSync(directory);
955
- const result = [];
956
- files.forEach((file) => {
957
- const filePath = path__namespace.join(directory, file);
958
- if (fs__namespace$1.statSync(filePath).isDirectory()) {
959
- // Recursively check files in subdirectories
960
- result.push(...findFilesWithWrongUsage(filePath, pattern, mustEndWith));
961
- }
962
- else {
963
- const fileContent = fs__namespace$1.readFileSync(filePath, "utf8");
964
- if (fileContent.match(pattern)) {
965
- result.push(filePath);
966
- }
967
- }
968
- });
969
- return result.filter((file) => !mustEndWith.some((ending) => file.endsWith(ending)));
970
- }
971
- function findTypeNames(directory) {
972
- const files = fs__namespace$1.readdirSync(directory);
973
- const typeNames = [];
974
- files.forEach((file) => {
975
- const filePath = path__namespace.join(directory, file);
976
- if (fs__namespace$1.statSync(filePath).isDirectory()) {
977
- // Recursively check files in subdirectories
978
- typeNames.push(...findTypeNames(filePath));
979
- }
980
- else {
981
- const fileContent = fs__namespace$1.readFileSync(filePath, "utf8");
982
- const regexDefineTypeFunctionTypeName = /defineType\(["'](.*?)["']\,/g;
983
- const matches = fileContent.match(regexDefineTypeFunctionTypeName) || [];
984
- const extractedContent = matches.map((match) => match.slice(12, -2))[0];
985
- if (extractedContent) {
986
- typeNames.push({ file: filePath, typeName: extractedContent });
987
- }
988
- }
989
- });
990
- return typeNames;
991
- }
992
- const regexDefineComponentFunction = /defineComponent(<\w+>)?\(/;
993
- const regexDefineTypeFunction = /defineType\(/;
994
- const regexDefineOptionFunction = /defineOption\(/;
995
- const regexCubeFunction = /cube\(/;
996
- const regexCubes = /cubes:/;
997
- const usageValidator = async (directory) => {
998
- let isValid = true;
999
- const progress = ora("React: function usage validating...").start();
1000
- // defineComponent function
1001
- const filesWithWrongDefineComponentFunctionUsage = findFilesWithWrongUsage(directory, regexDefineComponentFunction, [".emb.js", ".emb.ts"]);
1002
- if (filesWithWrongDefineComponentFunctionUsage.length) {
1003
- isValid = false;
1004
- progress.fail("React: defineComponent() usage is only allowed inside files with the extension .emb.(js|ts) files.\nFix the following files:\n" +
1005
- filesWithWrongDefineComponentFunctionUsage.join("\n"));
1006
- }
1007
- // defineType function
1008
- const filesWithWrongDefineTypeFunctionUsage = findFilesWithWrongUsage(directory, regexDefineTypeFunction, [".type.emb.js", ".type.emb.ts"]);
1009
- if (filesWithWrongDefineTypeFunctionUsage.length) {
1010
- isValid = false;
1011
- progress.fail("React: defineType() usage is only allowed inside files with the extension .type.emb.(js|ts) files.\nFix the following files:\n" +
1012
- filesWithWrongDefineTypeFunctionUsage.join("\n"));
1013
- }
1014
- // defineOption function
1015
- const filesWithWrongDefineOptionFunctionUsage = findFilesWithWrongUsage(directory, regexDefineOptionFunction, [".type.emb.js", ".type.emb.ts"]);
1016
- if (filesWithWrongDefineOptionFunctionUsage.length) {
1017
- isValid = false;
1018
- progress.fail("React: defineOption() usage is only allowed inside files with the extension .type.emb.(js|ts) files.\nFix the following files:\n" +
1019
- filesWithWrongDefineOptionFunctionUsage.join("\n"));
1020
- }
1021
- // cube function
1022
- const filesWithWrongCubeFunctionUsage = findFilesWithWrongUsage(directory, regexCubeFunction, [".cube.js", ".cube.ts"]);
1023
- if (filesWithWrongCubeFunctionUsage.length) {
1024
- isValid = false;
1025
- progress.fail("React: cube() usage is only allowed inside files with the extension .cube.(ts|js) files.\nFix the following files:\n" +
1026
- filesWithWrongCubeFunctionUsage.join("\n"));
1027
- }
1028
- // cube in yml or yaml files
1029
- const filesWithWrongCubeUsage = findFilesWithWrongUsage(directory, regexCubes, [".cube.yml", ".cube.yaml"]);
1030
- if (filesWithWrongCubeUsage.length) {
1031
- isValid = false;
1032
- progress.fail("React: cubes: usage is only allowed inside files with the extension .cube.(yml|yaml) files.\nFix the following files:\n" +
1033
- filesWithWrongCubeUsage.join("\n"));
1034
- }
1035
- const typeNames = findTypeNames(directory);
1036
- // check for definedTypes using a native typeNames
1037
- const duplicatedNativeTypeNames = typeNames.filter((item) => ALL_NATIVE_TYPES.includes(item.typeName));
1038
- if (duplicatedNativeTypeNames.length) {
1039
- isValid = false;
1040
- progress.fail("React: defineType() can't be used with the same typeName as the nativeTypes. Fix the following files:\n" +
1041
- duplicatedNativeTypeNames
1042
- .map((dtn) => `${dtn.typeName} (file: ${dtn.file})`)
1043
- .join("\n"));
1044
- }
1045
- // check for duplicated typeNames
1046
- const duplicatedTypeNames = typeNames.filter((item, index) => {
1047
- return typeNames.some((otherItem, otherIndex) => {
1048
- if (index !== otherIndex) {
1049
- return item.typeName === otherItem.typeName;
1050
- }
1051
- return false;
1052
- });
1053
- });
1054
- if (duplicatedTypeNames.length) {
1055
- isValid = false;
1056
- progress.fail("React: defineType() must be used with a unique typeName. Fix the following files:\n" +
1057
- duplicatedTypeNames
1058
- .map((dtn) => `${dtn.typeName} (file: ${dtn.file})`)
1059
- .join("\n"));
1060
- }
1061
- isValid
1062
- ? progress.succeed("React: function usage validated")
1063
- : process.exit(1);
1064
- };
1065
-
1066
- const EMB_FILE_REGEX = /^(.*)(?<!\.type|\.options)\.emb\.[jt]s$/;
1067
- var generate = async (ctx) => {
1068
- var _a;
1069
- await usageValidator(ctx.client.srcDir);
1070
- const filesList = await findFiles(ctx.client.srcDir, EMB_FILE_REGEX);
1071
- await prepareEntrypoint(ctx, filesList);
1072
- let result;
1073
- if ((_a = ctx.dev) === null || _a === undefined ? undefined : _a.watch) {
1074
- result = await runViteWatch(ctx);
1075
- }
1076
- else {
1077
- const progress = ora("React: building components...").start();
1078
- result = await runViteBuild(ctx);
1079
- progress.succeed("Building React components completed");
1080
- }
1081
- return result;
1082
- };
1083
- async function runViteBuild(ctx, watch = null) {
1084
- var _a;
1085
- return await vite__namespace.build({
1086
- logLevel: !!watch ? "info" : "error",
1087
- resolve: {
1088
- extensions: [".ts", ".tsx", ".js", ".jsx", ".json"],
1089
- ...(_a = ctx.client.viteConfig) === null || _a === undefined ? undefined : _a.resolve,
1090
- },
1091
- plugins: [
1092
- viteReactPlugin(),
1093
- extractComponentsConfigPlugin({
1094
- isDev: !!watch,
1095
- globalKey: "componentsMeta",
1096
- fileName: "embeddable-components-meta.js",
1097
- outputDir: ctx.client.buildDir,
1098
- componentFileRegex: EMB_FILE_REGEX,
1099
- searchEntry: "defineComponent",
1100
- }),
1101
- extractComponentsConfigPlugin({
1102
- isDev: !!watch,
1103
- globalKey: "editorsMeta",
1104
- fileName: "embeddable-editors-meta.js",
1105
- outputDir: ctx.client.buildDir,
1106
- componentFileRegex: EMB_FILE_REGEX,
1107
- searchEntry: "defineEditor",
1108
- }),
1109
- validateComponentMetaPlugin(EMB_FILE_REGEX),
1110
- ],
1111
- build: {
1112
- sourcemap: true,
1113
- watch: watch
1114
- ? {
1115
- include: [ctx.client.srcDir + "/**"],
1116
- exclude: ["**/node_modules/**"],
1117
- }
1118
- : undefined,
1119
- minify: !watch,
1120
- rollupOptions: watch
1121
- ? {
1122
- cache: true,
1123
- ...ctx.client.rollupOptions,
1124
- output: {
1125
- sourcemapPathTransform: (relativeSourcePath, sourcemapPath) => {
1126
- // will replace relative paths with absolute paths
1127
- return path__namespace.resolve(path__namespace.dirname(sourcemapPath), relativeSourcePath);
1128
- },
1129
- },
1130
- }
1131
- : ctx.client.rollupOptions,
1132
- lib: {
1133
- entry: path__namespace.resolve(ctx.client.buildDir, ctx["sdk-react"].outputOptions.componentsEntryPointFilename),
1134
- formats: ["es"],
1135
- fileName: ctx["sdk-react"].outputOptions.fileName,
1136
- },
1137
- outDir: path__namespace.resolve(ctx.client.buildDir, ctx["sdk-react"].outputOptions.buildName),
1138
- },
1139
- define: {
1140
- "process.env.NODE_ENV": `${watch ? '"development"' : '"production"'}`,
1141
- },
1142
- });
1143
- }
1144
- async function runViteWatch(ctx) {
1145
- const watch = {
1146
- chokidar: {
1147
- ignored: ["**/node_modules/**", /.*\.emb-temp.js$/, /.*\.cube.js$/],
1148
- },
1149
- };
1150
- return (await runViteBuild(ctx, watch));
1151
- }
1152
- const IMPORT_REPLACE_TOKEN = "{{LAZY_IMPORTS}}";
1153
- const ERROR_FALLBACK_COMPONENT_IMPORT_TOKEN = "{{ERROR_FALLBACK_COMPONENT_IMPORT}}";
1154
- const ERROR_FALLBACK_COMPONENT_TOKEN = "{{ERROR_FALLBACK_COMPONENT}}";
1155
- const ERROR_FALLBACK_COMPONENT_DEFAULT_NAME = "ErrorFallbackComponent";
1156
- const ADDITIONAL_CONTENT_IMPORT_TOKEN = "{{ADDITIONAL_CONTENT_IMPORT}}";
1157
- const ADDITIONAL_CONTENT_BEGIN_TOKEN = "{{ADDITIONAL_CONTENT_BEGIN}}";
1158
- const ADDITIONAL_CONTENT_END_TOKEN = "{{ADDITIONAL_CONTENT_END}}";
1159
- function getRelativeFileNameForImport(ctx, fileName) {
1160
- return `../${path__namespace
1161
- .relative(ctx.client.rootDir, fileName)
1162
- // it is a bit of a hack. On windows the path will look like '.src\something\something'
1163
- // but for imports it must be '.src/something/something'
1164
- .replaceAll("\\", "/")}`;
1165
- }
1166
- async function prepareEntrypoint(ctx, filesList) {
1167
- const imports = filesList
1168
- .map(([fileName, filePath]) => `\t${fileName}: React.lazy(() => import('${getRelativeFileNameForImport(ctx, filePath)}'))`)
1169
- .join(",\n");
1170
- let errorBoundaryImport = "";
1171
- let errorFallbackComponent = "null";
1172
- if (ctx.client.errorFallbackComponent) {
1173
- errorBoundaryImport = `import ${ERROR_FALLBACK_COMPONENT_DEFAULT_NAME} from '${getRelativeFileNameForImport(ctx, ctx.client.errorFallbackComponent)}';`;
1174
- errorFallbackComponent = ERROR_FALLBACK_COMPONENT_DEFAULT_NAME;
1175
- }
1176
- const additionalContentImport = [];
1177
- let additionalContentBegin = [];
1178
- let additionalContentEnd = [];
1179
- for (const entrypointModifier of entrypointModifiers) {
1180
- if (entrypointModifier.needToModify(ctx)) {
1181
- additionalContentImport.push(entrypointModifier.getImports(ctx));
1182
- additionalContentBegin.push(entrypointModifier.getContentBegin(ctx));
1183
- additionalContentEnd.unshift(entrypointModifier.getContentEnd(ctx));
1184
- }
1185
- }
1186
- const content = await fs__namespace$2.readFile(path__namespace.resolve(ctx["sdk-react"].templatesDir, `${ctx["sdk-react"].outputOptions.componentsEntryPointFilename}.template`), "utf8");
1187
- await fs__namespace$2.writeFile(path__namespace.resolve(ctx.client.buildDir, ctx["sdk-react"].outputOptions.componentsEntryPointFilename), content
1188
- .replace(IMPORT_REPLACE_TOKEN, imports)
1189
- .replace(ERROR_FALLBACK_COMPONENT_IMPORT_TOKEN, errorBoundaryImport)
1190
- .replace(ERROR_FALLBACK_COMPONENT_TOKEN, errorFallbackComponent)
1191
- .replace(ADDITIONAL_CONTENT_IMPORT_TOKEN, additionalContentImport.join("\n"))
1192
- .replace(ADDITIONAL_CONTENT_BEGIN_TOKEN, additionalContentBegin.join("\n"))
1193
- .replace(ADDITIONAL_CONTENT_END_TOKEN, additionalContentEnd.join("\n")));
1194
- }
1195
-
1196
- var build = async (ctx) => {
1197
- createContext(path__namespace$1.resolve(__dirname, ".."), ctx);
1198
- return generate(ctx);
1199
- };
1200
-
1201
- var cleanup = async (ctx) => {
1202
- await fs.rm(path.resolve(ctx.client.buildDir, ctx["sdk-react"].outputOptions.componentsEntryPointFilename));
1203
- };
1204
-
1205
- var index = () => {
1206
- return {
1207
- pluginName: "sdk-react",
1208
- validate: async () => { },
1209
- build,
1210
- cleanup,
1211
- };
1212
- };
1213
-
1214
- module.exports = index;
1215
- //# sourceMappingURL=index.js.map