@embeddable.com/sdk-core 3.2.0-next.9 → 3.2.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
@@ -4,7 +4,9 @@ import * as path$1 from 'node:path';
4
4
  import { join } from 'node:path';
5
5
  import * as vite from 'vite';
6
6
  import 'node:child_process';
7
+ import * as crypto from 'node:crypto';
7
8
  import * as fs$2 from 'node:fs';
9
+ import { existsSync } from 'node:fs';
8
10
  import { createNodeLogger, createNodeSys } from '@stencil/core/sys/node';
9
11
  import { loadConfig, createCompiler } from '@stencil/core/compiler';
10
12
  import * as YAML from 'yaml';
@@ -230,6 +232,11 @@ let ZodError$1 = class ZodError extends Error {
230
232
  processError(this);
231
233
  return fieldErrors;
232
234
  }
235
+ static assert(value) {
236
+ if (!(value instanceof ZodError)) {
237
+ throw new Error(`Not a ZodError: ${value}`);
238
+ }
239
+ }
233
240
  toString() {
234
241
  return this.message;
235
242
  }
@@ -261,6 +268,11 @@ ZodError$1.create = (issues) => {
261
268
  const error = new ZodError$1(issues);
262
269
  return error;
263
270
  };
271
+
272
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
273
+ var e = new Error(message);
274
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
275
+ };
264
276
 
265
277
  var errorUtil$1;
266
278
  (function (errorUtil) {
@@ -336,6 +348,20 @@ const formatErrorPath = (path) => {
336
348
  return formatted;
337
349
  };
338
350
 
351
+ /**
352
+ * Get the hash of the content string. It returns the first 5 characters of the hash
353
+ * Example: getContentHash("Hello World")
354
+ * @param contentString The content string to hash
355
+ * @returns
356
+ */
357
+ const getContentHash = (contentString) => {
358
+ return crypto
359
+ .createHash("md5")
360
+ .update(contentString)
361
+ .digest("hex")
362
+ .substring(0, 5);
363
+ };
364
+
339
365
  const oraP$4 = import('ora');
340
366
  const EMB_TYPE_FILE_REGEX = /^(.*)\.type\.emb\.[jt]s$/;
341
367
  const EMB_OPTIONS_FILE_REGEX = /^(.*)\.options\.emb\.[jt]s$/;
@@ -359,6 +385,7 @@ async function generate$1(ctx) {
359
385
  await fs$1.writeFile(path$1.resolve(ctx.client.rootDir, ctx.outputOptions.typesEntryPointFilename), typeImports);
360
386
  }
361
387
  async function build$1(ctx) {
388
+ var _a;
362
389
  await vite.build({
363
390
  logLevel: "error",
364
391
  build: {
@@ -368,6 +395,13 @@ async function build$1(ctx) {
368
395
  formats: ["es"],
369
396
  fileName: "embeddable-types",
370
397
  },
398
+ rollupOptions: ((_a = ctx.dev) === null || _a === void 0 ? void 0 : _a.watch)
399
+ ? undefined
400
+ : {
401
+ output: {
402
+ entryFileNames: "embeddable-types-[hash].js",
403
+ },
404
+ },
371
405
  outDir: ctx.client.buildDir,
372
406
  },
373
407
  });
@@ -384,6 +418,8 @@ var prepare = async (ctx) => {
384
418
  async function removeIfExists(ctx) {
385
419
  if (fs$2.existsSync(ctx.client.buildDir))
386
420
  await fs$1.rm(ctx.client.buildDir, { recursive: true });
421
+ if (fs$2.existsSync(ctx.client.tmpDir))
422
+ await fs$1.rm(ctx.client.tmpDir, { recursive: true });
387
423
  }
388
424
  async function copyStencilConfigsToClient(ctx) {
389
425
  await fs$1.cp(ctx.core.configsDir, ctx.client.buildDir, { recursive: true });
@@ -417,16 +453,18 @@ async function injectBundleRender(ctx, pluginName) {
417
453
  await fs$1.writeFile(path$1.resolve(ctx.client.componentDir, "component.tsx"), content.replace(RENDER_IMPORT_TOKEN, importStr));
418
454
  }
419
455
  async function runStencil(ctx) {
420
- var _a, _b;
456
+ var _a, _b, _c;
421
457
  const logger = ((_a = ctx.dev) === null || _a === void 0 ? void 0 : _a.logger) || createNodeLogger({ process });
422
458
  const sys = ((_b = ctx.dev) === null || _b === void 0 ? void 0 : _b.sys) || createNodeSys({ process });
423
459
  const devMode = !!ctx.dev;
460
+ const isWindows = process.platform === "win32";
424
461
  const validated = await loadConfig({
425
462
  initTsConfig: true,
426
463
  logger,
427
464
  sys,
428
465
  config: {
429
466
  devMode,
467
+ maxConcurrentWorkers: isWindows ? 0 : 8, // workers break on windows
430
468
  rootDir: ctx.client.buildDir,
431
469
  configPath: path$1.resolve(ctx.client.buildDir, "stencil.config.ts"),
432
470
  tsconfig: path$1.resolve(ctx.client.buildDir, "tsconfig.json"),
@@ -441,6 +479,14 @@ async function runStencil(ctx) {
441
479
  });
442
480
  const compiler = await createCompiler(validated.config);
443
481
  await compiler.build();
482
+ const entryFilePath = path$1.resolve(ctx.client.stencilBuild, "embeddable-wrapper.esm.js");
483
+ let fileName = "embeddable-wrapper.esm.js";
484
+ if (!((_c = ctx.dev) === null || _c === void 0 ? void 0 : _c.watch)) {
485
+ const entryFileContent = await fs$1.readFile(entryFilePath, "utf8");
486
+ const fileHash = getContentHash(entryFileContent);
487
+ fileName = `embeddable-wrapper.esm-${fileHash}.js`;
488
+ }
489
+ await fs$1.rename(entryFilePath, path$1.resolve(ctx.client.stencilBuild, fileName));
444
490
  await compiler.destroy();
445
491
  process.chdir(ctx.client.rootDir);
446
492
  }
@@ -470,10 +516,28 @@ var cleanup = async (ctx) => {
470
516
  await moveBuildTOBuildDir(ctx);
471
517
  };
472
518
  async function extractBuild(ctx) {
519
+ const [[, stencilWrapperFilePath]] = await findFiles(ctx.client.stencilBuild, /embeddable-wrapper.esm-[a-z0-9]+\.js/);
520
+ const stencilWrapperFileName = path$1.basename(stencilWrapperFilePath);
473
521
  await fs$1.rename(path$1.resolve(ctx.client.buildDir, ctx.client.stencilBuild), ctx.client.tmpDir);
474
- await fs$1.rename(path$1.resolve(ctx.client.buildDir, "embeddable-types.js"), path$1.join(ctx.client.tmpDir, "embeddable-types.js"));
475
- await fs$1.rename(path$1.resolve(ctx.client.buildDir, "embeddable-components-meta.js"), path$1.join(ctx.client.tmpDir, "embeddable-components-meta.js"));
476
- await fs$1.rename(path$1.resolve(ctx.client.buildDir, "embeddable-editors-meta.js"), path$1.join(ctx.client.tmpDir, "embeddable-editors-meta.js"));
522
+ const [[, typesFilePath]] = await findFiles(ctx.client.buildDir, /embeddable-types-[a-z0-9]+\.js/);
523
+ const typesFileName = path$1.basename(typesFilePath);
524
+ await fs$1.rename(typesFilePath, path$1.join(ctx.client.tmpDir, typesFileName));
525
+ const [[, metaFilePath]] = await findFiles(ctx.client.buildDir, /embeddable-components-meta-[a-z0-9]+\.js/);
526
+ const metaFileName = path$1.basename(metaFilePath);
527
+ await fs$1.rename(metaFilePath, path$1.join(ctx.client.tmpDir, metaFileName));
528
+ const [[, editorsMetaFilePath]] = await findFiles(ctx.client.buildDir, /embeddable-editors-meta-[a-z0-9]+\.js/);
529
+ const editorsMetaFileName = path$1.basename(editorsMetaFilePath);
530
+ await fs$1.rename(editorsMetaFilePath, path$1.join(ctx.client.tmpDir, editorsMetaFileName));
531
+ // write manifest file with files with hash
532
+ const manifest = {
533
+ entryFiles: {
534
+ "embeddable-types.js": typesFileName,
535
+ "embeddable-components-meta.js": metaFileName,
536
+ "embeddable-editors-meta.js": editorsMetaFileName,
537
+ "embeddable-wrapper.esm.js": stencilWrapperFileName,
538
+ },
539
+ };
540
+ await fs$1.writeFile(path$1.join(ctx.client.tmpDir, "embeddable-manifest.json"), JSON.stringify(manifest));
477
541
  }
478
542
  async function removeObsoleteDir(dir) {
479
543
  await fs$1.rm(dir, { recursive: true });
@@ -716,6 +780,11 @@ class ZodError extends Error {
716
780
  processError(this);
717
781
  return fieldErrors;
718
782
  }
783
+ static assert(value) {
784
+ if (!(value instanceof ZodError)) {
785
+ throw new Error(`Not a ZodError: ${value}`);
786
+ }
787
+ }
719
788
  toString() {
720
789
  return this.message;
721
790
  }
@@ -888,6 +957,13 @@ const makeIssue = (params) => {
888
957
  ...issueData,
889
958
  path: fullPath,
890
959
  };
960
+ if (issueData.message !== undefined) {
961
+ return {
962
+ ...issueData,
963
+ path: fullPath,
964
+ message: issueData.message,
965
+ };
966
+ }
891
967
  let errorMessage = "";
892
968
  const maps = errorMaps
893
969
  .filter((m) => !!m)
@@ -899,11 +975,12 @@ const makeIssue = (params) => {
899
975
  return {
900
976
  ...issueData,
901
977
  path: fullPath,
902
- message: issueData.message || errorMessage,
978
+ message: errorMessage,
903
979
  };
904
980
  };
905
981
  const EMPTY_PATH = [];
906
982
  function addIssueToContext(ctx, issueData) {
983
+ const overrideMap = getErrorMap();
907
984
  const issue = makeIssue({
908
985
  issueData: issueData,
909
986
  data: ctx.data,
@@ -911,8 +988,8 @@ function addIssueToContext(ctx, issueData) {
911
988
  errorMaps: [
912
989
  ctx.common.contextualErrorMap,
913
990
  ctx.schemaErrorMap,
914
- getErrorMap(),
915
- errorMap, // then global default map
991
+ overrideMap,
992
+ overrideMap === errorMap ? undefined : errorMap, // then global default map
916
993
  ].filter((x) => !!x),
917
994
  });
918
995
  ctx.common.issues.push(issue);
@@ -943,9 +1020,11 @@ class ParseStatus {
943
1020
  static async mergeObjectAsync(status, pairs) {
944
1021
  const syncPairs = [];
945
1022
  for (const pair of pairs) {
1023
+ const key = await pair.key;
1024
+ const value = await pair.value;
946
1025
  syncPairs.push({
947
- key: await pair.key,
948
- value: await pair.value,
1026
+ key,
1027
+ value,
949
1028
  });
950
1029
  }
951
1030
  return ParseStatus.mergeObjectSync(status, syncPairs);
@@ -980,12 +1059,46 @@ const isDirty = (x) => x.status === "dirty";
980
1059
  const isValid = (x) => x.status === "valid";
981
1060
  const isAsync$1 = (x) => typeof Promise !== "undefined" && x instanceof Promise;
982
1061
 
1062
+ /******************************************************************************
1063
+ Copyright (c) Microsoft Corporation.
1064
+
1065
+ Permission to use, copy, modify, and/or distribute this software for any
1066
+ purpose with or without fee is hereby granted.
1067
+
1068
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
1069
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
1070
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
1071
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
1072
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
1073
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
1074
+ PERFORMANCE OF THIS SOFTWARE.
1075
+ ***************************************************************************** */
1076
+
1077
+ function __classPrivateFieldGet(receiver, state, kind, f) {
1078
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
1079
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
1080
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
1081
+ }
1082
+
1083
+ function __classPrivateFieldSet(receiver, state, value, kind, f) {
1084
+ if (kind === "m") throw new TypeError("Private method is not writable");
1085
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
1086
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
1087
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
1088
+ }
1089
+
1090
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
1091
+ var e = new Error(message);
1092
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
1093
+ };
1094
+
983
1095
  var errorUtil;
984
1096
  (function (errorUtil) {
985
1097
  errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {};
986
1098
  errorUtil.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message;
987
1099
  })(errorUtil || (errorUtil = {}));
988
1100
 
1101
+ var _ZodEnum_cache, _ZodNativeEnum_cache;
989
1102
  class ParseInputLazyPath {
990
1103
  constructor(parent, value, path, key) {
991
1104
  this._cachedPath = [];
@@ -1036,12 +1149,17 @@ function processCreateParams(params) {
1036
1149
  if (errorMap)
1037
1150
  return { errorMap: errorMap, description };
1038
1151
  const customMap = (iss, ctx) => {
1039
- if (iss.code !== "invalid_type")
1040
- return { message: ctx.defaultError };
1152
+ var _a, _b;
1153
+ const { message } = params;
1154
+ if (iss.code === "invalid_enum_value") {
1155
+ return { message: message !== null && message !== void 0 ? message : ctx.defaultError };
1156
+ }
1041
1157
  if (typeof ctx.data === "undefined") {
1042
- return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError };
1158
+ return { message: (_a = message !== null && message !== void 0 ? message : required_error) !== null && _a !== void 0 ? _a : ctx.defaultError };
1043
1159
  }
1044
- return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError };
1160
+ if (iss.code !== "invalid_type")
1161
+ return { message: ctx.defaultError };
1162
+ return { message: (_b = message !== null && message !== void 0 ? message : invalid_type_error) !== null && _b !== void 0 ? _b : ctx.defaultError };
1045
1163
  };
1046
1164
  return { errorMap: customMap, description };
1047
1165
  }
@@ -1299,11 +1417,13 @@ class ZodType {
1299
1417
  }
1300
1418
  }
1301
1419
  const cuidRegex = /^c[^\s-]{8,}$/i;
1302
- const cuid2Regex = /^[a-z][a-z0-9]*$/;
1420
+ const cuid2Regex = /^[0-9a-z]+$/;
1303
1421
  const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/;
1304
1422
  // const uuidRegex =
1305
1423
  // /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;
1306
1424
  const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
1425
+ const nanoidRegex = /^[a-z0-9_-]{21}$/i;
1426
+ const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
1307
1427
  // from https://stackoverflow.com/a/46181/1550155
1308
1428
  // old version: too slow, didn't support unicode
1309
1429
  // const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i;
@@ -1316,41 +1436,48 @@ const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-
1316
1436
  // /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
1317
1437
  // const emailRegex =
1318
1438
  // /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i;
1319
- const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_+-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
1439
+ const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
1320
1440
  // const emailRegex =
1321
1441
  // /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i;
1322
1442
  // from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression
1323
1443
  const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
1324
1444
  let emojiRegex;
1325
- const ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/;
1445
+ // faster, simpler, safer
1446
+ const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
1326
1447
  const ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;
1327
- // Adapted from https://stackoverflow.com/a/3143231
1328
- const datetimeRegex = (args) => {
1448
+ // https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript
1449
+ const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
1450
+ // simple
1451
+ // const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`;
1452
+ // no leap year validation
1453
+ // const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`;
1454
+ // with leap year validation
1455
+ const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`;
1456
+ const dateRegex = new RegExp(`^${dateRegexSource}$`);
1457
+ function timeRegexSource(args) {
1458
+ // let regex = `\\d{2}:\\d{2}:\\d{2}`;
1459
+ let regex = `([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d`;
1329
1460
  if (args.precision) {
1330
- if (args.offset) {
1331
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
1332
- }
1333
- else {
1334
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`);
1335
- }
1461
+ regex = `${regex}\\.\\d{${args.precision}}`;
1336
1462
  }
1337
- else if (args.precision === 0) {
1338
- if (args.offset) {
1339
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
1340
- }
1341
- else {
1342
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`);
1343
- }
1344
- }
1345
- else {
1346
- if (args.offset) {
1347
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`);
1348
- }
1349
- else {
1350
- return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`);
1351
- }
1463
+ else if (args.precision == null) {
1464
+ regex = `${regex}(\\.\\d+)?`;
1352
1465
  }
1353
- };
1466
+ return regex;
1467
+ }
1468
+ function timeRegex(args) {
1469
+ return new RegExp(`^${timeRegexSource(args)}$`);
1470
+ }
1471
+ // Adapted from https://stackoverflow.com/a/3143231
1472
+ function datetimeRegex(args) {
1473
+ let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
1474
+ const opts = [];
1475
+ opts.push(args.local ? `Z?` : `Z`);
1476
+ if (args.offset)
1477
+ opts.push(`([+-]\\d{2}:?\\d{2})`);
1478
+ regex = `${regex}(${opts.join("|")})`;
1479
+ return new RegExp(`^${regex}$`);
1480
+ }
1354
1481
  function isValidIP(ip, version) {
1355
1482
  if ((version === "v4" || !version) && ipv4Regex.test(ip)) {
1356
1483
  return true;
@@ -1372,9 +1499,7 @@ class ZodString extends ZodType {
1372
1499
  code: ZodIssueCode.invalid_type,
1373
1500
  expected: ZodParsedType.string,
1374
1501
  received: ctx.parsedType,
1375
- }
1376
- //
1377
- );
1502
+ });
1378
1503
  return INVALID;
1379
1504
  }
1380
1505
  const status = new ParseStatus();
@@ -1472,6 +1597,17 @@ class ZodString extends ZodType {
1472
1597
  status.dirty();
1473
1598
  }
1474
1599
  }
1600
+ else if (check.kind === "nanoid") {
1601
+ if (!nanoidRegex.test(input.data)) {
1602
+ ctx = this._getOrReturnCtx(input, ctx);
1603
+ addIssueToContext(ctx, {
1604
+ validation: "nanoid",
1605
+ code: ZodIssueCode.invalid_string,
1606
+ message: check.message,
1607
+ });
1608
+ status.dirty();
1609
+ }
1610
+ }
1475
1611
  else if (check.kind === "cuid") {
1476
1612
  if (!cuidRegex.test(input.data)) {
1477
1613
  ctx = this._getOrReturnCtx(input, ctx);
@@ -1586,6 +1722,41 @@ class ZodString extends ZodType {
1586
1722
  status.dirty();
1587
1723
  }
1588
1724
  }
1725
+ else if (check.kind === "date") {
1726
+ const regex = dateRegex;
1727
+ if (!regex.test(input.data)) {
1728
+ ctx = this._getOrReturnCtx(input, ctx);
1729
+ addIssueToContext(ctx, {
1730
+ code: ZodIssueCode.invalid_string,
1731
+ validation: "date",
1732
+ message: check.message,
1733
+ });
1734
+ status.dirty();
1735
+ }
1736
+ }
1737
+ else if (check.kind === "time") {
1738
+ const regex = timeRegex(check);
1739
+ if (!regex.test(input.data)) {
1740
+ ctx = this._getOrReturnCtx(input, ctx);
1741
+ addIssueToContext(ctx, {
1742
+ code: ZodIssueCode.invalid_string,
1743
+ validation: "time",
1744
+ message: check.message,
1745
+ });
1746
+ status.dirty();
1747
+ }
1748
+ }
1749
+ else if (check.kind === "duration") {
1750
+ if (!durationRegex.test(input.data)) {
1751
+ ctx = this._getOrReturnCtx(input, ctx);
1752
+ addIssueToContext(ctx, {
1753
+ validation: "duration",
1754
+ code: ZodIssueCode.invalid_string,
1755
+ message: check.message,
1756
+ });
1757
+ status.dirty();
1758
+ }
1759
+ }
1589
1760
  else if (check.kind === "ip") {
1590
1761
  if (!isValidIP(input.data, check.version)) {
1591
1762
  ctx = this._getOrReturnCtx(input, ctx);
@@ -1597,6 +1768,17 @@ class ZodString extends ZodType {
1597
1768
  status.dirty();
1598
1769
  }
1599
1770
  }
1771
+ else if (check.kind === "base64") {
1772
+ if (!base64Regex.test(input.data)) {
1773
+ ctx = this._getOrReturnCtx(input, ctx);
1774
+ addIssueToContext(ctx, {
1775
+ validation: "base64",
1776
+ code: ZodIssueCode.invalid_string,
1777
+ message: check.message,
1778
+ });
1779
+ status.dirty();
1780
+ }
1781
+ }
1600
1782
  else {
1601
1783
  util$7.assertNever(check);
1602
1784
  }
@@ -1628,6 +1810,9 @@ class ZodString extends ZodType {
1628
1810
  uuid(message) {
1629
1811
  return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
1630
1812
  }
1813
+ nanoid(message) {
1814
+ return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
1815
+ }
1631
1816
  cuid(message) {
1632
1817
  return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
1633
1818
  }
@@ -1637,16 +1822,20 @@ class ZodString extends ZodType {
1637
1822
  ulid(message) {
1638
1823
  return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
1639
1824
  }
1825
+ base64(message) {
1826
+ return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
1827
+ }
1640
1828
  ip(options) {
1641
1829
  return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
1642
1830
  }
1643
1831
  datetime(options) {
1644
- var _a;
1832
+ var _a, _b;
1645
1833
  if (typeof options === "string") {
1646
1834
  return this._addCheck({
1647
1835
  kind: "datetime",
1648
1836
  precision: null,
1649
1837
  offset: false,
1838
+ local: false,
1650
1839
  message: options,
1651
1840
  });
1652
1841
  }
@@ -1654,9 +1843,30 @@ class ZodString extends ZodType {
1654
1843
  kind: "datetime",
1655
1844
  precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
1656
1845
  offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false,
1846
+ local: (_b = options === null || options === void 0 ? void 0 : options.local) !== null && _b !== void 0 ? _b : false,
1657
1847
  ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
1658
1848
  });
1659
1849
  }
1850
+ date(message) {
1851
+ return this._addCheck({ kind: "date", message });
1852
+ }
1853
+ time(options) {
1854
+ if (typeof options === "string") {
1855
+ return this._addCheck({
1856
+ kind: "time",
1857
+ precision: null,
1858
+ message: options,
1859
+ });
1860
+ }
1861
+ return this._addCheck({
1862
+ kind: "time",
1863
+ precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision,
1864
+ ...errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message),
1865
+ });
1866
+ }
1867
+ duration(message) {
1868
+ return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
1869
+ }
1660
1870
  regex(regex, message) {
1661
1871
  return this._addCheck({
1662
1872
  kind: "regex",
@@ -1735,6 +1945,15 @@ class ZodString extends ZodType {
1735
1945
  get isDatetime() {
1736
1946
  return !!this._def.checks.find((ch) => ch.kind === "datetime");
1737
1947
  }
1948
+ get isDate() {
1949
+ return !!this._def.checks.find((ch) => ch.kind === "date");
1950
+ }
1951
+ get isTime() {
1952
+ return !!this._def.checks.find((ch) => ch.kind === "time");
1953
+ }
1954
+ get isDuration() {
1955
+ return !!this._def.checks.find((ch) => ch.kind === "duration");
1956
+ }
1738
1957
  get isEmail() {
1739
1958
  return !!this._def.checks.find((ch) => ch.kind === "email");
1740
1959
  }
@@ -1747,6 +1966,9 @@ class ZodString extends ZodType {
1747
1966
  get isUUID() {
1748
1967
  return !!this._def.checks.find((ch) => ch.kind === "uuid");
1749
1968
  }
1969
+ get isNANOID() {
1970
+ return !!this._def.checks.find((ch) => ch.kind === "nanoid");
1971
+ }
1750
1972
  get isCUID() {
1751
1973
  return !!this._def.checks.find((ch) => ch.kind === "cuid");
1752
1974
  }
@@ -1759,6 +1981,9 @@ class ZodString extends ZodType {
1759
1981
  get isIP() {
1760
1982
  return !!this._def.checks.find((ch) => ch.kind === "ip");
1761
1983
  }
1984
+ get isBase64() {
1985
+ return !!this._def.checks.find((ch) => ch.kind === "base64");
1986
+ }
1762
1987
  get minLength() {
1763
1988
  let min = null;
1764
1989
  for (const ch of this._def.checks) {
@@ -2746,9 +2971,10 @@ class ZodObject extends ZodType {
2746
2971
  const syncPairs = [];
2747
2972
  for (const pair of pairs) {
2748
2973
  const key = await pair.key;
2974
+ const value = await pair.value;
2749
2975
  syncPairs.push({
2750
2976
  key,
2751
- value: await pair.value,
2977
+ value,
2752
2978
  alwaysSet: pair.alwaysSet,
2753
2979
  });
2754
2980
  }
@@ -3122,7 +3348,7 @@ const getDiscriminator = (type) => {
3122
3348
  }
3123
3349
  else if (type instanceof ZodNativeEnum) {
3124
3350
  // eslint-disable-next-line ban/ban
3125
- return Object.keys(type.enum);
3351
+ return util$7.objectValues(type.enum);
3126
3352
  }
3127
3353
  else if (type instanceof ZodDefault) {
3128
3354
  return getDiscriminator(type._def.innerType);
@@ -3133,8 +3359,23 @@ const getDiscriminator = (type) => {
3133
3359
  else if (type instanceof ZodNull) {
3134
3360
  return [null];
3135
3361
  }
3362
+ else if (type instanceof ZodOptional) {
3363
+ return [undefined, ...getDiscriminator(type.unwrap())];
3364
+ }
3365
+ else if (type instanceof ZodNullable) {
3366
+ return [null, ...getDiscriminator(type.unwrap())];
3367
+ }
3368
+ else if (type instanceof ZodBranded) {
3369
+ return getDiscriminator(type.unwrap());
3370
+ }
3371
+ else if (type instanceof ZodReadonly) {
3372
+ return getDiscriminator(type.unwrap());
3373
+ }
3374
+ else if (type instanceof ZodCatch) {
3375
+ return getDiscriminator(type._def.innerType);
3376
+ }
3136
3377
  else {
3137
- return null;
3378
+ return [];
3138
3379
  }
3139
3380
  };
3140
3381
  class ZodDiscriminatedUnion extends ZodType {
@@ -3197,7 +3438,7 @@ class ZodDiscriminatedUnion extends ZodType {
3197
3438
  // try {
3198
3439
  for (const type of options) {
3199
3440
  const discriminatorValues = getDiscriminator(type.shape[discriminator]);
3200
- if (!discriminatorValues) {
3441
+ if (!discriminatorValues.length) {
3201
3442
  throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
3202
3443
  }
3203
3444
  for (const value of discriminatorValues) {
@@ -3410,6 +3651,7 @@ class ZodRecord extends ZodType {
3410
3651
  pairs.push({
3411
3652
  key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
3412
3653
  value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
3654
+ alwaysSet: key in ctx.data,
3413
3655
  });
3414
3656
  }
3415
3657
  if (ctx.common.async) {
@@ -3769,6 +4011,10 @@ function createZodEnum(values, params) {
3769
4011
  });
3770
4012
  }
3771
4013
  class ZodEnum extends ZodType {
4014
+ constructor() {
4015
+ super(...arguments);
4016
+ _ZodEnum_cache.set(this, void 0);
4017
+ }
3772
4018
  _parse(input) {
3773
4019
  if (typeof input.data !== "string") {
3774
4020
  const ctx = this._getOrReturnCtx(input);
@@ -3780,7 +4026,10 @@ class ZodEnum extends ZodType {
3780
4026
  });
3781
4027
  return INVALID;
3782
4028
  }
3783
- if (this._def.values.indexOf(input.data) === -1) {
4029
+ if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f")) {
4030
+ __classPrivateFieldSet(this, _ZodEnum_cache, new Set(this._def.values), "f");
4031
+ }
4032
+ if (!__classPrivateFieldGet(this, _ZodEnum_cache, "f").has(input.data)) {
3784
4033
  const ctx = this._getOrReturnCtx(input);
3785
4034
  const expectedValues = this._def.values;
3786
4035
  addIssueToContext(ctx, {
@@ -3816,15 +4065,26 @@ class ZodEnum extends ZodType {
3816
4065
  }
3817
4066
  return enumValues;
3818
4067
  }
3819
- extract(values) {
3820
- return ZodEnum.create(values);
4068
+ extract(values, newDef = this._def) {
4069
+ return ZodEnum.create(values, {
4070
+ ...this._def,
4071
+ ...newDef,
4072
+ });
3821
4073
  }
3822
- exclude(values) {
3823
- return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)));
4074
+ exclude(values, newDef = this._def) {
4075
+ return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
4076
+ ...this._def,
4077
+ ...newDef,
4078
+ });
3824
4079
  }
3825
4080
  }
4081
+ _ZodEnum_cache = new WeakMap();
3826
4082
  ZodEnum.create = createZodEnum;
3827
4083
  class ZodNativeEnum extends ZodType {
4084
+ constructor() {
4085
+ super(...arguments);
4086
+ _ZodNativeEnum_cache.set(this, void 0);
4087
+ }
3828
4088
  _parse(input) {
3829
4089
  const nativeEnumValues = util$7.getValidEnumValues(this._def.values);
3830
4090
  const ctx = this._getOrReturnCtx(input);
@@ -3838,7 +4098,10 @@ class ZodNativeEnum extends ZodType {
3838
4098
  });
3839
4099
  return INVALID;
3840
4100
  }
3841
- if (nativeEnumValues.indexOf(input.data) === -1) {
4101
+ if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f")) {
4102
+ __classPrivateFieldSet(this, _ZodNativeEnum_cache, new Set(util$7.getValidEnumValues(this._def.values)), "f");
4103
+ }
4104
+ if (!__classPrivateFieldGet(this, _ZodNativeEnum_cache, "f").has(input.data)) {
3842
4105
  const expectedValues = util$7.objectValues(nativeEnumValues);
3843
4106
  addIssueToContext(ctx, {
3844
4107
  received: ctx.data,
@@ -3853,6 +4116,7 @@ class ZodNativeEnum extends ZodType {
3853
4116
  return this._def.values;
3854
4117
  }
3855
4118
  }
4119
+ _ZodNativeEnum_cache = new WeakMap();
3856
4120
  ZodNativeEnum.create = (values, params) => {
3857
4121
  return new ZodNativeEnum({
3858
4122
  values: values,
@@ -3922,33 +4186,43 @@ class ZodEffects extends ZodType {
3922
4186
  checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
3923
4187
  if (effect.type === "preprocess") {
3924
4188
  const processed = effect.transform(ctx.data, checkCtx);
3925
- if (ctx.common.issues.length) {
3926
- return {
3927
- status: "dirty",
3928
- value: ctx.data,
3929
- };
3930
- }
3931
4189
  if (ctx.common.async) {
3932
- return Promise.resolve(processed).then((processed) => {
3933
- return this._def.schema._parseAsync({
4190
+ return Promise.resolve(processed).then(async (processed) => {
4191
+ if (status.value === "aborted")
4192
+ return INVALID;
4193
+ const result = await this._def.schema._parseAsync({
3934
4194
  data: processed,
3935
4195
  path: ctx.path,
3936
4196
  parent: ctx,
3937
4197
  });
4198
+ if (result.status === "aborted")
4199
+ return INVALID;
4200
+ if (result.status === "dirty")
4201
+ return DIRTY(result.value);
4202
+ if (status.value === "dirty")
4203
+ return DIRTY(result.value);
4204
+ return result;
3938
4205
  });
3939
4206
  }
3940
4207
  else {
3941
- return this._def.schema._parseSync({
4208
+ if (status.value === "aborted")
4209
+ return INVALID;
4210
+ const result = this._def.schema._parseSync({
3942
4211
  data: processed,
3943
4212
  path: ctx.path,
3944
4213
  parent: ctx,
3945
4214
  });
4215
+ if (result.status === "aborted")
4216
+ return INVALID;
4217
+ if (result.status === "dirty")
4218
+ return DIRTY(result.value);
4219
+ if (status.value === "dirty")
4220
+ return DIRTY(result.value);
4221
+ return result;
3946
4222
  }
3947
4223
  }
3948
4224
  if (effect.type === "refinement") {
3949
- const executeRefinement = (acc
3950
- // effect: RefinementEffect<any>
3951
- ) => {
4225
+ const executeRefinement = (acc) => {
3952
4226
  const result = effect.refinement(acc, checkCtx);
3953
4227
  if (ctx.common.async) {
3954
4228
  return Promise.resolve(result);
@@ -4251,10 +4525,18 @@ class ZodPipeline extends ZodType {
4251
4525
  class ZodReadonly extends ZodType {
4252
4526
  _parse(input) {
4253
4527
  const result = this._def.innerType._parse(input);
4254
- if (isValid(result)) {
4255
- result.value = Object.freeze(result.value);
4256
- }
4257
- return result;
4528
+ const freeze = (data) => {
4529
+ if (isValid(data)) {
4530
+ data.value = Object.freeze(data.value);
4531
+ }
4532
+ return data;
4533
+ };
4534
+ return isAsync$1(result)
4535
+ ? result.then((data) => freeze(data))
4536
+ : freeze(result);
4537
+ }
4538
+ unwrap() {
4539
+ return this._def.innerType;
4258
4540
  }
4259
4541
  }
4260
4542
  ZodReadonly.create = (type, params) => {
@@ -4264,7 +4546,7 @@ ZodReadonly.create = (type, params) => {
4264
4546
  ...processCreateParams(params),
4265
4547
  });
4266
4548
  };
4267
- const custom = (check, params = {},
4549
+ function custom(check, params = {},
4268
4550
  /**
4269
4551
  * @deprecated
4270
4552
  *
@@ -4275,7 +4557,7 @@ const custom = (check, params = {},
4275
4557
  * ```
4276
4558
  *
4277
4559
  */
4278
- fatal) => {
4560
+ fatal) {
4279
4561
  if (check)
4280
4562
  return ZodAny.create().superRefine((data, ctx) => {
4281
4563
  var _a, _b;
@@ -4291,7 +4573,7 @@ fatal) => {
4291
4573
  }
4292
4574
  });
4293
4575
  return ZodAny.create();
4294
- };
4576
+ }
4295
4577
  const late = {
4296
4578
  object: ZodObject.lazycreate,
4297
4579
  };
@@ -4409,6 +4691,7 @@ var z = /*#__PURE__*/Object.freeze({
4409
4691
  ZodParsedType: ZodParsedType,
4410
4692
  getParsedType: getParsedType,
4411
4693
  ZodType: ZodType,
4694
+ datetimeRegex: datetimeRegex,
4412
4695
  ZodString: ZodString,
4413
4696
  ZodNumber: ZodNumber,
4414
4697
  ZodBigInt: ZodBigInt,
@@ -4513,7 +4796,7 @@ var validate = async (ctx, exitIfInvalid = true) => {
4513
4796
  const ora = (await import('ora')).default;
4514
4797
  const spinnerValidate = ora("Data model validation...").start();
4515
4798
  const filesList = await findFiles(ctx.client.srcDir, CUBE_YAML_FILE_REGEX);
4516
- const securityContextFilesList = await findFiles(ctx.client.srcDir, SECURITY_CONTEXT_FILE_REGEX);
4799
+ const securityContextFilesList = await findFiles(ctx.client.modelsSrc || ctx.client.srcDir, SECURITY_CONTEXT_FILE_REGEX);
4517
4800
  const dataModelErrors = await dataModelsValidation(filesList);
4518
4801
  if (dataModelErrors.length) {
4519
4802
  spinnerValidate.fail("One or more cube.yaml files are invalid:");
@@ -4538,9 +4821,18 @@ async function dataModelsValidation(filesList) {
4538
4821
  for (const [_, filePath] of filesList) {
4539
4822
  const fileContentRaw = await fs$1.readFile(filePath, "utf8");
4540
4823
  const cube = YAML.parse(fileContentRaw);
4541
- const safeParse = cubeModelSchema.safeParse(cube);
4542
- if (!safeParse.success) {
4543
- errorFormatter(safeParse.error.issues).forEach((error) => {
4824
+ if (!(cube === null || cube === void 0 ? void 0 : cube.cubes) && !(cube === null || cube === void 0 ? void 0 : cube.views)) {
4825
+ return [`${filePath}: At least one cubes or views must be defined`];
4826
+ }
4827
+ const cubeModelSafeParse = cubeModelSchema.safeParse(cube);
4828
+ const viewModelSafeParse = viewModelSchema.safeParse(cube);
4829
+ if (cube.cubes && !cubeModelSafeParse.success) {
4830
+ errorFormatter(cubeModelSafeParse.error.issues).forEach((error) => {
4831
+ errors.push(`${filePath}: ${error}`);
4832
+ });
4833
+ }
4834
+ if (cube.views && !viewModelSafeParse.success) {
4835
+ errorFormatter(viewModelSafeParse.error.issues).forEach((error) => {
4544
4836
  errors.push(`${filePath}: ${error}`);
4545
4837
  });
4546
4838
  }
@@ -4619,6 +4911,19 @@ const cubeModelSchema = z
4619
4911
  message: "At least one measure or dimension must be defined",
4620
4912
  path: ["cubes"],
4621
4913
  });
4914
+ const viewModelSchema = z.object({
4915
+ views: z
4916
+ .object({
4917
+ name: z.string(),
4918
+ cubes: z
4919
+ .object({
4920
+ join_path: z.string(),
4921
+ })
4922
+ .array(),
4923
+ })
4924
+ .array()
4925
+ .min(1),
4926
+ });
4622
4927
  const securityContextSchema = z.array(z.object({
4623
4928
  name: z.string(),
4624
4929
  securityContext: z.object({}), // can be any object
@@ -19975,6 +20280,25 @@ const checkNodeVersion = async () => {
19975
20280
  process.exit(1);
19976
20281
  }
19977
20282
  };
20283
+ /**
20284
+ * Get the value of a process argument by key
20285
+ * Example: getArgumentByKey("--email") or getArgumentByKey(["--email", "-e"])
20286
+ * @param key The key to search for in the process arguments
20287
+ * @returns
20288
+ */
20289
+ const getArgumentByKey = (key) => {
20290
+ if (Array.isArray(key)) {
20291
+ for (const k of key) {
20292
+ if (process.argv.includes(k)) {
20293
+ const index = process.argv.indexOf(k);
20294
+ return index !== -1 ? process.argv[index + 1] : undefined;
20295
+ }
20296
+ }
20297
+ return undefined;
20298
+ }
20299
+ const index = process.argv.indexOf(key);
20300
+ return index !== -1 ? process.argv[index + 1] : undefined;
20301
+ };
19978
20302
 
19979
20303
  var build = async () => {
19980
20304
  try {
@@ -20085,29 +20409,58 @@ const inquirerSelect = import('@inquirer/select');
20085
20409
  const YAML_OR_JS_FILES = /^(.*)\.(cube|sc)\.(ya?ml|js)$/;
20086
20410
  let ora$1;
20087
20411
  var push = async () => {
20088
- var _a;
20412
+ var _a, _b;
20089
20413
  let spinnerPushing;
20090
20414
  try {
20091
20415
  checkNodeVersion();
20092
20416
  ora$1 = (await oraP$1).default;
20093
20417
  const config = await provideConfig();
20418
+ if (process.argv.includes("--api-key") || process.argv.includes("-k")) {
20419
+ spinnerPushing = ora$1("Using API key...").start();
20420
+ await pushByApiKey(config, spinnerPushing);
20421
+ spinnerPushing.succeed("Published using API key");
20422
+ return;
20423
+ }
20094
20424
  const token = await verify(config);
20095
20425
  const { workspaceId, name: workspaceName } = await selectWorkspace(config, token);
20096
- const spinnerArchive = ora$1("Building...").start();
20097
- const filesList = await findFiles(config.client.srcDir, YAML_OR_JS_FILES);
20098
- await archive(config, filesList);
20099
- spinnerArchive.succeed("Bundling completed");
20100
- spinnerPushing = ora$1(`Publishing to ${workspaceName} using ${config.pushBaseUrl}...`).start();
20426
+ const workspacePreviewUrl = `${config.previewBaseUrl}/workspace/${workspaceId}`;
20427
+ await buildArchive(config);
20428
+ spinnerPushing = ora$1(`Publishing to ${workspaceName} using ${workspacePreviewUrl}...`).start();
20101
20429
  await sendBuild(config, { workspaceId, token });
20102
- spinnerPushing.succeed(`Published to ${workspaceName} using ${config.pushBaseUrl}`);
20430
+ spinnerPushing.succeed(`Published to ${workspaceName} using ${workspacePreviewUrl}`);
20103
20431
  }
20104
20432
  catch (error) {
20105
20433
  spinnerPushing === null || spinnerPushing === void 0 ? void 0 : spinnerPushing.fail("Publishing failed");
20106
- console.error(((_a = error.response) === null || _a === void 0 ? void 0 : _a.data) || (error === null || error === void 0 ? void 0 : error.message) || error);
20434
+ if (((_a = error.response) === null || _a === void 0 ? void 0 : _a.statusText) === "Unauthorized") {
20435
+ console.error("Unauthorized. Please check your credentials.");
20436
+ }
20437
+ else {
20438
+ console.error(((_b = error.response) === null || _b === void 0 ? void 0 : _b.data) || (error === null || error === void 0 ? void 0 : error.message) || error);
20439
+ }
20107
20440
  await reportErrorToRollbar(error);
20108
20441
  process.exit(1);
20109
20442
  }
20110
20443
  };
20444
+ async function pushByApiKey(config, spinner) {
20445
+ const apiKey = getArgumentByKey(["--api-key", "-k"]);
20446
+ if (!apiKey) {
20447
+ spinner.fail("No API key provided");
20448
+ process.exit(1);
20449
+ }
20450
+ const email = getArgumentByKey(["--email", "-e"]);
20451
+ if (!email || !/\S+@\S+\.\S+/.test(email)) {
20452
+ spinner.fail("Invalid email provided. Please provide a valid email using --email (-e) flag");
20453
+ process.exit(1);
20454
+ }
20455
+ // message is optional
20456
+ const message = getArgumentByKey(["--message", "-m"]);
20457
+ await buildArchive(config);
20458
+ return sendBuildByApiKey(config, {
20459
+ apiKey,
20460
+ email,
20461
+ message,
20462
+ });
20463
+ }
20111
20464
  async function selectWorkspace(ctx, token) {
20112
20465
  const workspaceSpinner = ora$1({
20113
20466
  text: `Fetching workspaces using ${ctx.pushBaseUrl}...`,
@@ -20153,6 +20506,12 @@ async function verify(ctx) {
20153
20506
  }
20154
20507
  return token;
20155
20508
  }
20509
+ async function buildArchive(config) {
20510
+ const spinnerArchive = ora$1("Building...").start();
20511
+ const filesList = await findFiles(config.client.modelsSrc || config.client.srcDir, YAML_OR_JS_FILES);
20512
+ await archive(config, filesList);
20513
+ return spinnerArchive.succeed("Bundling completed");
20514
+ }
20156
20515
  async function archive(ctx, yamlFiles, includeBuild = true) {
20157
20516
  const output = fs$2.createWriteStream(ctx.client.archiveFile);
20158
20517
  const _archiver = archiver.create("zip", {
@@ -20173,13 +20532,30 @@ async function archive(ctx, yamlFiles, includeBuild = true) {
20173
20532
  output.on("close", resolve);
20174
20533
  });
20175
20534
  }
20535
+ async function sendBuildByApiKey(ctx, { apiKey, email, message }) {
20536
+ var _a;
20537
+ const { FormData, Blob } = await import('formdata-node');
20538
+ const { fileFromPath } = await Promise.resolve().then(function () { return fileFromPath$1; });
20539
+ const file = await fileFromPath(ctx.client.archiveFile, "embeddable-build.zip");
20540
+ const form = new FormData();
20541
+ form.set("file", file, "embeddable-build.zip");
20542
+ const metadataBlob = new Blob([JSON.stringify({ authorEmail: email, description: message })], { type: "application/json" });
20543
+ form.set("metadata", metadataBlob, "metadata.json");
20544
+ const response = await uploadFile(form, `${ctx.pushBaseUrl}/api/v1/bundle/upload`, apiKey);
20545
+ await fs$1.rm(ctx.client.archiveFile);
20546
+ return { bundleId: (_a = response.data) === null || _a === void 0 ? void 0 : _a.bundleId, email, message };
20547
+ }
20176
20548
  async function sendBuild(ctx, { workspaceId, token }) {
20177
20549
  const { FormData } = await import('formdata-node');
20178
20550
  const { fileFromPath } = await Promise.resolve().then(function () { return fileFromPath$1; });
20179
20551
  const file = await fileFromPath(ctx.client.archiveFile, "embeddable-build.zip");
20180
20552
  const form = new FormData();
20181
20553
  form.set("file", file, "embeddable-build.zip");
20182
- await axios.post(`${ctx.pushBaseUrl}/bundle/${workspaceId}/upload`, form, {
20554
+ await uploadFile(form, `${ctx.pushBaseUrl}/bundle/${workspaceId}/upload`, token);
20555
+ await fs$1.rm(ctx.client.archiveFile);
20556
+ }
20557
+ async function uploadFile(formData, url, token) {
20558
+ return axios.post(url, formData, {
20183
20559
  headers: {
20184
20560
  "Content-Type": "multipart/form-data",
20185
20561
  Authorization: `Bearer ${token}`,
@@ -20187,7 +20563,6 @@ async function sendBuild(ctx, { workspaceId, token }) {
20187
20563
  maxContentLength: Infinity,
20188
20564
  maxBodyLength: Infinity,
20189
20565
  });
20190
- await fs$1.rm(ctx.client.archiveFile);
20191
20566
  }
20192
20567
  async function getWorkspaces(ctx, token, workspaceSpinner) {
20193
20568
  var _a;
@@ -20394,9 +20769,21 @@ const getPreviewWorkspace = async (ctx) => {
20394
20769
  }
20395
20770
  };
20396
20771
 
20397
- var defineConfig = ({ plugins, pushBaseUrl, audienceUrl, authDomain, authClientId, errorFallbackComponent, applicationEnvironment, rollbarAccessToken, previewBaseUrl, }) => {
20772
+ var defineConfig = ({ plugins, pushBaseUrl, audienceUrl, authDomain, authClientId, errorFallbackComponent, applicationEnvironment, rollbarAccessToken, previewBaseUrl, modelsSrc, componentsSrc = "src", }) => {
20398
20773
  const coreRoot = path$1.resolve(__dirname, "..");
20399
20774
  const clientRoot = process.cwd();
20775
+ if (!path$1.isAbsolute(componentsSrc)) {
20776
+ componentsSrc = path$1.resolve(clientRoot, componentsSrc);
20777
+ if (!existsSync(componentsSrc)) {
20778
+ throw new Error(`componentsSrc directory ${componentsSrc} does not exist`);
20779
+ }
20780
+ }
20781
+ if (modelsSrc && !path$1.isAbsolute(modelsSrc)) {
20782
+ modelsSrc = path$1.resolve(clientRoot, modelsSrc);
20783
+ if (!existsSync(modelsSrc)) {
20784
+ throw new Error(`modelsSrc directory ${modelsSrc} does not exist`);
20785
+ }
20786
+ }
20400
20787
  return {
20401
20788
  core: {
20402
20789
  rootDir: coreRoot,
@@ -20405,8 +20792,9 @@ var defineConfig = ({ plugins, pushBaseUrl, audienceUrl, authDomain, authClientI
20405
20792
  },
20406
20793
  client: {
20407
20794
  rootDir: clientRoot,
20795
+ srcDir: path$1.resolve(clientRoot, componentsSrc),
20796
+ modelsSrc: modelsSrc ? path$1.resolve(clientRoot, modelsSrc) : undefined,
20408
20797
  buildDir: path$1.resolve(clientRoot, ".embeddable-build"),
20409
- srcDir: path$1.resolve(clientRoot, "src"),
20410
20798
  tmpDir: path$1.resolve(clientRoot, ".embeddable-tmp"),
20411
20799
  componentDir: path$1.resolve(clientRoot, ".embeddable-build", "component"),
20412
20800
  stencilBuild: path$1.resolve(clientRoot, ".embeddable-build", "dist", "embeddable-wrapper"),