@knocklabs/cli 1.0.0 → 1.0.2

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.
@@ -0,0 +1,149 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: Object.getOwnPropertyDescriptor(all, name).get
9
+ });
10
+ }
11
+ _export(exports, {
12
+ get readAllForCommandTarget () {
13
+ return readAllForCommandTarget;
14
+ },
15
+ get readAudienceDir () {
16
+ return readAudienceDir;
17
+ }
18
+ });
19
+ const _nodepath = /*#__PURE__*/ _interop_require_default(require("node:path"));
20
+ const _core = require("@oclif/core");
21
+ const _fsextra = /*#__PURE__*/ _interop_require_wildcard(require("fs-extra"));
22
+ const _error = require("../../helpers/error");
23
+ const _json = require("../../helpers/json");
24
+ const _objectisomorphic = require("../../helpers/object.isomorphic");
25
+ const _helpers = require("./helpers");
26
+ const _processorisomorphic = require("./processor.isomorphic");
27
+ function _interop_require_default(obj) {
28
+ return obj && obj.__esModule ? obj : {
29
+ default: obj
30
+ };
31
+ }
32
+ function _getRequireWildcardCache(nodeInterop) {
33
+ if (typeof WeakMap !== "function") return null;
34
+ var cacheBabelInterop = new WeakMap();
35
+ var cacheNodeInterop = new WeakMap();
36
+ return (_getRequireWildcardCache = function(nodeInterop) {
37
+ return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
38
+ })(nodeInterop);
39
+ }
40
+ function _interop_require_wildcard(obj, nodeInterop) {
41
+ if (!nodeInterop && obj && obj.__esModule) {
42
+ return obj;
43
+ }
44
+ if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
45
+ return {
46
+ default: obj
47
+ };
48
+ }
49
+ var cache = _getRequireWildcardCache(nodeInterop);
50
+ if (cache && cache.has(obj)) {
51
+ return cache.get(obj);
52
+ }
53
+ var newObj = {
54
+ __proto__: null
55
+ };
56
+ var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
57
+ for(var key in obj){
58
+ if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
59
+ var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
60
+ if (desc && (desc.get || desc.set)) {
61
+ Object.defineProperty(newObj, key, desc);
62
+ } else {
63
+ newObj[key] = obj[key];
64
+ }
65
+ }
66
+ }
67
+ newObj.default = obj;
68
+ if (cache) {
69
+ cache.set(obj, newObj);
70
+ }
71
+ return newObj;
72
+ }
73
+ /*
74
+ * For the given list of audience directory contexts, read each audience dir and
75
+ * return audience directory data.
76
+ */ const readAudienceDirs = async (audienceDirCtxs)=>{
77
+ const audiences = [];
78
+ const errors = [];
79
+ for (const audienceDirCtx of audienceDirCtxs){
80
+ // eslint-disable-next-line no-await-in-loop
81
+ const [audience, readErrors] = await readAudienceDir(audienceDirCtx);
82
+ if (readErrors.length > 0) {
83
+ const audienceJsonPath = _nodepath.default.resolve(audienceDirCtx.abspath, _processorisomorphic.AUDIENCE_JSON);
84
+ const e = new _error.SourceError((0, _error.formatErrors)(readErrors), audienceJsonPath);
85
+ errors.push(e);
86
+ continue;
87
+ }
88
+ audiences.push({
89
+ ...audienceDirCtx,
90
+ content: audience
91
+ });
92
+ }
93
+ return [
94
+ audiences,
95
+ errors
96
+ ];
97
+ };
98
+ const readAudienceDir = async (audienceDirCtx)=>{
99
+ const { abspath } = audienceDirCtx;
100
+ const dirExists = await _fsextra.pathExists(abspath);
101
+ if (!dirExists) throw new Error(`${abspath} does not exist`);
102
+ const audienceJsonPath = await (0, _helpers.lsAudienceJson)(abspath);
103
+ if (!audienceJsonPath) throw new Error(`${abspath} is not an audience directory`);
104
+ const result = await (0, _json.readJson)(audienceJsonPath);
105
+ if (!result[0]) return result;
106
+ let [audienceJson] = result;
107
+ audienceJson = (0, _objectisomorphic.omitDeep)(audienceJson, [
108
+ "__readonly"
109
+ ]);
110
+ return [
111
+ audienceJson,
112
+ []
113
+ ];
114
+ };
115
+ const readAllForCommandTarget = async (target)=>{
116
+ const { type: targetType, context: targetCtx } = target;
117
+ if (!targetCtx.exists) {
118
+ const subject = targetType === "audienceDir" ? "an audience directory at" : "audience directories in";
119
+ return _core.ux.error(`Cannot locate ${subject} \`${targetCtx.abspath}\``);
120
+ }
121
+ switch(targetType){
122
+ case "audienceDir":
123
+ {
124
+ return readAudienceDirs([
125
+ targetCtx
126
+ ]);
127
+ }
128
+ case "audiencesIndexDir":
129
+ {
130
+ const dirents = await _fsextra.readdir(targetCtx.abspath, {
131
+ withFileTypes: true
132
+ });
133
+ const promises = dirents.map(async (dirent)=>{
134
+ const abspath = _nodepath.default.resolve(targetCtx.abspath, dirent.name);
135
+ const audienceDirCtx = {
136
+ type: "audience",
137
+ key: dirent.name,
138
+ abspath,
139
+ exists: await (0, _helpers.isAudienceDir)(abspath)
140
+ };
141
+ return audienceDirCtx;
142
+ });
143
+ const audienceDirCtxs = (await Promise.all(promises)).filter((audienceDirCtx)=>audienceDirCtx.exists);
144
+ return readAudienceDirs(audienceDirCtxs);
145
+ }
146
+ default:
147
+ throw new Error(`Invalid audience command target: ${target}`);
148
+ }
149
+ };
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ Object.defineProperty(exports, "AudienceType", {
6
+ enumerable: true,
7
+ get: function() {
8
+ return AudienceType;
9
+ }
10
+ });
11
+ var AudienceType = /*#__PURE__*/ function(AudienceType) {
12
+ AudienceType["Static"] = "static";
13
+ AudienceType["Dynamic"] = "dynamic";
14
+ return AudienceType;
15
+ }({});
@@ -0,0 +1,177 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", {
3
+ value: true
4
+ });
5
+ function _export(target, all) {
6
+ for(var name in all)Object.defineProperty(target, name, {
7
+ enumerable: true,
8
+ get: Object.getOwnPropertyDescriptor(all, name).get
9
+ });
10
+ }
11
+ _export(exports, {
12
+ get pruneAudiencesIndexDir () {
13
+ return pruneAudiencesIndexDir;
14
+ },
15
+ get writeAudienceDirFromBundle () {
16
+ return writeAudienceDirFromBundle;
17
+ },
18
+ get writeAudienceDirFromData () {
19
+ return writeAudienceDirFromData;
20
+ },
21
+ get writeAudiencesIndexDir () {
22
+ return writeAudiencesIndexDir;
23
+ }
24
+ });
25
+ const _nodepath = /*#__PURE__*/ _interop_require_wildcard(require("node:path"));
26
+ const _fsextra = /*#__PURE__*/ _interop_require_wildcard(require("fs-extra"));
27
+ const _lodash = require("lodash");
28
+ const _const = require("../../helpers/const");
29
+ const _json = require("../../helpers/json");
30
+ const _helpers = require("./helpers");
31
+ const _processorisomorphic = require("./processor.isomorphic");
32
+ const _reader = require("./reader");
33
+ function _getRequireWildcardCache(nodeInterop) {
34
+ if (typeof WeakMap !== "function") return null;
35
+ var cacheBabelInterop = new WeakMap();
36
+ var cacheNodeInterop = new WeakMap();
37
+ return (_getRequireWildcardCache = function(nodeInterop) {
38
+ return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
39
+ })(nodeInterop);
40
+ }
41
+ function _interop_require_wildcard(obj, nodeInterop) {
42
+ if (!nodeInterop && obj && obj.__esModule) {
43
+ return obj;
44
+ }
45
+ if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
46
+ return {
47
+ default: obj
48
+ };
49
+ }
50
+ var cache = _getRequireWildcardCache(nodeInterop);
51
+ if (cache && cache.has(obj)) {
52
+ return cache.get(obj);
53
+ }
54
+ var newObj = {
55
+ __proto__: null
56
+ };
57
+ var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
58
+ for(var key in obj){
59
+ if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
60
+ var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
61
+ if (desc && (desc.get || desc.set)) {
62
+ Object.defineProperty(newObj, key, desc);
63
+ } else {
64
+ newObj[key] = obj[key];
65
+ }
66
+ }
67
+ }
68
+ newObj.default = obj;
69
+ if (cache) {
70
+ cache.set(obj, newObj);
71
+ }
72
+ return newObj;
73
+ }
74
+ const AUDIENCE_SCHEMA = "https://schemas.knock.app/cli/audience.json";
75
+ const writeAudienceDirFromData = async (audienceDirCtx, remoteAudience, options)=>{
76
+ const { withSchema = false } = options || {};
77
+ // If the audience directory exists on the file system (i.e. previously
78
+ // pulled before), then read the audience file to use as a reference.
79
+ const [localAudience] = audienceDirCtx.exists ? await (0, _reader.readAudienceDir)(audienceDirCtx) : [];
80
+ const bundle = (0, _processorisomorphic.buildAudienceDirBundle)(remoteAudience, localAudience, withSchema ? AUDIENCE_SCHEMA : undefined);
81
+ return writeAudienceDirFromBundle(audienceDirCtx, bundle);
82
+ };
83
+ /*
84
+ * A lower level write function that takes a constructed audience dir bundle
85
+ * and writes it into an audience directory on a local file system.
86
+ *
87
+ * It does not make any assumptions about how the audience directory bundle was
88
+ * built; for example, it can be from parsing the audience data fetched from
89
+ * the Knock API, or built manually for scaffolding purposes.
90
+ */ const writeAudienceDirFromBundle = async (audienceDirCtx, audienceDirBundle)=>{
91
+ const backupDirPath = _nodepath.resolve(_const.sandboxDir, (0, _lodash.uniqueId)("backup"));
92
+ try {
93
+ if (audienceDirCtx.exists) {
94
+ await _fsextra.copy(audienceDirCtx.abspath, backupDirPath);
95
+ await _fsextra.emptyDir(audienceDirCtx.abspath);
96
+ }
97
+ const promises = Object.entries(audienceDirBundle).map(([relpath, fileContent])=>{
98
+ const filePath = _nodepath.resolve(audienceDirCtx.abspath, relpath);
99
+ return relpath === _processorisomorphic.AUDIENCE_JSON ? _fsextra.outputJson(filePath, fileContent, {
100
+ spaces: _json.DOUBLE_SPACES
101
+ }) : _fsextra.outputFile(filePath, fileContent !== null && fileContent !== void 0 ? fileContent : "");
102
+ });
103
+ await Promise.all(promises);
104
+ } catch (error) {
105
+ // In case of any error, wipe the target directory that is likely in a bad
106
+ // state then restore the backup if one existed before.
107
+ if (audienceDirCtx.exists) {
108
+ await _fsextra.emptyDir(audienceDirCtx.abspath);
109
+ await _fsextra.copy(backupDirPath, audienceDirCtx.abspath);
110
+ } else {
111
+ await _fsextra.remove(audienceDirCtx.abspath);
112
+ }
113
+ throw error;
114
+ } finally{
115
+ // Always clean up the backup directory in the temp sandbox.
116
+ await _fsextra.remove(backupDirPath);
117
+ }
118
+ };
119
+ /*
120
+ * Prunes the index directory by removing any files, or directories that aren't
121
+ * audience dirs found in fetched audiences. We want to preserve any audience
122
+ * dirs that are going to be updated with remote audiences, so extracted links
123
+ * can be respected.
124
+ */ const pruneAudiencesIndexDir = async (indexDirCtx, remoteAudiences)=>{
125
+ const audiencesByKey = Object.fromEntries(remoteAudiences.map((a)=>[
126
+ a.key.toLowerCase(),
127
+ a
128
+ ]));
129
+ const dirents = await _fsextra.readdir(indexDirCtx.abspath, {
130
+ withFileTypes: true
131
+ });
132
+ const promises = dirents.map(async (dirent)=>{
133
+ const direntPath = _nodepath.resolve(indexDirCtx.abspath, dirent.name);
134
+ const direntKey = dirent.name.toLowerCase();
135
+ if (await (0, _helpers.isAudienceDir)(direntPath) && audiencesByKey[direntKey]) {
136
+ return;
137
+ }
138
+ await _fsextra.remove(direntPath);
139
+ });
140
+ await Promise.all(promises);
141
+ };
142
+ const writeAudiencesIndexDir = async (indexDirCtx, remoteAudiences, options)=>{
143
+ const backupDirPath = _nodepath.resolve(_const.sandboxDir, (0, _lodash.uniqueId)("backup"));
144
+ try {
145
+ // If the index directory already exists, back it up in the temp sandbox
146
+ // before wiping it clean.
147
+ if (indexDirCtx.exists) {
148
+ await _fsextra.copy(indexDirCtx.abspath, backupDirPath);
149
+ await pruneAudiencesIndexDir(indexDirCtx, remoteAudiences);
150
+ }
151
+ // Write given remote audiences into the given audiences directory path.
152
+ const writeAudienceDirPromises = remoteAudiences.map(async (audience)=>{
153
+ const audienceDirPath = _nodepath.resolve(indexDirCtx.abspath, audience.key);
154
+ const audienceDirCtx = {
155
+ type: "audience",
156
+ key: audience.key,
157
+ abspath: audienceDirPath,
158
+ exists: indexDirCtx.exists ? await (0, _helpers.isAudienceDir)(audienceDirPath) : false
159
+ };
160
+ return writeAudienceDirFromData(audienceDirCtx, audience, options);
161
+ });
162
+ await Promise.all(writeAudienceDirPromises);
163
+ } catch (error) {
164
+ // In case of any error, wipe the index directory that is likely in a bad
165
+ // state then restore the backup if one existed before.
166
+ if (indexDirCtx.exists) {
167
+ await _fsextra.emptyDir(indexDirCtx.abspath);
168
+ await _fsextra.copy(backupDirPath, indexDirCtx.abspath);
169
+ } else {
170
+ await _fsextra.remove(indexDirCtx.abspath);
171
+ }
172
+ throw error;
173
+ } finally{
174
+ // Always clean up the backup directory in the temp sandbox.
175
+ await _fsextra.remove(backupDirPath);
176
+ }
177
+ };
@@ -11,32 +11,36 @@ function _export(target, all) {
11
11
  });
12
12
  }
13
13
  _export(exports, {
14
+ get buildAudienceDirBundle () {
15
+ return _processorisomorphic.buildAudienceDirBundle;
16
+ },
14
17
  get buildEmailLayoutDirBundle () {
15
- return _processorisomorphic.buildEmailLayoutDirBundle;
18
+ return _processorisomorphic1.buildEmailLayoutDirBundle;
16
19
  },
17
20
  get buildGuideDirBundle () {
18
- return _processorisomorphic1.buildGuideDirBundle;
21
+ return _processorisomorphic2.buildGuideDirBundle;
19
22
  },
20
23
  get buildMessageTypeDirBundle () {
21
- return _processorisomorphic2.buildMessageTypeDirBundle;
24
+ return _processorisomorphic3.buildMessageTypeDirBundle;
22
25
  },
23
26
  get buildPartialDirBundle () {
24
- return _processorisomorphic3.buildPartialDirBundle;
27
+ return _processorisomorphic4.buildPartialDirBundle;
25
28
  },
26
29
  get buildReusableStepDirBundle () {
27
- return _processorisomorphic4.buildReusableStepDirBundle;
30
+ return _processorisomorphic5.buildReusableStepDirBundle;
28
31
  },
29
32
  get buildTranslationDirBundle () {
30
- return _processorisomorphic5.buildTranslationDirBundle;
33
+ return _processorisomorphic6.buildTranslationDirBundle;
31
34
  },
32
35
  get buildWorkflowDirBundle () {
33
- return _processorisomorphic6.buildWorkflowDirBundle;
36
+ return _processorisomorphic7.buildWorkflowDirBundle;
34
37
  }
35
38
  });
36
- const _processorisomorphic = require("./email-layout/processor.isomorphic");
37
- const _processorisomorphic1 = require("./guide/processor.isomorphic");
38
- const _processorisomorphic2 = require("./message-type/processor.isomorphic");
39
- const _processorisomorphic3 = require("./partial/processor.isomorphic");
40
- const _processorisomorphic4 = require("./reusable-step/processor.isomorphic");
41
- const _processorisomorphic5 = require("./translation/processor.isomorphic");
42
- const _processorisomorphic6 = require("./workflow/processor.isomorphic");
39
+ const _processorisomorphic = require("./audience/processor.isomorphic");
40
+ const _processorisomorphic1 = require("./email-layout/processor.isomorphic");
41
+ const _processorisomorphic2 = require("./guide/processor.isomorphic");
42
+ const _processorisomorphic3 = require("./message-type/processor.isomorphic");
43
+ const _processorisomorphic4 = require("./partial/processor.isomorphic");
44
+ const _processorisomorphic5 = require("./reusable-step/processor.isomorphic");
45
+ const _processorisomorphic6 = require("./translation/processor.isomorphic");
46
+ const _processorisomorphic7 = require("./workflow/processor.isomorphic");
@@ -17,6 +17,8 @@ _export(exports, {
17
17
  }
18
18
  });
19
19
  const ALL_RESOURCE_TYPES = [
20
+ // Audiences can be referenced by workflows, so push them early
21
+ "audience",
20
22
  // Partials first, as email layouts and workflows may reference them
21
23
  "partial",
22
24
  // Email layouts next, as workflows with email channel steps may reference them
@@ -28,6 +30,7 @@ const ALL_RESOURCE_TYPES = [
28
30
  "translation"
29
31
  ];
30
32
  const RESOURCE_SUBDIRS = {
33
+ audience: "audiences",
31
34
  email_layout: "layouts",
32
35
  partial: "partials",
33
36
  translation: "translations",
@@ -13,6 +13,7 @@ Object.defineProperty(exports, "load", {
13
13
  }
14
14
  });
15
15
  const _nodepath = /*#__PURE__*/ _interop_require_wildcard(require("node:path"));
16
+ const _audience = /*#__PURE__*/ _interop_require_wildcard(require("../marshal/audience"));
16
17
  const _emaillayout = /*#__PURE__*/ _interop_require_wildcard(require("../marshal/email-layout"));
17
18
  const _guide = /*#__PURE__*/ _interop_require_wildcard(require("../marshal/guide"));
18
19
  const _messagetype = /*#__PURE__*/ _interop_require_wildcard(require("../marshal/message-type"));
@@ -71,31 +72,22 @@ const buildResourceDirContext = (type, currDir)=>{
71
72
  const evaluateRecursively = async (ctx, currDir)=>{
72
73
  // Check if we are inside a resource directory and if so update the context.
73
74
  if (!ctx.resourceDir) {
74
- const isWorkflowDir = await _workflow.isWorkflowDir(currDir);
75
- if (isWorkflowDir) {
75
+ if (await _audience.isAudienceDir(currDir)) {
76
+ ctx.resourceDir = buildResourceDirContext("audience", currDir);
77
+ } else if (await _workflow.isWorkflowDir(currDir)) {
76
78
  ctx.resourceDir = buildResourceDirContext("workflow", currDir);
77
- }
78
- const isGuideDir = await _guide.isGuideDir(currDir);
79
- if (isGuideDir) {
79
+ } else if (await _guide.isGuideDir(currDir)) {
80
80
  ctx.resourceDir = buildResourceDirContext("guide", currDir);
81
- }
82
- const isEmailLayoutDir = await _emaillayout.isEmailLayoutDir(currDir);
83
- if (isEmailLayoutDir) {
81
+ } else if (await _emaillayout.isEmailLayoutDir(currDir)) {
84
82
  ctx.resourceDir = buildResourceDirContext("email_layout", currDir);
85
- }
86
- const isPartialDir = await _partial.isPartialDir(currDir);
87
- if (isPartialDir) {
83
+ } else if (await _partial.isPartialDir(currDir)) {
88
84
  ctx.resourceDir = buildResourceDirContext("partial", currDir);
89
- }
90
- const isMessageTypeDir = await _messagetype.isMessageTypeDir(currDir);
91
- if (isMessageTypeDir) {
85
+ } else if (await _messagetype.isMessageTypeDir(currDir)) {
92
86
  ctx.resourceDir = buildResourceDirContext("message_type", currDir);
93
- }
94
- // NOTE: Must keep this check as last in the order of directory-type checks
95
- // since the `isTranslationDir` only checks that the directory name is a
96
- // valid locale name.
97
- const isTranslationDir = _translation.isTranslationDir(currDir);
98
- if (isTranslationDir) {
87
+ } else if (_translation.isTranslationDir(currDir)) {
88
+ // NOTE: Must keep this check as last in the order of directory-type checks
89
+ // since the `isTranslationDir` only checks that the directory name is a
90
+ // valid locale name.
99
91
  ctx.resourceDir = buildResourceDirContext("translation", currDir);
100
92
  }
101
93
  }
package/dist/lib/urls.js CHANGED
@@ -24,6 +24,9 @@ _export(exports, {
24
24
  get authSuccessUrl () {
25
25
  return authSuccessUrl;
26
26
  },
27
+ get viewAudienceUrl () {
28
+ return viewAudienceUrl;
29
+ },
27
30
  get viewGuideUrl () {
28
31
  return viewGuideUrl;
29
32
  },
@@ -50,3 +53,4 @@ const viewGuideUrl = (dashboardUrl, accountSlug, envOrBranchSlug, guideKey)=>`${
50
53
  const viewLayoutUrl = (dashboardUrl, accountSlug, envOrBranchSlug, layoutKey)=>`${dashboardUrl}/${accountSlug}/${envOrBranchSlug.toLowerCase()}/layouts/${layoutKey}`;
51
54
  const viewMessageTypeUrl = (dashboardUrl, accountSlug, envOrBranchSlug, messageTypeKey)=>`${dashboardUrl}/${accountSlug}/${envOrBranchSlug.toLowerCase()}/message-types/${messageTypeKey}`;
52
55
  const viewPartialUrl = (dashboardUrl, accountSlug, envOrBranchSlug, partialKey)=>`${dashboardUrl}/${accountSlug}/${envOrBranchSlug.toLowerCase()}/partials/${partialKey}`;
56
+ const viewAudienceUrl = (dashboardUrl, accountSlug, envOrBranchSlug, audienceKey)=>`${dashboardUrl}/${accountSlug}/${envOrBranchSlug.toLowerCase()}/audiences/${audienceKey}`;