@sanity/export 2.29.5-purple-unicorn-remix.873 → 2.30.2-shopify.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/jest.config.js ADDED
@@ -0,0 +1,6 @@
1
+ const createConfig = require('../../../createJestConfig')
2
+
3
+ module.exports = createConfig({
4
+ displayName: require('./package.json').name,
5
+ testEnvironment: 'node',
6
+ })
@@ -1,69 +1,105 @@
1
1
  "use strict";
2
2
 
3
- function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
3
+ var _excluded = ["asset"];
4
+
5
+ function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
6
+
7
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
8
+
9
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
10
+
11
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
4
12
 
5
- const path = require('path');
13
+ function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
6
14
 
7
- const crypto = require('crypto');
15
+ function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
8
16
 
9
- const {
10
- parse: parseUrl,
11
- format: formatUrl
12
- } = require('url');
17
+ 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; }
13
18
 
14
- const {
15
- mkdirSync,
16
- createWriteStream
17
- } = require('fs');
19
+ 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; }
18
20
 
19
- const miss = require('mississippi');
21
+ 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; }
20
22
 
21
- const PQueue = require('p-queue');
23
+ 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
+
25
+ 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); } }
26
+
27
+ 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); }); }; }
28
+
29
+ function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
22
30
 
23
- const {
24
- omit,
25
- noop
26
- } = require('lodash');
31
+ var path = require('path');
27
32
 
28
- const pkg = require('../package.json');
33
+ var crypto = require('crypto');
29
34
 
30
- const requestStream = require('./requestStream');
35
+ var _require = require('url'),
36
+ parseUrl = _require.parse,
37
+ formatUrl = _require.format;
31
38
 
32
- const debug = require('./debug');
39
+ var fse = require('fs-extra');
33
40
 
34
- const rimraf = require('./util/rimraf');
41
+ var miss = require('mississippi');
35
42
 
36
- const EXCLUDE_PROPS = ['_id', '_type', 'assetId', 'extension', 'mimeType', 'path', 'url'];
37
- const ACTION_REMOVE = 'remove';
38
- const ACTION_REWRITE = 'rewrite';
39
- const ASSET_DOWNLOAD_CONCURRENCY = 8;
43
+ var PQueue = require('p-queue');
44
+
45
+ var _require2 = require('lodash'),
46
+ omit = _require2.omit,
47
+ noop = _require2.noop;
48
+
49
+ var pkg = require('../package.json');
50
+
51
+ var requestStream = require('./requestStream');
52
+
53
+ var debug = require('./debug');
54
+
55
+ var EXCLUDE_PROPS = ['_id', '_type', 'assetId', 'extension', 'mimeType', 'path', 'url'];
56
+ var ACTION_REMOVE = 'remove';
57
+ var ACTION_REWRITE = 'rewrite';
58
+ var ASSET_DOWNLOAD_CONCURRENCY = 8;
40
59
 
41
60
  class AssetHandler {
42
61
  constructor(options) {
43
- _defineProperty(this, "rewriteAssets", miss.through.obj(async (doc, enc, callback) => {
44
- if (['sanity.imageAsset', 'sanity.fileAsset'].includes(doc._type)) {
45
- const type = doc._type === 'sanity.imageAsset' ? 'image' : 'file';
46
- const filePath = "".concat(type, "s/").concat(generateFilename(doc._id));
47
- this.assetsSeen.set(doc._id, type);
48
- this.queueAssetDownload(doc, filePath, type);
49
- callback();
50
- return;
51
- }
62
+ var _this = this;
52
63
 
53
- callback(null, this.findAndModify(doc, ACTION_REWRITE));
54
- }));
64
+ _defineProperty(this, "rewriteAssets", miss.through.obj( /*#__PURE__*/function () {
65
+ var _ref = _asyncToGenerator(function* (doc, enc, callback) {
66
+ if (['sanity.imageAsset', 'sanity.fileAsset'].includes(doc._type)) {
67
+ var type = doc._type === 'sanity.imageAsset' ? 'image' : 'file';
68
+ var filePath = "".concat(type, "s/").concat(generateFilename(doc._id));
55
69
 
56
- _defineProperty(this, "stripAssets", miss.through.obj(async (doc, enc, callback) => {
57
- if (['sanity.imageAsset', 'sanity.fileAsset'].includes(doc._type)) {
58
- callback();
59
- return;
60
- }
70
+ _this.assetsSeen.set(doc._id, type);
61
71
 
62
- callback(null, this.findAndModify(doc, ACTION_REMOVE));
63
- }));
72
+ _this.queueAssetDownload(doc, filePath, type);
73
+
74
+ callback();
75
+ return;
76
+ }
77
+
78
+ callback(null, _this.findAndModify(doc, ACTION_REWRITE));
79
+ });
80
+
81
+ return function (_x, _x2, _x3) {
82
+ return _ref.apply(this, arguments);
83
+ };
84
+ }()));
85
+
86
+ _defineProperty(this, "stripAssets", miss.through.obj( /*#__PURE__*/function () {
87
+ var _ref2 = _asyncToGenerator(function* (doc, enc, callback) {
88
+ if (['sanity.imageAsset', 'sanity.fileAsset'].includes(doc._type)) {
89
+ callback();
90
+ return;
91
+ }
92
+
93
+ callback(null, _this.findAndModify(doc, ACTION_REMOVE));
94
+ });
95
+
96
+ return function (_x4, _x5, _x6) {
97
+ return _ref2.apply(this, arguments);
98
+ };
99
+ }()));
64
100
 
65
101
  _defineProperty(this, "skipAssets", miss.through.obj((doc, enc, callback) => {
66
- const isAsset = ['sanity.imageAsset', 'sanity.fileAsset'].includes(doc._type);
102
+ var isAsset = ['sanity.imageAsset', 'sanity.fileAsset'].includes(doc._type);
67
103
 
68
104
  if (isAsset) {
69
105
  callback();
@@ -77,7 +113,7 @@ class AssetHandler {
77
113
 
78
114
  _defineProperty(this, "findAndModify", (item, action) => {
79
115
  if (Array.isArray(item)) {
80
- const children = item.map(child => this.findAndModify(child, action));
116
+ var children = item.map(child => this.findAndModify(child, action));
81
117
  return children.filter(Boolean);
82
118
  }
83
119
 
@@ -85,32 +121,30 @@ class AssetHandler {
85
121
  return item;
86
122
  }
87
123
 
88
- const isAsset = isAssetField(item);
124
+ var isAsset = isAssetField(item);
89
125
 
90
126
  if (isAsset && action === ACTION_REMOVE) {
91
127
  return undefined;
92
128
  }
93
129
 
94
130
  if (isAsset && action === ACTION_REWRITE) {
95
- const {
96
- asset,
97
- ...other
98
- } = item;
99
- const assetId = asset._ref;
100
- const assetType = getAssetType(item);
101
- const filePath = "".concat(assetType, "s/").concat(generateFilename(assetId));
102
- return {
103
- _sanityAsset: "".concat(assetType, "@file://./").concat(filePath),
104
- ...this.findAndModify(other, action)
105
- };
131
+ var asset = item.asset,
132
+ other = _objectWithoutProperties(item, _excluded);
133
+
134
+ var assetId = asset._ref;
135
+ var assetType = getAssetType(item);
136
+ var filePath = "".concat(assetType, "s/").concat(generateFilename(assetId));
137
+ return _objectSpread({
138
+ _sanityAsset: "".concat(assetType, "@file://./").concat(filePath)
139
+ }, this.findAndModify(other, action));
106
140
  }
107
141
 
108
- const newItem = {};
109
- const keys = Object.keys(item);
142
+ var newItem = {};
143
+ var keys = Object.keys(item);
110
144
 
111
- for (let i = 0; i < keys.length; i++) {
112
- const key = keys[i];
113
- const value = item[key];
145
+ for (var i = 0; i < keys.length; i++) {
146
+ var key = keys[i];
147
+ var value = item[key];
114
148
  newItem[key] = this.findAndModify(value, action);
115
149
 
116
150
  if (typeof newItem[key] === 'undefined') {
@@ -121,7 +155,7 @@ class AssetHandler {
121
155
  return newItem;
122
156
  });
123
157
 
124
- const concurrency = options.concurrency || ASSET_DOWNLOAD_CONCURRENCY;
158
+ var concurrency = options.concurrency || ASSET_DOWNLOAD_CONCURRENCY;
125
159
  debug('Using asset download concurrency of %d', concurrency);
126
160
  this.client = options.client;
127
161
  this.tmpDir = options.tmpDir;
@@ -180,30 +214,26 @@ class AssetHandler {
180
214
  /* eslint-disable no-sync */
181
215
 
182
216
 
183
- mkdirSync(path.join(this.tmpDir, 'files'), {
184
- recursive: true
185
- });
186
- mkdirSync(path.join(this.tmpDir, 'images'), {
187
- recursive: true
188
- });
217
+ fse.ensureDirSync(path.join(this.tmpDir, 'files'));
218
+ fse.ensureDirSync(path.join(this.tmpDir, 'images'));
189
219
  /* eslint-enable no-sync */
190
220
 
191
221
  this.assetDirsCreated = true;
192
222
  }
193
223
 
194
224
  getAssetRequestOptions(assetDoc) {
195
- const token = this.client.config().token;
196
- const headers = {
225
+ var token = this.client.config().token;
226
+ var headers = {
197
227
  'User-Agent': "".concat(pkg.name, "@").concat(pkg.version)
198
228
  };
199
- const isImage = assetDoc._type === 'sanity.imageAsset';
200
- const url = parseUrl(assetDoc.url, true);
229
+ var isImage = assetDoc._type === 'sanity.imageAsset';
230
+ var url = parseUrl(assetDoc.url, true);
201
231
 
202
232
  if (isImage && ['cdn.sanity.io', 'cdn.sanity.work'].includes(url.hostname)) {
203
233
  headers.Authorization = "Bearer ".concat(token);
204
- url.query = { ...(url.query || {}),
234
+ url.query = _objectSpread(_objectSpread({}, url.query || {}), {}, {
205
235
  dlRaw: 'true'
206
- };
236
+ });
207
237
  }
208
238
 
209
239
  return {
@@ -212,81 +242,96 @@ class AssetHandler {
212
242
  };
213
243
  }
214
244
 
215
- async downloadAsset(assetDoc, dstPath) {
216
- let attemptNum = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0;
217
- const {
218
- url
219
- } = assetDoc;
220
- const options = this.getAssetRequestOptions(assetDoc);
221
- let stream;
222
-
223
- try {
224
- stream = await requestStream(options);
225
- } catch (err) {
226
- this.reject(err);
227
- return false;
228
- }
245
+ downloadAsset(assetDoc, dstPath) {
246
+ var _arguments = arguments,
247
+ _this2 = this;
248
+
249
+ return _asyncToGenerator(function* () {
250
+ var attemptNum = _arguments.length > 2 && _arguments[2] !== undefined ? _arguments[2] : 0;
251
+ var url = assetDoc.url;
252
+
253
+ var options = _this2.getAssetRequestOptions(assetDoc);
229
254
 
230
- if (stream.statusCode !== 200) {
231
- this.queue.clear();
232
- const err = await tryGetErrorFromStream(stream);
233
- let errMsg = "Referenced asset URL \"".concat(url, "\" returned HTTP ").concat(stream.statusCode);
255
+ var stream;
234
256
 
235
- if (err) {
236
- errMsg = "".concat(errMsg, ":\n\n").concat(err);
257
+ try {
258
+ stream = yield requestStream(options);
259
+ } catch (err) {
260
+ _this2.reject(err);
261
+
262
+ return false;
237
263
  }
238
264
 
239
- this.reject(new Error(errMsg));
240
- return false;
241
- }
265
+ if (stream.statusCode !== 200) {
266
+ _this2.queue.clear();
242
267
 
243
- this.maybeCreateAssetDirs();
244
- debug('Asset stream ready, writing to filesystem at %s', dstPath);
245
- const tmpPath = path.join(this.tmpDir, dstPath);
246
- const {
247
- sha1,
248
- md5,
249
- size
250
- } = await writeHashedStream(tmpPath, stream); // Verify it against our downloaded stream to make sure we have the same copy
251
-
252
- const contentLength = stream.headers['content-length'];
253
- const remoteSha1 = stream.headers['x-sanity-sha1'];
254
- const remoteMd5 = stream.headers['x-sanity-md5'];
255
- const hasHash = Boolean(remoteSha1 || remoteMd5);
256
- const method = md5 ? 'md5' : 'sha1';
257
- let differs = false;
258
-
259
- if (remoteMd5 && md5) {
260
- differs = remoteMd5 !== md5;
261
- } else if (remoteSha1 && sha1) {
262
- differs = remoteSha1 !== sha1;
263
- }
268
+ var err = yield tryGetErrorFromStream(stream);
269
+ var errMsg = "Referenced asset URL \"".concat(url, "\" returned HTTP ").concat(stream.statusCode);
264
270
 
265
- if (differs && attemptNum < 3) {
266
- debug('%s does not match downloaded asset, retrying (#%d) [%s]', method, attemptNum + 1, url);
267
- return this.downloadAsset(assetDoc, dstPath, attemptNum + 1);
268
- } else if (differs) {
269
- const details = [hasHash && (method === 'md5' ? "md5 should be ".concat(remoteMd5, ", got ").concat(md5) : "sha1 should be ".concat(remoteSha1, ", got ").concat(sha1)), contentLength && parseInt(contentLength, 10) !== size && "Asset should be ".concat(contentLength, " bytes, got ").concat(size), "Did not succeed after ".concat(attemptNum, " attempts.")];
270
- const detailsString = "Details:\n - ".concat(details.filter(Boolean).join('\n - '));
271
- await rimraf(tmpPath);
272
- this.queue.clear();
273
- const error = new Error("Failed to download asset at ".concat(assetDoc.url, ", giving up. ").concat(detailsString));
274
- this.reject(error);
275
- return false;
276
- }
271
+ if (err) {
272
+ errMsg = "".concat(errMsg, ":\n\n").concat(err);
273
+ }
277
274
 
278
- const isImage = assetDoc._type === 'sanity.imageAsset';
279
- const type = isImage ? 'image' : 'file';
280
- const id = "".concat(type, "-").concat(sha1);
281
- const metaProps = omit(assetDoc, EXCLUDE_PROPS);
275
+ _this2.reject(new Error(errMsg));
282
276
 
283
- if (Object.keys(metaProps).length > 0) {
284
- this.assetMap[id] = metaProps;
285
- }
277
+ return false;
278
+ }
279
+
280
+ _this2.maybeCreateAssetDirs();
281
+
282
+ debug('Asset stream ready, writing to filesystem at %s', dstPath);
283
+ var tmpPath = path.join(_this2.tmpDir, dstPath);
284
+
285
+ var _yield$writeHashedStr = yield writeHashedStream(tmpPath, stream),
286
+ sha1 = _yield$writeHashedStr.sha1,
287
+ md5 = _yield$writeHashedStr.md5,
288
+ size = _yield$writeHashedStr.size; // Verify it against our downloaded stream to make sure we have the same copy
286
289
 
287
- this.downloading.splice(this.downloading.findIndex(datUrl => datUrl === url), 1);
288
- this.filesWritten++;
289
- return true;
290
+
291
+ var contentLength = stream.headers['content-length'];
292
+ var remoteSha1 = stream.headers['x-sanity-sha1'];
293
+ var remoteMd5 = stream.headers['x-sanity-md5'];
294
+ var hasHash = Boolean(remoteSha1 || remoteMd5);
295
+ var method = md5 ? 'md5' : 'sha1';
296
+ var differs = false;
297
+
298
+ if (remoteMd5 && md5) {
299
+ differs = remoteMd5 !== md5;
300
+ } else if (remoteSha1 && sha1) {
301
+ differs = remoteSha1 !== sha1;
302
+ }
303
+
304
+ if (differs && attemptNum < 3) {
305
+ debug('%s does not match downloaded asset, retrying (#%d) [%s]', method, attemptNum + 1, url);
306
+ return _this2.downloadAsset(assetDoc, dstPath, attemptNum + 1);
307
+ } else if (differs) {
308
+ var details = [hasHash && (method === 'md5' ? "md5 should be ".concat(remoteMd5, ", got ").concat(md5) : "sha1 should be ".concat(remoteSha1, ", got ").concat(sha1)), contentLength && parseInt(contentLength, 10) !== size && "Asset should be ".concat(contentLength, " bytes, got ").concat(size), "Did not succeed after ".concat(attemptNum, " attempts.")];
309
+ var detailsString = "Details:\n - ".concat(details.filter(Boolean).join('\n - '));
310
+ yield fse.unlink(tmpPath);
311
+
312
+ _this2.queue.clear();
313
+
314
+ var error = new Error("Failed to download asset at ".concat(assetDoc.url, ", giving up. ").concat(detailsString));
315
+
316
+ _this2.reject(error);
317
+
318
+ return false;
319
+ }
320
+
321
+ var isImage = assetDoc._type === 'sanity.imageAsset';
322
+ var type = isImage ? 'image' : 'file';
323
+ var id = "".concat(type, "-").concat(sha1);
324
+ var metaProps = omit(assetDoc, EXCLUDE_PROPS);
325
+
326
+ if (Object.keys(metaProps).length > 0) {
327
+ _this2.assetMap[id] = metaProps;
328
+ }
329
+
330
+ _this2.downloading.splice(_this2.downloading.findIndex(datUrl => datUrl === url), 1);
331
+
332
+ _this2.filesWritten++;
333
+ return true;
334
+ })();
290
335
  }
291
336
 
292
337
  }
@@ -300,7 +345,10 @@ function getAssetType(item) {
300
345
  return null;
301
346
  }
302
347
 
303
- const [, type] = item.asset._ref.match(/^(image|file)-/) || [];
348
+ var _ref3 = item.asset._ref.match(/^(image|file)-/) || [],
349
+ _ref4 = _slicedToArray(_ref3, 2),
350
+ type = _ref4[1];
351
+
304
352
  return type || null;
305
353
  }
306
354
 
@@ -309,22 +357,26 @@ function isSanityAsset(assetId) {
309
357
  }
310
358
 
311
359
  function generateFilename(assetId) {
312
- const [,, asset, ext] = assetId.match(/^(image|file)-(.*?)(-[a-z]+)?$/) || [];
313
- const extension = (ext || 'bin').replace(/^-/, '');
360
+ var _ref5 = assetId.match(/^(image|file)-(.*?)(-[a-z]+)?$/) || [],
361
+ _ref6 = _slicedToArray(_ref5, 4),
362
+ asset = _ref6[2],
363
+ ext = _ref6[3];
364
+
365
+ var extension = (ext || 'bin').replace(/^-/, '');
314
366
  return asset ? "".concat(asset, ".").concat(extension) : "".concat(assetId, ".bin");
315
367
  }
316
368
 
317
369
  function writeHashedStream(filePath, stream) {
318
- let size = 0;
319
- const md5 = crypto.createHash('md5');
320
- const sha1 = crypto.createHash('sha1');
321
- const hasher = miss.through((chunk, enc, cb) => {
370
+ var size = 0;
371
+ var md5 = crypto.createHash('md5');
372
+ var sha1 = crypto.createHash('sha1');
373
+ var hasher = miss.through((chunk, enc, cb) => {
322
374
  size += chunk.length;
323
375
  md5.update(chunk);
324
376
  sha1.update(chunk);
325
377
  cb(null, chunk);
326
378
  });
327
- return new Promise((resolve, reject) => miss.pipe(stream, hasher, createWriteStream(filePath), err => {
379
+ return new Promise((resolve, reject) => miss.pipe(stream, hasher, fse.createWriteStream(filePath), err => {
328
380
  if (err) {
329
381
  reject(err);
330
382
  return;
@@ -344,7 +396,7 @@ function tryGetErrorFromStream(stream) {
344
396
 
345
397
  function parse(body) {
346
398
  try {
347
- const parsed = JSON.parse(body.toString('utf8'));
399
+ var parsed = JSON.parse(body.toString('utf8'));
348
400
  resolve(parsed.message || parsed.error || null);
349
401
  } catch (err) {
350
402
  resolve(body.toString('utf8').slice(0, 16000));