vike
Version:
The Framework *You* Control - Next.js & Nuxt alternative for unprecedented flexibility and dependability.
32 lines (31 loc) • 1.84 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getPageContextSerializedInHtml = getPageContextSerializedInHtml;
exports.getGlobalContextSerializedInHtml = getGlobalContextSerializedInHtml;
const parse_1 = require("@brillout/json-serializer/parse");
const utils_js_1 = require("./utils.js");
const htmlElementIds_js_1 = require("../../shared/htmlElementIds.js");
// elements should exist because:
// 1. <script id="vike_pageContext" type="application/json"> appears before the <script> that loads Vike's client runtime (which includes this file)
// 2. <script id="vike_pageContext" type="application/json"> is neither async nor defer
// See https://github.com/vikejs/vike/pull/1271
function getPageContextSerializedInHtml() {
const pageContextSerializedInHtml = findAndParseJson(htmlElementIds_js_1.htmlElementId_pageContext);
(0, utils_js_1.assert)((0, utils_js_1.hasProp)(pageContextSerializedInHtml, 'pageId', 'string'));
(0, utils_js_1.assert)((0, utils_js_1.hasProp)(pageContextSerializedInHtml, 'routeParams', 'string{}'));
return pageContextSerializedInHtml;
}
function getGlobalContextSerializedInHtml() {
const globalContextSerializedInHtml = findAndParseJson(htmlElementIds_js_1.htmlElementId_globalContext);
return globalContextSerializedInHtml;
}
function findAndParseJson(id) {
const elem = document.getElementById(id);
(0, utils_js_1.assertUsage)(elem,
// It seems like it can be missing when HTML is malformed: https://github.com/vikejs/vike/issues/913
`Couldn't find #${id} (which Vike automatically injects in the HTML): make sure it exists (i.e. don't remove it and make sure your HTML isn't malformed)`);
const jsonStr = elem.textContent;
(0, utils_js_1.assert)(jsonStr);
const json = (0, parse_1.parse)(jsonStr);
return json;
}