1 | "use strict";
|
2 | var __importDefault = (this && this.__importDefault) || function (mod) {
|
3 | return (mod && mod.__esModule) ? mod : { "default": mod };
|
4 | };
|
5 | Object.defineProperty(exports, "__esModule", { value: true });
|
6 | exports.setFieldsOnGraphQLNodeType = exports.onPreExtractQueries = exports.sourceNodes = exports.createSchemaCustomization = exports.createResolvers = exports.onPreBootstrap = void 0;
|
7 | const path = require("path");
|
8 | const oneline = require("oneline");
|
9 | const split2_1 = __importDefault(require("split2"));
|
10 | const through2_1 = __importDefault(require("through2"));
|
11 | const fs_extra_1 = require("fs-extra");
|
12 | const operators_1 = require("rxjs/operators");
|
13 | const client_1 = __importDefault(require("@sanity/client"));
|
14 | const pump_1 = require("./util/pump");
|
15 | const rejectOnApiError_1 = require("./util/rejectOnApiError");
|
16 | const normalize_1 = require("./util/normalize");
|
17 | const getDocumentStream_1 = require("./util/getDocumentStream");
|
18 | const cache_1 = require("./util/cache");
|
19 | const removeSystemDocuments_1 = require("./util/removeSystemDocuments");
|
20 | const handleDrafts_1 = require("./util/handleDrafts");
|
21 | const handleListenerEvent_1 = require("./util/handleListenerEvent");
|
22 | const handleWebhookEvent_1 = require("./util/handleWebhookEvent");
|
23 | const remoteGraphQLSchema_1 = require("./util/remoteGraphQLSchema");
|
24 | const debug_1 = __importDefault(require("./debug"));
|
25 | const extendImageNode_1 = require("./images/extendImageNode");
|
26 | const rewriteGraphQLSchema_1 = require("./util/rewriteGraphQLSchema");
|
27 | const getGraphQLResolverMap_1 = require("./util/getGraphQLResolverMap");
|
28 | const documentIds_1 = require("./util/documentIds");
|
29 | const defaultConfig = {
|
30 | version: '1',
|
31 | overlayDrafts: false,
|
32 | graphqlTag: 'default',
|
33 | };
|
34 | const stateCache = {};
|
35 | exports.onPreBootstrap = async (context, pluginConfig) => {
|
36 | const config = Object.assign(Object.assign({}, defaultConfig), pluginConfig);
|
37 | const { reporter, actions } = context;
|
38 | if (!actions.createTypes) {
|
39 | reporter.panic(oneline `
|
40 | You are using a version of Gatsby not supported by gatsby-source-sanity.
|
41 | Either upgrade gatsby to >= 2.2.0 or downgrade to gatsby-source-sanity@^1.0.0
|
42 | `);
|
43 | return;
|
44 | }
|
45 | validateConfig(config, reporter);
|
46 | try {
|
47 | reporter.info('[sanity] Fetching remote GraphQL schema');
|
48 | const client = getClient(config);
|
49 | const api = await remoteGraphQLSchema_1.getRemoteGraphQLSchema(client, config);
|
50 | reporter.info('[sanity] Transforming to Gatsby-compatible GraphQL SDL');
|
51 | const graphqlSdl = await rewriteGraphQLSchema_1.rewriteGraphQLSchema(api, { config, reporter });
|
52 | const graphqlSdlKey = cache_1.getCacheKey(pluginConfig, cache_1.CACHE_KEYS.GRAPHQL_SDL);
|
53 | stateCache[graphqlSdlKey] = graphqlSdl;
|
54 | reporter.info('[sanity] Stitching GraphQL schemas from SDL');
|
55 | const typeMap = remoteGraphQLSchema_1.getTypeMapFromGraphQLSchema(api);
|
56 | const typeMapKey = cache_1.getCacheKey(pluginConfig, cache_1.CACHE_KEYS.TYPE_MAP);
|
57 | stateCache[typeMapKey] = typeMap;
|
58 | }
|
59 | catch (err) {
|
60 | if (err.isWarning) {
|
61 | err.message.split('\n').forEach((line) => reporter.warn(line));
|
62 | }
|
63 | else {
|
64 | reporter.panic(err.stack);
|
65 | }
|
66 | }
|
67 | };
|
68 | exports.createResolvers = (context, pluginConfig) => {
|
69 | const typeMapKey = cache_1.getCacheKey(pluginConfig, cache_1.CACHE_KEYS.TYPE_MAP);
|
70 | const typeMap = (stateCache[typeMapKey] || remoteGraphQLSchema_1.defaultTypeMap);
|
71 | context.createResolvers(getGraphQLResolverMap_1.getGraphQLResolverMap(typeMap, pluginConfig, context));
|
72 | };
|
73 | exports.createSchemaCustomization = ({ actions }, pluginConfig) => {
|
74 | const { createTypes } = actions;
|
75 | const graphqlSdlKey = cache_1.getCacheKey(pluginConfig, cache_1.CACHE_KEYS.GRAPHQL_SDL);
|
76 | const graphqlSdl = stateCache[graphqlSdlKey];
|
77 | createTypes(graphqlSdl);
|
78 | };
|
79 | exports.sourceNodes = async (context, pluginConfig) => {
|
80 | const config = Object.assign(Object.assign({}, defaultConfig), pluginConfig);
|
81 | const { dataset, overlayDrafts, watchMode } = config;
|
82 | const { actions, getNode, createNodeId, createContentDigest, reporter, webhookBody } = context;
|
83 | const { createNode, createParentChildLink } = actions;
|
84 | const typeMapKey = cache_1.getCacheKey(pluginConfig, cache_1.CACHE_KEYS.TYPE_MAP);
|
85 | const typeMap = (stateCache[typeMapKey] || remoteGraphQLSchema_1.defaultTypeMap);
|
86 | const client = getClient(config);
|
87 | const url = client.getUrl(`/data/export/${dataset}`);
|
88 | const processingOptions = {
|
89 | typeMap,
|
90 | createNodeId,
|
91 | createNode,
|
92 | createContentDigest,
|
93 | createParentChildLink,
|
94 | overlayDrafts,
|
95 | };
|
96 | if (webhookBody &&
|
97 | webhookBody.ids &&
|
98 | (await handleWebhookEvent_1.handleWebhookEvent(context, { client, processingOptions }))) {
|
99 |
|
100 |
|
101 |
|
102 | return;
|
103 | }
|
104 | reporter.info('[sanity] Fetching export stream for dataset');
|
105 | let numDocuments = 0;
|
106 | const inputStream = await getDocumentStream_1.getDocumentStream(url, config.token);
|
107 | const draftDocs = [];
|
108 | const publishedNodes = new Map();
|
109 | await pump_1.pump([
|
110 | inputStream,
|
111 | split2_1.default(JSON.parse),
|
112 | rejectOnApiError_1.rejectOnApiError(),
|
113 | overlayDrafts ? handleDrafts_1.extractDrafts(draftDocs) : handleDrafts_1.removeDrafts(),
|
114 | removeSystemDocuments_1.removeSystemDocuments(),
|
115 | through2_1.default.obj((doc, enc, cb) => {
|
116 | numDocuments++;
|
117 | const type = normalize_1.getTypeName(doc._type);
|
118 | if (!typeMap.objects[type]) {
|
119 | 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.`);
|
120 | cb();
|
121 | return;
|
122 | }
|
123 | const node = normalize_1.processDocument(doc, processingOptions);
|
124 | debug_1.default('Got document with ID %s (mapped to %s)', doc._id, node.id);
|
125 | cb();
|
126 | }),
|
127 | ]);
|
128 | if (draftDocs.length > 0) {
|
129 | reporter.info(`[sanity] Overlaying ${draftDocs.length} drafts`);
|
130 | draftDocs.forEach((draft) => {
|
131 | normalize_1.processDocument(draft, processingOptions);
|
132 | const published = getNode(draft.id);
|
133 | if (published) {
|
134 | publishedNodes.set(documentIds_1.unprefixId(draft._id), published);
|
135 | }
|
136 | });
|
137 | }
|
138 | if (watchMode) {
|
139 | reporter.info('[sanity] Watch mode enabled, starting a listener');
|
140 | client
|
141 | .listen('*[!(_id in path("_.**"))]')
|
142 | .pipe(operators_1.filter((event) => overlayDrafts || !event.documentId.startsWith('drafts.')))
|
143 | .subscribe((event) => handleListenerEvent_1.handleListenerEvent(event, publishedNodes, context, processingOptions));
|
144 | }
|
145 | reporter.info(`[sanity] Done! Exported ${numDocuments} documents.`);
|
146 | };
|
147 | exports.onPreExtractQueries = async (context, pluginConfig) => {
|
148 | const { getNodes, store } = context;
|
149 | const typeMapKey = cache_1.getCacheKey(pluginConfig, cache_1.CACHE_KEYS.TYPE_MAP);
|
150 | const typeMap = (stateCache[typeMapKey] || remoteGraphQLSchema_1.defaultTypeMap);
|
151 | let shouldAddFragments = typeof typeMap.objects.SanityImageAsset !== 'undefined';
|
152 | if (!shouldAddFragments) {
|
153 | shouldAddFragments = getNodes().some((node) => Boolean(node.internal && node.internal.type === 'SanityImageAsset'));
|
154 | }
|
155 | if (shouldAddFragments) {
|
156 | const program = store.getState().program;
|
157 | await fs_extra_1.copy(path.join(__dirname, '..', 'fragments', 'imageFragments.js'), `${program.directory}/.cache/fragments/sanity-image-fragments.js`);
|
158 | }
|
159 | };
|
160 | exports.setFieldsOnGraphQLNodeType = async (context, pluginConfig) => {
|
161 | const { type } = context;
|
162 | let fields = {};
|
163 | if (type.name === 'SanityImageAsset') {
|
164 | fields = Object.assign(Object.assign({}, fields), extendImageNode_1.extendImageNode(context, pluginConfig));
|
165 | }
|
166 | return fields;
|
167 | };
|
168 | function validateConfig(config, reporter) {
|
169 | if (!config.projectId) {
|
170 | throw new Error('[sanity] `projectId` must be specified');
|
171 | }
|
172 | if (!config.dataset) {
|
173 | throw new Error('[sanity] `dataset` must be specified');
|
174 | }
|
175 | if (config.overlayDrafts && !config.token) {
|
176 | reporter.warn('[sanity] `overlayDrafts` is set to `true`, but no token is given');
|
177 | }
|
178 | const inDevelopMode = process.env.gatsby_executing_command === 'develop';
|
179 | if (config.watchMode && !inDevelopMode) {
|
180 | reporter.warn('[sanity] Using `watchMode` when not in develop mode might prevent your build from completing');
|
181 | }
|
182 | }
|
183 | function getClient(config) {
|
184 | const { projectId, dataset, token } = config;
|
185 | return new client_1.default({
|
186 | projectId,
|
187 | dataset,
|
188 | token,
|
189 | useCdn: false,
|
190 | });
|
191 | }
|
192 |
|
\ | No newline at end of file |