|
| 1 | +const fs = require('fs') |
| 2 | +const path = require('path') |
| 3 | +const yaml = require('js-yaml') |
| 4 | + |
| 5 | +function getCMSConfigPath(config) { |
| 6 | + try { |
| 7 | + const cmsEntry = config.plugins.find( |
| 8 | + ({use}) => use === 'gridsome-plugin-netlify-cms', |
| 9 | + ) |
| 10 | + const configPath = cmsEntry.options.configPath |
| 11 | + if (configPath !== undefined) return configPath |
| 12 | + } catch (e) {} |
| 13 | + |
| 14 | + throw new Error( |
| 15 | + 'gridsome-plugin-netlify-cms must be configured before gridsome-plugin-netlify-cms-paths', |
| 16 | + ) |
| 17 | +} |
| 18 | + |
| 19 | +class NetlifyPaths { |
| 20 | + // defaultOptions merged with this.options in App.vue |
| 21 | + static defaultOptions() { |
| 22 | + return { |
| 23 | + contentTypes: [], |
| 24 | + coverField: 'cover_image', |
| 25 | + mimeType: 'text/markdown', |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + constructor(api, options = {}) { |
| 30 | + this.options = options |
| 31 | + |
| 32 | + const {_app, config, context, store} = api |
| 33 | + |
| 34 | + const cmsConfig = yaml.safeLoad( |
| 35 | + fs.readFileSync(getCMSConfigPath(config), 'utf8'), |
| 36 | + ) |
| 37 | + |
| 38 | + this.mediaFolder = path.join(context, cmsConfig.media_folder) |
| 39 | + this.publicFolder = cmsConfig.public_folder |
| 40 | + |
| 41 | + let remark = store._transformers[options.mimeType] |
| 42 | + const _resolve = remark.resolveNodeFilePath.bind(remark) |
| 43 | + remark.resolveNodeFilePath = (node, toPath) => |
| 44 | + _resolve(node, this.fixPath(toPath)) |
| 45 | + |
| 46 | + for (const {use, options: opts} of config.plugins) { |
| 47 | + if ( |
| 48 | + use === '@gridsome/source-filesystem' && |
| 49 | + options.contentTypes.includes(opts.typeName) |
| 50 | + ) { |
| 51 | + const {typeName, route} = opts, |
| 52 | + coverField = opts.coverField || options.coverField, |
| 53 | + ContentType = store.addContentType({ |
| 54 | + typeName: typeName, |
| 55 | + route: route, |
| 56 | + }) |
| 57 | + |
| 58 | + ContentType.on('add', node => { |
| 59 | + node[coverField] = this.fixPath(node[coverField]) |
| 60 | + }) |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + fixPath(imagePath) { |
| 66 | + let out = imagePath |
| 67 | + if (imagePath !== undefined) { |
| 68 | + if (/^\w/.test(imagePath) && !/:\/\//.test(imagePath)) |
| 69 | + out = path.join(this.mediaFolder, imagePath) |
| 70 | + else if (imagePath.startsWith(this.publicFolder)) |
| 71 | + out = path.join( |
| 72 | + this.mediaFolder, |
| 73 | + imagePath.substring(this.publicFolder.length), |
| 74 | + ) |
| 75 | + } |
| 76 | + return out |
| 77 | + } |
| 78 | +} |
| 79 | + |
| 80 | +module.exports = NetlifyPaths |
0 commit comments