1 | "use strict";
|
2 | var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
|
3 | if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
|
4 | return cooked;
|
5 | };
|
6 | var __assign = (this && this.__assign) || function () {
|
7 | __assign = Object.assign || function(t) {
|
8 | for (var s, i = 1, n = arguments.length; i < n; i++) {
|
9 | s = arguments[i];
|
10 | for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
|
11 | t[p] = s[p];
|
12 | }
|
13 | return t;
|
14 | };
|
15 | return __assign.apply(this, arguments);
|
16 | };
|
17 | var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
18 | function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
19 | return new (P || (P = Promise))(function (resolve, reject) {
|
20 | function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
21 | function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
22 | function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
23 | step((generator = generator.apply(thisArg, _arguments || [])).next());
|
24 | });
|
25 | };
|
26 | var __generator = (this && this.__generator) || function (thisArg, body) {
|
27 | var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
|
28 | return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
29 | function verb(n) { return function (v) { return step([n, v]); }; }
|
30 | function step(op) {
|
31 | if (f) throw new TypeError("Generator is already executing.");
|
32 | while (_) try {
|
33 | 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;
|
34 | if (y = 0, t) op = [op[0] & 2, t.value];
|
35 | switch (op[0]) {
|
36 | case 0: case 1: t = op; break;
|
37 | case 4: _.label++; return { value: op[1], done: false };
|
38 | case 5: _.label++; y = op[1]; op = [0]; continue;
|
39 | case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
40 | default:
|
41 | if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
42 | if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
43 | if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
44 | if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
45 | if (t[2]) _.ops.pop();
|
46 | _.trys.pop(); continue;
|
47 | }
|
48 | op = body.call(thisArg, _);
|
49 | } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
50 | if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
51 | }
|
52 | };
|
53 | var __importDefault = (this && this.__importDefault) || function (mod) {
|
54 | return (mod && mod.__esModule) ? mod : { "default": mod };
|
55 | };
|
56 | Object.defineProperty(exports, "__esModule", { value: true });
|
57 | exports.setFieldsOnGraphQLNodeType = exports.onPreExtractQueries = exports.sourceNodes = exports.createSchemaCustomization = exports.createResolvers = exports.onPreBootstrap = void 0;
|
58 | var path = require("path");
|
59 | var oneline = require("oneline");
|
60 | var split2_1 = __importDefault(require("split2"));
|
61 | var through2_1 = __importDefault(require("through2"));
|
62 | var fs_extra_1 = require("fs-extra");
|
63 | var operators_1 = require("rxjs/operators");
|
64 | var client_1 = __importDefault(require("@sanity/client"));
|
65 | var pump_1 = require("./util/pump");
|
66 | var rejectOnApiError_1 = require("./util/rejectOnApiError");
|
67 | var normalize_1 = require("./util/normalize");
|
68 | var getDocumentStream_1 = require("./util/getDocumentStream");
|
69 | var cache_1 = require("./util/cache");
|
70 | var removeSystemDocuments_1 = require("./util/removeSystemDocuments");
|
71 | var handleDrafts_1 = require("./util/handleDrafts");
|
72 | var handleListenerEvent_1 = require("./util/handleListenerEvent");
|
73 | var handleWebhookEvent_1 = require("./util/handleWebhookEvent");
|
74 | var remoteGraphQLSchema_1 = require("./util/remoteGraphQLSchema");
|
75 | var debug_1 = __importDefault(require("./debug"));
|
76 | var extendImageNode_1 = require("./images/extendImageNode");
|
77 | var rewriteGraphQLSchema_1 = require("./util/rewriteGraphQLSchema");
|
78 | var getGraphQLResolverMap_1 = require("./util/getGraphQLResolverMap");
|
79 | var documentIds_1 = require("./util/documentIds");
|
80 | var defaultConfig = {
|
81 | version: '1',
|
82 | overlayDrafts: false,
|
83 | graphqlTag: 'default',
|
84 | };
|
85 | var stateCache = {};
|
86 | exports.onPreBootstrap = function (context, pluginConfig) { return __awaiter(void 0, void 0, void 0, function () {
|
87 | var config, reporter, actions, client, api, graphqlSdl, graphqlSdlKey, typeMap, typeMapKey, err_1;
|
88 | return __generator(this, function (_a) {
|
89 | switch (_a.label) {
|
90 | case 0:
|
91 | config = __assign(__assign({}, defaultConfig), pluginConfig);
|
92 | reporter = context.reporter, actions = context.actions;
|
93 | if (!actions.createTypes) {
|
94 | reporter.panic(oneline(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n You are using a version of Gatsby not supported by gatsby-source-sanity.\n Either upgrade gatsby to >= 2.2.0 or downgrade to gatsby-source-sanity@^1.0.0\n "], ["\n You are using a version of Gatsby not supported by gatsby-source-sanity.\n Either upgrade gatsby to >= 2.2.0 or downgrade to gatsby-source-sanity@^1.0.0\n "]))));
|
95 | return [2 ];
|
96 | }
|
97 | validateConfig(config, reporter);
|
98 | _a.label = 1;
|
99 | case 1:
|
100 | _a.trys.push([1, 4, , 5]);
|
101 | reporter.info('[sanity] Fetching remote GraphQL schema');
|
102 | client = getClient(config);
|
103 | return [4 , remoteGraphQLSchema_1.getRemoteGraphQLSchema(client, config)];
|
104 | case 2:
|
105 | api = _a.sent();
|
106 | reporter.info('[sanity] Transforming to Gatsby-compatible GraphQL SDL');
|
107 | return [4 , rewriteGraphQLSchema_1.rewriteGraphQLSchema(api, { config: config, reporter: reporter })];
|
108 | case 3:
|
109 | graphqlSdl = _a.sent();
|
110 | graphqlSdlKey = cache_1.getCacheKey(pluginConfig, cache_1.CACHE_KEYS.GRAPHQL_SDL);
|
111 | stateCache[graphqlSdlKey] = graphqlSdl;
|
112 | reporter.info('[sanity] Stitching GraphQL schemas from SDL');
|
113 | typeMap = remoteGraphQLSchema_1.getTypeMapFromGraphQLSchema(api);
|
114 | typeMapKey = cache_1.getCacheKey(pluginConfig, cache_1.CACHE_KEYS.TYPE_MAP);
|
115 | stateCache[typeMapKey] = typeMap;
|
116 | return [3 , 5];
|
117 | case 4:
|
118 | err_1 = _a.sent();
|
119 | if (err_1.isWarning) {
|
120 | err_1.message.split('\n').forEach(function (line) { return reporter.warn(line); });
|
121 | }
|
122 | else {
|
123 | reporter.panic(err_1.stack);
|
124 | }
|
125 | return [3 , 5];
|
126 | case 5: return [2 ];
|
127 | }
|
128 | });
|
129 | }); };
|
130 | exports.createResolvers = function (context, pluginConfig) {
|
131 | var typeMapKey = cache_1.getCacheKey(pluginConfig, cache_1.CACHE_KEYS.TYPE_MAP);
|
132 | var typeMap = (stateCache[typeMapKey] || remoteGraphQLSchema_1.defaultTypeMap);
|
133 | context.createResolvers(getGraphQLResolverMap_1.getGraphQLResolverMap(typeMap, pluginConfig, context));
|
134 | };
|
135 | exports.createSchemaCustomization = function (_a, pluginConfig) {
|
136 | var actions = _a.actions;
|
137 | var createTypes = actions.createTypes;
|
138 | var graphqlSdlKey = cache_1.getCacheKey(pluginConfig, cache_1.CACHE_KEYS.GRAPHQL_SDL);
|
139 | var graphqlSdl = stateCache[graphqlSdlKey];
|
140 | createTypes(graphqlSdl);
|
141 | };
|
142 | exports.sourceNodes = function (context, pluginConfig) { return __awaiter(void 0, void 0, void 0, function () {
|
143 | var config, dataset, overlayDrafts, watchMode, actions, getNode, createNodeId, createContentDigest, reporter, webhookBody, createNode, createParentChildLink, typeMapKey, typeMap, client, url, processingOptions, _a, numDocuments, inputStream, draftDocs, publishedNodes;
|
144 | return __generator(this, function (_b) {
|
145 | switch (_b.label) {
|
146 | case 0:
|
147 | config = __assign(__assign({}, defaultConfig), pluginConfig);
|
148 | dataset = config.dataset, overlayDrafts = config.overlayDrafts, watchMode = config.watchMode;
|
149 | actions = context.actions, getNode = context.getNode, createNodeId = context.createNodeId, createContentDigest = context.createContentDigest, reporter = context.reporter, webhookBody = context.webhookBody;
|
150 | createNode = actions.createNode, createParentChildLink = actions.createParentChildLink;
|
151 | typeMapKey = cache_1.getCacheKey(pluginConfig, cache_1.CACHE_KEYS.TYPE_MAP);
|
152 | typeMap = (stateCache[typeMapKey] || remoteGraphQLSchema_1.defaultTypeMap);
|
153 | client = getClient(config);
|
154 | url = client.getUrl("/data/export/" + dataset);
|
155 | processingOptions = {
|
156 | typeMap: typeMap,
|
157 | createNodeId: createNodeId,
|
158 | createNode: createNode,
|
159 | createContentDigest: createContentDigest,
|
160 | createParentChildLink: createParentChildLink,
|
161 | overlayDrafts: overlayDrafts,
|
162 | };
|
163 | _a = webhookBody &&
|
164 | webhookBody.ids;
|
165 | if (!_a) return [3 , 2];
|
166 | return [4 , handleWebhookEvent_1.handleWebhookEvent(context, { client: client, processingOptions: processingOptions })];
|
167 | case 1:
|
168 | _a = (_b.sent());
|
169 | _b.label = 2;
|
170 | case 2:
|
171 | if (_a) {
|
172 |
|
173 |
|
174 |
|
175 | return [2 ];
|
176 | }
|
177 | reporter.info('[sanity] Fetching export stream for dataset');
|
178 | numDocuments = 0;
|
179 | return [4 , getDocumentStream_1.getDocumentStream(url, config.token)];
|
180 | case 3:
|
181 | inputStream = _b.sent();
|
182 | draftDocs = [];
|
183 | publishedNodes = new Map();
|
184 | return [4 , pump_1.pump([
|
185 | inputStream,
|
186 | split2_1.default(JSON.parse),
|
187 | rejectOnApiError_1.rejectOnApiError(),
|
188 | overlayDrafts ? handleDrafts_1.extractDrafts(draftDocs) : handleDrafts_1.removeDrafts(),
|
189 | removeSystemDocuments_1.removeSystemDocuments(),
|
190 | through2_1.default.obj(function (doc, enc, cb) {
|
191 | numDocuments++;
|
192 | var type = normalize_1.getTypeName(doc._type);
|
193 | if (!typeMap.objects[type]) {
|
194 | reporter.warn("[sanity] Document \"" + doc._id + "\" has type " + doc._type + " (" + type + "), which is not declared in the GraphQL schema. Make sure you run \"graphql deploy\". Skipping document.");
|
195 | cb();
|
196 | return;
|
197 | }
|
198 | var node = normalize_1.processDocument(doc, processingOptions);
|
199 | debug_1.default('Got document with ID %s (mapped to %s)', doc._id, node.id);
|
200 | cb();
|
201 | }),
|
202 | ])];
|
203 | case 4:
|
204 | _b.sent();
|
205 | if (draftDocs.length > 0) {
|
206 | reporter.info("[sanity] Overlaying " + draftDocs.length + " drafts");
|
207 | draftDocs.forEach(function (draft) {
|
208 | normalize_1.processDocument(draft, processingOptions);
|
209 | var published = getNode(draft.id);
|
210 | if (published) {
|
211 | publishedNodes.set(documentIds_1.unprefixId(draft._id), published);
|
212 | }
|
213 | });
|
214 | }
|
215 | if (watchMode) {
|
216 | reporter.info('[sanity] Watch mode enabled, starting a listener');
|
217 | client
|
218 | .listen('*[!(_id in path("_.**"))]')
|
219 | .pipe(operators_1.filter(function (event) { return overlayDrafts || !event.documentId.startsWith('drafts.'); }))
|
220 | .subscribe(function (event) { return handleListenerEvent_1.handleListenerEvent(event, publishedNodes, context, processingOptions); });
|
221 | }
|
222 | reporter.info("[sanity] Done! Exported " + numDocuments + " documents.");
|
223 | return [2 ];
|
224 | }
|
225 | });
|
226 | }); };
|
227 | exports.onPreExtractQueries = function (context, pluginConfig) { return __awaiter(void 0, void 0, void 0, function () {
|
228 | var getNodes, store, typeMapKey, typeMap, shouldAddFragments, program;
|
229 | return __generator(this, function (_a) {
|
230 | switch (_a.label) {
|
231 | case 0:
|
232 | getNodes = context.getNodes, store = context.store;
|
233 | typeMapKey = cache_1.getCacheKey(pluginConfig, cache_1.CACHE_KEYS.TYPE_MAP);
|
234 | typeMap = (stateCache[typeMapKey] || remoteGraphQLSchema_1.defaultTypeMap);
|
235 | shouldAddFragments = typeof typeMap.objects.SanityImageAsset !== 'undefined';
|
236 | if (!shouldAddFragments) {
|
237 | shouldAddFragments = getNodes().some(function (node) {
|
238 | return Boolean(node.internal && node.internal.type === 'SanityImageAsset');
|
239 | });
|
240 | }
|
241 | if (!shouldAddFragments) return [3 , 2];
|
242 | program = store.getState().program;
|
243 | return [4 , fs_extra_1.copy(path.join(__dirname, '..', 'fragments', 'imageFragments.js'), program.directory + "/.cache/fragments/sanity-image-fragments.js")];
|
244 | case 1:
|
245 | _a.sent();
|
246 | _a.label = 2;
|
247 | case 2: return [2 ];
|
248 | }
|
249 | });
|
250 | }); };
|
251 | exports.setFieldsOnGraphQLNodeType = function (context, pluginConfig) { return __awaiter(void 0, void 0, void 0, function () {
|
252 | var type, fields;
|
253 | return __generator(this, function (_a) {
|
254 | type = context.type;
|
255 | fields = {};
|
256 | if (type.name === 'SanityImageAsset') {
|
257 | fields = __assign(__assign({}, fields), extendImageNode_1.extendImageNode(context, pluginConfig));
|
258 | }
|
259 | return [2 , fields];
|
260 | });
|
261 | }); };
|
262 | function validateConfig(config, reporter) {
|
263 | if (!config.projectId) {
|
264 | throw new Error('[sanity] `projectId` must be specified');
|
265 | }
|
266 | if (!config.dataset) {
|
267 | throw new Error('[sanity] `dataset` must be specified');
|
268 | }
|
269 | if (config.overlayDrafts && !config.token) {
|
270 | reporter.warn('[sanity] `overlayDrafts` is set to `true`, but no token is given');
|
271 | }
|
272 | var inDevelopMode = process.env.gatsby_executing_command === 'develop';
|
273 | if (config.watchMode && !inDevelopMode) {
|
274 | reporter.warn('[sanity] Using `watchMode` when not in develop mode might prevent your build from completing');
|
275 | }
|
276 | }
|
277 | function getClient(config) {
|
278 | var projectId = config.projectId, dataset = config.dataset, token = config.token;
|
279 | return new client_1.default({
|
280 | projectId: projectId,
|
281 | dataset: dataset,
|
282 | token: token,
|
283 | useCdn: false,
|
284 | });
|
285 | }
|
286 | var templateObject_1;
|
287 |
|
\ | No newline at end of file |