@salesforce/pwa-kit-dev 3.1.0-preview.2 → 3.1.0-preview.4

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.
@@ -13,7 +13,6 @@ const WebSocket = require('ws')
13
13
  const program = require('commander')
14
14
  const validator = require('validator')
15
15
  const {execSync: _execSync} = require('child_process')
16
- const projectPkg = require(process.cwd() + '/package.json')
17
16
  const {getConfig} = require('@salesforce/pwa-kit-runtime/utils/ssr-config')
18
17
 
19
18
  // Scripts in ./bin have never gone through babel, so we
@@ -179,20 +178,18 @@ const main = async () => {
179
178
  })
180
179
 
181
180
  const appSSRpath = p.join(process.cwd(), 'app', 'ssr.js')
182
- const appSSRjs = fse.pathExistsSync(appSSRpath)
181
+ const appSSRexists = fse.pathExistsSync(appSSRpath)
182
+ const {overridesDir} = scriptUtils.getProjectPkg()?.ccExtensibility ?? {}
183
183
  const overrideSSRpath = p.join(
184
184
  process.cwd(),
185
- typeof projectPkg?.ccExtensibility?.overridesDir === 'string' &&
186
- !projectPkg?.ccExtensibility?.overridesDir?.startsWith(p.sep)
187
- ? p.sep + projectPkg?.ccExtensibility?.overridesDir
188
- : projectPkg?.ccExtensibility?.overridesDir
189
- ? projectPkg?.ccExtensibility?.overridesDir
190
- : '',
185
+ typeof overridesDir === 'string' && !overridesDir?.startsWith(p.sep)
186
+ ? p.sep + overridesDir
187
+ : overridesDir || '',
191
188
  'app',
192
189
  'ssr.js'
193
190
  )
194
- const overrideSSRjs = fse.pathExistsSync(overrideSSRpath)
195
- const resolvedSSRPath = appSSRjs ? appSSRpath : overrideSSRjs ? overrideSSRpath : null
191
+ const overrideSSRexists = fse.pathExistsSync(overrideSSRpath)
192
+ const resolvedSSRPath = appSSRexists ? appSSRpath : overrideSSRexists ? overrideSSRpath : null
196
193
 
197
194
  program
198
195
  .command('start')
@@ -323,7 +323,6 @@ describe('OverridePlugin.toOverrideRelative', () => {
323
323
  });
324
324
  describe('OverridePlugin.findFileFromMap', () => {
325
325
  let os;
326
- let opts = options;
327
326
  let cases;
328
327
  if (_path.default.sep === '\\') {
329
328
  // WINDOWS test cases
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@salesforce/pwa-kit-dev",
3
- "version": "3.1.0-preview.2",
3
+ "version": "3.1.0-preview.4",
4
4
  "description": "Build tools for pwa-kit",
5
5
  "homepage": "https://github.com/SalesforceCommerceCloud/pwa-kit/tree/develop/packages/pwa-kit-dev#readme",
6
6
  "bugs": {
@@ -58,7 +58,7 @@
58
58
  "@loadable/server": "^5.15.3",
59
59
  "@loadable/webpack-plugin": "^5.15.2",
60
60
  "@pmmmwh/react-refresh-webpack-plugin": "^0.5.10",
61
- "@salesforce/pwa-kit-runtime": "3.1.0-preview.2",
61
+ "@salesforce/pwa-kit-runtime": "3.1.0-preview.4",
62
62
  "@typescript-eslint/eslint-plugin": "^5.57.0",
63
63
  "@typescript-eslint/parser": "^5.57.0",
64
64
  "archiver": "1.3.0",
@@ -119,7 +119,7 @@
119
119
  "@types/node-fetch": "^2.6.3",
120
120
  "@types/validator": "^13.7.14",
121
121
  "eslint-plugin-no-relative-import-paths": "^1.5.2",
122
- "internal-lib-build": "3.1.0-preview.2",
122
+ "internal-lib-build": "3.1.0-preview.4",
123
123
  "nock": "^13.3.0",
124
124
  "nodemon": "^2.0.22",
125
125
  "superagent": "^6.1.0",
@@ -148,5 +148,5 @@
148
148
  "publishConfig": {
149
149
  "directory": "dist"
150
150
  },
151
- "gitHead": "3492171017c426688e11ae4c0d725d272e71ed0d"
151
+ "gitHead": "8ef8310dabf77dfdc50b76fbe2464f771c6a69c0"
152
152
  }
@@ -43,6 +43,12 @@ const DevServerMixin = {
43
43
  _logStartupMessage(options) {
44
44
  console.log(`Starting the DevServer on ${_chalk.default.cyan(this._getDevServerURL(options))}`);
45
45
  },
46
+ /**
47
+ * @private
48
+ */
49
+ _getAllowCookies(options) {
50
+ return 'MRT_ALLOW_COOKIES' in process.env ? process.env.MRT_ALLOW_COOKIES === 'true' : options.localAllowCookies;
51
+ },
46
52
  /**
47
53
  * @private
48
54
  */
@@ -124,8 +130,10 @@ const DevServerMixin = {
124
130
  app.__devMiddleware = (0, _webpackDevMiddleware.default)(app.__compiler, {
125
131
  serverSideRender: true
126
132
  });
133
+ app.__isInitialBuild = true;
127
134
  app.__webpackReady = () => Boolean(app.__devMiddleware.context.state);
128
135
  app.__devMiddleware.waitUntilValid(() => {
136
+ app.__isInitialBuild = false;
129
137
  // Be just a little more generous before letting eg. Lighthouse hit it!
130
138
  setTimeout(() => {
131
139
  console.log(_chalk.default.cyan('First build complete'));
@@ -238,19 +246,25 @@ const DevServerMixin = {
238
246
  },
239
247
  render(req, res, next) {
240
248
  const app = req.app;
241
- if (app.__webpackReady()) {
242
- app.__hotServerMiddleware(req, res, next);
243
- } else {
249
+ if (app !== null && app !== void 0 && app.__isInitialBuild) {
244
250
  this._redirectToLoadingScreen(req, res, next);
251
+ } else {
252
+ // Ensure that we do not try to render anything until the webpack bundle is valid.
253
+ // There was a bug previously where developers would refresh the page while webpack was building,
254
+ // causing them to get redirected to the loading page and sometimes getting stuck,
255
+ // requiring them to restart their dev server
256
+ app.__devMiddleware.waitUntilValid(() => {
257
+ app.__hotServerMiddleware(req, res, next);
258
+ });
245
259
  }
246
260
  },
247
261
  /**
248
262
  * @private
249
263
  */
250
-
251
264
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
252
265
  _redirectToLoadingScreen(req, res, next) {
253
- res.redirect('/__mrt/loading-screen/index.html?loading=1');
266
+ const path = encodeURIComponent(req.originalUrl);
267
+ res.redirect(`/__mrt/loading-screen/index.html?loading=1&path=${path}`);
254
268
  },
255
269
  /**
256
270
  * @private
@@ -129,9 +129,20 @@ describe('DevServer loading page', () => {
129
129
  const options = opts();
130
130
  const app = NoWebpackDevServerFactory._createApp(options);
131
131
  app.use('/', _buildDevServer.DevServerFactory._redirectToLoadingScreen);
132
+ const expectedPath = '/__mrt/loading-screen/index.html?loading=1&path=%2F';
132
133
  return (0, _supertest.default)(app).get('/').expect(302) // Expecting the 302 temporary redirect (not 301)
133
134
  .then(response => {
134
- expect(response.headers.location).toBe('/__mrt/loading-screen/index.html?loading=1');
135
+ expect(response.headers.location).toBe(expectedPath);
136
+ });
137
+ }));
138
+ test('should contain path query parameter with encoded original url', /*#__PURE__*/_asyncToGenerator(function* () {
139
+ const options = opts();
140
+ const app = NoWebpackDevServerFactory._createApp(options);
141
+ app.use('/', _buildDevServer.DevServerFactory._redirectToLoadingScreen);
142
+ const originalUrl = '/global/en-GB/product/25519318M?color=JJ8UTXX&size=9MD&pid=701642923497M';
143
+ const expectedPath = `/__mrt/loading-screen/index.html?loading=1&path=${encodeURIComponent(originalUrl)}`;
144
+ return (0, _supertest.default)(app).get(originalUrl).then(response => {
145
+ expect(response.headers.location).toBe(expectedPath);
135
146
  });
136
147
  }));
137
148
  });
@@ -524,7 +535,10 @@ describe('DevServer rendering', () => {
524
535
  const req = {
525
536
  app: {
526
537
  __webpackReady: jest.fn().mockReturnValue(true),
527
- __hotServerMiddleware: jest.fn()
538
+ __hotServerMiddleware: jest.fn(),
539
+ __devMiddleware: {
540
+ waitUntilValid: callback => callback()
541
+ }
528
542
  }
529
543
  };
530
544
  const res = {};
@@ -532,13 +546,13 @@ describe('DevServer rendering', () => {
532
546
  NoWebpackDevServerFactory.render(req, res, next);
533
547
  expect(req.app.__hotServerMiddleware).toHaveBeenCalledWith(req, res, next);
534
548
  });
535
- test('redirects to loading screen when not ready', () => {
549
+ test('redirects to loading screen during the inital build', () => {
536
550
  const TestFactory = _objectSpread(_objectSpread({}, NoWebpackDevServerFactory), {}, {
537
551
  _redirectToLoadingScreen: jest.fn()
538
552
  });
539
553
  const req = {
540
554
  app: {
541
- __webpackReady: jest.fn().mockReturnValue(false)
555
+ __isInitialBuild: true
542
556
  }
543
557
  };
544
558
  const res = {};
@@ -86,8 +86,9 @@
86
86
  }
87
87
 
88
88
  waitForReady().then(() => {
89
- // Redirect to homepage
90
- window.location = url.origin
89
+ // Redirect to homepage if path is not defined
90
+ const path = url.searchParams.get('path') ?? ''
91
+ window.location = new URL(path, url.origin)
91
92
  })
92
93
  }
93
94
 
@@ -186,6 +186,7 @@ const createBundle = /*#__PURE__*/function () {
186
186
  const tmpDir = yield (0, _promises.mkdtemp)(_path.default.join(_os.default.tmpdir(), 'pwa-kit-dev-'));
187
187
  const destination = _path.default.join(tmpDir, 'build.tar');
188
188
  const filesInArchive = [];
189
+ let bundle_metadata = {};
189
190
  if (ssr_only.length === 0 || ssr_shared.length === 0) {
190
191
  throw new Error('no ssrOnly or ssrShared files are defined');
191
192
  }
@@ -212,6 +213,14 @@ const createBundle = /*#__PURE__*/function () {
212
213
  archive.on('error', reject);
213
214
  output.on('finish', resolve);
214
215
  archive.finalize();
216
+ })).then( /*#__PURE__*/_asyncToGenerator(function* () {
217
+ const {
218
+ dependencies = {},
219
+ devDependencies = {}
220
+ } = yield getProjectPkg();
221
+ bundle_metadata = {
222
+ dependencies: _objectSpread(_objectSpread({}, dependencies), devDependencies)
223
+ };
215
224
  })).then(() => (0, _promises.readFile)(destination)).then(data => {
216
225
  const encoding = 'base64';
217
226
  return {
@@ -220,7 +229,8 @@ const createBundle = /*#__PURE__*/function () {
220
229
  data: data.toString(encoding),
221
230
  ssr_parameters,
222
231
  ssr_only: filesInArchive.filter(glob(ssr_only)),
223
- ssr_shared: filesInArchive.filter(glob(ssr_shared))
232
+ ssr_shared: filesInArchive.filter(glob(ssr_shared)),
233
+ bundle_metadata
224
234
  };
225
235
  })
226
236
  // This is a false positive. The promise returned by `.finally()` won't resolve until
@@ -267,7 +277,7 @@ const getCredentialsFile = (cloudOrigin, credentialsFile) => {
267
277
  };
268
278
  exports.getCredentialsFile = getCredentialsFile;
269
279
  const readCredentials = /*#__PURE__*/function () {
270
- var _ref4 = _asyncToGenerator(function* (filepath) {
280
+ var _ref5 = _asyncToGenerator(function* (filepath) {
271
281
  try {
272
282
  const data = yield (0, _fsExtra.readJson)(filepath);
273
283
  return {
@@ -279,7 +289,7 @@ const readCredentials = /*#__PURE__*/function () {
279
289
  }
280
290
  });
281
291
  return function readCredentials(_x2) {
282
- return _ref4.apply(this, arguments);
292
+ return _ref5.apply(this, arguments);
283
293
  };
284
294
  }();
285
295
  exports.readCredentials = readCredentials;
@@ -7,19 +7,24 @@ var scriptUtils = _interopRequireWildcard(require("./script-utils"));
7
7
  function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
8
8
  function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
9
9
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
10
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
11
+ function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
10
12
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
11
13
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
12
14
  function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
13
15
  function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return typeof key === "symbol" ? key : String(key); }
14
- function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
15
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
16
- function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } /*
17
- * Copyright (c) 2021, salesforce.com, inc.
18
- * All rights reserved.
19
- * SPDX-License-Identifier: BSD-3-Clause
20
- * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
21
- */
16
+ function _toPrimitive(input, hint) { if (typeof input !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (typeof res !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } /*
17
+ * Copyright (c) 2021, salesforce.com, inc.
18
+ * All rights reserved.
19
+ * SPDX-License-Identifier: BSD-3-Clause
20
+ * For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
21
+ */
22
22
  const pkg = (0, _fsExtra.readJsonSync)(_path.default.join(__dirname, '../package.json'));
23
+ jest.mock('fs-extra', () => {
24
+ return _objectSpread(_objectSpread({}, jest.requireActual('fs-extra')), {}, {
25
+ readJson: jest.fn()
26
+ });
27
+ });
23
28
  describe('scriptUtils', () => {
24
29
  const originalEnv = process.env;
25
30
  let tmpDir;
@@ -32,6 +37,7 @@ describe('scriptUtils', () => {
32
37
  tmpDir && (yield (0, _fsExtra.rm)(tmpDir, {
33
38
  recursive: true
34
39
  }));
40
+ jest.resetAllMocks();
35
41
  }));
36
42
  test('glob() with no patterns matches nothing', () => {
37
43
  const matcher = scriptUtils.glob();
@@ -77,6 +83,7 @@ describe('scriptUtils', () => {
77
83
  expect(client.getAuthHeader()).toEqual(expectedAuthHeader);
78
84
  }));
79
85
  test('getHeaders', /*#__PURE__*/_asyncToGenerator(function* () {
86
+ _fsExtra.readJson.mockReturnValue(pkg);
80
87
  const client = new scriptUtils.CloudAPIClient({
81
88
  credentials: {
82
89
  username,
@@ -88,10 +95,33 @@ describe('scriptUtils', () => {
88
95
  }, expectedAuthHeader));
89
96
  }));
90
97
  });
91
- test('getPkgJSON', /*#__PURE__*/_asyncToGenerator(function* () {
92
- const pkg = yield scriptUtils.getPkgJSON();
93
- expect(pkg.name).toBe('@salesforce/pwa-kit-dev');
94
- }));
98
+ describe('getPkgJSON', () => {
99
+ test('should work', /*#__PURE__*/_asyncToGenerator(function* () {
100
+ _fsExtra.readJson.mockReturnValue(pkg);
101
+ const pkgJson = yield scriptUtils.getPkgJSON();
102
+ expect(pkgJson.name).toBe('@salesforce/pwa-kit-dev');
103
+ }));
104
+ test('should return default package.json data when no valid file is found', /*#__PURE__*/_asyncToGenerator(function* () {
105
+ _fsExtra.readJson.mockRejectedValue(Error);
106
+ const result = yield scriptUtils.getPkgJSON();
107
+ expect(result).toEqual({
108
+ name: '@salesforce/pwa-kit-dev',
109
+ version: 'unknown'
110
+ });
111
+ }));
112
+ });
113
+ describe('getProjectPkg', () => {
114
+ test('should work', /*#__PURE__*/_asyncToGenerator(function* () {
115
+ _fsExtra.readJson.mockReturnValue(pkg);
116
+ const pkgJson = yield scriptUtils.getProjectPkg();
117
+ expect(pkgJson.name).toBe('@salesforce/pwa-kit-dev');
118
+ }));
119
+ test('should throw', /*#__PURE__*/_asyncToGenerator(function* () {
120
+ _fsExtra.readJson.mockRejectedValue(Error);
121
+ yield expect(scriptUtils.getProjectPkg()).rejects.toThrow(`Could not read project package at "${_path.default.join(process.cwd(), 'package.json')}"`);
122
+ }));
123
+ });
124
+ jest.unmock('fs-extra');
95
125
  describe('defaultMessage', () => {
96
126
  test('works', /*#__PURE__*/_asyncToGenerator(function* () {
97
127
  const mockGit = {
@@ -128,6 +158,10 @@ describe('scriptUtils', () => {
128
158
  }));
129
159
  describe('readCredentials', () => {
130
160
  test('should work', /*#__PURE__*/_asyncToGenerator(function* () {
161
+ _fsExtra.readJson.mockReturnValue({
162
+ username: 'alice',
163
+ api_key: 'xyz'
164
+ });
131
165
  const creds = {
132
166
  username: 'alice',
133
167
  api_key: 'xyz'
@@ -169,6 +203,7 @@ describe('scriptUtils', () => {
169
203
  })).rejects.toThrow('Build directory at path');
170
204
  }));
171
205
  test('should archive a bundle', /*#__PURE__*/_asyncToGenerator(function* () {
206
+ _fsExtra.readJson.mockReturnValue(pkg);
172
207
  const message = 'message';
173
208
  const bundle = yield scriptUtils.createBundle({
174
209
  message,
@@ -205,12 +240,13 @@ describe('scriptUtils', () => {
205
240
  expectedURL: 'https://cloud.mobify.com/api/projects/project-slug/builds/',
206
241
  status: 401
207
242
  }]])('should push a built bundle and handle status codes (%p)', /*#__PURE__*/function () {
208
- var _ref18 = _asyncToGenerator(function* ({
243
+ var _ref21 = _asyncToGenerator(function* ({
209
244
  projectSlug,
210
245
  targetSlug,
211
246
  expectedURL,
212
247
  status
213
248
  }) {
249
+ _fsExtra.readJson.mockReturnValue(pkg);
214
250
  const message = 'message';
215
251
  const bundle = yield scriptUtils.createBundle({
216
252
  message,
@@ -247,11 +283,11 @@ describe('scriptUtils', () => {
247
283
  fetch: fetchMock
248
284
  });
249
285
  const fn = /*#__PURE__*/function () {
250
- var _ref20 = _asyncToGenerator(function* () {
286
+ var _ref23 = _asyncToGenerator(function* () {
251
287
  return yield client.push(bundle, projectSlug, targetSlug);
252
288
  });
253
289
  return function fn() {
254
- return _ref20.apply(this, arguments);
290
+ return _ref23.apply(this, arguments);
255
291
  };
256
292
  }();
257
293
 
@@ -275,8 +311,83 @@ describe('scriptUtils', () => {
275
311
  }));
276
312
  });
277
313
  return function (_x) {
278
- return _ref18.apply(this, arguments);
314
+ return _ref21.apply(this, arguments);
279
315
  };
280
316
  }());
281
317
  });
318
+ describe('createLoggingToken', () => {
319
+ const username = 'user123';
320
+ const api_key = '123';
321
+ test('createLoggingToken passes', /*#__PURE__*/_asyncToGenerator(function* () {
322
+ _fsExtra.readJson.mockReturnValue(pkg);
323
+ const projectSlug = 'project-slug';
324
+ const targetSlug = 'target-slug';
325
+ const text = () => Promise.resolve(JSON.stringify({
326
+ token: 'token-value'
327
+ }));
328
+ const json = () => Promise.resolve({
329
+ token: 'token-value'
330
+ });
331
+ const fetchMock = jest.fn( /*#__PURE__*/_asyncToGenerator(function* () {
332
+ return {
333
+ status: 200,
334
+ text,
335
+ json
336
+ };
337
+ }));
338
+ const client = new scriptUtils.CloudAPIClient({
339
+ credentials: {
340
+ username,
341
+ api_key
342
+ },
343
+ fetch: fetchMock
344
+ });
345
+ const fn = /*#__PURE__*/function () {
346
+ var _ref26 = _asyncToGenerator(function* () {
347
+ return yield client.createLoggingToken(projectSlug, targetSlug);
348
+ });
349
+ return function fn() {
350
+ return _ref26.apply(this, arguments);
351
+ };
352
+ }();
353
+ expect(yield fn()).toBe('token-value');
354
+ expect(fetchMock).toHaveBeenCalledTimes(1);
355
+ expect(fetchMock).toHaveBeenCalledWith('https://cloud.mobify.com/api/projects/project-slug/target/target-slug/jwt/', expect.objectContaining({
356
+ method: 'POST',
357
+ headers: {
358
+ Authorization: expect.stringMatching(/^Bearer /),
359
+ 'User-Agent': `${pkg.name}@${pkg.version}`
360
+ }
361
+ }));
362
+ }));
363
+ });
364
+ describe('parseLog', () => {
365
+ it('correctly parses an application log', () => {
366
+ const log = '2023-07-15T10:00:00Z\t550e8400-e29b-41d4-a716-446655440000\tINFO\tThis is a test log message';
367
+ const result = scriptUtils.parseLog(log);
368
+ expect(result).toEqual({
369
+ level: 'INFO',
370
+ message: 'This is a test log message',
371
+ shortRequestId: '550e8400'
372
+ });
373
+ });
374
+ it('correctly parses a platform log', () => {
375
+ const log = 'WARN\tThis is a test log message';
376
+ const result = scriptUtils.parseLog(log);
377
+ expect(result).toEqual({
378
+ level: 'WARN',
379
+ message: '\tThis is a test log message',
380
+ shortRequestId: undefined
381
+ });
382
+ });
383
+ it('finds the shortRequestId in the message if not present in the request id', () => {
384
+ const log = 'INFO\tThis is a test log message 550e8400';
385
+ const result = scriptUtils.parseLog(log);
386
+ expect(result).toEqual({
387
+ level: 'INFO',
388
+ message: '\tThis is a test log message 550e8400',
389
+ shortRequestId: '550e8400'
390
+ });
391
+ });
392
+ });
282
393
  });