#!/usr/bin/env bun import fs from "node:fs/promises"; import { dirname } from "node:path"; import { toJSONSchema } from "../datasources"; import { getManifest, getMigrationFilePath } from "../datasources/manifest-fs"; import { datasourceToSQL } from "../datasources/to-sql"; import { getEnvConfig } from "../utils/env-config"; import { getUpstartApiClient } from "../utils/upstart-api"; async function main() { const { UP_SITE_ID: siteId, UP_API_TOKEN: apiToken } = getEnvConfig(); const filePath = process.argv[2]; if (!filePath) { throw new Error("Please provide the path to a datasource manifest file."); } const manifest = await getManifest(filePath); console.log(`Creating datasource "${manifest.id}" for site ${siteId}...`); const migrationFilePath = getMigrationFilePath({ migrationType: "create", suffix: manifest.id, }); console.log("Converting datasource manifest to SQL migration at path:", migrationFilePath); const sql = datasourceToSQL(manifest); if (!(await fs.exists(dirname(migrationFilePath)))) { await fs.mkdir(dirname(migrationFilePath), { recursive: true }); } await fs.writeFile(migrationFilePath, sql); const serializedManifest = { ...manifest, schema: toJSONSchema(manifest.schema), }; const client = getUpstartApiClient(apiToken); const response = await client.callApi<{ error?: string }>(`v1/sites/${siteId}/datasources`, "POST", { id: manifest.id, provider: manifest.provider, label: manifest.label, description: manifest.description, manifest: serializedManifest, }); if (!response.success) { // Idempotency: the datasource may already exist server-side (e.g. registered // by a previous session/worktree, or a partial commit that POSTed before // failing). Git still sees the manifest file as newly added relative to this // branch, so the pre-commit hook routes us here. Fall back to an update // instead of failing the whole commit. if (response.data?.error === "datasource-already-exists") { console.log(`Datasource "${manifest.id}" already exists server-side — updating instead.`); const updateResponse = await client.callApi<{ error?: string }>( `v1/sites/${siteId}/datasources/${manifest.id}`, "PATCH", { provider: manifest.provider, label: manifest.label, description: manifest.description, manifest: serializedManifest, }, ); if (!updateResponse.success) { console.error( `Failed to update existing datasource "${manifest.id}" with Upstart: ${filePath} Server reported this error: `, updateResponse.data, ); process.exit(1); } return; } console.error( `Failed to register datasource "${manifest.id}" with Upstart. The datasource manifest may be invalid: ${filePath} Server reported this error: `, response.data, ); process.exit(1); } } main() .then(() => { process.exit(0); }) .catch((e) => { console.error(e); process.exit(1); });