UNPKG

@harlem/plugin-ssr

Version:

The official server-side rendering plugin for Harlem

83 lines (79 loc) 2.82 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); // src/index.ts var src_exports = {}; __export(src_exports, { createClientSSRPlugin: () => createClientSSRPlugin, createServerSSRPlugin: () => createServerSSRPlugin, getBridgingScript: () => getBridgingScript, getBridgingScriptBlock: () => getBridgingScriptBlock }); module.exports = __toCommonJS(src_exports); // src/constants.ts var SENDER = "plugin:ssr"; var SERIALIZER = (snapshot2) => JSON.stringify(snapshot2); var MUTATIONS = { init: "plugin:ssr:init" }; // src/index.ts var import_core = require("@harlem/core"); var import_utilities = require("@harlem/utilities"); var snapshot = {}; function onStoreEvent(stores, payload, callback) { if (!payload) { return; } const store = stores.get(payload.store); if (store) { callback(store); } } function getBridgingScript(serializer = SERIALIZER) { return `window.__harlemState = ${serializer(snapshot)};`; } function getBridgingScriptBlock(serializer = SERIALIZER) { return `<script>${getBridgingScript(serializer)}</script>`; } function createServerSSRPlugin() { return (app, eventEmitter, stores) => { stores.forEach((store) => store.flags.set("ssr:server", true)); eventEmitter.on(import_core.EVENTS.ssr.initServer, (payload) => onStoreEvent(stores, payload, (store) => { snapshot[store.name] = store.state; })); }; } function createClientSSRPlugin() { return (app, eventEmitter, stores) => { const data = window.__harlemState; stores.forEach((store) => store.flags.set("ssr:client", true)); eventEmitter.on(import_core.EVENTS.ssr.initClient, (payload) => onStoreEvent(stores, payload, (store) => { if (store.name in data) { store.write(MUTATIONS.init, SENDER, (state) => (0, import_utilities.objectOverwrite)(state, data[store.name])); delete data[store.name]; } })); }; } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { createClientSSRPlugin, createServerSSRPlugin, getBridgingScript, getBridgingScriptBlock });