@sanity/migrate
Version:
Tooling for running data migrations on Sanity.io projects
734 lines (733 loc) • 27.7 kB
JavaScript
function _array_like_to_array(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;
}
function _array_with_holes(arr) {
if (Array.isArray(arr)) return arr;
}
function _array_without_holes(arr) {
if (Array.isArray(arr)) return _array_like_to_array(arr);
}
function _async_generator(gen) {
var front, back;
function send(key, arg) {
return new Promise(function(resolve, reject) {
var request = {
key: key,
arg: arg,
resolve: resolve,
reject: reject,
next: null
};
if (back) back = back.next = request;
else {
front = back = request;
resume(key, arg);
}
});
}
function resume(key, arg) {
try {
var result = gen[key](arg);
var value = result.value;
var overloaded = value instanceof _overload_yield;
Promise.resolve(overloaded ? value.v : value).then(function(arg) {
if (overloaded) {
var nextKey = key === "return" ? "return" : "next";
if (!value.k || arg.done) return resume(nextKey, arg);
else arg = gen[nextKey](arg).value;
}
settle(result.done ? "return" : "normal", arg);
}, function(err) {
resume("throw", err);
});
} catch (err) {
settle("throw", err);
}
}
function settle(type, value) {
switch(type){
case "return":
front.resolve({
value: value,
done: true
});
break;
case "throw":
front.reject(value);
break;
default:
front.resolve({
value: value,
done: false
});
break;
}
front = front.next;
if (front) resume(front.key, front.arg);
else back = null;
}
this._invoke = send;
if (typeof gen.return !== "function") this.return = undefined;
}
_async_generator.prototype[typeof Symbol === "function" && Symbol.asyncIterator || "@@asyncIterator"] = function() {
return this;
};
_async_generator.prototype.next = function(arg) {
return this._invoke("next", arg);
};
_async_generator.prototype.throw = function(arg) {
return this._invoke("throw", arg);
};
_async_generator.prototype.return = function(arg) {
return this._invoke("return", arg);
};
function _async_iterator(iterable) {
var method, async, sync, retry = 2;
for("undefined" != typeof Symbol && (async = Symbol.asyncIterator, sync = Symbol.iterator); retry--;){
if (async && null != (method = iterable[async])) return method.call(iterable);
if (sync && null != (method = iterable[sync])) return new AsyncFromSyncIterator(method.call(iterable));
async = "@@asyncIterator", sync = "@@iterator";
}
throw new TypeError("Object is not async iterable");
}
function AsyncFromSyncIterator(s) {
function AsyncFromSyncIteratorContinuation(r) {
if (Object(r) !== r) return Promise.reject(new TypeError(r + " is not an object."));
var done = r.done;
return Promise.resolve(r.value).then(function(value) {
return {
value: value,
done: done
};
});
}
return AsyncFromSyncIterator = function(s) {
this.s = s, this.n = s.next;
}, AsyncFromSyncIterator.prototype = {
s: null,
n: null,
next: function() {
return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));
},
return: function(value) {
var ret = this.s.return;
return void 0 === ret ? Promise.resolve({
value: value,
done: !0
}) : AsyncFromSyncIteratorContinuation(ret.apply(this.s, arguments));
},
throw: function(value) {
var thr = this.s.return;
return void 0 === thr ? Promise.reject(value) : AsyncFromSyncIteratorContinuation(thr.apply(this.s, arguments));
}
}, new AsyncFromSyncIterator(s);
}
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);
}
}
function _async_to_generator(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);
});
};
}
function _await_async_generator(value) {
return new _overload_yield(value, 0);
}
function _define_property(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;
}
function _iterable_to_array(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _iterable_to_array_limit(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;
}
function _non_iterable_rest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _non_iterable_spread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _object_spread(target) {
for(var i = 1; i < arguments.length; i++){
var source = arguments[i] != null ? arguments[i] : {};
var ownKeys = Object.keys(source);
if (typeof Object.getOwnPropertySymbols === "function") {
ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
return Object.getOwnPropertyDescriptor(source, sym).enumerable;
}));
}
ownKeys.forEach(function(key) {
_define_property(target, key, source[key]);
});
}
return target;
}
function _overload_yield(value, kind) {
this.v = value;
this.k = kind;
}
function _sliced_to_array(arr, i) {
return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
}
function _to_consumable_array(arr) {
return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
}
function _unsupported_iterable_to_array(o, minLen) {
if (!o) return;
if (typeof o === "string") return _array_like_to_array(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(n);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
}
function _wrap_async_generator(fn) {
return function() {
return new _async_generator(fn.apply(this, arguments));
};
}
function _ts_generator(thisArg, body) {
var f, y, t, _ = {
label: 0,
sent: function() {
if (t[0] & 1) throw t[1];
return t[1];
},
trys: [],
ops: []
}, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
return d(g, "next", {
value: verb(0)
}), d(g, "throw", {
value: verb(1)
}), d(g, "return", {
value: verb(2)
}), typeof Symbol === "function" && d(g, Symbol.iterator, {
value: function() {
return this;
}
}), g;
function verb(n) {
return function(v) {
return step([
n,
v
]);
};
}
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while(g && (g = 0, op[0] && (_ = 0)), _)try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [
op[0] & 2,
t.value
];
switch(op[0]){
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return {
value: op[1],
done: false
};
case 5:
_.label++;
y = op[1];
op = [
0
];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2]) _.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
} catch (e) {
op = [
6,
e
];
y = 0;
} finally{
f = t = 0;
}
if (op[0] & 5) throw op[1];
return {
value: op[0] ? op[1] : void 0,
done: true
};
}
}
import { SanityEncoder } from '@sanity/mutate';
import arrify from 'arrify';
import { isMutation, isNodePatch, isOperation, isTransaction } from '../mutations/asserters.js';
import { at, patch } from '../mutations/index.js';
import { flatMapDeep } from './utils/flatMapDeep.js';
import { getValueType } from './utils/getValueType.js';
export function normalizeMigrateDefinition(migration) {
if (typeof migration.migrate == 'function') {
// assume AsyncIterableMigration
return normalizeIteratorValues(migration.migrate);
}
return createAsyncIterableMutation(migration.migrate, _object_spread({}, migration.filter !== undefined && {
filter: migration.filter
}, migration.documentTypes !== undefined && {
documentTypes: migration.documentTypes
}));
}
function normalizeIteratorValues(asyncIterable) {
return function run(docs, context) {
return _wrap_async_generator(function() {
var _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, _value, documentMutations, err;
return _ts_generator(this, function(_state) {
switch(_state.label){
case 0:
_iteratorAbruptCompletion = false, _didIteratorError = false;
_state.label = 1;
case 1:
_state.trys.push([
1,
7,
8,
13
]);
_iterator = _async_iterator(asyncIterable(docs, context));
_state.label = 2;
case 2:
return [
4,
_await_async_generator(_iterator.next())
];
case 3:
if (!(_iteratorAbruptCompletion = !(_step = _state.sent()).done)) return [
3,
6
];
_value = _step.value;
documentMutations = _value;
return [
4,
normalizeMutation(documentMutations)
];
case 4:
_state.sent();
_state.label = 5;
case 5:
_iteratorAbruptCompletion = false;
return [
3,
2
];
case 6:
return [
3,
13
];
case 7:
err = _state.sent();
_didIteratorError = true;
_iteratorError = err;
return [
3,
13
];
case 8:
_state.trys.push([
8,
,
11,
12
]);
if (!(_iteratorAbruptCompletion && _iterator.return != null)) return [
3,
10
];
return [
4,
_await_async_generator(_iterator.return())
];
case 9:
_state.sent();
_state.label = 10;
case 10:
return [
3,
12
];
case 11:
if (_didIteratorError) {
throw _iteratorError;
}
return [
7
];
case 12:
return [
7
];
case 13:
return [
2
];
}
});
})();
};
}
/**
* Normalize a mutation or a NodePatch to a document mutation
* @param documentId - The document id
* @param change - The Mutation or NodePatch
*/ function normalizeMutation(change) {
if (Array.isArray(change)) {
return change.flatMap(function(ch) {
return normalizeMutation(ch);
});
}
if (isRawMutation(change)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- SanityEncoder.decodeAll requires specific mutation format
return SanityEncoder.decodeAll([
change
]);
}
return [
change
];
}
function isRawMutation(mutation) {
return 'createIfNotExists' in mutation || 'createOrReplace' in mutation || 'create' in mutation || 'patch' in mutation || 'delete' in mutation;
}
export function createAsyncIterableMutation(migration, opts) {
var documentTypesSet = new Set(opts.documentTypes);
return function run(docs, context) {
return _wrap_async_generator(function() {
var _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, _value, doc, documentMutations, err;
return _ts_generator(this, function(_state) {
switch(_state.label){
case 0:
_iteratorAbruptCompletion = false, _didIteratorError = false;
_state.label = 1;
case 1:
_state.trys.push([
1,
8,
9,
14
]);
_iterator = _async_iterator(docs());
_state.label = 2;
case 2:
return [
4,
_await_async_generator(_iterator.next())
];
case 3:
if (!(_iteratorAbruptCompletion = !(_step = _state.sent()).done)) return [
3,
7
];
_value = _step.value;
doc = _value;
if (opts.documentTypes && !documentTypesSet.has(doc._type)) return [
3,
6
];
return [
4,
_await_async_generator(collectDocumentMutations(migration, doc, context))
];
case 4:
documentMutations = _state.sent();
if (!(documentMutations.length > 0)) return [
3,
6
];
return [
4,
documentMutations
];
case 5:
_state.sent();
_state.label = 6;
case 6:
_iteratorAbruptCompletion = false;
return [
3,
2
];
case 7:
return [
3,
14
];
case 8:
err = _state.sent();
_didIteratorError = true;
_iteratorError = err;
return [
3,
14
];
case 9:
_state.trys.push([
9,
,
12,
13
]);
if (!(_iteratorAbruptCompletion && _iterator.return != null)) return [
3,
11
];
return [
4,
_await_async_generator(_iterator.return())
];
case 10:
_state.sent();
_state.label = 11;
case 11:
return [
3,
13
];
case 12:
if (_didIteratorError) {
throw _iteratorError;
}
return [
7
];
case 13:
return [
7
];
case 14:
return [
2
];
}
});
})();
};
}
function collectDocumentMutations(migration, doc, context) {
return _async_to_generator(function() {
var _migration_document, documentMutations, nodeMigrations, resolvedDocumentMutations, resolvedNodeMigrations;
return _ts_generator(this, function(_state) {
switch(_state.label){
case 0:
documentMutations = Promise.resolve((_migration_document = migration.document) === null || _migration_document === void 0 ? void 0 : _migration_document.call(migration, doc, context));
nodeMigrations = flatMapDeep(doc, function(value, path) {
return _async_to_generator(function() {
var _migration_node, _ref, nodeReturnValues, nodeTypeReturnValues;
return _ts_generator(this, function(_state) {
switch(_state.label){
case 0:
return [
4,
Promise.all([
Promise.resolve((_migration_node = migration.node) === null || _migration_node === void 0 ? void 0 : _migration_node.call(migration, value, path, context)),
Promise.resolve(migrateNodeType(migration, value, path, context))
])
];
case 1:
_ref = _sliced_to_array.apply(void 0, [
_state.sent(),
2
]), nodeReturnValues = _ref[0], nodeTypeReturnValues = _ref[1];
return [
2,
_to_consumable_array(arrify(nodeReturnValues)).concat(_to_consumable_array(arrify(nodeTypeReturnValues))).map(function(change) {
return change && normalizeNodeMutation(path, change);
})
];
}
});
})();
});
return [
4,
documentMutations
];
case 1:
resolvedDocumentMutations = arrify.apply(void 0, [
_state.sent()
]);
return [
4,
Promise.all(nodeMigrations)
];
case 2:
resolvedNodeMigrations = _state.sent();
return [
2,
_to_consumable_array(resolvedDocumentMutations).concat(_to_consumable_array(resolvedNodeMigrations)).flat().flatMap(function(change) {
return change ? normalizeDocumentMutation(doc._id, change) : [];
})
];
}
});
})();
}
/**
* Normalize a mutation or a NodePatch to a document mutation
* @param documentId - The document id
* @param change - The Mutation or NodePatch
*/ function normalizeDocumentMutation(documentId, change) {
if (Array.isArray(change)) {
return change.flatMap(function(ch) {
return normalizeDocumentMutation(documentId, ch);
});
}
if (isRawMutation(change)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- SanityEncoder.decodeAll requires specific mutation format
return SanityEncoder.decodeAll([
change
])[0];
}
if (isTransaction(change)) {
return change;
}
return isMutation(change) ? change : patch(documentId, change);
}
/**
* Normalize a mutation or a NodePatch to a document mutation
* @param path - The path the operation should be applied at
* @param change - The Mutation or NodePatch
*/ function normalizeNodeMutation(path, change) {
if (Array.isArray(change)) {
return change.flatMap(function(ch) {
return normalizeNodeMutation(path, ch);
});
}
if (isRawMutation(change)) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- SanityEncoder.decodeAll requires specific mutation format
return SanityEncoder.decodeAll([
change
])[0];
}
if (isNodePatch(change)) {
return at(_to_consumable_array(path).concat(_to_consumable_array(change.path)), change.op);
}
return isOperation(change) ? at(path, change) : change;
}
function migrateNodeType(migration, value, path, context) {
switch(getValueType(value)){
case 'array':
{
var _migration_array;
return (_migration_array = migration.array) === null || _migration_array === void 0 ? void 0 : _migration_array.call(migration, value, path, context);
}
case 'boolean':
{
var _migration_boolean;
return (_migration_boolean = migration.boolean) === null || _migration_boolean === void 0 ? void 0 : _migration_boolean.call(migration, value, path, context);
}
case 'null':
{
var _migration_null;
return (_migration_null = migration.null) === null || _migration_null === void 0 ? void 0 : _migration_null.call(migration, value, path, context);
}
case 'number':
{
var _migration_number;
return (_migration_number = migration.number) === null || _migration_number === void 0 ? void 0 : _migration_number.call(migration, value, path, context);
}
case 'object':
{
var _migration_object;
return (_migration_object = migration.object) === null || _migration_object === void 0 ? void 0 : _migration_object.call(migration, value, path, context);
}
case 'string':
{
var _migration_string;
return (_migration_string = migration.string) === null || _migration_string === void 0 ? void 0 : _migration_string.call(migration, value, path, context);
}
default:
{
throw new Error('Unknown value type');
}
}
}