@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/scripts/build.js DELETED
@@ -1,20 +0,0 @@
1
- const path = require("path");
2
- const { prepare } = require("./prepare");
3
- const { generate } = require("./generate");
4
- const { cleanup } = require("./cleanup");
5
- const { createContext } = require("./createContext");
6
-
7
- async function build(pluginOptions = {}) {
8
- const ctx = {
9
- ...createContext(path.resolve(__dirname, ".."), process.cwd()),
10
- pluginOptions,
11
- };
12
-
13
- await prepare(ctx);
14
-
15
- await generate(ctx);
16
-
17
- await cleanup(ctx);
18
- }
19
-
20
- module.exports = { build };
@@ -1,61 +0,0 @@
1
- const fs = require("node:fs/promises");
2
- const path = require("node:path");
3
- const vite = require("vite");
4
-
5
- const { findEmbFiles } = require("./findEmbFiles");
6
-
7
- const EMB_TYPE_FILE_REGEX = /^(.*)\.type\.emb\.[jt]s$/;
8
- const EMB_OPTIONS_FILE_REGEX = /^(.*)\.options\.emb\.[jt]s$/;
9
-
10
- async function buildTypes(ctx) {
11
- await generate(ctx);
12
-
13
- await build(ctx);
14
-
15
- await cleanup(ctx);
16
- }
17
-
18
- module.exports = { buildTypes };
19
-
20
- async function generate(ctx) {
21
- const typeFiles = await findEmbFiles(ctx.client.srcDir, EMB_TYPE_FILE_REGEX);
22
- const optionsFiles = await findEmbFiles(
23
- ctx.client.srcDir,
24
- EMB_OPTIONS_FILE_REGEX,
25
- );
26
-
27
- const typeImports = typeFiles
28
- .concat(optionsFiles)
29
- .map(
30
- ([fileName, filePath]) =>
31
- `import './${path.relative(ctx.client.rootDir, filePath)}';`,
32
- )
33
- .join("\n");
34
-
35
- await fs.writeFile(
36
- path.resolve(ctx.client.rootDir, ctx.outputOptions.typesEntryPointFilename),
37
- typeImports,
38
- );
39
- }
40
-
41
- async function build(ctx) {
42
- process.chdir(ctx.client.rootDir);
43
-
44
- await vite.build({
45
- build: {
46
- emptyOutDir: false,
47
- lib: {
48
- entry: `./${ctx.outputOptions.typesEntryPointFilename}`,
49
- formats: ["es"],
50
- fileName: "embeddable-types",
51
- },
52
- outDir: ".embeddable-build/",
53
- },
54
- });
55
- }
56
-
57
- async function cleanup(ctx) {
58
- await fs.rm(
59
- path.resolve(ctx.client.rootDir, "embeddable-types-entry-point.js"),
60
- );
61
- }
@@ -1,27 +0,0 @@
1
- const fs = require("fs/promises");
2
- const path = require("path");
3
-
4
- async function cleanup(ctx) {
5
- await extractBuild(ctx);
6
-
7
- await removeObsoleteDir(ctx.client.buildDir);
8
-
9
- await moveBuildTOBuildDir(ctx);
10
- }
11
-
12
- module.exports = { cleanup };
13
-
14
- async function extractBuild(ctx) {
15
- await fs.rename(
16
- path.resolve(ctx.client.buildDir, ctx.client.stencilBuild),
17
- ctx.client.tmpDir,
18
- );
19
- }
20
-
21
- async function removeObsoleteDir(dir) {
22
- await fs.rm(dir, { recursive: true });
23
- }
24
-
25
- async function moveBuildTOBuildDir(ctx) {
26
- await fs.rename(ctx.client.tmpDir, ctx.client.buildDir);
27
- }
@@ -1,27 +0,0 @@
1
- const path = require("path");
2
-
3
- function createContext(coreRoot, clientRoot) {
4
- return {
5
- core: {
6
- rootDir: coreRoot,
7
- templatesDir: path.resolve(coreRoot, "templates"),
8
- configsDir: path.resolve(coreRoot, "configs"),
9
- },
10
- client: {
11
- rootDir: clientRoot,
12
- buildDir: path.resolve(clientRoot, ".embeddable-build"),
13
- srcDir: path.resolve(clientRoot, "src"),
14
- tmpDir: path.resolve(clientRoot, ".embeddable-tmp"),
15
- componentDir: path.resolve(clientRoot, ".embeddable-build", "component"),
16
- stencilBuild: path.resolve(
17
- clientRoot,
18
- ".embeddable-build",
19
- "dist",
20
- "embeddable-wrapper",
21
- ),
22
- archiveFile: path.resolve(clientRoot, "embeddable-build.zip"),
23
- },
24
- };
25
- }
26
-
27
- module.exports = { createContext };
@@ -1,32 +0,0 @@
1
- const fs = require("fs/promises");
2
- const path = require("path");
3
-
4
- async function findEmbFiles(initialSrcDir, regex) {
5
- const filesList = [];
6
-
7
- async function findEmbFilesRec(srcDir) {
8
- const allFiles = await fs.readdir(srcDir);
9
-
10
- for (const file of allFiles) {
11
- const filePath = path.join(srcDir, file);
12
-
13
- const status = await fs.lstat(filePath);
14
-
15
- if (status.isDirectory()) {
16
- await findEmbFilesRec(filePath);
17
- }
18
-
19
- const fileName = file.match(regex);
20
-
21
- if (fileName) {
22
- filesList.push([fileName[1], filePath]);
23
- }
24
- }
25
- }
26
-
27
- await findEmbFilesRec(initialSrcDir);
28
-
29
- return filesList;
30
- }
31
-
32
- module.exports = { findEmbFiles };
@@ -1,72 +0,0 @@
1
- const fs = require("fs/promises");
2
- const path = require("path");
3
-
4
- const stencilNodeApi = require("@stencil/core/sys/node");
5
- const stencil = require("@stencil/core/cli");
6
-
7
- const STYLE_IMPORTS_TOKEN = "{{STYLES_IMPORT}}";
8
- const RENDER_IMPORT_TOKEN = "{{RENDER_IMPORT}}";
9
-
10
- const NODE_LOGGER = stencilNodeApi.createNodeLogger({ process: process });
11
- const NODE_SYS = stencilNodeApi.createNodeSys({
12
- process: process,
13
- logger: NODE_LOGGER,
14
- });
15
-
16
- async function generate(ctx) {
17
- await injectCSS(ctx);
18
-
19
- await injectBundleRender(ctx);
20
-
21
- await runStencil(ctx);
22
- }
23
-
24
- module.exports = { generate };
25
-
26
- async function injectCSS(ctx) {
27
- const CUSTOMER_BUILD = path.resolve(
28
- ctx.client.buildDir,
29
- ctx.pluginOptions.outDir,
30
- );
31
- const allFiles = await fs.readdir(CUSTOMER_BUILD);
32
-
33
- const cssFilesImportsStr = allFiles
34
- .filter((fileName) => fileName.endsWith(".css"))
35
- .map((fileName) => `@import '../${ctx.pluginOptions.outDir}/${fileName}';`)
36
- .join("\n");
37
-
38
- const content = await fs.readFile(
39
- path.resolve(ctx.core.templatesDir, "style.css.template"),
40
- "utf8",
41
- );
42
-
43
- await fs.writeFile(
44
- path.resolve(ctx.client.componentDir, "style.css"),
45
- content.replace(STYLE_IMPORTS_TOKEN, cssFilesImportsStr),
46
- );
47
- }
48
-
49
- async function injectBundleRender(ctx) {
50
- const importStr = `import render from '../${ctx.pluginOptions.outDir}/${ctx.pluginOptions.renderFunctionFileName}';`;
51
-
52
- const content = await fs.readFile(
53
- path.resolve(ctx.core.templatesDir, "component.tsx.template"),
54
- "utf8",
55
- );
56
-
57
- await fs.writeFile(
58
- path.resolve(ctx.client.componentDir, "component.tsx"),
59
- content.replace(RENDER_IMPORT_TOKEN, importStr),
60
- );
61
- }
62
-
63
- async function runStencil(ctx) {
64
- process.chdir(ctx.client.buildDir);
65
-
66
- await stencil.run({
67
- args: ["build"],
68
- logger: NODE_LOGGER,
69
- sys: NODE_SYS,
70
- checkVersion: stencilNodeApi.checkVersion,
71
- });
72
- }
@@ -1,13 +0,0 @@
1
- const fsP = require("node:fs/promises");
2
- const fs = require("node:fs")
3
- const path = require("node:path");
4
- async function globalCleanup(ctx) {
5
- const componentsEntryPath = path.resolve(ctx.client.rootDir, ctx.outputOptions.componentsEntryPointFilename);
6
- const typesEntryPath = path.resolve(ctx.client.rootDir, ctx.outputOptions.typesEntryPointFilename);
7
-
8
- if (fs.existsSync(ctx.client.buildDir)) await fsP.rm(ctx.client.buildDir, { recursive: true });
9
- if (fs.existsSync(componentsEntryPath)) await fsP.rm(componentsEntryPath);
10
- if (fs.existsSync(typesEntryPath)) await fsP.rm(typesEntryPath);
11
- }
12
-
13
- module.exports = { globalCleanup };
package/scripts/index.js DELETED
@@ -1,17 +0,0 @@
1
- const { build } = require("./build");
2
- const { buildTypes } = require("./buildTypes");
3
- const { findEmbFiles } = require("./findEmbFiles");
4
- const { login } = require("./login");
5
- const { push } = require("./push");
6
- const { validate } = require("./validate");
7
- const { globalCleanup } = require("./globalCleanup");
8
-
9
- module.exports = {
10
- build,
11
- buildTypes,
12
- findEmbFiles,
13
- login,
14
- push,
15
- validate,
16
- globalCleanup,
17
- };
package/scripts/login.js DELETED
@@ -1,93 +0,0 @@
1
- const path = require("path");
2
- const os = require("os");
3
- const fs = require("fs/promises");
4
- const axios = require("axios");
5
- const oraP = import("ora");
6
- const openP = import("open");
7
-
8
- const CREDENTIALS_DIR = path.resolve(os.homedir(), ".embeddable");
9
- const CREDENTIALS_FILE = path.resolve(CREDENTIALS_DIR, "credentials");
10
-
11
- const AUTH0_DOMAIN = "embeddable-dev.eu.auth0.com";
12
- const AUTH0_CLIENT_ID = "xOKco5ztFCpWn54bJbFkAcT8mV4LLcpG";
13
-
14
- async function login() {
15
- const ora = (await oraP).default;
16
- const open = (await openP).default
17
-
18
- await resolveFiles();
19
-
20
- const deviceCodePayload = {
21
- client_id: AUTH0_CLIENT_ID,
22
- audience: "https://api.embeddable.com/",
23
- };
24
-
25
- const deviceCodeResponse = await axios.post(
26
- `https://${AUTH0_DOMAIN}/oauth/device/code`,
27
- deviceCodePayload,
28
- );
29
-
30
- const tokenPayload = {
31
- grant_type: "urn:ietf:params:oauth:grant-type:device_code",
32
- device_code: deviceCodeResponse.data["device_code"],
33
- client_id: AUTH0_CLIENT_ID,
34
- };
35
-
36
- const authenticationSpinner = ora("waiting for code verification...").start();
37
-
38
- await open(deviceCodeResponse.data["verification_uri_complete"]);
39
-
40
- /**
41
- * This is a recommended way to poll, since it take some time for a user to enter a `user_code` in a browser.
42
- * deviceCodeResponse.data['interval'] is a recommended/calculated polling interval specified in seconds.
43
- */
44
- while (true) {
45
- try {
46
- const tokenResponse = await axios.post(
47
- `https://${AUTH0_DOMAIN}/oauth/token`,
48
- tokenPayload,
49
- );
50
- await fs.writeFile(CREDENTIALS_FILE, JSON.stringify(tokenResponse.data));
51
- authenticationSpinner.succeed("you are successfully authenticated now!");
52
- break;
53
- } catch (e) {
54
- if (e.response.data?.error !== "authorization_pending") {
55
- authenticationSpinner.fail("authentication failed. please try again.");
56
- process.exit(1);
57
- }
58
-
59
- await sleep(deviceCodeResponse.data["interval"] * 1000);
60
- }
61
- }
62
- }
63
-
64
- async function getToken() {
65
- try {
66
- const rawCredentials = await fs.readFile(CREDENTIALS_FILE, "utf-8");
67
- const credentials = JSON.parse(rawCredentials.toString());
68
-
69
- return credentials?.access_token ?? "";
70
- } catch (_e) {
71
- return "";
72
- }
73
- }
74
-
75
- module.exports = { login, getToken };
76
-
77
- function sleep(ms) {
78
- return new Promise((res) => setTimeout(res, ms));
79
- }
80
-
81
- async function resolveFiles() {
82
- try {
83
- await fs.access(CREDENTIALS_DIR);
84
- } catch (_e) {
85
- await fs.mkdir(CREDENTIALS_DIR);
86
- }
87
-
88
- try {
89
- await fs.access(CREDENTIALS_FILE);
90
- } catch (e) {
91
- await fs.writeFile(CREDENTIALS_FILE, "");
92
- }
93
- }
@@ -1,27 +0,0 @@
1
- const fsSync = require("fs");
2
- const fs = require("fs/promises");
3
-
4
- async function prepare(ctx) {
5
- await removeIfExists(ctx);
6
-
7
- await copyStencilConfigsToClient(ctx);
8
-
9
- await createComponentDir(ctx.client.componentDir);
10
- }
11
-
12
- module.exports = { prepare };
13
-
14
- async function removeIfExists(ctx) {
15
- if (ctx.pluginOptions) return;
16
-
17
- if (fsSync.existsSync(ctx.client.buildDir))
18
- await fs.rm(ctx.client.buildDir, { recursive: true });
19
- }
20
-
21
- async function copyStencilConfigsToClient(ctx) {
22
- await fs.cp(ctx.core.configsDir, ctx.client.buildDir, { recursive: true });
23
- }
24
-
25
- async function createComponentDir(dir) {
26
- await fs.mkdir(dir);
27
- }
package/scripts/push.js DELETED
@@ -1,153 +0,0 @@
1
- const fs = require("fs/promises");
2
- const fsSync = require("fs");
3
- const path = require("path");
4
- const archiver = require("archiver");
5
- const axios = require("axios");
6
- const oraP = import("ora");
7
- const inquirerSelect = import("@inquirer/select");
8
-
9
- const { findEmbFiles } = require("./findEmbFiles");
10
- const { createContext } = require("./createContext");
11
- const { getToken } = require("./login");
12
-
13
- const EMB_YAML_FILE_REGEX = /^(.*)\.emb\.ya?ml$/;
14
-
15
- let ora;
16
- async function push() {
17
- ora = (await oraP).default;
18
-
19
- const ctx = createContext(path.resolve(__dirname, ".."), process.cwd());
20
-
21
- const token = await verify(ctx);
22
-
23
- const { workspaceId, workspaceName } = await selectWorkspace(token);
24
-
25
- const spinnerArchive = ora("archivation...").start();
26
-
27
- const filesList = await findEmbFiles(ctx.client.srcDir, EMB_YAML_FILE_REGEX);
28
-
29
- await archive(ctx, filesList);
30
- spinnerArchive.succeed("archivation competed");
31
-
32
- const spinnerPushing = ora("publishing...").start();
33
-
34
- await sendBuild(ctx, { workspaceId, token });
35
- spinnerPushing.succeed(`published to ${workspaceName}`);
36
- }
37
-
38
- module.exports = { push };
39
-
40
- async function selectWorkspace(token) {
41
- const workspaceSpinner = ora({
42
- text: "Fetching workspaces...",
43
- color: "green",
44
- discardStdin: false,
45
- }).start();
46
-
47
- const availableWorkspaces = await getWorkspaces(token);
48
-
49
- let selectedWorkspace;
50
-
51
- if (availableWorkspaces.length === 0) {
52
- workspaceSpinner.fail("No workspaces found");
53
- process.exit(1);
54
- }
55
-
56
- workspaceSpinner.info(`Found ${availableWorkspaces.length} workspace(s)`);
57
-
58
- if (availableWorkspaces.length === 1) {
59
- selectedWorkspace = availableWorkspaces[0];
60
- } else {
61
- const select = (await inquirerSelect).default;
62
- selectedWorkspace = await select({
63
- message: "Select workspace to push changes",
64
- choices: availableWorkspaces.map((workspace) => ({
65
- name: `${workspace.name} (${workspace.workspaceId})`,
66
- value: workspace,
67
- })),
68
- });
69
- }
70
-
71
- workspaceSpinner.succeed(`Workspace: ${selectedWorkspace.name} (${selectedWorkspace.workspaceId})`);
72
-
73
- return selectedWorkspace;
74
- }
75
-
76
- async function verify(ctx) {
77
- try {
78
- await fs.access(ctx.client.buildDir);
79
- } catch (_e) {
80
- console.error("No embeddable build was produced.");
81
- process.exit(1);
82
- }
83
-
84
- // TODO: initiate login if no/invalid token.
85
- const token = await getToken();
86
-
87
- if (!token) {
88
- console.error("Expired token. Please login again.");
89
- process.exit(1);
90
- }
91
-
92
- return token;
93
- }
94
-
95
- function archive(ctx, yamlFiles) {
96
- const output = fsSync.createWriteStream(ctx.client.archiveFile);
97
- const _archiver = archiver("zip", {
98
- zlib: { level: 9 },
99
- });
100
-
101
- _archiver.pipe(output);
102
- _archiver.directory(ctx.client.buildDir, false);
103
-
104
- for (const fileData of yamlFiles) {
105
- _archiver.file(fileData[1], { name: `${fileData[0]}.emb.yaml` });
106
- }
107
-
108
- _archiver.finalize();
109
-
110
- return new Promise((resolve, _reject) => {
111
- output.on("close", resolve);
112
- });
113
- }
114
-
115
- async function sendBuild(ctx, { workspaceId, token }) {
116
- const { FormData } = await import("formdata-node");
117
- const { fileFromPath } = await import("formdata-node/file-from-path");
118
-
119
- const file = await fileFromPath(
120
- ctx.client.archiveFile,
121
- "embeddable-build.zip",
122
- );
123
-
124
- const form = new FormData();
125
- form.set("file", file, "embeddable-build.zip");
126
- form.set("workspaceId", workspaceId);
127
-
128
- await axios.post("https://metadata.embeddable.com/sdk/upload-files", form, {
129
- headers: {
130
- "Content-Type": "multipart/form-data",
131
- Authorization: `Bearer ${token}`,
132
- },
133
- maxContentLength: Infinity,
134
- maxBodyLength: Infinity,
135
- });
136
-
137
- await fs.rm(ctx.client.archiveFile);
138
- }
139
-
140
- async function getWorkspaces(token) {
141
- try {
142
- return axios
143
- .get("https://api.embeddable.com/workspace", {
144
- headers: {
145
- Authorization: `Bearer ${token}`,
146
- },
147
- })
148
- .then((res) => res.data);
149
- } catch (e) {
150
- console.error(e);
151
- return [];
152
- }
153
- }
@@ -1,66 +0,0 @@
1
- const fs = require("node:fs/promises");
2
- const oraP = import("ora");
3
- const YAML = require("yaml");
4
- const { findEmbFiles } = require("./findEmbFiles");
5
-
6
- const EMB_YAML_FILE_REGEX = /^(.*)\.emb\.ya?ml$/;
7
-
8
- async function validate(ctx) {
9
- const ora = (await oraP).default;
10
-
11
- const spinnerValidate = ora("validation...").start();
12
-
13
- const filesList = await findEmbFiles(ctx.client.srcDir, EMB_YAML_FILE_REGEX);
14
-
15
- const componentConfigErrors = await componentConfigValidation(filesList);
16
-
17
- if (componentConfigErrors.length) {
18
- spinnerValidate.fail("One or more component.emb.yaml files are invalid:");
19
-
20
- componentConfigErrors.forEach((errorMessage) =>
21
- spinnerValidate.info(errorMessage),
22
- );
23
-
24
- process.exit(1);
25
- }
26
-
27
- spinnerValidate.succeed("validation completed");
28
- }
29
-
30
- module.exports = { validate };
31
-
32
- async function componentConfigValidation(filesList) {
33
- const ARRAY_ALLOWED_TYPES = ["Dimension", "Measure"];
34
- const errors = [];
35
-
36
- for (const [fileName, filePath] of filesList) {
37
- if (!fileName.endsWith(".component")) continue;
38
-
39
- const fileContentRaw = await fs.readFile(filePath, "utf8");
40
-
41
- const config = YAML.parse(fileContentRaw);
42
-
43
- if (!("inputs" in config) || config.inputs.length === 0) continue;
44
-
45
- config.inputs
46
- .filter((inputConfig) => inputConfig?.array)
47
- .forEach((inputConfig) => {
48
- if (!ARRAY_ALLOWED_TYPES.includes(inputConfig?.type)) {
49
- const errorMessage = `${fileName} contains invalid type value for \x1b[33m${
50
- inputConfig.name
51
- }\x1b[0m input.
52
- \x1b[33m${
53
- inputConfig.name
54
- }\x1b[0m is marked as \x1b[33marray\x1b[0m. Inputs marked as array support the following types: ${ARRAY_ALLOWED_TYPES.join(
55
- ", ",
56
- )}.
57
- Specified \x1b[33m${inputConfig?.type}\x1b[0m type is not supported.
58
- Please check the following file: \x1b[33m${filePath}\x1b[0m\n`;
59
-
60
- errors.push(errorMessage);
61
- }
62
- });
63
- }
64
-
65
- return errors;
66
- }