gatsby-adapter-netlify
Version:
Gatsby adapter for Netlify
77 lines (76 loc) • 2.59 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.createStaticAssetsPathHandler = createStaticAssetsPathHandler;
exports.generatePrettyUrlFilePath = generatePrettyUrlFilePath;
exports.normalizeDynamicRoutePath = normalizeDynamicRoutePath;
var _fastq = _interopRequireDefault(require("fastq"));
var _fsExtra = _interopRequireDefault(require("fs-extra"));
function generatePrettyUrlFilePath(routePath) {
if (routePath.endsWith(`/`)) {
return `${routePath}index.html`;
} else {
return `${routePath}.html`;
}
}
function normalizeDynamicRoutePath(routePath) {
return routePath
// replace `:param` with `[param]`
.replace(/:([^:/\\]+)/gm, `[$1]`)
// replace `*param` with `[...param]` and `*` with `[...]`
.replace(/\*([^:/\\]*)/gm, `[...$1]`);
}
function createStaticAssetsPathHandler() {
const moveQueue = (0, _fastq.default)(async (task, cb) => {
try {
if (task.keepOriginalFile) {
await _fsExtra.default.copy(task.from, task.to, {
overwrite: true
});
} else {
await _fsExtra.default.move(task.from, task.to, {
overwrite: true
});
}
cb(null, undefined);
} catch (error) {
cb(error);
}
}, 2);
function ensureStaticAssetPath(filePath, routePath) {
const shouldUsePrettyUrl = filePath.endsWith(`.html`) && !routePath.endsWith(`.html`);
let isDynamic = false;
// dynamic routes syntax use characters that are reserved in a lot of filesystems
// so if route is dynamic we should normalize filepath
if (routePath.includes(`/:`) || routePath.includes(`/*`)) {
routePath = normalizeDynamicRoutePath(routePath);
isDynamic = true;
}
const finalFilePath = `public${shouldUsePrettyUrl ? generatePrettyUrlFilePath(routePath) : routePath}`;
if (finalFilePath !== filePath) {
moveQueue.push({
from: filePath,
to: finalFilePath,
// 404.html should stay in root of PUBLISH_DIR to be used as custom 404 page
// both 404.html and 500.html should stay in root of PUBLISH_DIR to be bundled correctly for SSR/DSG
keepOriginalFile: filePath === `public/404.html` || filePath === `public/500.html`
});
}
return {
finalFilePath,
isDynamic
};
}
const fileMovingDone = () => {
if (moveQueue.idle()) {
return Promise.resolve();
}
return new Promise(resolve => {
moveQueue.drain = resolve;
});
};
return {
ensureStaticAssetPath,
fileMovingDone
};
}