Skip to content
Myr

env-shape.ts

This file

Path

packages/visibility/src/env-shape.ts

379 lines · 10.5 KiB · TypeScript

Last changed by

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

History of this file

Take it

The walk stopped after 200 commits: lines older than 678c8b8 point at it.

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

lines 1–2why, one step back
1// Read the way varlock reads it, and never resolved. Where the header is
2// silent, items are required and sensitive, as in varlock.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 3–25why, one step back
3import type { EnvItem, EnvSchemaView } from "@repo/protocol/domain/env";
4import { EnvKey } from "@repo/protocol/ids";5import type { LandedSha, ProjectName, RepoPath } from "@repo/protocol/ids";6import { Array, Option, Predicate, Schema } from "effect";7import type { Types } from "effect";89import { isArgs, isCall, isList } from "./env-schema.ts";10import type {11 ParsedArgs,12 ParsedDecorator,13 ParsedEnvSchema,14 ParsedItem,15 ParsedValue,16} from "./env-schema.ts";1718type Header = ParsedEnvSchema["header"];1920const namedArg = (args: ParsedArgs, key: string): Option.Option<ParsedValue> =>21 Option.map(22 Array.findFirst(args.named, (arg) => arg.key === key),23 ({ value }) => value24 );25

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

line 26why, one step back
26/** As in varlock, the first flag written decides. */

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 27–32why, one step back
27const firstNamed = (
28 decorators: readonly ParsedDecorator[],29 ...names: readonly string[]30): Option.Option<ParsedDecorator> =>31 Array.findFirst(decorators, ({ name }) => names.includes(name));32

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

line 33why, one step back
33/** `depends` when the flag's value is anything but `true` or `false`, which only the environment decides. */

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 34–71why, one step back
34const flagOf = (
35 decorators: readonly ParsedDecorator[],36 flag: string,37 opposite: string38): Option.Option<boolean | "depends"> =>39 Option.map(firstNamed(decorators, flag, opposite), ({ name, value }) => {40 if (!Predicate.isBoolean(value)) {41 return "depends";42 }4344 return name === flag ? value : !value;45 });4647type Proxy = NonNullable<EnvItem["proxy"]>;4849const textsOf = (value: ParsedValue): Option.Option<readonly string[]> => {50 const each = Predicate.isString(value) ? [value] : value;5152 return isList(each) && each.every(Predicate.isString)53 ? Option.some(each)54 : Option.none();55};5657/**58 * Whether the platform's swap, the placeholder in any request header, stays59 * where the rule lets the value go: varlock's default (any header), or a60 * `substituteIn` that names `header` among its targets. A rule that allows61 * only some headers (`header:authorization`), the query or a body field62 * would see the value land where it never allowed it.63 */64const swapsInsideTargets = (args: ParsedArgs): boolean =>65 Option.match(namedArg(args, "substituteIn"), {66 onNone: () => true,67 onSome: (targets) =>68 Option.exists(textsOf(targets), (each) => each.includes("header")),69 });7071/**

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

line 72why, one step back
72 * None when it names no host as text. A rule the platform cannot honour

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 73–122why, one step back
73 * exactly is blocked rather than widened: one that waits on an `approval`,
74 * carries `rules` for other paths, computes its credential with a75 * `transform`, keeps the value out of some headers (`substituteIn`), or has76 * a path or method that is not text.77 */78const ruleOf = (args: ParsedArgs): Option.Option<Proxy> =>79 Option.flatMap(Option.flatMap(namedArg(args, "domain"), textsOf), (hosts) => {80 const domains = Array.filter(hosts, (host) => host !== "");8182 if (!Array.isReadonlyArrayNonEmpty(domains)) {83 return Option.none();84 }8586 const rule: Types.Mutable<Proxy> = { domains };87 const path = namedArg(args, "path");88 const method = namedArg(args, "method");89 const block = namedArg(args, "block");90 const methods = Option.flatMap(method, textsOf);9192 const exact =93 (Option.isNone(path) || Predicate.isString(path.value)) &&94 (Option.isNone(method) || Option.isSome(methods)) &&95 Option.isNone(namedArg(args, "approval")) &&96 Option.isNone(namedArg(args, "rules")) &&97 Option.isNone(namedArg(args, "transform")) &&98 swapsInsideTargets(args);99100 if (Option.isSome(path) && Predicate.isString(path.value)) {101 rule.path = path.value;102 }103104 if (Option.isSome(methods)) {105 rule.method = methods.value.join(", ");106 }107108 if (!exact || Option.isSome(block)) {109 rule.block =110 !exact || block.pipe(Option.exists((each) => each !== false));111 }112113 return Option.some(rule);114 });115116const isProxied = (item: ParsedItem): boolean =>117 item.decorators.some(118 ({ name, value }) =>119 name === "proxy" && value !== "passthrough" && value !== "omit"120 );121122/**

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

lines 123–124why, one step back
123 * Rules that differ only in hosts share one; a later rule that differs
124 * otherwise is left out, so the value goes nowhere the shape doesn't show.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 125–210why, one step back
125 */
126export const proxyOf = (item: ParsedItem): Option.Option<Proxy> => {127 const rules = Array.getSomes(128 Array.map(item.decorators, ({ name, value }): Option.Option<Proxy> =>129 name === "proxy" && isArgs(value) ? ruleOf(value) : Option.none()130 )131 );132133 return Option.map(Array.head(rules), (first) => {134 const same = (rule: Proxy) =>135 rule.path === first.path &&136 rule.method === first.method &&137 rule.block === first.block;138139 return {140 ...first,141 domains: Array.dedupe(142 Array.appendAll(143 first.domains,144 rules145 .slice(1)146 .filter(same)147 .flatMap((rule) => rule.domains)148 )149 ),150 };151 });152};153154const builtInTypes = [155 "array",156 "boolean",157 "domain",158 "duration",159 "email",160 "enum",161 "ip",162 "isoDate",163 "md5",164 "number",165 "port",166 "record",167 "semver",168 "simple-object",169 "string",170 "url",171 "uuid",172] as const satisfies readonly string[];173174/**175 * Whether the item's `@type` names a type only a plugin knows. A plugin's176 * type may be a credential that varlock treats as sensitive, and no plugin177 * is loaded here, so such an item counts as sensitive.178 */179const isPluginTyped = (item: ParsedItem): boolean =>180 Option.exists(firstNamed(item.decorators, "type"), ({ value }) => {181 const type = isCall(value) ? value.fn : value;182183 return !builtInTypes.some((builtIn) => builtIn === type);184 });185186const enabledOf = (decorator: ParsedDecorator): ParsedDecorator =>187 decorator.name === "sensitive" && isArgs(decorator.value)188 ? {189 name: decorator.name,190 value: Option.getOrElse(191 namedArg(decorator.value, "enabled"),192 () => true193 ),194 }195 : decorator;196197const defaultSensitive = (key: string, value: ParsedValue): boolean => {198 if (Predicate.isBoolean(value)) {199 return value;200 }201202 const prefix =203 isCall(value) && value.fn === "inferFromPrefix"204 ? value.positional[0]205 : undefined;206207 return !Predicate.isString(prefix) || !key.startsWith(prefix);208};209210/**

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

lines 211–213why, one step back
211 * A flag only the environment decides counts as sensitive, and so does an
212 * item whose `@type` only a plugin knows; an item routed through `@proxy(…)`213 * is sensitive whatever it says, as in varlock.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 214–379why, one step back
214 */
215export const isSensitive = (item: ParsedItem, header: Header): boolean =>216 isProxied(item) ||217 Option.match(flagOf(item.decorators.map(enabledOf), "sensitive", "public"), {218 onNone: () =>219 isPluginTyped(item) ||220 Option.match(firstNamed(header, "defaultSensitive"), {221 onNone: () => true,222 onSome: ({ value }) => defaultSensitive(item.key, value),223 }),224 onSome: (flag) => flag !== false,225 });226227export const requiredOf = (228 item: ParsedItem,229 header: Header230): boolean | "depends" =>231 Option.getOrElse(flagOf(item.decorators, "required", "optional"), () =>232 Option.match(firstNamed(header, "defaultRequired"), {233 onNone: () => true,234 onSome: ({ value }) => {235 if (value === "infer") {236 return item.value !== undefined && item.value !== "";237 }238239 return Predicate.isBoolean(value) ? value : "depends";240 },241 })242 );243244const textOf = (value: ParsedValue): string => {245 if (isCall(value)) {246 return value.text;247 }248249 if (isList(value)) {250 return `[${value.map(textOf).join(", ")}]`;251 }252253 if (isArgs(value)) {254 const named = value.named.map(255 ({ key, value: each }) => `${key}=${textOf(each)}`256 );257258 return `(${[...value.positional.map(textOf), ...named].join(", ")})`;259 }260261 return String(value);262};263264const tagsOf = (item: ParsedItem): readonly string[] =>265 Array.dedupe(266 item.decorators.flatMap(({ name, value }) =>267 name === "tag" && isArgs(value)268 ? value.positional269 .filter((tag) => Predicate.isString(tag) || Predicate.isNumber(tag))270 .map(String)271 .filter((tag) => tag !== "")272 : []273 )274 );275276const docsOf = (item: ParsedItem): Option.Option<string> =>277 Option.flatMap(firstNamed(item.decorators, "docs"), ({ value }) =>278 isArgs(value)279 ? Option.filter(Array.last(value.positional), Predicate.isString)280 : Option.none()281 );282283const itemOf = (284 item: ParsedItem & { readonly key: EnvKey },285 header: Header286): EnvItem => {287 const shown: Types.Mutable<EnvItem> = {288 key: item.key,289 required: requiredOf(item, header),290 sensitive: isSensitive(item, header),291 tags: tagsOf(item),292 };293294 const type = Option.filter(295 Option.map(firstNamed(item.decorators, "type"), ({ value }) =>296 textOf(value)297 ),298 (text) => text !== ""299 );300301 if (Option.isSome(type)) {302 shown.type = type.value;303 }304305 const docs = docsOf(item);306307 if (Option.isSome(docs)) {308 shown.docs = docs.value;309 }310311 const deprecated = firstNamed(item.decorators, "deprecated");312313 if (Option.isSome(deprecated)) {314 shown.deprecated = deprecated.value.value !== false;315 }316317 if (item.description !== undefined && item.description !== "") {318 shown.description = item.description;319 }320321 const proxy = proxyOf(item);322323 if (Option.isSome(proxy)) {324 shown.proxy = proxy.value;325 }326327 const placeholder = Option.filter(328 Option.map(329 firstNamed(item.decorators, "placeholder"),330 ({ value }) => value331 ),332 Predicate.isString333 );334335 if (Option.isSome(placeholder)) {336 shown.placeholder = placeholder.value;337 }338339 return shown;340};341342const isNamed = (343 item: ParsedItem344): item is ParsedItem & { readonly key: EnvKey } => Schema.is(EnvKey)(item.key);345346const currentEnvOf = (header: Header): Option.Option<EnvKey> =>347 Option.flatMap(firstNamed(header, "currentEnv"), ({ value }) => {348 const key =349 isCall(value) && value.fn === "ref" ? value.positional[0] : undefined;350351 return Schema.is(EnvKey)(key) ? Option.some(key) : Option.none();352 });353354export const envSchemaViewOf = (input: {355 readonly at: LandedSha;356 readonly file: RepoPath;357 readonly parsed: ParsedEnvSchema;358 readonly project: ProjectName;359}): EnvSchemaView => {360 const { header, items } = input.parsed;361362 const shown: Types.Mutable<EnvSchemaView> = {363 at: input.at,364 file: input.file,365 imports: input.parsed.imports,366 items: Array.map(Array.filter(items, isNamed), (item) =>367 itemOf(item, header)368 ),369 project: input.project,370 };371372 const currentEnv = currentEnvOf(header);373374 if (Option.isSome(currentEnv)) {375 shown.currentEnvKey = currentEnv.value;376 }377378 return shown;379};