| 220 | } |
| 221 | |
| 222 | async function upsertCname(zoneId, headers, name, target) { |
| 223 | const { ok, json } = await cf( |
| 224 | `${CF_API}/zones/${zoneId}/dns_records`, |
| 225 | headers, |
| 226 | { |
| 227 | method: "POST", |
| 228 | body: JSON.stringify({ |
| 229 | type: "CNAME", |
| 230 | name, |
| 231 | content: target, |
| 232 | ttl: 1, |
| 233 | proxied: false, |
| 234 | }), |
| 235 | }, |
| 236 | ); |
| 237 | |
| 238 | if (ok) { |
| 239 | console.log(`DNS CNAME ready: ${name} -> ${target}`); |
| 240 | return; |
| 241 | } |
| 242 | |
| 243 | if (hasCode(json, 81053, 81057)) { |
| 244 | const { ok: listOk, json: list } = await cf( |
| 245 | `${CF_API}/zones/${zoneId}/dns_records?type=CNAME&name=${name}`, |
| 246 | headers, |
| 247 | ); |
| 248 | if (!listOk) { |
| 249 | throw new Error(`DNS list ${name} failed: ${JSON.stringify(list)}`); |
| 250 | } |
| 251 | |
| 252 | const record = list.result?.[0]; |
| 253 | if (!record) { |
| 254 | throw new Error( |
| 255 | `DNS conflict for ${name}, but no CNAME was found: ${JSON.stringify(json)}`, |
| 256 | ); |
| 257 | } |
| 258 | |
| 259 | if (record.content === target && record.proxied === false) { |
| 260 | console.log(`DNS CNAME already correct: ${name}`); |
| 261 | return; |
| 262 | } |
| 263 | |
| 264 | const { ok: updateOk, json: updated } = await cf( |
| 265 | `${CF_API}/zones/${zoneId}/dns_records/${record.id}`, |
| 266 | headers, |
| 267 | { |
| 268 | method: "PATCH", |
| 269 | body: JSON.stringify({ content: target, proxied: false }), |
| 270 | }, |
| 271 | ); |
| 272 | if (!updateOk) { |
| 273 | throw new Error( |
| 274 | `DNS update ${name} failed: ${JSON.stringify(updated)}`, |
| 275 | ); |
| 276 | } |
| 277 | console.log(`DNS CNAME updated: ${name} -> ${target}`); |
| 278 | return; |
| 279 | } |