UNPKG

one

Version:

One is a new React Framework that makes Vite serve both native and web.

53 lines (52 loc) 1.71 kB
const VIRTUAL_PREFIX = "\0one-env-guard:"; const GUARD_SPECIFIERS = ["server-only", "client-only", "native-only", "web-only"]; const ALLOWED_ENVIRONMENTS = { "server-only": ["ssr"], "client-only": ["client"], "native-only": ["ios", "android"], "web-only": ["client", "ssr"] }; function resolveEnvironmentGuard(specifier, envName, options) { if (!GUARD_SPECIFIERS.includes(specifier)) { return null; } if (options?.disabled || options?.disableGuards?.includes(specifier)) { return `${VIRTUAL_PREFIX}${specifier}:disabled`; } return `${VIRTUAL_PREFIX}${specifier}:${envName}`; } function loadEnvironmentGuard(id) { if (!id.startsWith(VIRTUAL_PREFIX)) { return null; } const rest = id.slice(VIRTUAL_PREFIX.length); const lastColon = rest.lastIndexOf(":"); if (lastColon === -1) return null; const specifier = rest.slice(0, lastColon); const envName = rest.slice(lastColon + 1); if (envName === "disabled") { return "export {}"; } const allowed = ALLOWED_ENVIRONMENTS[specifier]; if (!allowed) return null; if (allowed.includes(envName)) { return "export {}"; } return `throw new Error("${specifier} cannot be imported in the \\"${envName}\\" environment")`; } function environmentGuardPlugin(options) { return { name: "one:environment-guard", enforce: "pre", resolveId(source) { const envName = this.environment?.name; if (!envName) return null; return resolveEnvironmentGuard(source, envName, options); }, load(id) { return loadEnvironmentGuard(id); } }; } export { environmentGuardPlugin, loadEnvironmentGuard, resolveEnvironmentGuard }; //# sourceMappingURL=environmentGuardPlugin.mjs.map