|
| 1 | +import fs from "node:fs/promises"; |
| 2 | +import path from "node:path"; |
| 3 | + |
| 4 | +function asString(value, fallback = "") { |
| 5 | + if (typeof value === "string") { |
| 6 | + return value.trim(); |
| 7 | + } |
| 8 | + if (typeof value === "number") { |
| 9 | + return String(value); |
| 10 | + } |
| 11 | + return fallback; |
| 12 | +} |
| 13 | + |
| 14 | +function isNullish(value) { |
| 15 | + return value === undefined || value === null; |
| 16 | +} |
| 17 | + |
| 18 | +function stableJson(value) { |
| 19 | + return JSON.stringify(value); |
| 20 | +} |
| 21 | + |
| 22 | +async function loadSeedFile() { |
| 23 | + const seedPath = path.resolve(process.cwd(), "directus/cms-module.seed.json"); |
| 24 | + const content = await fs.readFile(seedPath, "utf8"); |
| 25 | + return JSON.parse(content); |
| 26 | +} |
| 27 | + |
| 28 | +function buildPayload(seed, env) { |
| 29 | + const payload = { ...seed }; |
| 30 | + |
| 31 | + if (env.MODULE_STATUS) { |
| 32 | + payload.status = asString(env.MODULE_STATUS, payload.status || "published"); |
| 33 | + } |
| 34 | + if (env.MODULE_REFRESH_TARGET) { |
| 35 | + payload.refresh_target = asString( |
| 36 | + env.MODULE_REFRESH_TARGET, |
| 37 | + payload.refresh_target || "both", |
| 38 | + ); |
| 39 | + } |
| 40 | + if (Object.prototype.hasOwnProperty.call(env, "MODULE_SITE_KEY")) { |
| 41 | + const siteKey = asString(env.MODULE_SITE_KEY); |
| 42 | + payload.site_key = siteKey || null; |
| 43 | + } |
| 44 | + |
| 45 | + const bundleUrl = asString(env.MFE_BUNDLE_URL); |
| 46 | + const moduleVersion = asString(env.MFE_MODULE_VERSION || env.GITHUB_REF_NAME || ""); |
| 47 | + const releaseTag = asString(env.GITHUB_REF_NAME || ""); |
| 48 | + const releaseSha = asString(env.GITHUB_SHA || ""); |
| 49 | + |
| 50 | + const defaultProps = |
| 51 | + payload.default_props && typeof payload.default_props === "object" |
| 52 | + ? { ...payload.default_props } |
| 53 | + : {}; |
| 54 | + |
| 55 | + const releaseMeta = { |
| 56 | + bundleUrl, |
| 57 | + moduleVersion, |
| 58 | + releaseTag, |
| 59 | + releaseSha, |
| 60 | + publishedAt: new Date().toISOString(), |
| 61 | + }; |
| 62 | + |
| 63 | + // Keep runtime metadata under a reserved key. |
| 64 | + defaultProps.__mfe_release = releaseMeta; |
| 65 | + payload.default_props = defaultProps; |
| 66 | + |
| 67 | + return payload; |
| 68 | +} |
| 69 | + |
| 70 | +async function directusRequest(baseUrl, token, method, resourcePath, body) { |
| 71 | + const response = await fetch(`${baseUrl.replace(/\/+$/g, "")}${resourcePath}`, { |
| 72 | + method, |
| 73 | + headers: { |
| 74 | + Authorization: `Bearer ${token}`, |
| 75 | + "Content-Type": "application/json", |
| 76 | + }, |
| 77 | + body: body ? stableJson(body) : undefined, |
| 78 | + }); |
| 79 | + |
| 80 | + if (!response.ok) { |
| 81 | + const text = await response.text(); |
| 82 | + throw new Error( |
| 83 | + `Directus ${method} ${resourcePath} failed (${response.status}): ${text || "empty response"}`, |
| 84 | + ); |
| 85 | + } |
| 86 | + |
| 87 | + const text = await response.text(); |
| 88 | + if (!text) { |
| 89 | + return {}; |
| 90 | + } |
| 91 | + try { |
| 92 | + return JSON.parse(text); |
| 93 | + } catch { |
| 94 | + return { raw: text }; |
| 95 | + } |
| 96 | +} |
| 97 | + |
| 98 | +async function findExistingModule(baseUrl, token, moduleKey, siteKey) { |
| 99 | + const query = new URLSearchParams(); |
| 100 | + query.set("fields", "id,module_key,site_key,status,refresh_target"); |
| 101 | + query.set("limit", "1"); |
| 102 | + query.set("filter[module_key][_eq]", moduleKey); |
| 103 | + if (isNullish(siteKey) || siteKey === "") { |
| 104 | + query.set("filter[site_key][_null]", "true"); |
| 105 | + } else { |
| 106 | + query.set("filter[site_key][_eq]", String(siteKey)); |
| 107 | + } |
| 108 | + |
| 109 | + const response = await directusRequest( |
| 110 | + baseUrl, |
| 111 | + token, |
| 112 | + "GET", |
| 113 | + `/items/cms_modules?${query.toString()}`, |
| 114 | + ); |
| 115 | + const rows = Array.isArray(response?.data) ? response.data : []; |
| 116 | + return rows[0] ?? null; |
| 117 | +} |
| 118 | + |
| 119 | +async function upsertModule(baseUrl, token, payload) { |
| 120 | + const moduleKey = asString(payload.module_key); |
| 121 | + if (!moduleKey) { |
| 122 | + throw new Error("Seed payload is missing module_key."); |
| 123 | + } |
| 124 | + |
| 125 | + const existing = await findExistingModule(baseUrl, token, moduleKey, payload.site_key); |
| 126 | + if (existing?.id) { |
| 127 | + const updated = await directusRequest( |
| 128 | + baseUrl, |
| 129 | + token, |
| 130 | + "PATCH", |
| 131 | + `/items/cms_modules/${encodeURIComponent(existing.id)}`, |
| 132 | + payload, |
| 133 | + ); |
| 134 | + return { action: "updated", id: existing.id, data: updated?.data ?? null }; |
| 135 | + } |
| 136 | + |
| 137 | + const created = await directusRequest(baseUrl, token, "POST", "/items/cms_modules", payload); |
| 138 | + return { action: "created", id: created?.data?.id ?? null, data: created?.data ?? null }; |
| 139 | +} |
| 140 | + |
| 141 | +async function main() { |
| 142 | + const baseUrl = asString(process.env.DIRECTUS_BASE_URL); |
| 143 | + const token = asString(process.env.DIRECTUS_STATIC_TOKEN); |
| 144 | + if (!baseUrl || !token) { |
| 145 | + throw new Error( |
| 146 | + "DIRECTUS_BASE_URL and DIRECTUS_STATIC_TOKEN are required for Directus sync.", |
| 147 | + ); |
| 148 | + } |
| 149 | + |
| 150 | + const seed = await loadSeedFile(); |
| 151 | + const payload = buildPayload(seed, process.env); |
| 152 | + const result = await upsertModule(baseUrl, token, payload); |
| 153 | + |
| 154 | + const summary = { |
| 155 | + action: result.action, |
| 156 | + id: result.id, |
| 157 | + module_key: payload.module_key, |
| 158 | + site_key: payload.site_key ?? null, |
| 159 | + status: payload.status, |
| 160 | + refresh_target: payload.refresh_target, |
| 161 | + bundle_url: payload?.default_props?.__mfe_release?.bundleUrl ?? "", |
| 162 | + module_version: payload?.default_props?.__mfe_release?.moduleVersion ?? "", |
| 163 | + }; |
| 164 | + |
| 165 | + console.log("[sync-directus-module] success", stableJson(summary)); |
| 166 | +} |
| 167 | + |
| 168 | +main().catch((error) => { |
| 169 | + console.error("[sync-directus-module] failed:", error instanceof Error ? error.message : error); |
| 170 | + process.exit(1); |
| 171 | +}); |
0 commit comments