decap-cms-lib-util 3.1.0 → 3.2.0

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/CHANGELOG.md CHANGED
@@ -3,6 +3,12 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ # [3.2.0](https://github.com/decaporg/decap-cms/compare/decap-cms-lib-util@3.1.0...decap-cms-lib-util@3.2.0) (2025-01-29)
7
+
8
+ ### Features
9
+
10
+ - visual editing (click-to-edit) ([#7374](https://github.com/decaporg/decap-cms/issues/7374)) ([989c2dd](https://github.com/decaporg/decap-cms/commit/989c2dd6ed80f69b572b8b73c4e37b5106ae04fb))
11
+
6
12
  # [3.1.0](https://github.com/decaporg/decap-cms/compare/decap-cms-lib-util@3.0.4...decap-cms-lib-util@3.1.0) (2024-08-07)
7
13
 
8
14
  ### Bug Fixes
package/dist/esm/API.js CHANGED
@@ -1,24 +1,4 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.PreviewState = void 0;
7
- exports.apiRequest = apiRequest;
8
- exports.endpointConstants = exports.apiRoots = void 0;
9
- exports.getDefaultBranchName = getDefaultBranchName;
10
- exports.getPreviewStatus = getPreviewStatus;
11
- exports.isPreviewContext = isPreviewContext;
12
- exports.parseResponse = parseResponse;
13
- exports.readFile = readFile;
14
- exports.readFileMetadata = readFileMetadata;
15
- exports.requestWithBackoff = requestWithBackoff;
16
- exports.throwOnConflictingBranches = throwOnConflictingBranches;
17
- var _asyncLock = require("./asyncLock");
18
- var _unsentRequest = _interopRequireDefault(require("./unsentRequest"));
19
- var _APIError = _interopRequireDefault(require("./APIError"));
20
1
  const _excluded = ["token", "backend"];
21
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
22
2
  function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
23
3
  function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
24
4
  function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
@@ -47,6 +27,9 @@ function _extendableBuiltin(cls) {
47
27
  }
48
28
  return ExtendableBuiltin;
49
29
  }
30
+ import { asyncLock } from './asyncLock';
31
+ import unsentRequest from './unsentRequest';
32
+ import APIError from './APIError';
50
33
  class RateLimitError extends _extendableBuiltin(Error) {
51
34
  constructor(message, resetSeconds) {
52
35
  super(message);
@@ -67,7 +50,7 @@ async function parseJsonResponse(response) {
67
50
  }
68
51
  return json;
69
52
  }
70
- function parseResponse(response) {
53
+ export function parseResponse(response) {
71
54
  const contentType = response.headers.get('Content-Type');
72
55
  if (contentType && contentType.match(/json/)) {
73
56
  return parseJsonResponse(response);
@@ -78,13 +61,13 @@ function parseResponse(response) {
78
61
  });
79
62
  return textPromise;
80
63
  }
81
- async function requestWithBackoff(api, req, attempt = 1) {
64
+ export async function requestWithBackoff(api, req, attempt = 1) {
82
65
  if (api.rateLimiter) {
83
66
  await api.rateLimiter.acquire();
84
67
  }
85
68
  try {
86
69
  const builtRequest = await api.buildRequest(req);
87
- const requestFunction = api.requestFunction || _unsentRequest.default.performRequest;
70
+ const requestFunction = api.requestFunction || unsentRequest.performRequest;
88
71
  const response = await requestFunction(builtRequest);
89
72
  if (response.status === 429) {
90
73
  // GitLab/Bitbucket too many requests
@@ -110,7 +93,7 @@ async function requestWithBackoff(api, req, attempt = 1) {
110
93
  if (!api.rateLimiter) {
111
94
  const timeout = err.resetSeconds || attempt * attempt;
112
95
  console.log(`Pausing requests for ${timeout} ${attempt === 1 ? 'second' : 'seconds'} due to fetch failures:`, err.message);
113
- api.rateLimiter = (0, _asyncLock.asyncLock)();
96
+ api.rateLimiter = asyncLock();
114
97
  api.rateLimiter.acquire();
115
98
  setTimeout(() => {
116
99
  var _api$rateLimiter;
@@ -134,12 +117,12 @@ async function requestWithBackoff(api, req, attempt = 1) {
134
117
  // - `params` property for customizing response
135
118
  // - `backend`(compulsory) to specify which backend to be used: Github, Gitlab etc.
136
119
 
137
- const apiRoots = exports.apiRoots = {
120
+ export const apiRoots = {
138
121
  github: 'https://api.github.com',
139
122
  gitlab: 'https://gitlab.com/api/v4',
140
123
  bitbucket: 'https://api.bitbucket.org/2.0'
141
124
  };
142
- const endpointConstants = exports.endpointConstants = {
125
+ export const endpointConstants = {
143
126
  singleRepo: {
144
127
  bitbucket: '/repositories',
145
128
  github: '/repos',
@@ -177,9 +160,9 @@ async function constructRequestHeaders(headerConfig) {
177
160
  return Promise.resolve(baseHeaders);
178
161
  }
179
162
  function handleRequestError(error, responseStatus, backend) {
180
- throw new _APIError.default(error.message, responseStatus, backend);
163
+ throw new APIError(error.message, responseStatus, backend);
181
164
  }
182
- async function apiRequest(path, config, parser = response => parseResponse(response)) {
165
+ export async function apiRequest(path, config, parser = response => parseResponse(response)) {
183
166
  var _config$apiRoot;
184
167
  const {
185
168
  token,
@@ -197,7 +180,7 @@ async function apiRequest(path, config, parser = response => parseResponse(respo
197
180
  const url = constructUrlWithParams(`${baseUrl}${path}`, options.params);
198
181
  let responseStatus = 500;
199
182
  try {
200
- const req = _unsentRequest.default.fromFetchArguments(url, _objectSpread(_objectSpread({}, options), {}, {
183
+ const req = unsentRequest.fromFetchArguments(url, _objectSpread(_objectSpread({}, options), {}, {
201
184
  headers
202
185
  }));
203
186
  const response = await requestWithBackoff(api, req);
@@ -208,7 +191,7 @@ async function apiRequest(path, config, parser = response => parseResponse(respo
208
191
  return handleRequestError(error, responseStatus, backend);
209
192
  }
210
193
  }
211
- async function getDefaultBranchName(configs) {
194
+ export async function getDefaultBranchName(configs) {
212
195
  let apiPath;
213
196
  const {
214
197
  token,
@@ -253,7 +236,7 @@ async function getDefaultBranchName(configs) {
253
236
  }
254
237
  return defaultBranchName;
255
238
  }
256
- async function readFile(id, fetchContent, localForage, isText) {
239
+ export async function readFile(id, fetchContent, localForage, isText) {
257
240
  const key = id ? isText ? `gh.${id}` : `gh.${id}.blob` : null;
258
241
  const cached = key ? await localForage.getItem(key) : null;
259
242
  if (cached) {
@@ -268,7 +251,7 @@ async function readFile(id, fetchContent, localForage, isText) {
268
251
  function getFileMetadataKey(id) {
269
252
  return `gh.${id}.meta`;
270
253
  }
271
- async function readFileMetadata(id, fetchMetadata, localForage) {
254
+ export async function readFileMetadata(id, fetchMetadata, localForage) {
272
255
  const key = id ? getFileMetadataKey(id) : null;
273
256
  const cached = key && (await localForage.getItem(key));
274
257
  if (cached) {
@@ -291,22 +274,23 @@ const PREVIEW_CONTEXT_KEYWORDS = ['deploy'];
291
274
  * deploy preview. Checks for an exact match against `previewContext` if given,
292
275
  * otherwise checks for inclusion of a value from `PREVIEW_CONTEXT_KEYWORDS`.
293
276
  */
294
- function isPreviewContext(context, previewContext) {
277
+ export function isPreviewContext(context, previewContext) {
295
278
  if (previewContext) {
296
279
  return context === previewContext;
297
280
  }
298
281
  return PREVIEW_CONTEXT_KEYWORDS.some(keyword => context.includes(keyword));
299
282
  }
300
- let PreviewState = exports.PreviewState = /*#__PURE__*/function (PreviewState) {
283
+ export let PreviewState = /*#__PURE__*/function (PreviewState) {
301
284
  PreviewState["Other"] = "other";
302
285
  PreviewState["Success"] = "success";
303
286
  return PreviewState;
304
287
  }({});
288
+
305
289
  /**
306
290
  * Retrieve a deploy preview URL from an array of statuses. By default, a
307
291
  * matching status is inferred via `isPreviewContext`.
308
292
  */
309
- function getPreviewStatus(statuses, previewContext) {
293
+ export function getPreviewStatus(statuses, previewContext) {
310
294
  return statuses.find(({
311
295
  context
312
296
  }) => {
@@ -323,11 +307,11 @@ function getConflictingBranches(branchName) {
323
307
  }, []);
324
308
  return conflictingBranches;
325
309
  }
326
- async function throwOnConflictingBranches(branchName, getBranch, apiName) {
310
+ export async function throwOnConflictingBranches(branchName, getBranch, apiName) {
327
311
  const possibleConflictingBranches = getConflictingBranches(branchName);
328
312
  const conflictingBranches = await Promise.all(possibleConflictingBranches.map(b => getBranch(b).then(b => b.name).catch(() => '')));
329
313
  const conflictingBranch = conflictingBranches.filter(Boolean)[0];
330
314
  if (conflictingBranch) {
331
- throw new _APIError.default(`Failed creating branch '${branchName}' since there is already a branch named '${conflictingBranch}'. Please delete the '${conflictingBranch}' branch and try again`, 500, apiName);
315
+ throw new APIError(`Failed creating branch '${branchName}' since there is already a branch named '${conflictingBranch}'. Please delete the '${conflictingBranch}' branch and try again`, 500, apiName);
332
316
  }
333
317
  }
@@ -1,9 +1,3 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = exports.API_ERROR = void 0;
7
1
  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; }
8
2
  function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); }
9
3
  function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
@@ -28,8 +22,8 @@ function _extendableBuiltin(cls) {
28
22
  }
29
23
  return ExtendableBuiltin;
30
24
  }
31
- const API_ERROR = exports.API_ERROR = 'API_ERROR';
32
- class APIError extends _extendableBuiltin(Error) {
25
+ export const API_ERROR = 'API_ERROR';
26
+ export default class APIError extends _extendableBuiltin(Error) {
33
27
  constructor(message, status, api, meta = {}) {
34
28
  super(message);
35
29
  _defineProperty(this, "message", void 0);
@@ -42,5 +36,4 @@ class APIError extends _extendableBuiltin(Error) {
42
36
  this.name = API_ERROR;
43
37
  this.meta = meta;
44
38
  }
45
- }
46
- exports.default = APIError;
39
+ }
@@ -1,45 +1,32 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.MERGE_COMMIT_MESSAGE = exports.DEFAULT_PR_BODY = exports.CMS_BRANCH_PREFIX = void 0;
7
- exports.branchFromContentKey = branchFromContentKey;
8
- exports.contentKeyFromBranch = contentKeyFromBranch;
9
- exports.generateContentKey = generateContentKey;
10
- exports.isCMSLabel = isCMSLabel;
11
- exports.labelToStatus = labelToStatus;
12
- exports.parseContentKey = parseContentKey;
13
- exports.statusToLabel = statusToLabel;
14
- const CMS_BRANCH_PREFIX = exports.CMS_BRANCH_PREFIX = 'cms';
15
- const DEFAULT_PR_BODY = exports.DEFAULT_PR_BODY = 'Automatically generated by Decap CMS';
16
- const MERGE_COMMIT_MESSAGE = exports.MERGE_COMMIT_MESSAGE = 'Automatically generated. Merged on Decap CMS.';
1
+ export const CMS_BRANCH_PREFIX = 'cms';
2
+ export const DEFAULT_PR_BODY = 'Automatically generated by Decap CMS';
3
+ export const MERGE_COMMIT_MESSAGE = 'Automatically generated. Merged on Decap CMS.';
17
4
  const DEFAULT_DECAP_CMS_LABEL_PREFIX = 'decap-cms/';
18
5
  function getLabelPrefix(labelPrefix) {
19
6
  return labelPrefix || DEFAULT_DECAP_CMS_LABEL_PREFIX;
20
7
  }
21
- function isCMSLabel(label, labelPrefix) {
8
+ export function isCMSLabel(label, labelPrefix) {
22
9
  return label.startsWith(getLabelPrefix(labelPrefix));
23
10
  }
24
- function labelToStatus(label, labelPrefix) {
11
+ export function labelToStatus(label, labelPrefix) {
25
12
  return label.slice(getLabelPrefix(labelPrefix).length);
26
13
  }
27
- function statusToLabel(status, labelPrefix) {
14
+ export function statusToLabel(status, labelPrefix) {
28
15
  return `${getLabelPrefix(labelPrefix)}${status}`;
29
16
  }
30
- function generateContentKey(collectionName, slug) {
17
+ export function generateContentKey(collectionName, slug) {
31
18
  return `${collectionName}/${slug}`;
32
19
  }
33
- function parseContentKey(contentKey) {
20
+ export function parseContentKey(contentKey) {
34
21
  const index = contentKey.indexOf('/');
35
22
  return {
36
23
  collection: contentKey.slice(0, index),
37
24
  slug: contentKey.slice(index + 1)
38
25
  };
39
26
  }
40
- function contentKeyFromBranch(branch) {
27
+ export function contentKeyFromBranch(branch) {
41
28
  return branch.slice(`${CMS_BRANCH_PREFIX}/`.length);
42
29
  }
43
- function branchFromContentKey(contentKey) {
30
+ export function branchFromContentKey(contentKey) {
44
31
  return `${CMS_BRANCH_PREFIX}/${contentKey}`;
45
32
  }
@@ -1,9 +1,3 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = exports.ACCESS_TOKEN_ERROR = void 0;
7
1
  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; }
8
2
  function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); }
9
3
  function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
@@ -28,13 +22,12 @@ function _extendableBuiltin(cls) {
28
22
  }
29
23
  return ExtendableBuiltin;
30
24
  }
31
- const ACCESS_TOKEN_ERROR = exports.ACCESS_TOKEN_ERROR = 'ACCESS_TOKEN_ERROR';
32
- class AccessTokenError extends _extendableBuiltin(Error) {
25
+ export const ACCESS_TOKEN_ERROR = 'ACCESS_TOKEN_ERROR';
26
+ export default class AccessTokenError extends _extendableBuiltin(Error) {
33
27
  constructor(message) {
34
28
  super(message);
35
29
  _defineProperty(this, "message", void 0);
36
30
  this.message = message;
37
31
  this.name = ACCESS_TOKEN_ERROR;
38
32
  }
39
- }
40
- exports.default = AccessTokenError;
33
+ }
@@ -1,24 +1,18 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = exports.CURSOR_COMPATIBILITY_SYMBOL = void 0;
7
- var _immutable = require("immutable");
8
1
  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; }
9
2
  function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); }
10
3
  function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
4
+ import { fromJS, Map, Set } from 'immutable';
11
5
  function jsToMap(obj) {
12
6
  if (obj === undefined) {
13
- return (0, _immutable.Map)();
7
+ return Map();
14
8
  }
15
- const immutableObj = (0, _immutable.fromJS)(obj);
16
- if (!_immutable.Map.isMap(immutableObj)) {
9
+ const immutableObj = fromJS(obj);
10
+ if (!Map.isMap(immutableObj)) {
17
11
  throw new Error('Object must be equivalent to a Map.');
18
12
  }
19
13
  return immutableObj;
20
14
  }
21
- const knownMetaKeys = (0, _immutable.Set)(['index', 'page', 'count', 'pageSize', 'pageCount', 'usingOldPaginationAPI', 'extension', 'folder', 'depth']);
15
+ const knownMetaKeys = Set(['index', 'page', 'count', 'pageSize', 'pageCount', 'usingOldPaginationAPI', 'extension', 'folder', 'depth']);
22
16
  function filterUnknownMetaKeys(meta) {
23
17
  return meta.filter((_v, k) => knownMetaKeys.has(k));
24
18
  }
@@ -39,9 +33,9 @@ function createCursorStore(...args) {
39
33
  data: args[1],
40
34
  meta: args[2]
41
35
  };
42
- return (0, _immutable.Map)({
36
+ return Map({
43
37
  // actions are a Set, rather than a List, to ensure an efficient .has
44
- actions: (0, _immutable.Set)(actions),
38
+ actions: Set(actions),
45
39
  // data and meta are Maps
46
40
  data: jsToMap(data),
47
41
  meta: jsToMap(meta).update(filterUnknownMetaKeys)
@@ -51,12 +45,12 @@ function hasAction(store, action) {
51
45
  return store.hasIn(['actions', action]);
52
46
  }
53
47
  function getActionHandlers(store, handler) {
54
- return store.get('actions', (0, _immutable.Set)()).toMap().map(action => handler(action));
48
+ return store.get('actions', Set()).toMap().map(action => handler(action));
55
49
  }
56
50
 
57
51
  // The cursor logic is entirely functional, so this class simply
58
52
  // provides a chainable interface
59
- class Cursor {
53
+ export default class Cursor {
60
54
  static create(...args) {
61
55
  return new Cursor(...args);
62
56
  }
@@ -94,7 +88,7 @@ class Cursor {
94
88
  return this.updateStore('actions', actions => actions.delete(action));
95
89
  }
96
90
  setActions(actions) {
97
- return this.updateStore(store => store.set('actions', (0, _immutable.Set)(actions)));
91
+ return this.updateStore(store => store.set('actions', Set(actions)));
98
92
  }
99
93
  mergeActions(actions) {
100
94
  return this.updateStore('actions', oldActions => oldActions.union(actions));
@@ -115,7 +109,7 @@ class Cursor {
115
109
  return [this.store.get('data').delete('wrapped_cursor_data'), this.updateStore('data', data => data.get('wrapped_cursor_data'))];
116
110
  }
117
111
  clearData() {
118
- return this.updateStore('data', () => (0, _immutable.Map)());
112
+ return this.updateStore('data', () => Map());
119
113
  }
120
114
  setMeta(meta) {
121
115
  return this.updateStore(store => store.set('meta', jsToMap(meta)));
@@ -130,5 +124,4 @@ class Cursor {
130
124
  // backends at all. This should be removed in favor of wrapping old
131
125
  // backends with a compatibility layer, as part of the backend API
132
126
  // refactor.
133
- exports.default = Cursor;
134
- const CURSOR_COMPATIBILITY_SYMBOL = exports.CURSOR_COMPATIBILITY_SYMBOL = Symbol('cursor key for compatibility with old backends');
127
+ export const CURSOR_COMPATIBILITY_SYMBOL = Symbol('cursor key for compatibility with old backends');
@@ -1,9 +1,3 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = exports.EDITORIAL_WORKFLOW_ERROR = void 0;
7
1
  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; }
8
2
  function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); }
9
3
  function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
@@ -28,8 +22,8 @@ function _extendableBuiltin(cls) {
28
22
  }
29
23
  return ExtendableBuiltin;
30
24
  }
31
- const EDITORIAL_WORKFLOW_ERROR = exports.EDITORIAL_WORKFLOW_ERROR = 'EDITORIAL_WORKFLOW_ERROR';
32
- class EditorialWorkflowError extends _extendableBuiltin(Error) {
25
+ export const EDITORIAL_WORKFLOW_ERROR = 'EDITORIAL_WORKFLOW_ERROR';
26
+ export default class EditorialWorkflowError extends _extendableBuiltin(Error) {
33
27
  constructor(message, notUnderEditorialWorkflow) {
34
28
  super(message);
35
29
  _defineProperty(this, "message", void 0);
@@ -38,5 +32,4 @@ class EditorialWorkflowError extends _extendableBuiltin(Error) {
38
32
  this.notUnderEditorialWorkflow = notUnderEditorialWorkflow;
39
33
  this.name = EDITORIAL_WORKFLOW_ERROR;
40
34
  }
41
- }
42
- exports.default = EditorialWorkflowError;
35
+ }
@@ -1,19 +1,12 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.asyncLock = asyncLock;
7
- var _semaphore = _interopRequireDefault(require("semaphore"));
8
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
9
- function asyncLock() {
10
- let lock = (0, _semaphore.default)(1);
1
+ import semaphore from 'semaphore';
2
+ export function asyncLock() {
3
+ let lock = semaphore(1);
11
4
  function acquire(timeout = 15000) {
12
5
  const promise = new Promise(resolve => {
13
6
  // this makes sure a caller doesn't gets stuck forever awaiting on the lock
14
7
  const timeoutId = setTimeout(() => {
15
8
  // we reset the lock in that case to allow future consumers to use it without being blocked
16
- lock = (0, _semaphore.default)(1);
9
+ lock = semaphore(1);
17
10
  resolve(false);
18
11
  }, timeout);
19
12
  lock.take(() => {
@@ -34,7 +27,7 @@ function asyncLock() {
34
27
  throw e;
35
28
  } else {
36
29
  console.warn('leave called too many times.');
37
- lock = (0, _semaphore.default)(1);
30
+ lock = semaphore(1);
38
31
  }
39
32
  }
40
33
  }
@@ -1,22 +1,10 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.filterByExtension = filterByExtension;
7
- exports.getAllResponses = getAllResponses;
8
- exports.getPathDepth = getPathDepth;
9
- exports.parseLinkHeader = parseLinkHeader;
10
- exports.parseResponse = parseResponse;
11
- exports.responseParser = responseParser;
12
- var _map2 = _interopRequireDefault(require("lodash/fp/map"));
13
- var _fromPairs2 = _interopRequireDefault(require("lodash/fromPairs"));
14
- var _flow2 = _interopRequireDefault(require("lodash/flow"));
15
- var _immutable = require("immutable");
16
- var _unsentRequest = _interopRequireDefault(require("./unsentRequest"));
17
- var _APIError = _interopRequireDefault(require("./APIError"));
18
- function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
19
- function filterByExtension(file, extension) {
1
+ import _map from "lodash/fp/map";
2
+ import _fromPairs from "lodash/fromPairs";
3
+ import _flow from "lodash/flow";
4
+ import { fromJS } from 'immutable';
5
+ import unsentRequest from './unsentRequest';
6
+ import APIError from './APIError';
7
+ export function filterByExtension(file, extension) {
20
8
  const path = (file === null || file === void 0 ? void 0 : file.path) || '';
21
9
  return path.endsWith(extension.startsWith('.') ? extension : `.${extension}`);
22
10
  }
@@ -29,7 +17,7 @@ function catchFormatErrors(format, formatter) {
29
17
  }
30
18
  };
31
19
  }
32
- const responseFormatters = (0, _immutable.fromJS)({
20
+ const responseFormatters = fromJS({
33
21
  json: async res => {
34
22
  const contentType = res.headers.get('Content-Type') || '';
35
23
  if (!contentType.startsWith('application/json') && !contentType.startsWith('text/json')) {
@@ -40,7 +28,7 @@ const responseFormatters = (0, _immutable.fromJS)({
40
28
  text: async res => res.text(),
41
29
  blob: async res => res.blob()
42
30
  }).mapEntries(([format, formatter]) => [format, catchFormatErrors(format, formatter)]);
43
- async function parseResponse(res, {
31
+ export async function parseResponse(res, {
44
32
  expectingOk = true,
45
33
  format = 'text',
46
34
  apiName = ''
@@ -53,38 +41,38 @@ async function parseResponse(res, {
53
41
  }
54
42
  body = await formatter(res);
55
43
  } catch (err) {
56
- throw new _APIError.default(err.message, res.status, apiName);
44
+ throw new APIError(err.message, res.status, apiName);
57
45
  }
58
46
  if (expectingOk && !res.ok) {
59
47
  var _body$error;
60
48
  const isJSON = format === 'json';
61
49
  const message = isJSON ? body.message || body.msg || ((_body$error = body.error) === null || _body$error === void 0 ? void 0 : _body$error.message) : body;
62
- throw new _APIError.default(isJSON && message ? message : body, res.status, apiName);
50
+ throw new APIError(isJSON && message ? message : body, res.status, apiName);
63
51
  }
64
52
  return body;
65
53
  }
66
- function responseParser(options) {
54
+ export function responseParser(options) {
67
55
  return res => parseResponse(res, options);
68
56
  }
69
- function parseLinkHeader(header) {
57
+ export function parseLinkHeader(header) {
70
58
  if (!header) {
71
59
  return {};
72
60
  }
73
- return (0, _flow2.default)([linksString => linksString.split(','), (0, _map2.default)(str => str.trim().split(';')), (0, _map2.default)(([linkStr, keyStr]) => [keyStr.match(/rel="(.*?)"/)[1], linkStr.trim().match(/<(.*?)>/)[1].replace(/\+/g, '%20')]), _fromPairs2.default])(header);
61
+ return _flow([linksString => linksString.split(','), _map(str => str.trim().split(';')), _map(([linkStr, keyStr]) => [keyStr.match(/rel="(.*?)"/)[1], linkStr.trim().match(/<(.*?)>/)[1].replace(/\+/g, '%20')]), _fromPairs])(header);
74
62
  }
75
- async function getAllResponses(url, options = {}, linkHeaderRelName, nextUrlProcessor) {
63
+ export async function getAllResponses(url, options = {}, linkHeaderRelName, nextUrlProcessor) {
76
64
  const maxResponses = 30;
77
65
  let responseCount = 1;
78
- let req = _unsentRequest.default.fromFetchArguments(url, options);
66
+ let req = unsentRequest.fromFetchArguments(url, options);
79
67
  const pageResponses = [];
80
68
  while (req && responseCount < maxResponses) {
81
- const pageResponse = await _unsentRequest.default.performRequest(req);
69
+ const pageResponse = await unsentRequest.performRequest(req);
82
70
  const linkHeader = pageResponse.headers.get('Link');
83
71
  const nextURL = linkHeader && parseLinkHeader(linkHeader)[linkHeaderRelName];
84
72
  const {
85
73
  headers = {}
86
74
  } = options;
87
- req = nextURL && _unsentRequest.default.fromFetchArguments(nextUrlProcessor(nextURL), {
75
+ req = nextURL && unsentRequest.fromFetchArguments(nextUrlProcessor(nextURL), {
88
76
  headers
89
77
  });
90
78
  pageResponses.push(pageResponse);
@@ -92,7 +80,7 @@ async function getAllResponses(url, options = {}, linkHeaderRelName, nextUrlProc
92
80
  }
93
81
  return pageResponses;
94
82
  }
95
- function getPathDepth(path) {
83
+ export function getPathDepth(path) {
96
84
  const depth = path.split('/').length;
97
85
  return depth;
98
86
  }
@@ -1,19 +1,12 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.default = void 0;
7
- var _jsSha = require("js-sha256");
8
- var _default = blob => new Promise((resolve, reject) => {
1
+ import { sha256 } from 'js-sha256';
2
+ export default (blob => new Promise((resolve, reject) => {
9
3
  const fr = new FileReader();
10
4
  fr.onload = ({
11
5
  target
12
- }) => resolve((0, _jsSha.sha256)((target === null || target === void 0 ? void 0 : target.result) || ''));
6
+ }) => resolve(sha256((target === null || target === void 0 ? void 0 : target.result) || ''));
13
7
  fr.onerror = err => {
14
8
  fr.abort();
15
9
  reject(err);
16
10
  };
17
11
  fr.readAsArrayBuffer(blob);
18
- });
19
- exports.default = _default;
12
+ }));