@embeddable.com/sdk-core 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.esm.js CHANGED
@@ -1,148 +1,848 @@
1
- var normalizeEntities = function (entities, _a) {
2
- var _b = _a.mapFn, mapFn = _b === void 0 ? function (x) { return x; } : _b, _c = _a.filterFn, filterFn = _c === void 0 ? Boolean : _c;
3
- if (!entities)
4
- return undefined;
5
- var filtered = entities.filter(filterFn);
6
- if (filtered.length === 0)
7
- return undefined;
8
- return filtered.map(mapFn);
9
- };
10
- var getName = function (x) { return x.name; };
11
- var validateOrderBy = function (orderByParam, dimensions, measures) {
12
- var unknownDimensionsOrMeasures = [];
13
- var dimensionAndMeasureNames = measures
14
- .concat(dimensions)
15
- .map(function (x) { return x.name; });
16
- for (var _i = 0, orderByParam_1 = orderByParam; _i < orderByParam_1.length; _i++) {
17
- var orderBy = orderByParam_1[_i];
18
- var name_1 = orderBy.property.name;
19
- if (dimensionAndMeasureNames.includes(name_1))
1
+ import * as fs from 'node:fs/promises';
2
+ import { readdir, lstat } from 'node:fs/promises';
3
+ import * as path from 'node:path';
4
+ import { join } from 'node:path';
5
+ import * as vite from 'vite';
6
+ import 'node:child_process';
7
+ import * as fsSync from 'node:fs';
8
+ import { createNodeLogger, createNodeSys } from '@stencil/core/sys/node';
9
+ import { loadConfig, createCompiler } from '@stencil/core/compiler';
10
+ import * as YAML from 'yaml';
11
+ import * as os from 'node:os';
12
+ import axios from 'axios';
13
+ import * as archiver from 'archiver';
14
+ import { createReadStream } from 'fs';
15
+ import { stat } from 'fs/promises';
16
+ import { basename } from 'path';
17
+
18
+ var findFiles = async (initialSrcDir, regex) => {
19
+ const filesList = [];
20
+ async function findFilesRec(srcDir) {
21
+ const allFiles = await readdir(srcDir);
22
+ for (const file of allFiles) {
23
+ const filePath = join(srcDir, file);
24
+ const status = await lstat(filePath);
25
+ if (status.isDirectory()) {
26
+ await findFilesRec(filePath);
27
+ }
28
+ const fileName = file.match(regex);
29
+ if (fileName) {
30
+ filesList.push([fileName[1], filePath]);
31
+ }
32
+ }
33
+ }
34
+ await findFilesRec(initialSrcDir);
35
+ return filesList;
36
+ };
37
+
38
+ const oraP$2 = import('ora');
39
+ const EMB_TYPE_FILE_REGEX = /^(.*)\.type\.emb\.[jt]s$/;
40
+ const EMB_OPTIONS_FILE_REGEX = /^(.*)\.options\.emb\.[jt]s$/;
41
+ var buildTypes = async (ctx) => {
42
+ const ora = (await oraP$2).default;
43
+ const progress = ora("building types...").start();
44
+ await generate$1(ctx);
45
+ await build$1(ctx);
46
+ await cleanup$1(ctx);
47
+ progress.succeed("types built completed");
48
+ };
49
+ async function generate$1(ctx) {
50
+ const typeFiles = await findFiles(ctx.client.srcDir, EMB_TYPE_FILE_REGEX);
51
+ const optionsFiles = await findFiles(ctx.client.srcDir, EMB_OPTIONS_FILE_REGEX);
52
+ const typeImports = typeFiles
53
+ .concat(optionsFiles)
54
+ .map(([_fileName, filePath]) => `import './${path.relative(ctx.client.rootDir, filePath)}';`)
55
+ .join("\n");
56
+ await fs.writeFile(path.resolve(ctx.client.rootDir, ctx.outputOptions.typesEntryPointFilename), typeImports);
57
+ }
58
+ async function build$1(ctx) {
59
+ process.chdir(ctx.client.rootDir);
60
+ await vite.build({
61
+ logLevel: "error",
62
+ build: {
63
+ emptyOutDir: false,
64
+ lib: {
65
+ entry: `./${ctx.outputOptions.typesEntryPointFilename}`,
66
+ formats: ["es"],
67
+ fileName: "embeddable-types",
68
+ },
69
+ outDir: ".embeddable-build/",
70
+ },
71
+ });
72
+ }
73
+ async function cleanup$1(ctx) {
74
+ await fs.rm(path.resolve(ctx.client.rootDir, "embeddable-types-entry-point.js"));
75
+ }
76
+
77
+ var prepare = async (ctx) => {
78
+ await removeIfExists(ctx);
79
+ await copyStencilConfigsToClient(ctx);
80
+ await createComponentDir(ctx.client.componentDir);
81
+ };
82
+ async function removeIfExists(ctx) {
83
+ if (fsSync.existsSync(ctx.client.buildDir))
84
+ await fs.rm(ctx.client.buildDir, { recursive: true });
85
+ }
86
+ async function copyStencilConfigsToClient(ctx) {
87
+ await fs.cp(ctx.core.configsDir, ctx.client.buildDir, { recursive: true });
88
+ }
89
+ async function createComponentDir(dir) {
90
+ await fs.mkdir(dir);
91
+ }
92
+
93
+ const STYLE_IMPORTS_TOKEN = "{{STYLES_IMPORT}}";
94
+ const RENDER_IMPORT_TOKEN = "{{RENDER_IMPORT}}";
95
+ // const NODE_LOGGER = stencilNodeApi.createNodeLogger({ process: process });
96
+ // const NODE_SYS = stencilNodeApi.createNodeSys({
97
+ // process: process,
98
+ // // @ts-ignore
99
+ // logger: NODE_LOGGER,
100
+ // });
101
+ var generate = async (ctx, pluginName) => {
102
+ await injectCSS(ctx, pluginName);
103
+ await injectBundleRender(ctx, pluginName);
104
+ await runStencil(ctx);
105
+ };
106
+ async function injectCSS(ctx, pluginName) {
107
+ const CUSTOMER_BUILD = path.resolve(ctx.client.buildDir, ctx[pluginName].outputOptions.buildName);
108
+ const allFiles = await fs.readdir(CUSTOMER_BUILD);
109
+ const cssFilesImportsStr = allFiles
110
+ .filter((fileName) => fileName.endsWith(".css"))
111
+ .map((fileName) => `@import '../${ctx[pluginName].outputOptions.buildName}/${fileName}';`)
112
+ .join("\n");
113
+ const content = await fs.readFile(path.resolve(ctx.core.templatesDir, "style.css.template"), "utf8");
114
+ await fs.writeFile(path.resolve(ctx.client.componentDir, "style.css"), content.replace(STYLE_IMPORTS_TOKEN, cssFilesImportsStr));
115
+ }
116
+ async function injectBundleRender(ctx, pluginName) {
117
+ const importStr = `import render from '../${ctx[pluginName].outputOptions.buildName}/${ctx[pluginName].outputOptions.fileName}';`;
118
+ const content = await fs.readFile(path.resolve(ctx.core.templatesDir, "component.tsx.template"), "utf8");
119
+ await fs.writeFile(path.resolve(ctx.client.componentDir, "component.tsx"), content.replace(RENDER_IMPORT_TOKEN, importStr));
120
+ }
121
+ async function runStencil(ctx) {
122
+ process.chdir(ctx.client.buildDir);
123
+ const logger = createNodeLogger({ process });
124
+ const sys = createNodeSys({ process });
125
+ const validated = await loadConfig({
126
+ logger,
127
+ sys,
128
+ config: {
129
+ namespace: "embeddable-wrapper",
130
+ srcDir: "component",
131
+ outputTargets: [{
132
+ type: "dist"
133
+ }],
134
+ },
135
+ });
136
+ const compiler = await createCompiler(validated.config);
137
+ await compiler.build();
138
+ await compiler.destroy();
139
+ // await stencil.run({
140
+ // args: ["build"],
141
+ // logger: NODE_LOGGER,
142
+ // sys: NODE_SYS,
143
+ // // @ts-ignore
144
+ // checkVersion: stencilNodeApi.checkVersion,
145
+ // });
146
+ }
147
+
148
+ var cleanup = async (ctx) => {
149
+ await extractBuild(ctx);
150
+ await removeObsoleteDir(ctx.client.buildDir);
151
+ await moveBuildTOBuildDir(ctx);
152
+ };
153
+ async function extractBuild(ctx) {
154
+ await fs.rename(path.resolve(ctx.client.buildDir, ctx.client.stencilBuild), ctx.client.tmpDir);
155
+ await fs.rename(path.resolve(ctx.client.buildDir, "embeddable-types.js"), path.join(ctx.client.tmpDir, "embeddable-types.js"));
156
+ await fs.rename(path.resolve(ctx.client.buildDir, "embeddable-components-meta.js"), path.join(ctx.client.tmpDir, "embeddable-components-meta.js"));
157
+ await fs.rename(path.resolve(ctx.client.buildDir, "embeddable-editors-meta.js"), path.join(ctx.client.tmpDir, "embeddable-editors-meta.js"));
158
+ }
159
+ async function removeObsoleteDir(dir) {
160
+ await fs.rm(dir, { recursive: true });
161
+ }
162
+ async function moveBuildTOBuildDir(ctx) {
163
+ await fs.rename(ctx.client.tmpDir, ctx.client.buildDir);
164
+ }
165
+
166
+ const EMB_YAML_FILE_REGEX$1 = /^(.*)\.emb\.ya?ml$/;
167
+ var validate = async (ctx) => {
168
+ const ora = (await import('ora')).default;
169
+ const spinnerValidate = ora("validation...").start();
170
+ const filesList = await findFiles(ctx.client.srcDir, EMB_YAML_FILE_REGEX$1);
171
+ const componentConfigErrors = await componentConfigValidation(filesList);
172
+ if (componentConfigErrors.length) {
173
+ spinnerValidate.fail("One or more component.emb.yaml files are invalid:");
174
+ componentConfigErrors.forEach((errorMessage) => spinnerValidate.info(errorMessage));
175
+ process.exit(1);
176
+ }
177
+ spinnerValidate.succeed("validation completed");
178
+ };
179
+ async function componentConfigValidation(filesList) {
180
+ const ARRAY_ALLOWED_TYPES = ["Dimension", "Measure"];
181
+ const errors = [];
182
+ for (const [fileName, filePath] of filesList) {
183
+ if (!fileName.endsWith(".component"))
184
+ continue;
185
+ const fileContentRaw = await fs.readFile(filePath, "utf8");
186
+ const config = YAML.parse(fileContentRaw);
187
+ if (!("inputs" in config) || config.inputs.length === 0)
20
188
  continue;
21
- unknownDimensionsOrMeasures.push(name_1);
189
+ config.inputs
190
+ .filter((inputConfig) => inputConfig === null || inputConfig === void 0 ? void 0 : inputConfig.array)
191
+ .forEach((inputConfig) => {
192
+ if (!ARRAY_ALLOWED_TYPES.includes(inputConfig === null || inputConfig === void 0 ? void 0 : inputConfig.type)) {
193
+ const errorMessage = `${fileName} contains invalid type value for \x1b[33m${inputConfig.name}\x1b[0m input.
194
+ \x1b[33m${inputConfig.name}\x1b[0m is marked as \x1b[33marray\x1b[0m. Inputs marked as array support the following types: ${ARRAY_ALLOWED_TYPES.join(", ")}.
195
+ Specified \x1b[33m${inputConfig === null || inputConfig === void 0 ? void 0 : inputConfig.type}\x1b[0m type is not supported.
196
+ Please check the following file: \x1b[33m${filePath}\x1b[0m\n`;
197
+ errors.push(errorMessage);
198
+ }
199
+ });
22
200
  }
23
- return unknownDimensionsOrMeasures;
201
+ return errors;
202
+ }
203
+
204
+ var build = async () => {
205
+ const config = (await import(`${process.cwd()}/embeddable.config.js`))
206
+ .default;
207
+ await validate(config);
208
+ await prepare(config);
209
+ await buildTypes(config);
210
+ for (const getPlugin of config.plugins) {
211
+ const plugin = getPlugin();
212
+ await plugin.validate(config);
213
+ await plugin.build(config);
214
+ await plugin.cleanup(config);
215
+ }
216
+ // NOTE: likely this will be called inside the loop above if we decide to support clients with mixed frameworks simultaneously.
217
+ await generate(config, "sdk-react");
218
+ await cleanup(config);
24
219
  };
25
220
 
26
- var LOAD_DATA_EVENT = "embeddable-event:load-data";
27
- var isLoadDataParams = function (ldp) {
28
- return typeof ldp === "object" && "requestParams" in ldp && "dataLoader" in ldp;
221
+ const oraP$1 = import('ora');
222
+ const openP = import('open');
223
+ const CREDENTIALS_DIR = path.resolve(os.homedir(), ".embeddable");
224
+ const CREDENTIALS_FILE = path.resolve(CREDENTIALS_DIR, "credentials");
225
+ const AUTH0_DOMAIN = "embeddable-dev.eu.auth0.com";
226
+ const AUTH0_CLIENT_ID = "xOKco5ztFCpWn54bJbFkAcT8mV4LLcpG";
227
+ var login = async () => {
228
+ var _a;
229
+ const ora = (await oraP$1).default;
230
+ const open = (await openP).default;
231
+ await resolveFiles();
232
+ const deviceCodePayload = {
233
+ client_id: AUTH0_CLIENT_ID,
234
+ audience: "https://api.embeddable.com/",
235
+ };
236
+ const deviceCodeResponse = await axios.post(`https://${AUTH0_DOMAIN}/oauth/device/code`, deviceCodePayload);
237
+ const tokenPayload = {
238
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
239
+ device_code: deviceCodeResponse.data["device_code"],
240
+ client_id: AUTH0_CLIENT_ID,
241
+ };
242
+ const authenticationSpinner = ora("waiting for code verification...").start();
243
+ await open(deviceCodeResponse.data["verification_uri_complete"]);
244
+ /**
245
+ * This is a recommended way to poll, since it take some time for a user to enter a `user_code` in a browser.
246
+ * deviceCodeResponse.data['interval'] is a recommended/calculated polling interval specified in seconds.
247
+ */
248
+ while (true) {
249
+ try {
250
+ const tokenResponse = await axios.post(`https://${AUTH0_DOMAIN}/oauth/token`, tokenPayload);
251
+ await fs.writeFile(CREDENTIALS_FILE, JSON.stringify(tokenResponse.data));
252
+ authenticationSpinner.succeed("you are successfully authenticated now!");
253
+ break;
254
+ }
255
+ catch (e) {
256
+ if (((_a = e.response.data) === null || _a === void 0 ? void 0 : _a.error) !== "authorization_pending") {
257
+ authenticationSpinner.fail("authentication failed. please try again.");
258
+ process.exit(1);
259
+ }
260
+ await sleep(deviceCodeResponse.data["interval"] * 1000);
261
+ }
262
+ }
29
263
  };
30
- var executeDataRequest = function (request, componentId, propertyName) {
264
+ async function getToken() {
31
265
  var _a;
32
- if (!request.from)
33
- return "No dataset selected";
34
- var dimensions = normalizeEntities(request.dimensions, { mapFn: getName });
35
- var measures = normalizeEntities(request.measures, { mapFn: getName });
36
- var timeDimensions = normalizeEntities(request.timeDimensions, {
37
- // @ts-expect-error
38
- filterFn: getName,
266
+ try {
267
+ const rawCredentials = await fs.readFile(CREDENTIALS_FILE, "utf-8");
268
+ const credentials = JSON.parse(rawCredentials.toString());
269
+ return (_a = credentials === null || credentials === void 0 ? void 0 : credentials.access_token) !== null && _a !== void 0 ? _a : "";
270
+ }
271
+ catch (_e) {
272
+ return "";
273
+ }
274
+ }
275
+ function sleep(ms) {
276
+ return new Promise((res) => setTimeout(res, ms));
277
+ }
278
+ async function resolveFiles() {
279
+ try {
280
+ await fs.access(CREDENTIALS_DIR);
281
+ }
282
+ catch (_e) {
283
+ await fs.mkdir(CREDENTIALS_DIR);
284
+ }
285
+ try {
286
+ await fs.access(CREDENTIALS_FILE);
287
+ }
288
+ catch (e) {
289
+ await fs.writeFile(CREDENTIALS_FILE, "");
290
+ }
291
+ }
292
+
293
+ var createContext = (coreRoot, clientRoot) => ({
294
+ core: {
295
+ rootDir: coreRoot,
296
+ templatesDir: path.resolve(coreRoot, "templates"),
297
+ configsDir: path.resolve(coreRoot, "configs"),
298
+ },
299
+ client: {
300
+ rootDir: clientRoot,
301
+ buildDir: path.resolve(clientRoot, ".embeddable-build"),
302
+ srcDir: path.resolve(clientRoot, "src"),
303
+ tmpDir: path.resolve(clientRoot, ".embeddable-tmp"),
304
+ componentDir: path.resolve(clientRoot, ".embeddable-build", "component"),
305
+ stencilBuild: path.resolve(clientRoot, ".embeddable-build", "dist", "embeddable-wrapper"),
306
+ archiveFile: path.resolve(clientRoot, "embeddable-build.zip"),
307
+ },
308
+ outputOptions: {
309
+ typesEntryPointFilename: "embeddable-types-entry-point.js",
310
+ },
311
+ });
312
+
313
+ const oraP = import('ora');
314
+ const inquirerSelect = import('@inquirer/select');
315
+ const EMB_YAML_FILE_REGEX = /^(.*)\.emb\.ya?ml$/;
316
+ let ora;
317
+ var push = async () => {
318
+ ora = (await oraP).default;
319
+ const ctx = createContext(path.resolve(__dirname, ".."), process.cwd());
320
+ const token = await verify(ctx);
321
+ const { workspaceId, name: workspaceName } = await selectWorkspace(token);
322
+ const spinnerArchive = ora("archivation...").start();
323
+ const filesList = await findFiles(ctx.client.srcDir, EMB_YAML_FILE_REGEX);
324
+ await archive(ctx, filesList);
325
+ spinnerArchive.succeed("archivation competed");
326
+ const spinnerPushing = ora("publishing...").start();
327
+ await sendBuild(ctx, { workspaceId, token });
328
+ spinnerPushing.succeed(`published to ${workspaceName}`);
329
+ };
330
+ async function selectWorkspace(token) {
331
+ const workspaceSpinner = ora({
332
+ text: "Fetching workspaces...",
333
+ color: "green",
334
+ discardStdin: false,
335
+ }).start();
336
+ const availableWorkspaces = await getWorkspaces(token);
337
+ let selectedWorkspace;
338
+ if (availableWorkspaces.length === 0) {
339
+ workspaceSpinner.fail("No workspaces found");
340
+ process.exit(1);
341
+ }
342
+ workspaceSpinner.info(`Found ${availableWorkspaces.length} workspace(s)`);
343
+ if (availableWorkspaces.length === 1) {
344
+ selectedWorkspace = availableWorkspaces[0];
345
+ }
346
+ else {
347
+ const select = (await inquirerSelect).default;
348
+ selectedWorkspace = await select({
349
+ message: "Select workspace to push changes",
350
+ choices: availableWorkspaces.map((workspace) => ({
351
+ name: `${workspace.name} (${workspace.workspaceId})`,
352
+ value: workspace,
353
+ })),
354
+ });
355
+ }
356
+ workspaceSpinner.succeed(`Workspace: ${selectedWorkspace.name} (${selectedWorkspace.workspaceId})`);
357
+ return selectedWorkspace;
358
+ }
359
+ async function verify(ctx) {
360
+ try {
361
+ await fs.access(ctx.client.buildDir);
362
+ }
363
+ catch (_e) {
364
+ console.error("No embeddable build was produced.");
365
+ process.exit(1);
366
+ }
367
+ // TODO: initiate login if no/invalid token.
368
+ const token = await getToken();
369
+ if (!token) {
370
+ console.error("Expired token. Please login again.");
371
+ process.exit(1);
372
+ }
373
+ return token;
374
+ }
375
+ async function archive(ctx, yamlFiles) {
376
+ const output = fsSync.createWriteStream(ctx.client.archiveFile);
377
+ const _archiver = archiver.create("zip", {
378
+ zlib: { level: 9 },
39
379
  });
40
- var dimensionsOrMeasuresDefined = dimensions || measures || timeDimensions;
41
- if (!dimensionsOrMeasuresDefined)
42
- return "At least a dimension or a measure should be selected.";
43
- var unknownDimensionsOrMeasures = validateOrderBy((_a = request.orderBy) !== null && _a !== void 0 ? _a : [], dimensions !== null && dimensions !== void 0 ? dimensions : [], measures !== null && measures !== void 0 ? measures : []);
44
- if (unknownDimensionsOrMeasures.length) {
45
- return "Cannot order by ".concat(unknownDimensionsOrMeasures.join(", "), " as no such ").concat(unknownDimensionsOrMeasures.length === 1 ? "property" : "properties", " has been loaded.");
46
- }
47
- var query = {
48
- datasetId: request.from.datasetId,
49
- embeddableId: request.from.embeddableId,
50
- dimensions: dimensions,
51
- measures: measures,
52
- timeDimensions: timeDimensions,
53
- offset: request.offset,
54
- limit: request.limit,
55
- };
56
- window.dispatchEvent(new CustomEvent(LOAD_DATA_EVENT, {
57
- bubbles: false,
58
- detail: {
59
- query: query,
60
- componentId: componentId,
61
- propertyName: propertyName,
380
+ _archiver.pipe(output);
381
+ _archiver.directory(ctx.client.buildDir, false);
382
+ for (const fileData of yamlFiles) {
383
+ _archiver.file(fileData[1], { name: `${fileData[0]}.emb.yaml` });
384
+ }
385
+ await _archiver.finalize();
386
+ return new Promise((resolve, _reject) => {
387
+ output.on("close", resolve);
388
+ });
389
+ }
390
+ async function sendBuild(ctx, { workspaceId, token }) {
391
+ const { FormData } = await import('formdata-node');
392
+ const { fileFromPath } = await Promise.resolve().then(function () { return fileFromPath$1; });
393
+ const file = await fileFromPath(ctx.client.archiveFile, "embeddable-build.zip");
394
+ const form = new FormData();
395
+ form.set("file", file, "embeddable-build.zip");
396
+ await axios.post(`https://api.embeddable.com/sdk/upload-files?workspaceId=${workspaceId}`, form, {
397
+ headers: {
398
+ "Content-Type": "multipart/form-data",
399
+ Authorization: `Bearer ${token}`,
62
400
  },
63
- }));
64
- };
65
- var loadData = function (requestParams) { return ({
66
- requestParams: requestParams,
67
- dataLoader: executeDataRequest,
68
- }); };
69
-
70
- var getOperationObject = function (operation, value) { return ({
71
- operation: operation,
72
- value: value,
73
- __embeddableVariableMeta: true,
74
- }); };
75
- var Value = {
76
- noFilter: function () { return getOperationObject("NO_FILTER"); },
77
- of: function (value) { return getOperationObject("VALUE", value); },
78
- };
79
-
80
- var UPDATE_VALUE_EVENT = "embeddable:value:changed";
81
- var setValue = function (value, componentId, eventName) {
82
- var event = new CustomEvent(UPDATE_VALUE_EVENT, {
83
- bubbles: false,
84
- detail: {
85
- componentId: componentId,
86
- value: value,
87
- eventName: eventName,
401
+ maxContentLength: Infinity,
402
+ maxBodyLength: Infinity,
403
+ });
404
+ await fs.rm(ctx.client.archiveFile);
405
+ }
406
+ async function getWorkspaces(token) {
407
+ try {
408
+ return axios
409
+ .get("https://api.embeddable.com/workspace", {
410
+ headers: {
411
+ Authorization: `Bearer ${token}`,
412
+ },
413
+ })
414
+ .then((res) => res.data);
415
+ }
416
+ catch (e) {
417
+ console.error(e);
418
+ return [];
419
+ }
420
+ }
421
+
422
+ var defineConfig = ({ plugins }) => {
423
+ const coreRoot = path.resolve(__dirname, "..");
424
+ const clientRoot = process.cwd();
425
+ return {
426
+ core: {
427
+ rootDir: coreRoot,
428
+ templatesDir: path.resolve(coreRoot, "templates"),
429
+ configsDir: path.resolve(coreRoot, "configs"),
430
+ },
431
+ client: {
432
+ rootDir: clientRoot,
433
+ buildDir: path.resolve(clientRoot, ".embeddable-build"),
434
+ srcDir: path.resolve(clientRoot, "src"),
435
+ tmpDir: path.resolve(clientRoot, ".embeddable-tmp"),
436
+ componentDir: path.resolve(clientRoot, ".embeddable-build", "component"),
437
+ stencilBuild: path.resolve(clientRoot, ".embeddable-build", "dist", "embeddable-wrapper"),
438
+ archiveFile: path.resolve(clientRoot, "embeddable-build.zip"),
439
+ },
440
+ outputOptions: {
441
+ typesEntryPointFilename: "embeddable-types-entry-point.js",
88
442
  },
443
+ plugins,
444
+ };
445
+ };
446
+
447
+ var __accessCheck = (obj, member, msg) => {
448
+ if (!member.has(obj))
449
+ throw TypeError("Cannot " + msg);
450
+ };
451
+ var __privateGet = (obj, member, getter) => {
452
+ __accessCheck(obj, member, "read from private field");
453
+ return getter ? getter.call(obj) : member.get(obj);
454
+ };
455
+ var __privateAdd = (obj, member, value) => {
456
+ if (member.has(obj))
457
+ throw TypeError("Cannot add the same private member more than once");
458
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
459
+ };
460
+ var __privateSet = (obj, member, value, setter) => {
461
+ __accessCheck(obj, member, "write to private field");
462
+ setter ? setter.call(obj, value) : member.set(obj, value);
463
+ return value;
464
+ };
465
+
466
+ // src/isObject.ts
467
+ var isObject = (value) => typeof value === "object" && value != null && !Array.isArray(value);
468
+
469
+ // src/isFunction.ts
470
+ var isFunction = (value) => typeof value === "function";
471
+
472
+ // src/isAsyncIterable.ts
473
+ var isAsyncIterable = (value) => isObject(value) && isFunction(value[Symbol.asyncIterator]);
474
+
475
+ // src/blobHelpers.ts
476
+ var MAX_CHUNK_SIZE = 65536;
477
+ async function* clonePart(value) {
478
+ if (value.byteLength <= MAX_CHUNK_SIZE) {
479
+ yield value;
480
+ return;
481
+ }
482
+ let offset = 0;
483
+ while (offset < value.byteLength) {
484
+ const size = Math.min(value.byteLength - offset, MAX_CHUNK_SIZE);
485
+ const buffer = value.buffer.slice(offset, offset + size);
486
+ offset += buffer.byteLength;
487
+ yield new Uint8Array(buffer);
488
+ }
489
+ }
490
+ async function* readStream(readable) {
491
+ const reader = readable.getReader();
492
+ while (true) {
493
+ const { done, value } = await reader.read();
494
+ if (done) {
495
+ break;
496
+ }
497
+ yield value;
498
+ }
499
+ }
500
+ async function* chunkStream(stream) {
501
+ for await (const value of stream) {
502
+ yield* clonePart(value);
503
+ }
504
+ }
505
+ var getStreamIterator = (source) => {
506
+ if (isAsyncIterable(source)) {
507
+ return chunkStream(source);
508
+ }
509
+ if (isFunction(source.getReader)) {
510
+ return chunkStream(readStream(source));
511
+ }
512
+ throw new TypeError(
513
+ "Unsupported data source: Expected either ReadableStream or async iterable."
514
+ );
515
+ };
516
+ async function* consumeNodeBlob(blob) {
517
+ let position = 0;
518
+ while (position !== blob.size) {
519
+ const chunk = blob.slice(
520
+ position,
521
+ Math.min(blob.size, position + MAX_CHUNK_SIZE)
522
+ );
523
+ const buffer = await chunk.arrayBuffer();
524
+ position += buffer.byteLength;
525
+ yield new Uint8Array(buffer);
526
+ }
527
+ }
528
+ async function* consumeBlobParts(parts, clone = false) {
529
+ for (const part of parts) {
530
+ if (ArrayBuffer.isView(part)) {
531
+ if (clone) {
532
+ yield* clonePart(part);
533
+ } else {
534
+ yield part;
535
+ }
536
+ } else if (isFunction(part.stream)) {
537
+ yield* getStreamIterator(part.stream());
538
+ } else {
539
+ yield* consumeNodeBlob(part);
540
+ }
541
+ }
542
+ }
543
+ function* sliceBlob(blobParts, blobSize, start = 0, end) {
544
+ end ??= blobSize;
545
+ let relativeStart = start < 0 ? Math.max(blobSize + start, 0) : Math.min(start, blobSize);
546
+ let relativeEnd = end < 0 ? Math.max(blobSize + end, 0) : Math.min(end, blobSize);
547
+ const span = Math.max(relativeEnd - relativeStart, 0);
548
+ let added = 0;
549
+ for (const part of blobParts) {
550
+ if (added >= span) {
551
+ break;
552
+ }
553
+ const partSize = ArrayBuffer.isView(part) ? part.byteLength : part.size;
554
+ if (relativeStart && partSize <= relativeStart) {
555
+ relativeStart -= partSize;
556
+ relativeEnd -= partSize;
557
+ } else {
558
+ let chunk;
559
+ if (ArrayBuffer.isView(part)) {
560
+ chunk = part.subarray(relativeStart, Math.min(partSize, relativeEnd));
561
+ added += chunk.byteLength;
562
+ } else {
563
+ chunk = part.slice(relativeStart, Math.min(partSize, relativeEnd));
564
+ added += chunk.size;
565
+ }
566
+ relativeEnd -= partSize;
567
+ relativeStart = 0;
568
+ yield chunk;
569
+ }
570
+ }
571
+ }
572
+
573
+ // src/Blob.ts
574
+ var _parts, _type, _size;
575
+ var _Blob = class _Blob {
576
+ /**
577
+ * Returns a new [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) object.
578
+ * The content of the blob consists of the concatenation of the values given in the parameter array.
579
+ *
580
+ * @param blobParts An `Array` strings, or [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`ArrayBufferView`](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView), [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects, or a mix of any of such objects, that will be put inside the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).
581
+ * @param options An optional object of type `BlobPropertyBag`.
582
+ */
583
+ constructor(blobParts = [], options = {}) {
584
+ /**
585
+ * An `Array` of [`ArrayBufferView`](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) or [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects, or a mix of any of such objects, that will be put inside the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).
586
+ */
587
+ __privateAdd(this, _parts, []);
588
+ /**
589
+ * Returns the [`MIME type`](https://developer.mozilla.org/en-US/docs/Glossary/MIME_type) of the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File).
590
+ */
591
+ __privateAdd(this, _type, "");
592
+ /**
593
+ * Returns the size of the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) in bytes.
594
+ */
595
+ __privateAdd(this, _size, 0);
596
+ options ??= {};
597
+ if (typeof blobParts !== "object" || blobParts === null) {
598
+ throw new TypeError(
599
+ "Failed to construct 'Blob': The provided value cannot be converted to a sequence."
600
+ );
601
+ }
602
+ if (!isFunction(blobParts[Symbol.iterator])) {
603
+ throw new TypeError(
604
+ "Failed to construct 'Blob': The object must have a callable @@iterator property."
605
+ );
606
+ }
607
+ if (typeof options !== "object" && !isFunction(options)) {
608
+ throw new TypeError(
609
+ "Failed to construct 'Blob': parameter 2 cannot convert to dictionary."
610
+ );
611
+ }
612
+ const encoder = new TextEncoder();
613
+ for (const raw of blobParts) {
614
+ let part;
615
+ if (ArrayBuffer.isView(raw)) {
616
+ part = new Uint8Array(raw.buffer.slice(
617
+ raw.byteOffset,
618
+ raw.byteOffset + raw.byteLength
619
+ ));
620
+ } else if (raw instanceof ArrayBuffer) {
621
+ part = new Uint8Array(raw.slice(0));
622
+ } else if (raw instanceof _Blob) {
623
+ part = raw;
624
+ } else {
625
+ part = encoder.encode(String(raw));
626
+ }
627
+ __privateSet(this, _size, __privateGet(this, _size) + (ArrayBuffer.isView(part) ? part.byteLength : part.size));
628
+ __privateGet(this, _parts).push(part);
629
+ }
630
+ const type = options.type === void 0 ? "" : String(options.type);
631
+ __privateSet(this, _type, /^[\x20-\x7E]*$/.test(type) ? type : "");
632
+ }
633
+ static [Symbol.hasInstance](value) {
634
+ return Boolean(
635
+ value && typeof value === "object" && isFunction(value.constructor) && (isFunction(value.stream) || isFunction(value.arrayBuffer)) && /^(Blob|File)$/.test(value[Symbol.toStringTag])
636
+ );
637
+ }
638
+ /**
639
+ * Returns the [`MIME type`](https://developer.mozilla.org/en-US/docs/Glossary/MIME_type) of the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File).
640
+ */
641
+ get type() {
642
+ return __privateGet(this, _type);
643
+ }
644
+ /**
645
+ * Returns the size of the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) in bytes.
646
+ */
647
+ get size() {
648
+ return __privateGet(this, _size);
649
+ }
650
+ /**
651
+ * Creates and returns a new [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) object which contains data from a subset of the blob on which it's called.
652
+ *
653
+ * @param start An index into the Blob indicating the first byte to include in the new Blob. If you specify a negative value, it's treated as an offset from the end of the Blob toward the beginning. For example, -10 would be the 10th from last byte in the Blob. The default value is 0. If you specify a value for start that is larger than the size of the source Blob, the returned Blob has size 0 and contains no data.
654
+ * @param end An index into the Blob indicating the first byte that will *not* be included in the new Blob (i.e. the byte exactly at this index is not included). If you specify a negative value, it's treated as an offset from the end of the Blob toward the beginning. For example, -10 would be the 10th from last byte in the Blob. The default value is size.
655
+ * @param contentType The content type to assign to the new Blob; this will be the value of its type property. The default value is an empty string.
656
+ */
657
+ slice(start, end, contentType) {
658
+ return new _Blob(sliceBlob(__privateGet(this, _parts), this.size, start, end), {
659
+ type: contentType
89
660
  });
90
- window.dispatchEvent(event);
91
- };
92
-
93
- /******************************************************************************
94
- Copyright (c) Microsoft Corporation.
95
-
96
- Permission to use, copy, modify, and/or distribute this software for any
97
- purpose with or without fee is hereby granted.
98
-
99
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
100
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
101
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
102
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
103
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
104
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
105
- PERFORMANCE OF THIS SOFTWARE.
106
- ***************************************************************************** */
107
- /* global Reflect, Promise, SuppressedError, Symbol */
108
-
109
-
110
- var __assign = function() {
111
- __assign = Object.assign || function __assign(t) {
112
- for (var s, i = 1, n = arguments.length; i < n; i++) {
113
- s = arguments[i];
114
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
115
- }
116
- return t;
117
- };
118
- return __assign.apply(this, arguments);
119
- };
120
-
121
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
122
- var e = new Error(message);
123
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
124
- };
125
-
126
- var embedType = function (typeName, typeConfig) {
127
- // @ts-ignore
128
- window.__EMBEDDABLE__ = window.__EMBEDDABLE__ || {};
129
- // @ts-ignore
130
- window.__EMBEDDABLE__.types = window.__EMBEDDABLE__.types || {};
131
- // @ts-ignore
132
- window.__EMBEDDABLE__.types[typeName] = __assign({ name: typeName }, typeConfig);
133
- };
134
-
135
- var embedOption = function (typeName, option) {
136
- // @ts-ignore
137
- window.__EMBEDDABLE__ = window.__EMBEDDABLE__ || {};
138
- // @ts-ignore
139
- if (!window.__EMBEDDABLE__.types[typeName])
140
- return;
141
- // @ts-ignore
142
- window.__EMBEDDABLE__.types[typeName].options =
143
- window.__EMBEDDABLE__.types[typeName].options || [];
144
- // @ts-ignore
145
- window.__EMBEDDABLE__.types[typeName].options.push(option);
146
- };
147
-
148
- export { Value, embedOption, embedType, isLoadDataParams, loadData, setValue };
661
+ }
662
+ /**
663
+ * Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with a string containing the contents of the blob, interpreted as UTF-8.
664
+ */
665
+ async text() {
666
+ const decoder = new TextDecoder();
667
+ let result = "";
668
+ for await (const chunk of consumeBlobParts(__privateGet(this, _parts))) {
669
+ result += decoder.decode(chunk, { stream: true });
670
+ }
671
+ result += decoder.decode();
672
+ return result;
673
+ }
674
+ /**
675
+ * Returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) that resolves with the contents of the blob as binary data contained in an [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer).
676
+ */
677
+ async arrayBuffer() {
678
+ const view = new Uint8Array(this.size);
679
+ let offset = 0;
680
+ for await (const chunk of consumeBlobParts(__privateGet(this, _parts))) {
681
+ view.set(chunk, offset);
682
+ offset += chunk.length;
683
+ }
684
+ return view.buffer;
685
+ }
686
+ /**
687
+ * Returns a [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream) which upon reading returns the data contained within the [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob).
688
+ */
689
+ stream() {
690
+ const iterator = consumeBlobParts(__privateGet(this, _parts), true);
691
+ return new ReadableStream({
692
+ async pull(controller) {
693
+ const { value, done } = await iterator.next();
694
+ if (done) {
695
+ return queueMicrotask(() => controller.close());
696
+ }
697
+ controller.enqueue(value);
698
+ },
699
+ async cancel() {
700
+ await iterator.return();
701
+ }
702
+ });
703
+ }
704
+ get [Symbol.toStringTag]() {
705
+ return "Blob";
706
+ }
707
+ };
708
+ _parts = new WeakMap();
709
+ _type = new WeakMap();
710
+ _size = new WeakMap();
711
+ var Blob = _Blob;
712
+ Object.defineProperties(Blob.prototype, {
713
+ type: { enumerable: true },
714
+ size: { enumerable: true },
715
+ slice: { enumerable: true },
716
+ stream: { enumerable: true },
717
+ text: { enumerable: true },
718
+ arrayBuffer: { enumerable: true }
719
+ });
720
+
721
+ // src/File.ts
722
+ var _name, _lastModified;
723
+ var File = class extends Blob {
724
+ /**
725
+ * Creates a new File instance.
726
+ *
727
+ * @param fileBits An `Array` strings, or [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`ArrayBufferView`](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView), [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects, or a mix of any of such objects, that will be put inside the [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File).
728
+ * @param name The name of the file.
729
+ * @param options An options object containing optional attributes for the file.
730
+ */
731
+ constructor(fileBits, name, options = {}) {
732
+ super(fileBits, options);
733
+ /**
734
+ * Returns the name of the file referenced by the File object.
735
+ */
736
+ __privateAdd(this, _name, void 0);
737
+ /**
738
+ * The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date.
739
+ */
740
+ __privateAdd(this, _lastModified, 0);
741
+ if (arguments.length < 2) {
742
+ throw new TypeError(
743
+ `Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`
744
+ );
745
+ }
746
+ __privateSet(this, _name, String(name));
747
+ const lastModified = options.lastModified === void 0 ? Date.now() : Number(options.lastModified);
748
+ if (!Number.isNaN(lastModified)) {
749
+ __privateSet(this, _lastModified, lastModified);
750
+ }
751
+ }
752
+ static [Symbol.hasInstance](value) {
753
+ return value instanceof Blob && value[Symbol.toStringTag] === "File" && typeof value.name === "string";
754
+ }
755
+ /**
756
+ * Name of the file referenced by the File object.
757
+ */
758
+ get name() {
759
+ return __privateGet(this, _name);
760
+ }
761
+ /* c8 ignore next 3 */
762
+ get webkitRelativePath() {
763
+ return "";
764
+ }
765
+ /**
766
+ * The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date.
767
+ */
768
+ get lastModified() {
769
+ return __privateGet(this, _lastModified);
770
+ }
771
+ get [Symbol.toStringTag]() {
772
+ return "File";
773
+ }
774
+ };
775
+ _name = new WeakMap();
776
+ _lastModified = new WeakMap();
777
+
778
+ // src/fileFromPath.ts
779
+ var _path, _start;
780
+ var _FileFromPath = class _FileFromPath {
781
+ constructor(input) {
782
+ __privateAdd(this, _path, void 0);
783
+ __privateAdd(this, _start, void 0);
784
+ __privateSet(this, _path, input.path);
785
+ __privateSet(this, _start, input.start || 0);
786
+ this.name = basename(__privateGet(this, _path));
787
+ this.size = input.size;
788
+ this.lastModified = input.lastModified;
789
+ }
790
+ slice(start, end) {
791
+ return new _FileFromPath({
792
+ path: __privateGet(this, _path),
793
+ lastModified: this.lastModified,
794
+ start: __privateGet(this, _start) + start,
795
+ size: end - start
796
+ });
797
+ }
798
+ async *stream() {
799
+ const { mtimeMs } = await stat(__privateGet(this, _path));
800
+ if (mtimeMs > this.lastModified) {
801
+ throw new DOMException(
802
+ "The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.",
803
+ "NotReadableError"
804
+ );
805
+ }
806
+ if (this.size) {
807
+ yield* createReadStream(__privateGet(this, _path), {
808
+ start: __privateGet(this, _start),
809
+ end: __privateGet(this, _start) + this.size - 1
810
+ });
811
+ }
812
+ }
813
+ get [Symbol.toStringTag]() {
814
+ return "File";
815
+ }
816
+ };
817
+ _path = new WeakMap();
818
+ _start = new WeakMap();
819
+ var FileFromPath = _FileFromPath;
820
+ function createFileFromPath(path, { mtimeMs, size }, filenameOrOptions, options = {}) {
821
+ let filename;
822
+ if (isObject(filenameOrOptions)) {
823
+ [options, filename] = [filenameOrOptions, void 0];
824
+ } else {
825
+ filename = filenameOrOptions;
826
+ }
827
+ const file = new FileFromPath({ path, size, lastModified: mtimeMs });
828
+ if (!filename) {
829
+ filename = file.name;
830
+ }
831
+ return new File([file], filename, {
832
+ ...options,
833
+ lastModified: file.lastModified
834
+ });
835
+ }
836
+ async function fileFromPath(path, filenameOrOptions, options) {
837
+ const stats = await stat(path);
838
+ return createFileFromPath(path, stats, filenameOrOptions, options);
839
+ }
840
+ /*! Based on fetch-blob. MIT License. Jimmy Wärting <https://jimmy.warting.se/opensource> & David Frank */
841
+
842
+ var fileFromPath$1 = /*#__PURE__*/Object.freeze({
843
+ __proto__: null,
844
+ fileFromPath: fileFromPath
845
+ });
846
+
847
+ export { build, defineConfig, login, push };
848
+ //# sourceMappingURL=index.esm.js.map