spaps
Version:
Sweet Potato Authentication & Payment Service CLI - Docker Compose orchestrator for local Python/FastAPI SPAPS server with built-in admin middleware
137 lines (115 loc) • 2.91 kB
JavaScript
const fs = require('node:fs');
const path = require('node:path');
const { requestJson } = require('../local-runtime');
const CONTRACT_FILES = [
{
relativePath: 'spaps.app.json',
label: 'spaps.app.json',
},
{
relativePath: path.join('.spaps', 'app.json'),
label: '.spaps/app.json',
},
];
function readJsonIfPresent(filePath) {
if (!fs.existsSync(filePath)) {
return null;
}
try {
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
} catch {
return null;
}
}
function extractClientIdFromContract(contract) {
const candidates = [
contract?.spaps?.application?.slug,
contract?.server?.application_slug,
contract?.application_slug,
contract?.slug,
];
for (const candidate of candidates) {
if (typeof candidate === 'string' && candidate.trim()) {
return candidate.trim();
}
}
return null;
}
function findUpContract(startDir = process.cwd()) {
let current = path.resolve(startDir);
while (true) {
for (const contractFile of CONTRACT_FILES) {
const filePath = path.join(current, contractFile.relativePath);
const payload = readJsonIfPresent(filePath);
const clientId = extractClientIdFromContract(payload);
if (clientId) {
return {
clientId,
source: contractFile.label,
path: filePath,
};
}
}
const parent = path.dirname(current);
if (parent === current) {
return null;
}
current = parent;
}
}
async function findRuntimeClientId(serverUrl) {
if (!serverUrl) {
return null;
}
const result = await requestJson({
method: 'GET',
url: `${String(serverUrl).replace(/\/+$/, '')}/health/local-mode`,
});
const clientId = result.ok && result.data && typeof result.data === 'object'
? result.data.test_application?.slug || null
: null;
if (!clientId) {
return null;
}
return {
clientId,
source: '/health/local-mode',
path: null,
};
}
async function resolveLoginClientId({ options = {}, serverUrl, cwd = process.cwd() } = {}) {
if (typeof options.clientId === 'string' && options.clientId.trim()) {
return {
clientId: options.clientId.trim(),
source: '--client-id',
path: null,
};
}
if (typeof process.env.SPAPS_CLI_CLIENT_ID === 'string' && process.env.SPAPS_CLI_CLIENT_ID.trim()) {
return {
clientId: process.env.SPAPS_CLI_CLIENT_ID.trim(),
source: 'SPAPS_CLI_CLIENT_ID',
path: null,
};
}
const contractHit = findUpContract(cwd);
if (contractHit) {
return contractHit;
}
const runtimeHit = await findRuntimeClientId(serverUrl);
if (runtimeHit) {
return runtimeHit;
}
return {
clientId: null,
source: null,
path: null,
};
}
module.exports = {
CONTRACT_FILES,
extractClientIdFromContract,
findRuntimeClientId,
findUpContract,
resolveLoginClientId,
};