@safran/profile
@safran/profile is the part of Safran that knows what a profile is. This page documents everything it exports: the zod schema, the two profile types, the functions that load, validate and serialise a profile, and the pure lookups (who owns a repo, which words the glossary adds) that the rest of Safran is built on. You can use the package on its own, without createSafran, to validate or generate profiles in your own tooling.
For the meaning of each profile key, read the profile reference; this page is about the code.
A complete example
One file defines the acme profile in TypeScript and validates it. The later examples import it.
import { defineProfile, parseProfile, type Profile } from "@safran/profile";
export const input = defineProfile({
version: 1,
company: "acme",
languages: { tickets: "tr", code: "en" },
trackers: [
{ id: "jira", type: "jira", url: "https://acme.atlassian.net", email_env: "JIRA_EMAIL", token_env: "JIRA_TOKEN", projects: ["PAY", "MOB", "WEB"] },
],
code: {
hosts: [{ id: "azure", type: "azure-repos", organization: "acme", project: "Platform", token_env: "AZURE_DEVOPS_PAT" }],
groups: {
backend: ["payments-api", "ledger"],
mobile: ["acme-ios", "acme-android"],
frontend: ["web-app", "admin-panel"],
},
},
teams: [
{ name: "Payments", projects: ["PAY"], repos: ["payments-api", "ledger"] },
{ name: "Mobile", projects: ["MOB"], repos: ["acme-ios", "acme-android"], confidence: "low", source: "9 ticket-PR links" },
{ name: "Web", projects: ["WEB"], repos: ["web-app", "admin-panel"] },
],
glossary: [
{ term: "Sepet", code: ["basket", "cart"] },
{ term: "İade", code: ["refund", "chargeback"] },
],
});
/** Validated, with every default applied. */
export const profile: Profile = parseProfile(input);import { expandWithGlossary, teamsOwningRepo, unconfirmedTeams } from "@safran/profile";
import { profile } from "./acme-profile";
console.log(profile.embeddings); // { type: "ollama", model: "bge-m3" }: the default was applied
console.log(teamsOwningRepo(profile, "ledger").map((team) => team.name)); // ["Payments"]
console.log(unconfirmedTeams(profile)); // ["Mobile"]
console.log(expandWithGlossary(profile, "Kısmi iadeler sepette görünmüyor")); // ["basket", "cart", "refund", "chargeback"]What the package exports
| Export | Kind | What it is |
|---|---|---|
profileSchema | zod schema | The schema of a profile, with defaults and cross-field rules. |
Profile, ProfileInput | types | A validated profile; what a person may write. |
TrackerEntry, CodeHostEntry, DocSourceEntry, Team, GlossaryEntry | types | The entry types inside a Profile. |
defineProfile | function | Type helper for profiles written in TypeScript. |
parseProfile | function | Validates already-parsed data. |
loadProfileFile, loadProfile, LoadedProfile | functions, type | Read and validate a YAML file. |
stringifyProfile | function | Serialises a profile to YAML. |
unconfirmedTeams, groupsOfRepo, reposInGroups, teamsOwningRepo, teamsOwningProject, allProjectKeys, trackerForProject, matchGlossary, expandWithGlossary | functions | Pure queries over a Profile. |
DEFAULT_PROFILE_FILE, DEFAULT_EMBEDDINGS | constants | The default file name and the default embeddings entry. |
envVarName | zod schema | Re-exported from @safran/kit: the pattern of an environment variable name. |
loadProfileFile, loadProfile and stringifyProfile use Bun's file and YAML APIs, so they need the Bun runtime. Everything else is plain TypeScript.
The schema
profileSchema
export const profileSchema; // defined in packages/profile/src/schema.tsdefined in packages/profile/src/schema.ts
A z.strictObject: an unknown top-level key is an error, not something silently ignored. Only version and company are required.
| Key | Type after parsing | Default | Notes |
|---|---|---|---|
version | 1 | required | The literal 1. |
company | string | required | A slug: lowercase letters, digits and dashes, starting with a letter or digit. |
languages | { tickets: string; code: string } | { tickets: "en", code: "en" } | Two-letter language codes. |
trackers | TrackerEntry[] | [] | Each needs id (slug) and type; projects defaults to []. Other keys are kept for the plugin. |
code | { hosts: CodeHostEntry[]; groups: Record<string, string[]> } | { hosts: [], groups: {} } | Host entries need id and type; include and exclude default to []. |
docs | DocSourceEntry[] | [] | Each needs id and type. |
teams | Team[] | [] | Strict: name, projects, repos, confidence, source and nothing else. |
glossary | GlossaryEntry[] | [] | Strict: term, code (at least one word), note. |
conventions | string[] | [] | Free-form rules. |
embeddings | { type: string; … } | DEFAULT_EMBEDDINGS | Needs type; other keys are kept for the plugin. |
plugins | string[] | [] | Package names or paths relative to the profile file. |
Validation happens in two steps, and this package does the first one only. Connector entries (trackers, code.hosts, docs, embeddings) are loose objects here: the profile checks the fields every connector shares and keeps the rest. The plugin selected by type validates the whole entry again with its own strict schema when createSafran builds it; that is where a typo in token_env is caught. So parseProfile accepts an entry with an unknown type; createSafran does not.
Beyond the shape, the schema enforces these rules across fields:
- Tracker ids, code host ids, doc source ids and team names are unique.
- Glossary terms are unique after case folding (
İadeandiadeare one term). - A project key is listed under one tracker only: a ticket key must map to one tracker.
- When at least one tracker declares
projects, every project a team lists must be listed under some tracker.
The validation errors page shows the message of each rule.
Profile and ProfileInput
/** A validated profile: defaults applied, connector entries still carrying their type-specific fields. */
export type Profile = z.output<typeof profileSchema>;
/** What a user may write: every defaulted field optional. */
export type ProfileInput = z.input<typeof profileSchema>;defined in packages/profile/src/schema.ts
They are the output and the input type of the schema. In a ProfileInput every defaulted field is optional; in a Profile they are all present. Functions that accept what a person wrote take ProfileInput (defineProfile, stringifyProfile, SafranOptions.profile); functions that read a profile take Profile (every query on this page, safran.profile).
import { parseProfile, type Profile, type ProfileInput } from "@safran/profile";
const input: ProfileInput = { version: 1, company: "acme" };
const profile: Profile = parseProfile(input);
console.log(input.teams); // undefined: not written
console.log(profile.teams, profile.code.groups, profile.languages); // [] {} { tickets: "en", code: "en" }Entry types
export type TrackerEntry = Profile["trackers"][number];
export type CodeHostEntry = Profile["code"]["hosts"][number];
export type DocSourceEntry = Profile["docs"][number];
export type Team = Profile["teams"][number];
export type GlossaryEntry = Profile["glossary"][number];defined in packages/profile/src/schema.ts
They are indexed types of Profile, so they always match the schema. The two written by people rather than for a plugin:
Team field | Type | Meaning |
|---|---|---|
name | string | Unique team name. |
projects | string[] | Tracker project keys the team owns. Default []. |
repos | string[] | Repo names the team owns. Default []. |
confidence | "low" | "medium" | "high" (optional) | Set by discovery when the mapping was inferred; low must be confirmed by a person. |
source | string (optional) | Where the mapping came from, e.g. "9 ticket-PR links". |
GlossaryEntry field | Type | Meaning |
|---|---|---|
term | string | The word as people write it in tickets. |
code | string[] | Identifiers and words the code uses for it. At least one. |
note | string (optional) | A remark for readers of the profile. |
TrackerEntry is { id, type, projects }, CodeHostEntry is { id, type, include, exclude } and DocSourceEntry is { id, type }, each with the type-specific keys of its plugin still attached (typed as unknown).
Constants
export const DEFAULT_PROFILE_FILE = "safran.yaml";
export const DEFAULT_EMBEDDINGS = { type: "ollama", model: "bge-m3" } as const;DEFAULT_PROFILE_FILE is the default argument of parseProfile, loadProfileFile and loadProfile. DEFAULT_EMBEDDINGS is what embeddings becomes when the profile does not have the key.
Defining, parsing, loading, writing
defineProfile
/** Type helper for profiles written in TypeScript. Returns its argument unchanged. */
export function defineProfile(profile: ProfileInput): ProfileInput;defined in packages/profile/src/index.ts
Returns its argument unchanged. It exists so a profile written in TypeScript gets completion and type errors for the top-level structure. It does not validate: pass the result to parseProfile, or to createSafran({ profile }), which validates it.
parseProfile
/** Validates already-parsed data. `file` is only used in error messages. */
export function parseProfile(data: unknown, file: string = DEFAULT_PROFILE_FILE): Profile;defined in packages/profile/src/index.ts
Validates data that is already parsed (from YAML, JSON, or an object in code) and returns the Profile with defaults applied. file is used only in the error message. null and undefined are treated as an empty object, so an empty YAML file reports the missing version and company instead of a type error.
Throws PROFILE_INVALID. The message lists every problem as path: message; details.problems carries the same lines and details.file the name.
import { isSafranError } from "@safran/kit";
import { parseProfile } from "@safran/profile";
try {
parseProfile({ version: 2, company: "Acme", teams: [{ name: "Payments", repo: ["payments-api"] }] }, "acme.yaml");
} catch (error) {
if (!isSafranError(error, "PROFILE_INVALID")) throw error;
console.log(error.details?.problems);
// [ "version: Invalid input: expected 1",
// "company: use lowercase letters, digits and dashes",
// "teams.0: Unrecognized key: \"repo\"" ]
}loadProfileFile
export async function loadProfileFile(file: string = DEFAULT_PROFILE_FILE): Promise<LoadedProfile>;
export interface LoadedProfile {
profile: Profile;
/** Absolute path of the file it was read from. */
file: string;
/** Directory relative paths in the profile are resolved against. */
dir: string;
}defined in packages/profile/src/index.ts
Reads a YAML file and validates it. A relative path resolves against the current working directory.
| Field | Type | Meaning |
|---|---|---|
profile | Profile | The validated profile. |
file | string | Absolute path of the file it was read from. |
dir | string | Directory of that file: what relative paths in the profile (plugins:, a local host's path) resolve against. |
Throws PROFILE_INVALID in three cases: the file does not exist (details.problems is ["file not found"]; the hint names safran init), the file is not valid YAML (the parser's message is the one problem), or the content fails the schema.
import { isSafranError } from "@safran/kit";
import { loadProfileFile } from "@safran/profile";
try {
const { profile, file, dir } = await loadProfileFile("/work/acme/safran.yaml");
console.log(profile.company, file, dir);
} catch (error) {
if (isSafranError(error, "PROFILE_INVALID")) console.error(error.format());
else throw error;
}loadProfile
/** Shorthand for `(await loadProfileFile(file)).profile`. */
export async function loadProfile(file: string = DEFAULT_PROFILE_FILE): Promise<Profile>;defined in packages/profile/src/index.ts
Shorthand for (await loadProfileFile(file)).profile, for callers that do not need the path.
stringifyProfile
/** Serialises a profile back to YAML, for `safran init` and `safran discover`. */
export function stringifyProfile(profile: ProfileInput, header?: string): string;defined in packages/profile/src/index.ts
Serialises a profile to YAML that reads like a hand-written file: two-space indentation, empty collections on the key's own line (glossary: []), a trailing newline. Each line of the optional header becomes a # comment at the top. It does not validate and does not add defaults; it writes what it is given. safran init and safran discover write their output with it.
import { stringifyProfile } from "@safran/profile";
const yaml = stringifyProfile(
{ version: 1, company: "acme", trackers: [{ id: "jira", type: "jira", projects: ["PAY"] }], glossary: [] },
"Draft written by a script.\nReview before use.",
);
console.log(yaml);
// # Draft written by a script.
// # Review before use.
// version: 1
// company: acme
// trackers:
// - id: jira
// type: jira
// projects:
// - PAY
// glossary: []Comments and key order of a file you loaded are not preserved by a load → stringify round trip: the YAML is generated from the object.
Queries
Pure functions over a Profile: no I/O, no state, safe to call anywhere. All of them take the validated Profile, not a ProfileInput.
Teams
/** Pure lookups over a profile. No I/O; safe to call anywhere. */
/** Teams whose mapping was guessed by discovery and still needs a human to confirm. */
export function unconfirmedTeams(profile: Profile): string[];
export function teamsOwningRepo(profile: Profile, repo: string): Team[];
export function teamsOwningProject(profile: Profile, project: string): Team[];defined in packages/profile/src/queries.ts
| Function | Returns | Matching |
|---|---|---|
unconfirmedTeams(profile) | Names of the teams with confidence: "low" | — |
teamsOwningRepo(profile, repo) | Teams whose repos contains the name | Exact, case-sensitive |
teamsOwningProject(profile, project) | Teams whose projects contains the key | Case-insensitive |
teamsOwningRepo answers from the profile only. safran.company.whoOwns adds the fallback to merged pull requests when no team declares the repo.
import { teamsOwningProject, teamsOwningRepo, unconfirmedTeams } from "@safran/profile";
import { profile } from "./acme-profile";
console.log(teamsOwningRepo(profile, "payments-api").map((team) => team.name)); // ["Payments"]
console.log(teamsOwningProject(profile, "pay").map((team) => team.name)); // ["Payments"]
console.log(teamsOwningRepo(profile, "unknown-repo")); // []
for (const name of unconfirmedTeams(profile)) console.log(`${name}: inferred by discovery, confirm it`); // MobileGroups
/** Groups a repo belongs to. */
export function groupsOfRepo(profile: Profile, repo: string): string[];
/** Repo names in any of the given groups. Unknown groups contribute nothing. */
export function reposInGroups(profile: Profile, groups: readonly string[]): string[];defined in packages/profile/src/queries.ts
groupsOfRepo returns every group a repo sits in (a repo may be in several). reposInGroups returns the union of the repos of the given groups, de-duplicated; an unknown group contributes nothing and is not an error. (safran.code.search is stricter: it throws INVALID_INPUT for an unknown group.)
import { groupsOfRepo, reposInGroups } from "@safran/profile";
import { profile } from "./acme-profile";
console.log(groupsOfRepo(profile, "ledger")); // ["backend"]
console.log(reposInGroups(profile, ["backend", "mobile"])); // ["payments-api", "ledger", "acme-ios", "acme-android"]
console.log(reposInGroups(profile, ["no-such-group"])); // []Projects
/** Every project key declared by any tracker, upper-cased. */
export function allProjectKeys(profile: Profile): string[];
/** Id of the tracker that declares the project of a `PROJECT-123` style key. */
export function trackerForProject(profile: Profile, project: string): string | undefined;defined in packages/profile/src/queries.ts
allProjectKeys returns every project key any tracker declares, upper-cased and de-duplicated. It is the default set of keys links.refresh uses to recognise ticket keys in pull request titles and branch names. trackerForProject returns the id of the tracker that declares a project (case-insensitive), or undefined.
Upper-casing is locale-independent on purpose: keys are identifiers, and a Turkish locale would turn billing into BİLLİNG.
import { allProjectKeys, trackerForProject } from "@safran/profile";
import { profile } from "./acme-profile";
console.log(allProjectKeys(profile)); // ["PAY", "MOB", "WEB"]
console.log(trackerForProject(profile, "mob")); // "jira"
console.log(trackerForProject(profile, "OPS")); // undefinedGlossary
/**
* Glossary entries whose term occurs in the text as a whole word (or word stem prefix,
* since Turkish and many other languages attach suffixes: "iadeler", "iadenin").
*
* Case is folded with `foldCase` on both sides, not with a locale. Turkish lower-casing turns
* `I` into `ı`, so under it the English term "invoice" never matched "INVOICE", and a profile
* usually holds terms in both languages.
*/
export function matchGlossary(profile: Profile, text: string): GlossaryEntry[];
/** Code-side words for every glossary term found in the text, de-duplicated. */
export function expandWithGlossary(profile: Profile, text: string): string[];defined in packages/profile/src/queries.ts
matchGlossary returns the glossary entries whose term occurs in the text; expandWithGlossary returns the code words of those entries, de-duplicated, in glossary order.
How a term matches:
- It must start at a word boundary, and may be followed by anything.
İadematchesiadelerandiadenin(languages that attach suffixes need this), but not a word that merely contains it. - Case is folded on both sides without a locale, so
İade,iade,IADEandıadeare the same term, and an English term such asinvoicematchesINVOICEon a machine with a Turkish locale too. - Terms may contain spaces; they are matched as written.
import { expandWithGlossary, matchGlossary } from "@safran/profile";
import { profile } from "./acme-profile";
const title = "Kısmi iadeler sepette görünmüyor";
console.log(matchGlossary(profile, title).map((entry) => entry.term)); // ["Sepet", "İade"]
console.log(expandWithGlossary(profile, title)); // ["basket", "cart", "refund", "chargeback"]
console.log(expandWithGlossary(profile, "IADE ve sepet")); // same four words: case is folded
console.log(expandWithGlossary(profile, "Refund webhook retries")); // []: "refund" is a code word, not a termThis is the expansion safran.code.search applies to a query before it reaches the index, and what the effectiveQuery of its result shows. The glossary page explains how to write good entries.
Common mistakes
- Treating
defineProfileas validation. It is a type helper. Unknown keys inside connector entries, duplicate ids and the cross-field rules are only caught byparseProfile. - Passing a
ProfileInputto a query. The queries read defaulted fields such asprofile.teamsandprofile.code.groups; parse first. - Expecting
parseProfileto catch connector typos. It checks the shared fields only. Build the instance (createSafran, orsafran profile check) to run each plugin's schema. - Putting a secret in the profile. Connector schemas accept the name of an environment variable (
token_env: JIRA_TOKEN), validated withenvVarName; a pasted token fails that pattern. See secrets. - Round-tripping a hand-edited file through
stringifyProfile. Comments are lost. Write generated profiles to a new file and let a person merge them.