@softr/sdk
Version:
The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.
71 lines (69 loc) • 2.77 kB
JavaScript
import { throwAtCaller } from "./assertions.js";
import { existsSync, readFileSync } from "node:fs";
import path from "node:path";
import { z } from "zod";
//#region src/softr-config.schema.ts
const SOFTR_CONFIG_FILE = "softr.json";
/** The cause is in softr.json, so the app's author can fix it. */
var SoftrConfigError = class extends Error {
name = "SoftrConfigError";
};
function panicConfig(message) {
throwAtCaller(panicConfig, new SoftrConfigError(message));
}
const AccessBehaviour = z.union([
z.string(),
z.object({
strategy: z.literal("redirect"),
to: z.string()
}),
z.object({ strategy: z.literal("throw") })
], { error: "must be a path like \"/login\", { \"strategy\": \"redirect\", \"to\": \"/login\" } or { \"strategy\": \"throw\" }" });
const AppPath = z.string().refine((path$1) => path$1.startsWith("/") && !path$1.includes("?") && !path$1.includes("#") && new URL(path$1, "https://app.invalid").origin === "https://app.invalid", { error: "must be a path on this app like \"/login\", with no \"?\" or \"#\"" });
const Origin = z.union([z.literal("*"), z.string().regex(/^https:\/\/[^/\\?#@\s;,]+$/).refine(URL.canParse).transform((origin) => new URL(origin).origin)], { error: "must be an https origin like \"https://partner.com\", with no path or trailing \"/\", or \"*\" for any site" });
const SoftrConfigSchema = z.object({
auth: z.strictObject({
routes: z.strictObject({
login: z.strictObject({
path: AppPath,
redirectParam: z.string()
}),
resetPassword: z.strictObject({
path: AppPath,
tokenParam: z.string()
}),
acceptInvitation: z.strictObject({
path: AppPath,
tokenParam: z.string()
}),
magicLink: z.strictObject({
path: AppPath,
tokenParam: z.string()
}),
sso: z.strictObject({ path: AppPath }).optional()
}),
guard: z.strictObject({
unauthenticated: AccessBehaviour,
forbidden: AccessBehaviour,
alreadyAuthenticated: AccessBehaviour
})
}),
user: z.strictObject({ properties: z.record(z.string(), z.string()) }).optional(),
allowEmbedding: z.array(Origin).optional()
});
function loadSoftrConfig(root) {
const file = path.join(root, SOFTR_CONFIG_FILE);
if (!existsSync(file)) panicConfig(`${SOFTR_CONFIG_FILE} is missing from ${root}`);
const source = readFileSync(file, "utf8");
let parsed;
try {
parsed = JSON.parse(source);
} catch (error) {
panicConfig(`${SOFTR_CONFIG_FILE} is not valid JSON: ${error instanceof Error ? error.message : error}`);
}
const result = SoftrConfigSchema.safeParse(parsed);
if (!result.success) panicConfig(`${SOFTR_CONFIG_FILE} does not match the schema:\n\n${z.prettifyError(result.error)}`);
return result.data;
}
//#endregion
export { SOFTR_CONFIG_FILE, SoftrConfigError, loadSoftrConfig, panicConfig };