UNPKG

drupal-vite

Version:

Vite plugin for Drupal integration

92 lines (87 loc) 3.12 kB
// src/index.ts import path from "path"; import fs from "fs"; // src/utils.ts var resolveValue = (configValue, defaultEnvKey) => { if (configValue && process.env[configValue]) { return process.env[configValue]; } if (configValue) { return configValue; } return process.env[defaultEnvKey]; }; // src/index.ts var VIRTUAL_MODULE_ID = "drupal-vite/client"; function drupal(options) { const { simple_oauth, graphql, drupalUrl } = options || {}; const { clientID, clientSecret } = simple_oauth || {}; const { endpoint = "/graphql" } = graphql || {}; const resolvedVirtualModuleId = `\x00${VIRTUAL_MODULE_ID}`; let resolvedClientID; let resolvedClientSecret; let resolvedDrupalUrl; return { name: "vite-plugin-drupal-init", configResolved(resolvedConfig) { const defaultClientId = "DRUPAL_CLIENT_ID"; const defaultClientSecret = "DRUPAL_CLIENT_SECRET"; const defaultDrupalUrl = "DRUPAL_URL"; resolvedClientID = resolveValue(clientID, defaultClientId); resolvedClientSecret = resolveValue(clientSecret, defaultClientSecret); resolvedDrupalUrl = resolveValue(drupalUrl, defaultDrupalUrl); if (!resolvedClientID) { console.error(`[drupal-vite] Client ID is not configured.`); } if (!resolvedClientSecret) { console.error(`[drupal-vite] Client Secret is not configured. `); } if (!resolvedDrupalUrl) { console.error(`[drupal-vite] Drupal URL is not configured. '.`); } }, resolveId(id) { if (id === VIRTUAL_MODULE_ID || id === resolvedVirtualModuleId || id.endsWith(VIRTUAL_MODULE_ID)) { return resolvedVirtualModuleId; } return null; }, async load(id) { if (!resolvedClientID || !resolvedClientSecret || !resolvedDrupalUrl) { this.error("Missing required Drupal configuration. Please check your options or environment variables."); } const sanitizedDrupalUrl = resolvedDrupalUrl.replace(/\/$/, ""); const fullGraphqlEndpoint = `${sanitizedDrupalUrl}${endpoint}`; if (id === resolvedVirtualModuleId || id.includes(VIRTUAL_MODULE_ID)) { const hasCustomConfig = fs.existsSync(path.resolve(process.cwd(), "drupal-decoupled.config.ts")); const module = ` import { drupalAuthClient } from "drupal-auth-client"; import { Client, fetchExchange } from "@urql/core"; ${hasCustomConfig ? `import customConfig from "./drupal-decoupled.config.ts";` : ""} export async function getDrupalAuth() { return await drupalAuthClient("${sanitizedDrupalUrl}", { clientId: "${resolvedClientID}", clientSecret: "${resolvedClientSecret}", }); } export async function getDrupalClient() { const auth = await getDrupalAuth(); return new Client({ url: "${fullGraphqlEndpoint}", exchanges: ${hasCustomConfig ? "customConfig.exchanges ?? [fetchExchange]" : "[fetchExchange]"}, fetchOptions: { headers: { Authorization: \`\${auth.token_type} \${auth.access_token}\`, }, }, }); }`; return module; } return null; } }; } export { drupal };