functype-os 1.8.0 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- import{ConfigError as e}from"../errors/errors.js";import{Fs as t}from"../fs/Fs.js";import{expandPath as n}from"../path/PathExpander.js";import{Err as r,Left as i,List as a,Ok as o,Option as s,Right as c}from"functype";const l=e=>n(e).fold(()=>s(void 0),e=>s(e)),u=async(e,n)=>{if(n>=e.length)return s(void 0);let r=e[n],i=l(r);if(i.isNone())return u(e,n+1);let a=await t.exists(i.orThrow());return a.isOk()&&a.value?i:u(e,n+1)},d=e=>a(e.flatMap(e=>l(e).toArray())),f={resolve:async e=>o(await u(e.candidates,0)),resolveRequired:async t=>{let n=await f.resolve(t);return n.isErr()?r(n.error):n.orThrow().fold(()=>Promise.resolve(r(e(t.candidates))),e=>Promise.resolve(o(e)))},resolveAll:async e=>{let n=d(e.candidates).toArray();return o(a((await Promise.all(n.map(async e=>{let n=await t.exists(e);return n.isOk()&&n.value?e:null}))).filter(e=>e!==null)))},resolveSync:e=>d(e.candidates).find(t.existsSync),resolveRequiredSync:t=>f.resolveSync(t).fold(()=>i(e(t.candidates)),e=>c(e)),resolveAllSync:e=>d(e.candidates).filter(t.existsSync)};export{f as ConfigResolver};
1
+ import{ConfigError as e}from"../errors/errors.js";import{Fs as t}from"../fs/Fs.js";import{expandPath as n}from"../path/PathExpander.js";import{Err as r,Left as i,List as a,Ok as o,Option as s,Right as c}from"functype";const l=e=>n(e).fold(()=>s(void 0),e=>s(e)),u=async(e,n)=>{if(n>=e.length)return s(void 0);let r=e[n],i=l(r);if(i.isNone())return u(e,n+1);let a=await t.exists(i.orThrow());return a.isOk()&&a.value?i:u(e,n+1)},d=e=>a(e.flatMap(e=>l(e).toArray())),f={resolve:async e=>{let t=await u(e.candidates,0);return o(t)},resolveRequired:async t=>{let n=await f.resolve(t);return n.isErr()?r(n.error):n.orThrow().fold(()=>Promise.resolve(r(e(t.candidates))),e=>Promise.resolve(o(e)))},resolveAll:async e=>{let n=d(e.candidates).toArray(),r=(await Promise.all(n.map(async e=>{let n=await t.exists(e);return n.isOk()&&n.value?e:null}))).filter(e=>e!==null);return o(a(r))},resolveSync:e=>d(e.candidates).find(t.existsSync),resolveRequiredSync:t=>f.resolveSync(t).fold(()=>i(e(t.candidates)),e=>c(e)),resolveAllSync:e=>d(e.candidates).filter(t.existsSync)};export{f as ConfigResolver};
2
2
  //# sourceMappingURL=ConfigResolver.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"ConfigResolver.js","names":["ConfigErrorConstructor"],"sources":["../../src/config/ConfigResolver.ts"],"sourcesContent":["import type { Either, TaskResult } from \"functype\"\nimport { Err, Left, List, Ok, Option, Right } from \"functype\"\n\nimport type { ConfigError } from \"../errors/errors\"\nimport { ConfigError as ConfigErrorConstructor } from \"../errors/errors\"\nimport { Fs } from \"../fs/Fs\"\nimport { expandPath } from \"../path/PathExpander\"\n\nconst tryExpandPath = (candidate: string): Option<string> => {\n const result = expandPath(candidate)\n return result.fold(\n () => Option<string>(undefined),\n (v) => Option(v),\n )\n}\n\nconst findFirstExistingAsync = async (candidates: readonly string[], startIndex: number): Promise<Option<string>> => {\n if (startIndex >= candidates.length) return Option<string>(undefined)\n const candidate = candidates[startIndex] as string\n const expanded = tryExpandPath(candidate)\n if (expanded.isNone()) return findFirstExistingAsync(candidates, startIndex + 1)\n const existsResult = await Fs.exists(expanded.orThrow())\n if (existsResult.isOk() && existsResult.value) return expanded\n return findFirstExistingAsync(candidates, startIndex + 1)\n}\n\n// Expand each candidate; drop entries whose env variables didn't resolve.\nconst presentPaths = (candidates: readonly string[]): List<string> =>\n List<string>(candidates.flatMap((c) => tryExpandPath(c).toArray() as string[]))\n\nexport const ConfigResolver = {\n // Async methods — return TaskResult<T>\n\n resolve: async (options: { readonly candidates: readonly string[] }): TaskResult<Option<string>> => {\n const found = await findFirstExistingAsync(options.candidates, 0)\n return Ok(found)\n },\n\n resolveRequired: async (options: { readonly candidates: readonly string[] }): TaskResult<string> => {\n const result = await ConfigResolver.resolve(options)\n if (result.isErr()) return Err(result.error)\n\n return result.orThrow().fold<TaskResult<string>>(\n () => Promise.resolve(Err(ConfigErrorConstructor(options.candidates))),\n (v) => Promise.resolve(Ok(v)),\n )\n },\n\n resolveAll: async (options: { readonly candidates: readonly string[] }): TaskResult<List<string>> => {\n const expanded = presentPaths(options.candidates).toArray()\n const checks = await Promise.all(\n expanded.map(async (p): Promise<string | null> => {\n const r = await Fs.exists(p)\n return r.isOk() && r.value ? p : null\n }),\n )\n const found = checks.filter((p): p is string => p !== null)\n return Ok(List<string>(found))\n },\n\n // Sync methods — return Either<ConfigError, T>\n\n resolveSync: (options: { readonly candidates: readonly string[] }): Option<string> =>\n presentPaths(options.candidates).find(Fs.existsSync),\n\n resolveRequiredSync: (options: { readonly candidates: readonly string[] }): Either<ConfigError, string> => {\n const result = ConfigResolver.resolveSync(options)\n return result.fold(\n () => Left(ConfigErrorConstructor(options.candidates)),\n (v) => Right(v),\n )\n },\n\n resolveAllSync: (options: { readonly candidates: readonly string[] }): List<string> =>\n presentPaths(options.candidates).filter(Fs.existsSync),\n}\n"],"mappings":"0NAQA,MAAM,EAAiB,GACN,EAAW,CACd,CAAC,CAAC,SACN,EAAe,IAAA,EAAS,EAC7B,GAAM,EAAO,CAAC,CACjB,EAGI,EAAyB,MAAO,EAA+B,IAAgD,CACnH,GAAI,GAAc,EAAW,OAAQ,OAAO,EAAe,IAAA,EAAS,EACpE,IAAM,EAAY,EAAW,GACvB,EAAW,EAAc,CAAS,EACxC,GAAI,EAAS,OAAO,EAAG,OAAO,EAAuB,EAAY,EAAa,CAAC,EAC/E,IAAM,EAAe,MAAM,EAAG,OAAO,EAAS,QAAQ,CAAC,EAEvD,OADI,EAAa,KAAK,GAAK,EAAa,MAAc,EAC/C,EAAuB,EAAY,EAAa,CAAC,CAC1D,EAGM,EAAgB,GACpB,EAAa,EAAW,QAAS,GAAM,EAAc,CAAC,CAAC,CAAC,QAAQ,CAAa,CAAC,EAEnE,EAAiB,CAG5B,QAAS,KAAO,IAEP,EAAG,MADU,EAAuB,EAAQ,WAAY,CAAC,CACjD,EAGjB,gBAAiB,KAAO,IAA4E,CAClG,IAAM,EAAS,MAAM,EAAe,QAAQ,CAAO,EAGnD,OAFI,EAAO,MAAM,EAAU,EAAI,EAAO,KAAK,EAEpC,EAAO,QAAQ,CAAC,CAAC,SAChB,QAAQ,QAAQ,EAAIA,EAAuB,EAAQ,UAAU,CAAC,CAAC,EACpE,GAAM,QAAQ,QAAQ,EAAG,CAAC,CAAC,CAC9B,CACF,EAEA,WAAY,KAAO,IAAkF,CACnG,IAAM,EAAW,EAAa,EAAQ,UAAU,CAAC,CAAC,QAAQ,EAQ1D,OAAO,EAAG,GADI,MANO,QAAQ,IAC3B,EAAS,IAAI,KAAO,IAA8B,CAChD,IAAM,EAAI,MAAM,EAAG,OAAO,CAAC,EAC3B,OAAO,EAAE,KAAK,GAAK,EAAE,MAAQ,EAAI,IACnC,CAAC,CACH,EAAA,CACqB,OAAQ,GAAmB,IAAM,IAC3B,CAAC,CAAC,CAC/B,EAIA,YAAc,GACZ,EAAa,EAAQ,UAAU,CAAC,CAAC,KAAK,EAAG,UAAU,EAErD,oBAAsB,GACL,EAAe,YAAY,CAC9B,CAAC,CAAC,SACN,EAAKA,EAAuB,EAAQ,UAAU,CAAC,EACpD,GAAM,EAAM,CAAC,CAChB,EAGF,eAAiB,GACf,EAAa,EAAQ,UAAU,CAAC,CAAC,OAAO,EAAG,UAAU,CACzD"}
1
+ {"version":3,"file":"ConfigResolver.js","names":["ConfigErrorConstructor","tryExpandPath","expandPath","candidate","Option","v","findFirstExistingAsync","startIndex","candidates","expanded","existsResult","Fs","presentPaths","List","c","ConfigResolver","found","options","Ok","result","Err","ConfigError","r","p","Left","Right"],"sources":["../../src/config/ConfigResolver.ts"],"sourcesContent":["import type { Either, TaskResult } from \"functype\"\nimport { Err, Left, List, Ok, Option, Right } from \"functype\"\n\nimport type { ConfigError } from \"../errors/errors\"\nimport { ConfigError as ConfigErrorConstructor } from \"../errors/errors\"\nimport { Fs } from \"../fs/Fs\"\nimport { expandPath } from \"../path/PathExpander\"\n\nconst tryExpandPath = (candidate: string): Option<string> => {\n const result = expandPath(candidate)\n return result.fold(\n () => Option<string>(undefined),\n (v) => Option(v),\n )\n}\n\nconst findFirstExistingAsync = async (candidates: readonly string[], startIndex: number): Promise<Option<string>> => {\n if (startIndex >= candidates.length) return Option<string>(undefined)\n const candidate = candidates[startIndex] as string\n const expanded = tryExpandPath(candidate)\n if (expanded.isNone()) return findFirstExistingAsync(candidates, startIndex + 1)\n const existsResult = await Fs.exists(expanded.orThrow())\n if (existsResult.isOk() && existsResult.value) return expanded\n return findFirstExistingAsync(candidates, startIndex + 1)\n}\n\n// Expand each candidate; drop entries whose env variables didn't resolve.\nconst presentPaths = (candidates: readonly string[]): List<string> =>\n List<string>(candidates.flatMap((c) => tryExpandPath(c).toArray() as string[]))\n\nexport const ConfigResolver = {\n // Async methods — return TaskResult<T>\n\n resolve: async (options: { readonly candidates: readonly string[] }): TaskResult<Option<string>> => {\n const found = await findFirstExistingAsync(options.candidates, 0)\n return Ok(found)\n },\n\n resolveRequired: async (options: { readonly candidates: readonly string[] }): TaskResult<string> => {\n const result = await ConfigResolver.resolve(options)\n if (result.isErr()) return Err(result.error)\n\n return result.orThrow().fold<TaskResult<string>>(\n () => Promise.resolve(Err(ConfigErrorConstructor(options.candidates))),\n (v) => Promise.resolve(Ok(v)),\n )\n },\n\n resolveAll: async (options: { readonly candidates: readonly string[] }): TaskResult<List<string>> => {\n const expanded = presentPaths(options.candidates).toArray()\n const checks = await Promise.all(\n expanded.map(async (p): Promise<string | null> => {\n const r = await Fs.exists(p)\n return r.isOk() && r.value ? p : null\n }),\n )\n const found = checks.filter((p): p is string => p !== null)\n return Ok(List<string>(found))\n },\n\n // Sync methods — return Either<ConfigError, T>\n\n resolveSync: (options: { readonly candidates: readonly string[] }): Option<string> =>\n presentPaths(options.candidates).find(Fs.existsSync),\n\n resolveRequiredSync: (options: { readonly candidates: readonly string[] }): Either<ConfigError, string> => {\n const result = ConfigResolver.resolveSync(options)\n return result.fold(\n () => Left(ConfigErrorConstructor(options.candidates)),\n (v) => Right(v),\n )\n },\n\n resolveAllSync: (options: { readonly candidates: readonly string[] }): List<string> =>\n presentPaths(options.candidates).filter(Fs.existsSync),\n}\n"],"mappings":"0NAQA,MAAMC,EAAiB,GACNC,EAAWC,CACd,CAAC,CAAC,SACNC,EAAe,IAAA,EAAS,EAC7B,GAAMA,EAAOC,CAAC,CACjB,EAGIC,EAAyB,MAAO,EAA+B,IAAgD,CACnH,GAAIC,GAAcC,EAAW,OAAQ,OAAOJ,EAAe,IAAA,EAAS,EACpE,IAAMD,EAAYK,EAAWD,GACvBE,EAAWR,EAAcE,CAAS,EACxC,GAAIM,EAAS,OAAO,EAAG,OAAOH,EAAuBE,EAAYD,EAAa,CAAC,EAC/E,IAAMG,EAAe,MAAMC,EAAG,OAAOF,EAAS,QAAQ,CAAC,EAEvD,OADIC,EAAa,KAAK,GAAKA,EAAa,MAAcD,EAC/CH,EAAuBE,EAAYD,EAAa,CAAC,CAC1D,EAGMK,EAAgB,GACpBC,EAAaL,EAAW,QAAS,GAAMP,EAAca,CAAC,CAAC,CAAC,QAAQ,CAAa,CAAC,EAEnEC,EAAiB,CAG5B,QAAS,KAAO,IAAoF,CAClG,IAAMC,EAAQ,MAAMV,EAAuBW,EAAQ,WAAY,CAAC,EAChE,OAAOC,EAAGF,CAAK,CACjB,EAEA,gBAAiB,KAAO,IAA4E,CAClG,IAAMG,EAAS,MAAMJ,EAAe,QAAQE,CAAO,EAGnD,OAFIE,EAAO,MAAM,EAAUC,EAAID,EAAO,KAAK,EAEpCA,EAAO,QAAQ,CAAC,CAAC,SAChB,QAAQ,QAAQC,EAAIpB,EAAuBiB,EAAQ,UAAU,CAAC,CAAC,EACpE,GAAM,QAAQ,QAAQC,EAAGb,CAAC,CAAC,CAC9B,CACF,EAEA,WAAY,KAAO,IAAkF,CACnG,IAAMI,EAAWG,EAAaK,EAAQ,UAAU,CAAC,CAAC,QAAQ,EAOpDD,GAAQ,MANO,QAAQ,IAC3BP,EAAS,IAAI,KAAO,IAA8B,CAChD,IAAMa,EAAI,MAAMX,EAAG,OAAOY,CAAC,EAC3B,OAAOD,EAAE,KAAK,GAAKA,EAAE,MAAQC,EAAI,IACnC,CAAC,CACH,EAAA,CACqB,OAAQ,GAAmBA,IAAM,IAAI,EAC1D,OAAOL,EAAGL,EAAaG,CAAK,CAAC,CAC/B,EAIA,YAAc,GACZJ,EAAaK,EAAQ,UAAU,CAAC,CAAC,KAAKN,EAAG,UAAU,EAErD,oBAAsB,GACLI,EAAe,YAAYE,CAC9B,CAAC,CAAC,SACNO,EAAKxB,EAAuBiB,EAAQ,UAAU,CAAC,EACpD,GAAMQ,EAAMpB,CAAC,CAChB,EAGF,eAAiB,GACfO,EAAaK,EAAQ,UAAU,CAAC,CAAC,OAAON,EAAG,UAAU,CACzD"}
@@ -1 +1 @@
1
- {"version":3,"file":"Layered.js","names":["OptionCtor"],"sources":["../../src/config/Layered.ts"],"sourcesContent":["import type { Option } from \"functype\"\nimport { Option as OptionCtor } from \"functype\"\n\nimport type { ConfigSource } from \"./ConfigSource\"\n\n/**\n * First-wins composition over N `ConfigSource`s.\n *\n * Lookup walks the sources in order and returns the first `Some(value)` it\n * finds. Falls through to the next source when one returns `None`. The\n * composed source's `name` reflects the resolution chain\n * (e.g. `\"process.env > infisical > defaults\"`) so `bootDiagnostics` can echo\n * it in its header.\n *\n * Sensitivity (which keys to mask) is declared at diagnostics time, not at\n * source time — a `Layered([env, vault])` is structurally identical to any\n * other `ConfigSource`.\n *\n * @example\n * ```ts\n * const config = Layered([\n * ProcessEnvSource(),\n * await InfisicalSource({ token, env, projectId }),\n * StaticSource({ ENV: \"local\" }, \"defaults\"),\n * ])\n * // config.name === \"process.env > infisical > defaults\"\n * ```\n */\nexport const Layered = (sources: readonly ConfigSource[]): ConfigSource => ({\n name: sources.map((s) => s.name).join(\" > \"),\n get: (key) =>\n sources.reduce<Option<string>>(\n (acc, source) =>\n acc.fold(\n () => source.get(key),\n () => acc,\n ),\n OptionCtor<string>(undefined),\n ),\n})\n"],"mappings":"kCA4BA,MAAa,EAAW,IAAoD,CAC1E,KAAM,EAAQ,IAAK,GAAM,EAAE,IAAI,CAAC,CAAC,KAAK,KAAK,EAC3C,IAAM,GACJ,EAAQ,QACL,EAAK,IACJ,EAAI,SACI,EAAO,IAAI,CAAG,MACd,CACR,EACFA,EAAmB,IAAA,EAAS,CAC9B,CACJ"}
1
+ {"version":3,"file":"Layered.js","names":["OptionCtor","Layered","sources","s","acc","source","key","Option"],"sources":["../../src/config/Layered.ts"],"sourcesContent":["import type { Option } from \"functype\"\nimport { Option as OptionCtor } from \"functype\"\n\nimport type { ConfigSource } from \"./ConfigSource\"\n\n/**\n * First-wins composition over N `ConfigSource`s.\n *\n * Lookup walks the sources in order and returns the first `Some(value)` it\n * finds. Falls through to the next source when one returns `None`. The\n * composed source's `name` reflects the resolution chain\n * (e.g. `\"process.env > infisical > defaults\"`) so `bootDiagnostics` can echo\n * it in its header.\n *\n * Sensitivity (which keys to mask) is declared at diagnostics time, not at\n * source time — a `Layered([env, vault])` is structurally identical to any\n * other `ConfigSource`.\n *\n * @example\n * ```ts\n * const config = Layered([\n * ProcessEnvSource(),\n * await InfisicalSource({ token, env, projectId }),\n * StaticSource({ ENV: \"local\" }, \"defaults\"),\n * ])\n * // config.name === \"process.env > infisical > defaults\"\n * ```\n */\nexport const Layered = (sources: readonly ConfigSource[]): ConfigSource => ({\n name: sources.map((s) => s.name).join(\" > \"),\n get: (key) =>\n sources.reduce<Option<string>>(\n (acc, source) =>\n acc.fold(\n () => source.get(key),\n () => acc,\n ),\n OptionCtor<string>(undefined),\n ),\n})\n"],"mappings":"kCA4BA,MAAaC,EAAW,IAAoD,CAC1E,KAAMC,EAAQ,IAAK,GAAMC,EAAE,IAAI,CAAC,CAAC,KAAK,KAAK,EAC3C,IAAM,GACJD,EAAQ,QACL,EAAK,IACJE,EAAI,SACIC,EAAO,IAAIC,CAAG,MACdF,CACR,EACFJ,EAAmB,IAAA,EAAS,CAC9B,CACJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"ProcessEnvSource.js","names":[],"sources":["../../src/config/ProcessEnvSource.ts"],"sourcesContent":["import { Env } from \"../env/Env\"\nimport type { ConfigSource } from \"./ConfigSource\"\n\n/**\n * Built-in `ConfigSource` backed by `process.env` via the existing `Env` wrapper.\n *\n * Use as the first layer of a `Layered` chain so env vars override vault and\n * default values:\n *\n * ```ts\n * const config = Layered([ProcessEnvSource(), await InfisicalSource(...), StaticSource(defaults)])\n * ```\n */\nexport const ProcessEnvSource = (): ConfigSource => ({\n name: \"process.env\",\n get: (key) => Env(key),\n})\n"],"mappings":"oCAaA,MAAa,OAAwC,CACnD,KAAM,cACN,IAAM,GAAQ,EAAI,CAAG,CACvB"}
1
+ {"version":3,"file":"ProcessEnvSource.js","names":["ProcessEnvSource","Env","key"],"sources":["../../src/config/ProcessEnvSource.ts"],"sourcesContent":["import { Env } from \"../env/Env\"\nimport type { ConfigSource } from \"./ConfigSource\"\n\n/**\n * Built-in `ConfigSource` backed by `process.env` via the existing `Env` wrapper.\n *\n * Use as the first layer of a `Layered` chain so env vars override vault and\n * default values:\n *\n * ```ts\n * const config = Layered([ProcessEnvSource(), await InfisicalSource(...), StaticSource(defaults)])\n * ```\n */\nexport const ProcessEnvSource = (): ConfigSource => ({\n name: \"process.env\",\n get: (key) => Env(key),\n})\n"],"mappings":"oCAaA,MAAaA,OAAwC,CACnD,KAAM,cACN,IAAM,GAAQC,EAAIC,CAAG,CACvB"}
@@ -1 +1 @@
1
- {"version":3,"file":"StaticSource.js","names":[],"sources":["../../src/config/StaticSource.ts"],"sourcesContent":["import { Option } from \"functype\"\n\nimport type { ConfigSource } from \"./ConfigSource\"\n\n/**\n * Built-in `ConfigSource` backed by an in-memory map.\n *\n * Useful for default values, test fixtures, or any static config layer that\n * doesn't need an external lookup. The `name` argument defaults to `\"static\"`\n * but should be set when composing multiple static sources for clearer\n * diagnostics output.\n *\n * @example\n * ```ts\n * const defaults = StaticSource({ ENV: \"local\", PORT: \"3000\" }, \"defaults\")\n * const config = Layered([ProcessEnvSource(), defaults])\n * ```\n */\nexport const StaticSource = (entries: Readonly<Record<string, string>>, name = \"static\"): ConfigSource => ({\n name,\n get: (key) => Option(entries[key]),\n})\n"],"mappings":"kCAkBA,MAAa,GAAgB,EAA2C,EAAO,YAA4B,CACzG,OACA,IAAM,GAAQ,EAAO,EAAQ,EAAI,CACnC"}
1
+ {"version":3,"file":"StaticSource.js","names":["StaticSource","Option","entries","key"],"sources":["../../src/config/StaticSource.ts"],"sourcesContent":["import { Option } from \"functype\"\n\nimport type { ConfigSource } from \"./ConfigSource\"\n\n/**\n * Built-in `ConfigSource` backed by an in-memory map.\n *\n * Useful for default values, test fixtures, or any static config layer that\n * doesn't need an external lookup. The `name` argument defaults to `\"static\"`\n * but should be set when composing multiple static sources for clearer\n * diagnostics output.\n *\n * @example\n * ```ts\n * const defaults = StaticSource({ ENV: \"local\", PORT: \"3000\" }, \"defaults\")\n * const config = Layered([ProcessEnvSource(), defaults])\n * ```\n */\nexport const StaticSource = (entries: Readonly<Record<string, string>>, name = \"static\"): ConfigSource => ({\n name,\n get: (key) => Option(entries[key]),\n})\n"],"mappings":"kCAkBA,MAAaA,GAAgB,EAA2C,EAAO,YAA4B,CACzG,OACA,IAAM,GAAQC,EAAOC,EAAQC,EAAI,CACnC"}
@@ -1 +1 @@
1
- {"version":3,"file":"bootDiagnostics.js","names":[],"sources":["../../src/config/bootDiagnostics.ts"],"sourcesContent":["import type { Either, List as ListType, Logger } from \"functype\"\nimport { Left, List, Right } from \"functype\"\n\nimport { blue, green, magenta, red, yellow } from \"./colors\"\nimport type { ConfigSource } from \"./ConfigSource\"\nimport { consoleBootLogger } from \"./consoleBootLogger\"\nimport { maskValue } from \"./mask\"\n\nexport interface MissingKey {\n readonly key: string\n readonly required: boolean\n}\n\nexport interface BootDiagnosticsOptions {\n /** The composed `ConfigSource` to inspect. */\n readonly source: ConfigSource\n /** Keys that MUST be present. Missing required keys produce a `Left`. */\n readonly required?: readonly string[]\n /** Keys to log with masked values (via {@link maskValue}). */\n readonly sensitive?: readonly string[]\n /** Keys to log with raw values. */\n readonly public?: readonly string[]\n /**\n * If provided with `vaultEnvKey`, compares the host environment string\n * (e.g. `process.env.NODE_ENV`) against the value at `vaultEnvKey` in the\n * source. Logs `✓` on match, an error-level message on mismatch.\n */\n readonly hostEnv?: string\n readonly vaultEnvKey?: string\n /**\n * `\"missing\"` triggers `process.exit(1)` after logging when any required key\n * is missing. `\"never\"` (default) returns `Left(missing)` and lets the caller\n * decide. Set to `\"missing\"` in production / staging boot paths to guarantee\n * fail-fast on misconfiguration.\n */\n readonly failOn?: \"missing\" | \"never\"\n /**\n * Logger to use. Defaults to {@link consoleBootLogger}. Any value satisfying\n * the core `Logger` interface from `functype` — including `DirectLogger`\n * from `functype-log/direct` — works without an adapter.\n */\n readonly logger?: Logger\n /** Service identifier shown in the diagnostics header. */\n readonly serviceName?: string\n}\n\n/**\n * Log a standardized boot diagnostics block and verify required-key presence.\n *\n * The block always emits, regardless of outcome — operational visibility (\"did\n * the deploy pick up my config?\") is the point. Sensitive keys are masked;\n * public keys are logged verbatim. An optional host-vs-vault env-mismatch\n * check catches the common deploy footgun where the host's `NODE_ENV` and the\n * vault's `ENV` (or equivalent) diverge.\n *\n * Returns `Either<List<MissingKey>, void>` so non-fatal callers can inspect\n * the result. Setting `failOn: \"missing\"` short-circuits to `process.exit(1)`\n * for production guards.\n *\n * @example\n * ```ts\n * const result = bootDiagnostics({\n * serviceName: \"cq-api\",\n * source: Layered([ProcessEnvSource(), await InfisicalSource(...)]),\n * required: [\"SUPABASE_URL\", \"SUPABASE_KEY\", \"OPENAI_API_KEY\"],\n * sensitive: [\"SUPABASE_URL\", \"SUPABASE_KEY\", \"OPENAI_API_KEY\"],\n * public: [\"ENV\", \"ENABLE_CHAT\"],\n * hostEnv: process.env.NODE_ENV ?? \"local\",\n * vaultEnvKey: \"ENV\",\n * failOn: process.env.NODE_ENV === \"production\" ? \"missing\" : \"never\",\n * })\n * ```\n */\nexport const bootDiagnostics = (opts: BootDiagnosticsOptions): Either<ListType<MissingKey>, void> => {\n const logger = opts.logger ?? consoleBootLogger\n const required = opts.required ?? []\n const sensitive = opts.sensitive ?? []\n const publicKeys = opts.public ?? []\n\n logger.info(`${blue(\"📦\")} Boot diagnostics: ${opts.serviceName ?? \"service\"}`)\n logger.info(` source: ${opts.source.name}`)\n\n const missing = required.filter((k) => opts.source.get(k).isEmpty)\n\n if (sensitive.length > 0) {\n logger.info(yellow(\"🔐 Sensitive:\"))\n sensitive.forEach((key) => {\n const value = opts.source.get(key)\n const display = value.fold(\n () => red(\"NOT_LOADED\"),\n (v) => maskValue(v),\n )\n logger.info(` ${key.padEnd(28)} ${display}`)\n })\n }\n\n if (publicKeys.length > 0) {\n logger.info(green(\"⚙️ Public:\"))\n publicKeys.forEach((key) => {\n const value = opts.source.get(key)\n const display = value.fold(\n () => red(\"NOT_LOADED\"),\n (v) => v,\n )\n logger.info(` ${key.padEnd(28)} ${display}`)\n })\n }\n\n if (opts.hostEnv !== undefined && opts.vaultEnvKey !== undefined) {\n const vaultEnv = opts.source.get(opts.vaultEnvKey)\n const { hostEnv } = opts\n const { vaultEnvKey } = opts\n vaultEnv.fold(\n () => {\n logger.warn(`Vault env key '${vaultEnvKey}' not present — skipping mismatch check`)\n return undefined\n },\n (v) => {\n if (v === hostEnv) {\n logger.info(`${magenta(\"🌍\")} Environment: ${hostEnv} (host) ↔ ${v} (vault) ${green(\"✓\")}`)\n } else {\n logger.error(`${magenta(\"🌍\")} Environment MISMATCH: host=${hostEnv} vault=${v}`, {\n hostEnv,\n vaultEnv: v,\n })\n }\n return undefined\n },\n )\n }\n\n if (missing.length === 0) {\n logger.info(green(\"✅ All required keys present\"))\n return Right<ListType<MissingKey>, void>(undefined)\n }\n\n logger.error(red(`❌ Missing required keys (${missing.length}):`))\n missing.forEach((key) => logger.error(` ${key}`))\n\n const missingList = List(missing.map((key): MissingKey => ({ key, required: true })))\n\n if (opts.failOn === \"missing\") {\n process.exit(1)\n }\n return Left<ListType<MissingKey>, void>(missingList)\n}\n"],"mappings":"sOAyEA,MAAa,EAAmB,GAAqE,CACnG,IAAM,EAAS,EAAK,QAAU,EACxB,EAAW,EAAK,UAAY,CAAC,EAC7B,EAAY,EAAK,WAAa,CAAC,EAC/B,EAAa,EAAK,QAAU,CAAC,EAEnC,EAAO,KAAK,GAAG,EAAK,IAAI,EAAE,qBAAqB,EAAK,aAAe,WAAW,EAC9E,EAAO,KAAK,cAAc,EAAK,OAAO,MAAM,EAE5C,IAAM,EAAU,EAAS,OAAQ,GAAM,EAAK,OAAO,IAAI,CAAC,CAAC,CAAC,OAAO,EA0BjE,GAxBI,EAAU,OAAS,IACrB,EAAO,KAAK,EAAO,eAAe,CAAC,EACnC,EAAU,QAAS,GAAQ,CAEzB,IAAM,EADQ,EAAK,OAAO,IAAI,CACV,CAAC,CAAC,SACd,EAAI,YAAY,EACrB,GAAM,EAAU,CAAC,CACpB,EACA,EAAO,KAAK,MAAM,EAAI,OAAO,EAAE,EAAE,GAAG,GAAS,CAC/C,CAAC,GAGC,EAAW,OAAS,IACtB,EAAO,KAAK,EAAM,aAAa,CAAC,EAChC,EAAW,QAAS,GAAQ,CAE1B,IAAM,EADQ,EAAK,OAAO,IAAI,CACV,CAAC,CAAC,SACd,EAAI,YAAY,EACrB,GAAM,CACT,EACA,EAAO,KAAK,MAAM,EAAI,OAAO,EAAE,EAAE,GAAG,GAAS,CAC/C,CAAC,GAGC,EAAK,UAAY,IAAA,IAAa,EAAK,cAAgB,IAAA,GAAW,CAChE,IAAM,EAAW,EAAK,OAAO,IAAI,EAAK,WAAW,EAC3C,CAAE,WAAY,EACd,CAAE,eAAgB,EACxB,EAAS,SACD,CACJ,EAAO,KAAK,kBAAkB,EAAY,wCAAwC,CAEpF,EACC,GAAM,CACD,IAAM,EACR,EAAO,KAAK,GAAG,EAAQ,IAAI,EAAE,gBAAgB,EAAQ,YAAY,EAAE,WAAW,EAAM,GAAG,GAAG,EAE1F,EAAO,MAAM,GAAG,EAAQ,IAAI,EAAE,8BAA8B,EAAQ,SAAS,IAAK,CAChF,UACA,SAAU,CACZ,CAAC,CAGL,CACF,CACF,CAEA,GAAI,EAAQ,SAAW,EAErB,OADA,EAAO,KAAK,EAAM,6BAA6B,CAAC,EACzC,EAAkC,IAAA,EAAS,EAGpD,EAAO,MAAM,EAAI,4BAA4B,EAAQ,OAAO,GAAG,CAAC,EAChE,EAAQ,QAAS,GAAQ,EAAO,MAAM,MAAM,GAAK,CAAC,EAElD,IAAM,EAAc,EAAK,EAAQ,IAAK,IAAqB,CAAE,MAAK,SAAU,EAAK,EAAE,CAAC,EAKpF,OAHI,EAAK,SAAW,WAClB,QAAQ,KAAK,CAAC,EAET,EAAiC,CAAW,CACrD"}
1
+ {"version":3,"file":"bootDiagnostics.js","names":["bootDiagnostics","logger","opts","consoleBootLogger","required","sensitive","publicKeys","blue","missing","k","yellow","display","key","red","maskValue","v","green","vaultEnv","vaultEnvKey","hostEnv","magenta","Right","missingList","List","Left"],"sources":["../../src/config/bootDiagnostics.ts"],"sourcesContent":["import type { Either, List as ListType, Logger } from \"functype\"\nimport { Left, List, Right } from \"functype\"\n\nimport { blue, green, magenta, red, yellow } from \"./colors\"\nimport type { ConfigSource } from \"./ConfigSource\"\nimport { consoleBootLogger } from \"./consoleBootLogger\"\nimport { maskValue } from \"./mask\"\n\nexport interface MissingKey {\n readonly key: string\n readonly required: boolean\n}\n\nexport interface BootDiagnosticsOptions {\n /** The composed `ConfigSource` to inspect. */\n readonly source: ConfigSource\n /** Keys that MUST be present. Missing required keys produce a `Left`. */\n readonly required?: readonly string[]\n /** Keys to log with masked values (via {@link maskValue}). */\n readonly sensitive?: readonly string[]\n /** Keys to log with raw values. */\n readonly public?: readonly string[]\n /**\n * If provided with `vaultEnvKey`, compares the host environment string\n * (e.g. `process.env.NODE_ENV`) against the value at `vaultEnvKey` in the\n * source. Logs `✓` on match, an error-level message on mismatch.\n */\n readonly hostEnv?: string\n readonly vaultEnvKey?: string\n /**\n * `\"missing\"` triggers `process.exit(1)` after logging when any required key\n * is missing. `\"never\"` (default) returns `Left(missing)` and lets the caller\n * decide. Set to `\"missing\"` in production / staging boot paths to guarantee\n * fail-fast on misconfiguration.\n */\n readonly failOn?: \"missing\" | \"never\"\n /**\n * Logger to use. Defaults to {@link consoleBootLogger}. Any value satisfying\n * the core `Logger` interface from `functype` — including `DirectLogger`\n * from `functype-log/direct` — works without an adapter.\n */\n readonly logger?: Logger\n /** Service identifier shown in the diagnostics header. */\n readonly serviceName?: string\n}\n\n/**\n * Log a standardized boot diagnostics block and verify required-key presence.\n *\n * The block always emits, regardless of outcome — operational visibility (\"did\n * the deploy pick up my config?\") is the point. Sensitive keys are masked;\n * public keys are logged verbatim. An optional host-vs-vault env-mismatch\n * check catches the common deploy footgun where the host's `NODE_ENV` and the\n * vault's `ENV` (or equivalent) diverge.\n *\n * Returns `Either<List<MissingKey>, void>` so non-fatal callers can inspect\n * the result. Setting `failOn: \"missing\"` short-circuits to `process.exit(1)`\n * for production guards.\n *\n * @example\n * ```ts\n * const result = bootDiagnostics({\n * serviceName: \"cq-api\",\n * source: Layered([ProcessEnvSource(), await InfisicalSource(...)]),\n * required: [\"SUPABASE_URL\", \"SUPABASE_KEY\", \"OPENAI_API_KEY\"],\n * sensitive: [\"SUPABASE_URL\", \"SUPABASE_KEY\", \"OPENAI_API_KEY\"],\n * public: [\"ENV\", \"ENABLE_CHAT\"],\n * hostEnv: process.env.NODE_ENV ?? \"local\",\n * vaultEnvKey: \"ENV\",\n * failOn: process.env.NODE_ENV === \"production\" ? \"missing\" : \"never\",\n * })\n * ```\n */\nexport const bootDiagnostics = (opts: BootDiagnosticsOptions): Either<ListType<MissingKey>, void> => {\n const logger = opts.logger ?? consoleBootLogger\n const required = opts.required ?? []\n const sensitive = opts.sensitive ?? []\n const publicKeys = opts.public ?? []\n\n logger.info(`${blue(\"📦\")} Boot diagnostics: ${opts.serviceName ?? \"service\"}`)\n logger.info(` source: ${opts.source.name}`)\n\n const missing = required.filter((k) => opts.source.get(k).isEmpty)\n\n if (sensitive.length > 0) {\n logger.info(yellow(\"🔐 Sensitive:\"))\n sensitive.forEach((key) => {\n const value = opts.source.get(key)\n const display = value.fold(\n () => red(\"NOT_LOADED\"),\n (v) => maskValue(v),\n )\n logger.info(` ${key.padEnd(28)} ${display}`)\n })\n }\n\n if (publicKeys.length > 0) {\n logger.info(green(\"⚙️ Public:\"))\n publicKeys.forEach((key) => {\n const value = opts.source.get(key)\n const display = value.fold(\n () => red(\"NOT_LOADED\"),\n (v) => v,\n )\n logger.info(` ${key.padEnd(28)} ${display}`)\n })\n }\n\n if (opts.hostEnv !== undefined && opts.vaultEnvKey !== undefined) {\n const vaultEnv = opts.source.get(opts.vaultEnvKey)\n const { hostEnv } = opts\n const { vaultEnvKey } = opts\n vaultEnv.fold(\n () => {\n logger.warn(`Vault env key '${vaultEnvKey}' not present — skipping mismatch check`)\n return undefined\n },\n (v) => {\n if (v === hostEnv) {\n logger.info(`${magenta(\"🌍\")} Environment: ${hostEnv} (host) ↔ ${v} (vault) ${green(\"✓\")}`)\n } else {\n logger.error(`${magenta(\"🌍\")} Environment MISMATCH: host=${hostEnv} vault=${v}`, {\n hostEnv,\n vaultEnv: v,\n })\n }\n return undefined\n },\n )\n }\n\n if (missing.length === 0) {\n logger.info(green(\"✅ All required keys present\"))\n return Right<ListType<MissingKey>, void>(undefined)\n }\n\n logger.error(red(`❌ Missing required keys (${missing.length}):`))\n missing.forEach((key) => logger.error(` ${key}`))\n\n const missingList = List(missing.map((key): MissingKey => ({ key, required: true })))\n\n if (opts.failOn === \"missing\") {\n process.exit(1)\n }\n return Left<ListType<MissingKey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,YAAYJ,EAAE,WAAWC,EAAM,GAAG,GAAG,EAE1Ff,EAAO,MAAM,GAAGmB,EAAQ,IAAI,EAAE,8BAA8BD,EAAQ,SAASJ,IAAK,CAChF,UACA,SAAUA,CACZ,CAAC,CAGL,CACF,CACF,CAEA,GAAIP,EAAQ,SAAW,EAErB,OADAP,EAAO,KAAKe,EAAM,6BAA6B,CAAC,EACzCK,EAAkC,IAAA,EAAS,EAGpDpB,EAAO,MAAMY,EAAI,4BAA4BL,EAAQ,OAAO,GAAG,CAAC,EAChEA,EAAQ,QAAS,GAAQP,EAAO,MAAM,MAAMW,GAAK,CAAC,EAElD,IAAMU,EAAcC,EAAKf,EAAQ,IAAK,IAAqB,CAAE,MAAK,SAAU,EAAK,EAAE,CAAC,EAKpF,OAHIN,EAAK,SAAW,WAClB,QAAQ,KAAK,CAAC,EAETsB,EAAiCF,CAAW,CACrD"}
@@ -13,13 +13,12 @@
13
13
  *
14
14
  * @internal — not re-exported from the package barrel.
15
15
  */
16
- declare const red: (s: string) => string;
17
- declare const green: (s: string) => string;
18
- declare const yellow: (s: string) => string;
19
- declare const blue: (s: string) => string;
20
- declare const magenta: (s: string) => string;
21
- declare const cyan: (s: string) => string;
22
- declare const gray: (s: string) => string;
16
+ export declare const red: (s: string) => string;
17
+ export declare const green: (s: string) => string;
18
+ export declare const yellow: (s: string) => string;
19
+ export declare const blue: (s: string) => string;
20
+ export declare const magenta: (s: string) => string;
21
+ export declare const cyan: (s: string) => string;
22
+ export declare const gray: (s: string) => string;
23
23
  //#endregion
24
- export { blue, cyan, gray, green, magenta, red, yellow };
25
24
  //# sourceMappingURL=colors.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"colors.js","names":[],"sources":["../../src/config/colors.ts"],"sourcesContent":["/**\n * Internal raw-ANSI color helpers for boot diagnostics output.\n *\n * Respects established conventions:\n * - `NO_COLOR=1` (any value) → output uncolored, regardless of TTY. See\n * https://no-color.org/.\n * - `FORCE_COLOR=1` (any value) → output colored, regardless of TTY. Useful\n * for CI logs that pipe stdout but want the colors preserved.\n * - Default: color when `process.stdout.isTTY`, plain otherwise.\n *\n * Zero deps. ANSI escape codes haven't changed since 1979.\n *\n * @internal — not re-exported from the package barrel.\n */\n\nconst shouldColor = (): boolean => {\n if (process.env.NO_COLOR !== undefined) return false\n if (process.env.FORCE_COLOR !== undefined) return true\n return process.stdout.isTTY\n}\n\nconst wrap =\n (code: string) =>\n (s: string): string =>\n shouldColor() ? `\\x1b[${code}m${s}\\x1b[0m` : s\n\nexport const red = wrap(\"31\")\nexport const green = wrap(\"32\")\nexport const yellow = wrap(\"33\")\nexport const blue = wrap(\"34\")\nexport const magenta = wrap(\"35\")\nexport const cyan = wrap(\"36\")\nexport const gray = wrap(\"90\")\n"],"mappings":"AAeA,MAAM,MACA,QAAQ,IAAI,WAAa,IAAA,GACzB,QAAQ,IAAI,cAAgB,IAAA,IACzB,QAAQ,OAAO,MAFyB,GAK3C,EACH,GACA,GACC,EAAY,EAAI,QAAQ,EAAK,GAAG,EAAE,SAAW,EAEpC,EAAM,EAAK,IAAI,EACf,EAAQ,EAAK,IAAI,EACjB,EAAS,EAAK,IAAI,EAClB,EAAO,EAAK,IAAI,EAChB,EAAU,EAAK,IAAI,EACnB,EAAO,EAAK,IAAI,EAChB,EAAO,EAAK,IAAI"}
1
+ {"version":3,"file":"colors.js","names":["shouldColor","wrap","code","s","red","green","yellow","blue","magenta","cyan","gray"],"sources":["../../src/config/colors.ts"],"sourcesContent":["/**\n * Internal raw-ANSI color helpers for boot diagnostics output.\n *\n * Respects established conventions:\n * - `NO_COLOR=1` (any value) → output uncolored, regardless of TTY. See\n * https://no-color.org/.\n * - `FORCE_COLOR=1` (any value) → output colored, regardless of TTY. Useful\n * for CI logs that pipe stdout but want the colors preserved.\n * - Default: color when `process.stdout.isTTY`, plain otherwise.\n *\n * Zero deps. ANSI escape codes haven't changed since 1979.\n *\n * @internal — not re-exported from the package barrel.\n */\n\nconst shouldColor = (): boolean => {\n if (process.env.NO_COLOR !== undefined) return false\n if (process.env.FORCE_COLOR !== undefined) return true\n return process.stdout.isTTY\n}\n\nconst wrap =\n (code: string) =>\n (s: string): string =>\n shouldColor() ? `\\x1b[${code}m${s}\\x1b[0m` : s\n\nexport const red = wrap(\"31\")\nexport const green = wrap(\"32\")\nexport const yellow = wrap(\"33\")\nexport const blue = wrap(\"34\")\nexport const magenta = wrap(\"35\")\nexport const cyan = wrap(\"36\")\nexport const gray = wrap(\"90\")\n"],"mappings":"AAeA,MAAMA,MACA,QAAQ,IAAI,WAAa,IAAA,GACzB,QAAQ,IAAI,cAAgB,IAAA,IACzB,QAAQ,OAAO,MAFyB,GAK3CC,EACH,GACA,GACCD,EAAY,EAAI,QAAQE,EAAK,GAAGC,EAAE,SAAWA,EAEpCC,EAAMH,EAAK,IAAI,EACfI,EAAQJ,EAAK,IAAI,EACjBK,EAASL,EAAK,IAAI,EAClBM,EAAON,EAAK,IAAI,EAChBO,EAAUP,EAAK,IAAI,EACnBQ,EAAOR,EAAK,IAAI,EAChBS,EAAOT,EAAK,IAAI"}
@@ -1,2 +1,2 @@
1
- import{gray as e,red as t,yellow as n}from"./colors.js";const r=()=>new Date().toISOString(),i={debug:(t,n)=>console.debug(`${e(r())} ${e(`DEBUG`)} ${t}`,n??``),info:(t,n)=>console.log(`${e(r())} ${t}`,n??``),warn:(t,i)=>console.warn(`${e(r())} ${n(`WARN`)} ${t}`,i??``),error:(n,i)=>console.error(`${e(r())} ${t(`ERROR`)} ${n}`,i??``)};export{i as consoleBootLogger};
1
+ import{gray as e,red as t,yellow as n}from"./colors.js";const r=()=>(/* @__PURE__ */ new Date()).toISOString(),i={debug:(t,n)=>console.debug(`${e(r())} ${e(`DEBUG`)} ${t}`,n??``),info:(t,n)=>console.log(`${e(r())} ${t}`,n??``),warn:(t,i)=>console.warn(`${e(r())} ${n(`WARN`)} ${t}`,i??``),error:(n,i)=>console.error(`${e(r())} ${t(`ERROR`)} ${n}`,i??``)};export{i as consoleBootLogger};
2
2
  //# sourceMappingURL=consoleBootLogger.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"consoleBootLogger.js","names":[],"sources":["../../src/config/consoleBootLogger.ts"],"sourcesContent":["import type { Logger } from \"functype\"\n\nimport { gray, red, yellow } from \"./colors\"\n\nconst stamp = (): string => new Date().toISOString()\n\n/**\n * Default `Logger` impl for boot diagnostics — zero-dep, raw ANSI colors,\n * NO_COLOR / FORCE_COLOR / isTTY-respecting.\n *\n * All 4 methods of core `Logger` are present (debug included). For consumers\n * already using `functype-log`, pass `createDirectConsoleLogger()` from\n * `functype-log/direct` directly — its `DirectLogger` structurally satisfies\n * core `Logger` (no adapter required).\n *\n * @example\n * ```ts\n * import { bootDiagnostics, consoleBootLogger } from \"functype-os/config\"\n *\n * await bootDiagnostics({ source, required, logger: consoleBootLogger })\n * // (logger defaults to consoleBootLogger anyway — passed explicitly here\n * // to show the swap point for `createDirectConsoleLogger()` etc.)\n * ```\n */\nexport const consoleBootLogger: Logger = {\n debug: (msg, meta) => console.debug(`${gray(stamp())} ${gray(\"DEBUG\")} ${msg}`, meta ?? \"\"),\n info: (msg, meta) => console.log(`${gray(stamp())} ${msg}`, meta ?? \"\"),\n warn: (msg, meta) => console.warn(`${gray(stamp())} ${yellow(\"WARN\")} ${msg}`, meta ?? \"\"),\n error: (msg, meta) => console.error(`${gray(stamp())} ${red(\"ERROR\")} ${msg}`, meta ?? \"\"),\n}\n"],"mappings":"wDAIA,MAAM,MAAsB,IAAI,KAAK,CAAA,CAAE,YAAY,EAoBtC,EAA4B,CACvC,OAAQ,EAAK,IAAS,QAAQ,MAAM,GAAG,EAAK,EAAM,CAAC,EAAE,GAAG,EAAK,OAAO,EAAE,GAAG,IAAO,GAAQ,EAAE,EAC1F,MAAO,EAAK,IAAS,QAAQ,IAAI,GAAG,EAAK,EAAM,CAAC,EAAE,GAAG,IAAO,GAAQ,EAAE,EACtE,MAAO,EAAK,IAAS,QAAQ,KAAK,GAAG,EAAK,EAAM,CAAC,EAAE,GAAG,EAAO,MAAM,EAAE,GAAG,IAAO,GAAQ,EAAE,EACzF,OAAQ,EAAK,IAAS,QAAQ,MAAM,GAAG,EAAK,EAAM,CAAC,EAAE,GAAG,EAAI,OAAO,EAAE,GAAG,IAAO,GAAQ,EAAE,CAC3F"}
1
+ {"version":3,"file":"consoleBootLogger.js","names":["stamp","consoleBootLogger","gray","msg","meta","yellow","red"],"sources":["../../src/config/consoleBootLogger.ts"],"sourcesContent":["import type { Logger } from \"functype\"\n\nimport { gray, red, yellow } from \"./colors\"\n\nconst stamp = (): string => new Date().toISOString()\n\n/**\n * Default `Logger` impl for boot diagnostics — zero-dep, raw ANSI colors,\n * NO_COLOR / FORCE_COLOR / isTTY-respecting.\n *\n * All 4 methods of core `Logger` are present (debug included). For consumers\n * already using `functype-log`, pass `createDirectConsoleLogger()` from\n * `functype-log/direct` directly — its `DirectLogger` structurally satisfies\n * core `Logger` (no adapter required).\n *\n * @example\n * ```ts\n * import { bootDiagnostics, consoleBootLogger } from \"functype-os/config\"\n *\n * await bootDiagnostics({ source, required, logger: consoleBootLogger })\n * // (logger defaults to consoleBootLogger anyway — passed explicitly here\n * // to show the swap point for `createDirectConsoleLogger()` etc.)\n * ```\n */\nexport const consoleBootLogger: Logger = {\n debug: (msg, meta) => console.debug(`${gray(stamp())} ${gray(\"DEBUG\")} ${msg}`, meta ?? \"\"),\n info: (msg, meta) => console.log(`${gray(stamp())} ${msg}`, meta ?? \"\"),\n warn: (msg, meta) => console.warn(`${gray(stamp())} ${yellow(\"WARN\")} ${msg}`, meta ?? \"\"),\n error: (msg, meta) => console.error(`${gray(stamp())} ${red(\"ERROR\")} ${msg}`, meta ?? \"\"),\n}\n"],"mappings":"wDAIA,MAAMA,uBAAsB,IAAI,KAAK,EAAA,CAAE,YAAY,EAoBtCC,EAA4B,CACvC,OAAQ,EAAK,IAAS,QAAQ,MAAM,GAAGC,EAAKF,EAAM,CAAC,EAAE,GAAGE,EAAK,OAAO,EAAE,GAAGC,IAAOC,GAAQ,EAAE,EAC1F,MAAO,EAAK,IAAS,QAAQ,IAAI,GAAGF,EAAKF,EAAM,CAAC,EAAE,GAAGG,IAAOC,GAAQ,EAAE,EACtE,MAAO,EAAK,IAAS,QAAQ,KAAK,GAAGF,EAAKF,EAAM,CAAC,EAAE,GAAGK,EAAO,MAAM,EAAE,GAAGF,IAAOC,GAAQ,EAAE,EACzF,OAAQ,EAAK,IAAS,QAAQ,MAAM,GAAGF,EAAKF,EAAM,CAAC,EAAE,GAAGM,EAAI,OAAO,EAAE,GAAGH,IAAOC,GAAQ,EAAE,CAC3F"}
@@ -1 +1 @@
1
- {"version":3,"file":"mask.js","names":[],"sources":["../../src/config/mask.ts"],"sourcesContent":["/**\n * Mask a sensitive value for display in boot diagnostics or logs.\n *\n * - Values ≤ 8 characters become `****` (no leakage of length or characters).\n * - Longer values become `ab****yz` — first two and last two characters\n * preserved so an operator can confirm which secret loaded without\n * exposing the bulk of it.\n *\n * Exported from `functype-os/config` for ad-hoc masking outside\n * `bootDiagnostics`.\n *\n * @example\n * ```ts\n * maskValue(\"short\") // \"****\"\n * maskValue(\"supersecretvalue\") // \"su****ue\"\n * ```\n */\nexport const maskValue = (value: string): string => {\n if (value.length <= 8) return \"****\"\n return `${value.slice(0, 2)}****${value.slice(-2)}`\n}\n"],"mappings":"AAiBA,MAAa,EAAa,GACpB,EAAM,QAAU,EAAU,OACvB,GAAG,EAAM,MAAM,EAAG,CAAC,EAAE,MAAM,EAAM,MAAM,EAAE"}
1
+ {"version":3,"file":"mask.js","names":["maskValue","value"],"sources":["../../src/config/mask.ts"],"sourcesContent":["/**\n * Mask a sensitive value for display in boot diagnostics or logs.\n *\n * - Values ≤ 8 characters become `****` (no leakage of length or characters).\n * - Longer values become `ab****yz` — first two and last two characters\n * preserved so an operator can confirm which secret loaded without\n * exposing the bulk of it.\n *\n * Exported from `functype-os/config` for ad-hoc masking outside\n * `bootDiagnostics`.\n *\n * @example\n * ```ts\n * maskValue(\"short\") // \"****\"\n * maskValue(\"supersecretvalue\") // \"su****ue\"\n * ```\n */\nexport const maskValue = (value: string): string => {\n if (value.length <= 8) return \"****\"\n return `${value.slice(0, 2)}****${value.slice(-2)}`\n}\n"],"mappings":"AAiBA,MAAaA,EAAa,GACpBC,EAAM,QAAU,EAAU,OACvB,GAAGA,EAAM,MAAM,EAAG,CAAC,EAAE,MAAMA,EAAM,MAAM,EAAE"}
package/dist/env/Env.js CHANGED
@@ -1,2 +1,2 @@
1
- import{EnvError as e}from"../errors/errors.js";import{Left as t,List as n,Option as r,Right as i,Try as a}from"functype";const o=Object.assign(e=>r(process.env[e]),{get:e=>r(process.env[e]),getRequired:t=>r(process.env[t]).toEither(e(t)),getOrDefault:(e,t)=>process.env[e]??t,has:e=>process.env[e]!==void 0,entries:()=>n(Object.entries(process.env).filter(e=>e[1]!==void 0).map(([e,t])=>[e,t])),parse:(n,o)=>{let s=r(process.env[n]);if(s.isEmpty)return t(e(n));let c=s.orThrow();return a(()=>o(c)).toEither(t=>e(n,`Failed to parse '${n}': ${t instanceof Error?t.message:String(t)}`)).flatMap(r=>typeof r==`number`&&isNaN(r)?t(e(n,`Cannot parse '${c}' as number for '${n}'`)):i(r))}});export{o as Env};
1
+ import{EnvError as e}from"../errors/errors.js";import{Left as t,List as n,Option as r,Right as i,Try as a}from"functype";const o=Object.assign(e=>r(process.env[e]),{get:e=>r(process.env[e]),getRequired:t=>r(process.env[t]).toEither(e(t)),getOrDefault:(e,t)=>process.env[e]??t,has:e=>process.env[e]!==void 0,entries:()=>{let e=Object.entries(process.env).filter(e=>e[1]!==void 0).map(([e,t])=>[e,t]);return n(e)},parse:(n,o)=>{let s=r(process.env[n]);if(s.isEmpty)return t(e(n));let c=s.orThrow();return a(()=>o(c)).toEither(t=>e(n,`Failed to parse '${n}': ${t instanceof Error?t.message:String(t)}`)).flatMap(r=>typeof r==`number`&&isNaN(r)?t(e(n,`Cannot parse '${c}' as number for '${n}'`)):i(r))}});export{o as Env};
2
2
  //# sourceMappingURL=Env.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Env.js","names":[],"sources":["../../src/env/Env.ts"],"sourcesContent":["import type { Either } from \"functype\"\nimport { Left, List, Option, Right, Try } from \"functype\"\n\nimport { EnvError } from \"../errors/errors\"\n\nconst EnvConstructor = (name: string): Option<string> => Option(process.env[name])\n\nconst EnvCompanion = {\n get: (name: string): Option<string> => Option(process.env[name]),\n\n getRequired: (name: string): Either<EnvError, string> => Option(process.env[name]).toEither(EnvError(name)),\n\n getOrDefault: (name: string, defaultValue: string): string => process.env[name] ?? defaultValue,\n\n has: (name: string): boolean => process.env[name] !== undefined,\n\n entries: (): List<readonly [string, string]> => {\n const pairs: Readonly<Array<readonly [string, string]>> = Object.entries(process.env)\n .filter((entry): entry is [string, string] => entry[1] !== undefined)\n .map(([k, v]) => [k, v] as const)\n return List(pairs)\n },\n\n parse: <T>(name: string, parser: (value: string) => T): Either<EnvError, T> => {\n const valueOpt = Option(process.env[name])\n if (valueOpt.isEmpty) return Left(EnvError(name))\n const value = valueOpt.orThrow()\n const parsed = Try(() => parser(value)).toEither((error) =>\n EnvError(name, `Failed to parse '${name}': ${error instanceof Error ? error.message : String(error)}`),\n )\n return parsed.flatMap((p) =>\n typeof p === \"number\" && isNaN(p)\n ? Left(EnvError(name, `Cannot parse '${value}' as number for '${name}'`))\n : Right(p),\n )\n },\n}\n\nexport const Env: typeof EnvConstructor & typeof EnvCompanion = Object.assign(EnvConstructor, EnvCompanion)\n"],"mappings":"yHAsCA,MAAa,EAAmD,OAAO,OAjC/C,GAAiC,EAAO,QAAQ,IAAI,EAAK,EAiCa,CA9B5F,IAAM,GAAiC,EAAO,QAAQ,IAAI,EAAK,EAE/D,YAAc,GAA2C,EAAO,QAAQ,IAAI,EAAK,CAAC,CAAC,SAAS,EAAS,CAAI,CAAC,EAE1G,cAAe,EAAc,IAAiC,QAAQ,IAAI,IAAS,EAEnF,IAAM,GAA0B,QAAQ,IAAI,KAAU,IAAA,GAEtD,YAIS,EAHmD,OAAO,QAAQ,QAAQ,GAAG,CAAC,CAClF,OAAQ,GAAqC,EAAM,KAAO,IAAA,EAAS,CAAC,CACpE,KAAK,CAAC,EAAG,KAAO,CAAC,EAAG,CAAC,CACR,CAAC,EAGnB,OAAW,EAAc,IAAsD,CAC7E,IAAM,EAAW,EAAO,QAAQ,IAAI,EAAK,EACzC,GAAI,EAAS,QAAS,OAAO,EAAK,EAAS,CAAI,CAAC,EAChD,IAAM,EAAQ,EAAS,QAAQ,EAI/B,OAHe,MAAU,EAAO,CAAK,CAAC,CAAC,CAAC,SAAU,GAChD,EAAS,EAAM,oBAAoB,EAAK,KAAK,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,GAAG,CAE3F,CAAC,CAAC,QAAS,GACrB,OAAO,GAAM,UAAY,MAAM,CAAC,EAC5B,EAAK,EAAS,EAAM,iBAAiB,EAAM,mBAAmB,EAAK,EAAE,CAAC,EACtE,EAAM,CAAC,CACb,CACF,CAG4F,CAAY"}
1
+ {"version":3,"file":"Env.js","names":["Env","Option","name","EnvError","defaultValue","pairs","entry","k","v","List","valueOpt","Left","value","Try","parser","error","p","Right"],"sources":["../../src/env/Env.ts"],"sourcesContent":["import type { Either } from \"functype\"\nimport { Left, List, Option, Right, Try } from \"functype\"\n\nimport { EnvError } from \"../errors/errors\"\n\nconst EnvConstructor = (name: string): Option<string> => Option(process.env[name])\n\nconst EnvCompanion = {\n get: (name: string): Option<string> => Option(process.env[name]),\n\n getRequired: (name: string): Either<EnvError, string> => Option(process.env[name]).toEither(EnvError(name)),\n\n getOrDefault: (name: string, defaultValue: string): string => process.env[name] ?? defaultValue,\n\n has: (name: string): boolean => process.env[name] !== undefined,\n\n entries: (): List<readonly [string, string]> => {\n const pairs: Readonly<Array<readonly [string, string]>> = Object.entries(process.env)\n .filter((entry): entry is [string, string] => entry[1] !== undefined)\n .map(([k, v]) => [k, v] as const)\n return List(pairs)\n },\n\n parse: <T>(name: string, parser: (value: string) => T): Either<EnvError, T> => {\n const valueOpt = Option(process.env[name])\n if (valueOpt.isEmpty) return Left(EnvError(name))\n const value = valueOpt.orThrow()\n const parsed = Try(() => parser(value)).toEither((error) =>\n EnvError(name, `Failed to parse '${name}': ${error instanceof Error ? error.message : String(error)}`),\n )\n return parsed.flatMap((p) =>\n typeof p === \"number\" && isNaN(p)\n ? Left(EnvError(name, `Cannot parse '${value}' as number for '${name}'`))\n : Right(p),\n )\n },\n}\n\nexport const Env: typeof EnvConstructor & typeof EnvCompanion = Object.assign(EnvConstructor, EnvCompanion)\n"],"mappings":"yHAsCA,MAAaA,EAAmD,OAAO,OAjC/C,GAAiCC,EAAO,QAAQ,IAAIC,EAAK,EAiCa,CA9B5F,IAAM,GAAiCD,EAAO,QAAQ,IAAIC,EAAK,EAE/D,YAAc,GAA2CD,EAAO,QAAQ,IAAIC,EAAK,CAAC,CAAC,SAASC,EAASD,CAAI,CAAC,EAE1G,cAAe,EAAc,IAAiC,QAAQ,IAAIA,IAASE,EAEnF,IAAM,GAA0B,QAAQ,IAAIF,KAAU,IAAA,GAEtD,YAAgD,CAC9C,IAAMG,EAAoD,OAAO,QAAQ,QAAQ,GAAG,CAAC,CAClF,OAAQ,GAAqCC,EAAM,KAAO,IAAA,EAAS,CAAC,CACpE,KAAK,CAACC,EAAGC,KAAO,CAACD,EAAGC,CAAC,CAAU,EAClC,OAAOC,EAAKJ,CAAK,CACnB,EAEA,OAAW,EAAc,IAAsD,CAC7E,IAAMK,EAAWT,EAAO,QAAQ,IAAIC,EAAK,EACzC,GAAIQ,EAAS,QAAS,OAAOC,EAAKR,EAASD,CAAI,CAAC,EAChD,IAAMU,EAAQF,EAAS,QAAQ,EAI/B,OAHeG,MAAUC,EAAOF,CAAK,CAAC,CAAC,CAAC,SAAU,GAChDT,EAASD,EAAM,oBAAoBA,EAAK,KAAKa,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,GAAG,CAE3F,CAAC,CAAC,QAAS,GACrB,OAAOC,GAAM,UAAY,MAAMA,CAAC,EAC5BL,EAAKR,EAASD,EAAM,iBAAiBU,EAAM,mBAAmBV,EAAK,EAAE,CAAC,EACtEe,EAAMD,CAAC,CACb,CACF,CAG4F,CAAY"}
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","names":[],"sources":["../../src/errors/errors.ts"],"sourcesContent":["import type { Option } from \"functype\"\n\nexport type EnvError = {\n readonly _tag: \"EnvError\"\n readonly variable: string\n readonly message: string\n}\n\nexport type PathError = {\n readonly _tag: \"PathError\"\n readonly path: string\n readonly reason: \"unresolved_variable\" | \"invalid_path\"\n readonly message: string\n}\n\nexport type FsError = {\n readonly _tag: \"FsError\"\n readonly path: string\n readonly operation: string\n readonly cause: Error\n readonly message: string\n}\n\nexport type ConfigError = {\n readonly _tag: \"ConfigError\"\n readonly candidates: readonly string[]\n readonly message: string\n}\n\nexport type ProcessError = {\n readonly _tag: \"ProcessError\"\n readonly command: string\n readonly exitCode: Option<number>\n readonly stderr: string\n readonly message: string\n}\n\nexport type OsError = EnvError | PathError | FsError | ConfigError | ProcessError\n\nexport const EnvError = (variable: string, message?: string): EnvError => ({\n _tag: \"EnvError\",\n variable,\n message: message ?? `Environment variable '${variable}' is not set`,\n})\n\nexport const PathError = (path: string, reason: PathError[\"reason\"], message?: string): PathError => ({\n _tag: \"PathError\",\n path,\n reason,\n message:\n message ?? (reason === \"unresolved_variable\" ? `Unresolved variable in path: ${path}` : `Invalid path: ${path}`),\n})\n\nexport const FsError = (path: string, operation: string, cause: Error): FsError => ({\n _tag: \"FsError\",\n path,\n operation,\n cause,\n message: `${operation} failed for '${path}': ${cause.message}`,\n})\n\nexport const ConfigError = (candidates: readonly string[], message?: string): ConfigError => ({\n _tag: \"ConfigError\",\n candidates,\n message: message ?? `No config file found among candidates: ${candidates.join(\", \")}`,\n})\n\nexport const ProcessError = (\n command: string,\n exitCode: Option<number>,\n stderr: string,\n message?: string,\n): ProcessError => ({\n _tag: \"ProcessError\",\n command,\n exitCode,\n stderr,\n message: message ?? `Command '${command}' failed (exit ${exitCode.fold(() => \"?\", String)}): ${stderr}`,\n})\n"],"mappings":"AAuCA,MAAa,GAAY,EAAkB,KAAgC,CACzE,KAAM,WACN,WACA,QAAS,GAAW,yBAAyB,EAAS,aACxD,GAEa,GAAa,EAAc,EAA6B,KAAiC,CACpG,KAAM,YACN,OACA,SACA,QACE,IAAY,IAAW,sBAAwB,gCAAgC,IAAS,iBAAiB,IAC7G,GAEa,GAAW,EAAc,EAAmB,KAA2B,CAClF,KAAM,UACN,OACA,YACA,QACA,QAAS,GAAG,EAAU,eAAe,EAAK,KAAK,EAAM,SACvD,GAEa,GAAe,EAA+B,KAAmC,CAC5F,KAAM,cACN,aACA,QAAS,GAAW,0CAA0C,EAAW,KAAK,IAAI,GACpF,GAEa,GACX,EACA,EACA,EACA,KACkB,CAClB,KAAM,eACN,UACA,WACA,SACA,QAAS,GAAW,YAAY,EAAQ,iBAAiB,EAAS,SAAW,IAAK,MAAM,EAAE,KAAK,GACjG"}
1
+ {"version":3,"file":"errors.js","names":["EnvError","message","variable","PathError","reason","path","FsError","operation","cause","ConfigError","candidates","ProcessError","command","exitCode","stderr"],"sources":["../../src/errors/errors.ts"],"sourcesContent":["import type { Option } from \"functype\"\n\nexport type EnvError = {\n readonly _tag: \"EnvError\"\n readonly variable: string\n readonly message: string\n}\n\nexport type PathError = {\n readonly _tag: \"PathError\"\n readonly path: string\n readonly reason: \"unresolved_variable\" | \"invalid_path\"\n readonly message: string\n}\n\nexport type FsError = {\n readonly _tag: \"FsError\"\n readonly path: string\n readonly operation: string\n readonly cause: Error\n readonly message: string\n}\n\nexport type ConfigError = {\n readonly _tag: \"ConfigError\"\n readonly candidates: readonly string[]\n readonly message: string\n}\n\nexport type ProcessError = {\n readonly _tag: \"ProcessError\"\n readonly command: string\n readonly exitCode: Option<number>\n readonly stderr: string\n readonly message: string\n}\n\nexport type OsError = EnvError | PathError | FsError | ConfigError | ProcessError\n\nexport const EnvError = (variable: string, message?: string): EnvError => ({\n _tag: \"EnvError\",\n variable,\n message: message ?? `Environment variable '${variable}' is not set`,\n})\n\nexport const PathError = (path: string, reason: PathError[\"reason\"], message?: string): PathError => ({\n _tag: \"PathError\",\n path,\n reason,\n message:\n message ?? (reason === \"unresolved_variable\" ? `Unresolved variable in path: ${path}` : `Invalid path: ${path}`),\n})\n\nexport const FsError = (path: string, operation: string, cause: Error): FsError => ({\n _tag: \"FsError\",\n path,\n operation,\n cause,\n message: `${operation} failed for '${path}': ${cause.message}`,\n})\n\nexport const ConfigError = (candidates: readonly string[], message?: string): ConfigError => ({\n _tag: \"ConfigError\",\n candidates,\n message: message ?? `No config file found among candidates: ${candidates.join(\", \")}`,\n})\n\nexport const ProcessError = (\n command: string,\n exitCode: Option<number>,\n stderr: string,\n message?: string,\n): ProcessError => ({\n _tag: \"ProcessError\",\n command,\n exitCode,\n stderr,\n message: message ?? `Command '${command}' failed (exit ${exitCode.fold(() => \"?\", String)}): ${stderr}`,\n})\n"],"mappings":"AAuCA,MAAaA,GAAY,EAAkB,KAAgC,CACzE,KAAM,WACN,WACA,QAASC,GAAW,yBAAyBC,EAAS,aACxD,GAEaC,GAAa,EAAc,EAA6B,KAAiC,CACpG,KAAM,YACN,OACA,SACA,QACEF,IAAYG,IAAW,sBAAwB,gCAAgCC,IAAS,iBAAiBA,IAC7G,GAEaC,GAAW,EAAc,EAAmB,KAA2B,CAClF,KAAM,UACN,OACA,YACA,QACA,QAAS,GAAGC,EAAU,eAAeF,EAAK,KAAKG,EAAM,SACvD,GAEaC,GAAe,EAA+B,KAAmC,CAC5F,KAAM,cACN,aACA,QAASR,GAAW,0CAA0CS,EAAW,KAAK,IAAI,GACpF,GAEaC,GACX,EACA,EACA,EACA,KACkB,CAClB,KAAM,eACN,UACA,WACA,SACA,QAASV,GAAW,YAAYW,EAAQ,iBAAiBC,EAAS,SAAW,IAAK,MAAM,EAAE,KAAKC,GACjG"}
package/dist/fs/Fs.js CHANGED
@@ -1,2 +1,2 @@
1
- import{FsError as e}from"../errors/errors.js";import{Err as t,Left as n,List as r,Ok as i,Option as a,Right as o,Try as s}from"functype";import*as c from"node:fs";import*as l from"node:fs/promises";const u=e=>({size:e.size,isFile:e.isFile(),isDirectory:e.isDirectory(),isSymbolicLink:e.isSymbolicLink(),createdAt:e.birthtime,modifiedAt:e.mtime,accessedAt:e.atime,permissions:e.mode}),d=(t,n,r)=>e(t,n,r instanceof Error?r:Error(String(r))),f=[`/proc/`,`/sys/`,`/dev/`],p=e=>f.some(t=>e.startsWith(t)),m=(e,t)=>{let n=t.replace(/[\\^$+?.()|[\]{}]/g,`\\$&`).replace(/\*\*\//g,`{{GLOBSTAR}}`).replace(/\*\*/g,`{{GLOBSTAR}}`).replace(/\*/g,`[^/]*`).replace(/\{\{GLOBSTAR\}\}/g,`(?:.*/)?`);return RegExp(`^${n}$`).test(e)},h=async(e,n,r)=>(await s.async(r)).fold(r=>Promise.resolve(t(d(e,n,r))),e=>Promise.resolve(i(e))),g=(e,t,n)=>s(n).toEither(n=>d(e,t,n)),_={exists:async e=>i((await s.async(()=>l.access(e))).isSuccess()),readFile:(e,t=`utf8`)=>h(e,`readFile`,()=>l.readFile(e,{encoding:t})),readFileOpt:async(e,n=`utf8`)=>(await s.async(()=>l.readFile(e,{encoding:n}))).fold(n=>n instanceof Error&&`code`in n&&n.code===`ENOENT`?Promise.resolve(i(a(void 0))):Promise.resolve(t(d(e,`readFile`,n))),e=>Promise.resolve(i(a(e)))),stat:e=>h(e,`stat`,()=>l.stat(e).then(u)),copyFile:(e,t)=>h(e,`copyFile`,()=>l.copyFile(e,t)),rename:(e,t)=>h(e,`rename`,()=>l.rename(e,t)),readdir:e=>h(e,`readdir`,()=>l.readdir(e).then(e=>r(e))),glob:async(e,n)=>(await s.async(()=>l.readdir(e,{recursive:!0,encoding:`utf8`}))).fold(n=>Promise.resolve(t(d(e,`glob`,n))),e=>{let t=e.filter(e=>m(e,n));return Promise.resolve(i(r(t)))}),writeFile:(e,t,n=`utf8`)=>h(e,`writeFile`,()=>l.writeFile(e,t,{encoding:n})),appendFile:(e,t,n=`utf8`)=>h(e,`appendFile`,()=>l.appendFile(e,t,{encoding:n})),mkdir:(e,n)=>n?.recursive&&p(e)?Promise.resolve(t(d(e,`mkdir`,Error(`recursive mkdir refused under magic filesystem root (/proc, /sys, /dev)`)))):h(e,`mkdir`,()=>l.mkdir(e,n).then(()=>void 0)),unlink:e=>h(e,`unlink`,()=>l.unlink(e)),existsSync:e=>s(()=>c.accessSync(e)).isSuccess(),readFileSync:(e,t=`utf8`)=>g(e,`readFileSync`,()=>c.readFileSync(e,{encoding:t})),readFileOptSync:(e,t=`utf8`)=>s(()=>c.readFileSync(e,{encoding:t})).fold(t=>t instanceof Error&&`code`in t&&t.code===`ENOENT`?o(a(void 0)):n(d(e,`readFileOptSync`,t)),e=>o(a(e))),statSync:e=>g(e,`statSync`,()=>u(c.statSync(e))),copyFileSync:(e,t)=>g(e,`copyFileSync`,()=>c.copyFileSync(e,t)),renameSync:(e,t)=>g(e,`renameSync`,()=>c.renameSync(e,t)),readdirSync:e=>g(e,`readdirSync`,()=>r(c.readdirSync(e))),writeFileSync:(e,t,n=`utf8`)=>g(e,`writeFileSync`,()=>c.writeFileSync(e,t,{encoding:n})),appendFileSync:(e,t,n=`utf8`)=>g(e,`appendFileSync`,()=>c.appendFileSync(e,t,{encoding:n})),mkdirSync:(e,t)=>t?.recursive&&p(e)?n(d(e,`mkdirSync`,Error(`recursive mkdir refused under magic filesystem root (/proc, /sys, /dev)`))):g(e,`mkdirSync`,()=>{c.mkdirSync(e,t)}),unlinkSync:e=>g(e,`unlinkSync`,()=>c.unlinkSync(e))};export{_ as Fs};
1
+ import{FsError as e}from"../errors/errors.js";import{Err as t,Left as n,List as r,Ok as i,Option as a,Right as o,Try as s}from"functype";import*as c from"node:fs";import*as l from"node:fs/promises";const u=e=>({size:e.size,isFile:e.isFile(),isDirectory:e.isDirectory(),isSymbolicLink:e.isSymbolicLink(),createdAt:e.birthtime,modifiedAt:e.mtime,accessedAt:e.atime,permissions:e.mode}),d=(t,n,r)=>e(t,n,r instanceof Error?r:Error(String(r))),f=[`/proc/`,`/sys/`,`/dev/`],p=e=>f.some(t=>e.startsWith(t)),m=(e,t)=>{let n=t.replace(/[\\^$+?.()|[\]{}]/g,`\\$&`).replace(/\*\*\//g,`{{GLOBSTAR}}`).replace(/\*\*/g,`{{GLOBSTAR}}`).replace(/\*/g,`[^/]*`).replace(/\{\{GLOBSTAR\}\}/g,`(?:.*/)?`);return RegExp(`^${n}$`).test(e)},h=async(e,n,r)=>(await s.async(r)).fold(r=>Promise.resolve(t(d(e,n,r))),e=>Promise.resolve(i(e))),g=(e,t,n)=>s(n).toEither(n=>d(e,t,n)),_={exists:async e=>{let t=await s.async(()=>l.access(e));return i(t.isSuccess())},readFile:(e,t=`utf8`)=>h(e,`readFile`,()=>l.readFile(e,{encoding:t})),readFileOpt:async(e,n=`utf8`)=>(await s.async(()=>l.readFile(e,{encoding:n}))).fold(n=>n instanceof Error&&`code`in n&&n.code===`ENOENT`?Promise.resolve(i(a(void 0))):Promise.resolve(t(d(e,`readFile`,n))),e=>Promise.resolve(i(a(e)))),stat:e=>h(e,`stat`,()=>l.stat(e).then(u)),copyFile:(e,t)=>h(e,`copyFile`,()=>l.copyFile(e,t)),rename:(e,t)=>h(e,`rename`,()=>l.rename(e,t)),readdir:e=>h(e,`readdir`,()=>l.readdir(e).then(e=>r(e))),glob:async(e,n)=>(await s.async(()=>l.readdir(e,{recursive:!0,encoding:`utf8`}))).fold(n=>Promise.resolve(t(d(e,`glob`,n))),e=>{let t=e.filter(e=>m(e,n));return Promise.resolve(i(r(t)))}),writeFile:(e,t,n=`utf8`)=>h(e,`writeFile`,()=>l.writeFile(e,t,{encoding:n})),appendFile:(e,t,n=`utf8`)=>h(e,`appendFile`,()=>l.appendFile(e,t,{encoding:n})),mkdir:(e,n)=>n?.recursive&&p(e)?Promise.resolve(t(d(e,`mkdir`,/* @__PURE__ */ Error(`recursive mkdir refused under magic filesystem root (/proc, /sys, /dev)`)))):h(e,`mkdir`,()=>l.mkdir(e,n).then(()=>void 0)),unlink:e=>h(e,`unlink`,()=>l.unlink(e)),existsSync:e=>s(()=>c.accessSync(e)).isSuccess(),readFileSync:(e,t=`utf8`)=>g(e,`readFileSync`,()=>c.readFileSync(e,{encoding:t})),readFileOptSync:(e,t=`utf8`)=>s(()=>c.readFileSync(e,{encoding:t})).fold(t=>t instanceof Error&&`code`in t&&t.code===`ENOENT`?o(a(void 0)):n(d(e,`readFileOptSync`,t)),e=>o(a(e))),statSync:e=>g(e,`statSync`,()=>u(c.statSync(e))),copyFileSync:(e,t)=>g(e,`copyFileSync`,()=>c.copyFileSync(e,t)),renameSync:(e,t)=>g(e,`renameSync`,()=>c.renameSync(e,t)),readdirSync:e=>g(e,`readdirSync`,()=>r(c.readdirSync(e))),writeFileSync:(e,t,n=`utf8`)=>g(e,`writeFileSync`,()=>c.writeFileSync(e,t,{encoding:n})),appendFileSync:(e,t,n=`utf8`)=>g(e,`appendFileSync`,()=>c.appendFileSync(e,t,{encoding:n})),mkdirSync:(e,t)=>t?.recursive&&p(e)?n(d(e,`mkdirSync`,/* @__PURE__ */ Error(`recursive mkdir refused under magic filesystem root (/proc, /sys, /dev)`))):g(e,`mkdirSync`,()=>{c.mkdirSync(e,t)}),unlinkSync:e=>g(e,`unlinkSync`,()=>c.unlinkSync(e))};export{_ as Fs};
2
2
  //# sourceMappingURL=Fs.js.map
package/dist/fs/Fs.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"Fs.js","names":[],"sources":["../../src/fs/Fs.ts"],"sourcesContent":["import * as fsSync from \"node:fs\"\nimport * as fs from \"node:fs/promises\"\n\nimport type { Either, TaskResult } from \"functype\"\nimport { Err, Left, List, Ok, Option, Right, Try } from \"functype\"\n\nimport { FsError } from \"../errors/errors\"\n\nexport type FileInfo = {\n readonly size: number\n readonly isFile: boolean\n readonly isDirectory: boolean\n readonly isSymbolicLink: boolean\n readonly createdAt: Date\n readonly modifiedAt: Date\n readonly accessedAt: Date\n readonly permissions: number\n}\n\nconst toFileInfo = (stats: fsSync.Stats): FileInfo => ({\n size: stats.size,\n isFile: stats.isFile(),\n isDirectory: stats.isDirectory(),\n isSymbolicLink: stats.isSymbolicLink(),\n createdAt: stats.birthtime,\n modifiedAt: stats.mtime,\n accessedAt: stats.atime,\n permissions: stats.mode,\n})\n\nconst toFsError = (p: string, op: string, error: unknown): FsError =>\n FsError(p, op, error instanceof Error ? error : new Error(String(error)))\n\n/**\n * Linux magic filesystems where recursive mkdir can hang indefinitely against\n * unwritable subpaths (libuv quirk; macOS errors immediately instead).\n * Refusing recursive mkdir under these prefixes keeps `mkdir({ recursive: true })`\n * fast-failing and predictable across platforms. See issue #135.\n */\nconst MAGIC_FS_PREFIXES: ReadonlyArray<string> = [\"/proc/\", \"/sys/\", \"/dev/\"]\n\nconst isMagicFsPath = (p: string): boolean => MAGIC_FS_PREFIXES.some((prefix) => p.startsWith(prefix))\n\nconst matchGlob = (filePath: string, pattern: string): boolean => {\n // Escape every regex metachar EXCEPT '*' first, so the subsequent\n // '*' transformations are the only special characters in the output.\n // Order matters: backslashes must be escaped before any '\\\\' insertion below.\n const escaped = pattern.replace(/[\\\\^$+?.()|[\\]{}]/g, \"\\\\$&\")\n const regex = escaped\n .replace(/\\*\\*\\//g, \"{{GLOBSTAR}}\")\n .replace(/\\*\\*/g, \"{{GLOBSTAR}}\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/\\{\\{GLOBSTAR\\}\\}/g, \"(?:.*/)?\")\n return new RegExp(`^${regex}$`).test(filePath)\n}\n\n// Async helper: lift a Promise-returning thunk into TaskResult, mapping\n// rejections to FsError. Uses `Try.async(thunk)` rather than\n// `Try.fromPromise(thunk())` so synchronous throws from inside the thunk\n// (e.g. a bad encoding argument) are caught the same way async rejections\n// are — same Failure path, no unhandled-rejection escape hatch.\nconst liftAsync = async <T>(p: string, op: string, thunk: () => Promise<T>): TaskResult<T> => {\n const result = await Try.async(thunk)\n return result.fold<TaskResult<T>>(\n (err) => Promise.resolve(Err(toFsError(p, op, err))),\n (value) => Promise.resolve(Ok(value)),\n )\n}\n\n// Sync helper: run a thunk via Try and convert to Either<FsError, T>.\nconst liftSync = <T>(p: string, op: string, thunk: () => T): Either<FsError, T> =>\n Try(thunk).toEither((err) => toFsError(p, op, err))\n\nexport const Fs = {\n // Async methods — return TaskResult<T>\n\n exists: async (p: string): TaskResult<boolean> => {\n const result = await Try.async(() => fs.access(p))\n return Ok(result.isSuccess())\n },\n\n readFile: (p: string, encoding: BufferEncoding = \"utf8\"): TaskResult<string> =>\n liftAsync(p, \"readFile\", () => fs.readFile(p, { encoding })),\n\n readFileOpt: async (p: string, encoding: BufferEncoding = \"utf8\"): TaskResult<Option<string>> => {\n const result = await Try.async(() => fs.readFile(p, { encoding }))\n return result.fold<TaskResult<Option<string>>>(\n (err) => {\n if (err instanceof Error && \"code\" in err && err.code === \"ENOENT\") {\n return Promise.resolve(Ok(Option<string>(undefined)))\n }\n return Promise.resolve(Err(toFsError(p, \"readFile\", err)))\n },\n (data) => Promise.resolve(Ok(Option(data))),\n )\n },\n\n stat: (p: string): TaskResult<FileInfo> => liftAsync(p, \"stat\", () => fs.stat(p).then(toFileInfo)),\n\n copyFile: (src: string, dest: string): TaskResult<void> => liftAsync(src, \"copyFile\", () => fs.copyFile(src, dest)),\n\n rename: (oldPath: string, newPath: string): TaskResult<void> =>\n liftAsync(oldPath, \"rename\", () => fs.rename(oldPath, newPath)),\n\n readdir: (p: string): TaskResult<List<string>> =>\n liftAsync(p, \"readdir\", () => fs.readdir(p).then((entries) => List<string>(entries))),\n\n glob: async (dir: string, pattern: string): TaskResult<List<string>> => {\n const result = await Try.async(() => fs.readdir(dir, { recursive: true, encoding: \"utf8\" }))\n return result.fold<TaskResult<List<string>>>(\n (err) => Promise.resolve(Err(toFsError(dir, \"glob\", err))),\n (entries) => {\n const matched = (entries as string[]).filter((entry) => matchGlob(entry, pattern))\n return Promise.resolve(Ok(List<string>(matched)))\n },\n )\n },\n\n writeFile: (p: string, data: string, encoding: BufferEncoding = \"utf8\"): TaskResult<void> =>\n liftAsync(p, \"writeFile\", () => fs.writeFile(p, data, { encoding })),\n\n appendFile: (p: string, data: string, encoding: BufferEncoding = \"utf8\"): TaskResult<void> =>\n liftAsync(p, \"appendFile\", () => fs.appendFile(p, data, { encoding })),\n\n mkdir: (p: string, options?: { recursive?: boolean }): TaskResult<void> => {\n if (options?.recursive && isMagicFsPath(p)) {\n return Promise.resolve(\n Err(\n toFsError(p, \"mkdir\", new Error(\"recursive mkdir refused under magic filesystem root (/proc, /sys, /dev)\")),\n ),\n )\n }\n return liftAsync(p, \"mkdir\", () => fs.mkdir(p, options).then(() => undefined))\n },\n\n unlink: (p: string): TaskResult<void> => liftAsync(p, \"unlink\", () => fs.unlink(p)),\n\n // Sync methods — return Either<FsError, T>\n\n existsSync: (p: string): boolean => Try(() => fsSync.accessSync(p)).isSuccess(),\n\n readFileSync: (p: string, encoding: BufferEncoding = \"utf8\"): Either<FsError, string> =>\n liftSync(p, \"readFileSync\", () => fsSync.readFileSync(p, { encoding })),\n\n readFileOptSync: (p: string, encoding: BufferEncoding = \"utf8\"): Either<FsError, Option<string>> => {\n const tryResult = Try(() => fsSync.readFileSync(p, { encoding }))\n return tryResult.fold<Either<FsError, Option<string>>>(\n (err) => {\n if (err instanceof Error && \"code\" in err && err.code === \"ENOENT\") {\n return Right(Option<string>(undefined))\n }\n return Left(toFsError(p, \"readFileOptSync\", err))\n },\n (data) => Right(Option(data)),\n )\n },\n\n statSync: (p: string): Either<FsError, FileInfo> => liftSync(p, \"statSync\", () => toFileInfo(fsSync.statSync(p))),\n\n copyFileSync: (src: string, dest: string): Either<FsError, void> =>\n liftSync(src, \"copyFileSync\", () => fsSync.copyFileSync(src, dest)),\n\n renameSync: (oldPath: string, newPath: string): Either<FsError, void> =>\n liftSync(oldPath, \"renameSync\", () => fsSync.renameSync(oldPath, newPath)),\n\n readdirSync: (p: string): Either<FsError, List<string>> =>\n liftSync(p, \"readdirSync\", () => List(fsSync.readdirSync(p))),\n\n writeFileSync: (p: string, data: string, encoding: BufferEncoding = \"utf8\"): Either<FsError, void> =>\n liftSync(p, \"writeFileSync\", () => fsSync.writeFileSync(p, data, { encoding })),\n\n appendFileSync: (p: string, data: string, encoding: BufferEncoding = \"utf8\"): Either<FsError, void> =>\n liftSync(p, \"appendFileSync\", () => fsSync.appendFileSync(p, data, { encoding })),\n\n mkdirSync: (p: string, options?: { recursive?: boolean }): Either<FsError, void> => {\n if (options?.recursive && isMagicFsPath(p)) {\n return Left(\n toFsError(p, \"mkdirSync\", new Error(\"recursive mkdir refused under magic filesystem root (/proc, /sys, /dev)\")),\n )\n }\n return liftSync(p, \"mkdirSync\", () => {\n fsSync.mkdirSync(p, options)\n })\n },\n\n unlinkSync: (p: string): Either<FsError, void> => liftSync(p, \"unlinkSync\", () => fsSync.unlinkSync(p)),\n}\n"],"mappings":"sMAmBA,MAAM,EAAc,IAAmC,CACrD,KAAM,EAAM,KACZ,OAAQ,EAAM,OAAO,EACrB,YAAa,EAAM,YAAY,EAC/B,eAAgB,EAAM,eAAe,EACrC,UAAW,EAAM,UACjB,WAAY,EAAM,MAClB,WAAY,EAAM,MAClB,YAAa,EAAM,IACrB,GAEM,GAAa,EAAW,EAAY,IACxC,EAAQ,EAAG,EAAI,aAAiB,MAAQ,EAAY,MAAM,OAAO,CAAK,CAAC,CAAC,EAQpE,EAA2C,CAAC,SAAU,QAAS,OAAO,EAEtE,EAAiB,GAAuB,EAAkB,KAAM,GAAW,EAAE,WAAW,CAAM,CAAC,EAE/F,GAAa,EAAkB,IAA6B,CAKhE,IAAM,EADU,EAAQ,QAAQ,qBAAsB,MAClC,CAAC,CAClB,QAAQ,UAAW,cAAc,CAAC,CAClC,QAAQ,QAAS,cAAc,CAAC,CAChC,QAAQ,MAAO,OAAO,CAAC,CACvB,QAAQ,oBAAqB,UAAU,EAC1C,OAAW,OAAO,IAAI,EAAM,EA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GF,SAAW,GAAyC,EAAS,EAAG,eAAkB,EAAW,EAAO,SAAS,CAAC,CAAC,CAAC,EAEhH,cAAe,EAAa,IAC1B,EAAS,EAAK,mBAAsB,EAAO,aAAa,EAAK,CAAI,CAAC,EAEpE,YAAa,EAAiB,IAC5B,EAAS,EAAS,iBAAoB,EAAO,WAAW,EAAS,CAAO,CAAC,EAE3E,YAAc,GACZ,EAAS,EAAG,kBAAqB,EAAK,EAAO,YAAY,CAAC,CAAC,CAAC,EAE9D,eAAgB,EAAW,EAAc,EAA2B,SAClE,EAAS,EAAG,oBAAuB,EAAO,cAAc,EAAG,EAAM,CAAE,UAAS,CAAC,CAAC,EAEhF,gBAAiB,EAAW,EAAc,EAA2B,SACnE,EAAS,EAAG,qBAAwB,EAAO,eAAe,EAAG,EAAM,CAAE,UAAS,CAAC,CAAC,EAElF,WAAY,EAAW,IACjB,GAAS,WAAa,EAAc,CAAC,EAChC,EACL,EAAU,EAAG,YAAiB,MAAM,yEAAyE,CAAC,CAChH,EAEK,EAAS,EAAG,gBAAmB,CACpC,EAAO,UAAU,EAAG,CAAO,CAC7B,CAAC,EAGH,WAAa,GAAqC,EAAS,EAAG,iBAAoB,EAAO,WAAW,CAAC,CAAC,CACxG"}
1
+ {"version":3,"file":"Fs.js","names":["fsSync","fs","toFileInfo","stats","toFsError","FsError","p","op","error","MAGIC_FS_PREFIXES","isMagicFsPath","prefix","matchGlob","regex","pattern","filePath","liftAsync","Try","thunk","Err","err","Ok","value","liftSync","Fs","result","Option","data","src","dest","oldPath","newPath","List","entries","dir","matched","entry","options","Right","Left"],"sources":["../../src/fs/Fs.ts"],"sourcesContent":["import * as fsSync from \"node:fs\"\nimport * as fs from \"node:fs/promises\"\n\nimport type { Either, TaskResult } from \"functype\"\nimport { Err, Left, List, Ok, Option, Right, Try } from \"functype\"\n\nimport { FsError } from \"../errors/errors\"\n\nexport type FileInfo = {\n readonly size: number\n readonly isFile: boolean\n readonly isDirectory: boolean\n readonly isSymbolicLink: boolean\n readonly createdAt: Date\n readonly modifiedAt: Date\n readonly accessedAt: Date\n readonly permissions: number\n}\n\nconst toFileInfo = (stats: fsSync.Stats): FileInfo => ({\n size: stats.size,\n isFile: stats.isFile(),\n isDirectory: stats.isDirectory(),\n isSymbolicLink: stats.isSymbolicLink(),\n createdAt: stats.birthtime,\n modifiedAt: stats.mtime,\n accessedAt: stats.atime,\n permissions: stats.mode,\n})\n\nconst toFsError = (p: string, op: string, error: unknown): FsError =>\n FsError(p, op, error instanceof Error ? error : new Error(String(error)))\n\n/**\n * Linux magic filesystems where recursive mkdir can hang indefinitely against\n * unwritable subpaths (libuv quirk; macOS errors immediately instead).\n * Refusing recursive mkdir under these prefixes keeps `mkdir({ recursive: true })`\n * fast-failing and predictable across platforms. See issue #135.\n */\nconst MAGIC_FS_PREFIXES: ReadonlyArray<string> = [\"/proc/\", \"/sys/\", \"/dev/\"]\n\nconst isMagicFsPath = (p: string): boolean => MAGIC_FS_PREFIXES.some((prefix) => p.startsWith(prefix))\n\nconst matchGlob = (filePath: string, pattern: string): boolean => {\n // Escape every regex metachar EXCEPT '*' first, so the subsequent\n // '*' transformations are the only special characters in the output.\n // Order matters: backslashes must be escaped before any '\\\\' insertion below.\n const escaped = pattern.replace(/[\\\\^$+?.()|[\\]{}]/g, \"\\\\$&\")\n const regex = escaped\n .replace(/\\*\\*\\//g, \"{{GLOBSTAR}}\")\n .replace(/\\*\\*/g, \"{{GLOBSTAR}}\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/\\{\\{GLOBSTAR\\}\\}/g, \"(?:.*/)?\")\n return new RegExp(`^${regex}$`).test(filePath)\n}\n\n// Async helper: lift a Promise-returning thunk into TaskResult, mapping\n// rejections to FsError. Uses `Try.async(thunk)` rather than\n// `Try.fromPromise(thunk())` so synchronous throws from inside the thunk\n// (e.g. a bad encoding argument) are caught the same way async rejections\n// are — same Failure path, no unhandled-rejection escape hatch.\nconst liftAsync = async <T>(p: string, op: string, thunk: () => Promise<T>): TaskResult<T> => {\n const result = await Try.async(thunk)\n return result.fold<TaskResult<T>>(\n (err) => Promise.resolve(Err(toFsError(p, op, err))),\n (value) => Promise.resolve(Ok(value)),\n )\n}\n\n// Sync helper: run a thunk via Try and convert to Either<FsError, T>.\nconst liftSync = <T>(p: string, op: string, thunk: () => T): Either<FsError, T> =>\n Try(thunk).toEither((err) => toFsError(p, op, err))\n\nexport const Fs = {\n // Async methods — return TaskResult<T>\n\n exists: async (p: string): TaskResult<boolean> => {\n const result = await Try.async(() => fs.access(p))\n return Ok(result.isSuccess())\n },\n\n readFile: (p: string, encoding: BufferEncoding = \"utf8\"): TaskResult<string> =>\n liftAsync(p, \"readFile\", () => fs.readFile(p, { encoding })),\n\n readFileOpt: async (p: string, encoding: BufferEncoding = \"utf8\"): TaskResult<Option<string>> => {\n const result = await Try.async(() => fs.readFile(p, { encoding }))\n return result.fold<TaskResult<Option<string>>>(\n (err) => {\n if (err instanceof Error && \"code\" in err && err.code === \"ENOENT\") {\n return Promise.resolve(Ok(Option<string>(undefined)))\n }\n return Promise.resolve(Err(toFsError(p, \"readFile\", err)))\n },\n (data) => Promise.resolve(Ok(Option(data))),\n )\n },\n\n stat: (p: string): TaskResult<FileInfo> => liftAsync(p, \"stat\", () => fs.stat(p).then(toFileInfo)),\n\n copyFile: (src: string, dest: string): TaskResult<void> => liftAsync(src, \"copyFile\", () => fs.copyFile(src, dest)),\n\n rename: (oldPath: string, newPath: string): TaskResult<void> =>\n liftAsync(oldPath, \"rename\", () => fs.rename(oldPath, newPath)),\n\n readdir: (p: string): TaskResult<List<string>> =>\n liftAsync(p, \"readdir\", () => fs.readdir(p).then((entries) => List<string>(entries))),\n\n glob: async (dir: string, pattern: string): TaskResult<List<string>> => {\n const result = await Try.async(() => fs.readdir(dir, { recursive: true, encoding: \"utf8\" }))\n return result.fold<TaskResult<List<string>>>(\n (err) => Promise.resolve(Err(toFsError(dir, \"glob\", err))),\n (entries) => {\n const matched = (entries as string[]).filter((entry) => matchGlob(entry, pattern))\n return Promise.resolve(Ok(List<string>(matched)))\n },\n )\n },\n\n writeFile: (p: string, data: string, encoding: BufferEncoding = \"utf8\"): TaskResult<void> =>\n liftAsync(p, \"writeFile\", () => fs.writeFile(p, data, { encoding })),\n\n appendFile: (p: string, data: string, encoding: BufferEncoding = \"utf8\"): TaskResult<void> =>\n liftAsync(p, \"appendFile\", () => fs.appendFile(p, data, { encoding })),\n\n mkdir: (p: string, options?: { recursive?: boolean }): TaskResult<void> => {\n if (options?.recursive && isMagicFsPath(p)) {\n return Promise.resolve(\n Err(\n toFsError(p, \"mkdir\", new Error(\"recursive mkdir refused under magic filesystem root (/proc, /sys, /dev)\")),\n ),\n )\n }\n return liftAsync(p, \"mkdir\", () => fs.mkdir(p, options).then(() => undefined))\n },\n\n unlink: (p: string): TaskResult<void> => liftAsync(p, \"unlink\", () => fs.unlink(p)),\n\n // Sync methods — return Either<FsError, T>\n\n existsSync: (p: string): boolean => Try(() => fsSync.accessSync(p)).isSuccess(),\n\n readFileSync: (p: string, encoding: BufferEncoding = \"utf8\"): Either<FsError, string> =>\n liftSync(p, \"readFileSync\", () => fsSync.readFileSync(p, { encoding })),\n\n readFileOptSync: (p: string, encoding: BufferEncoding = \"utf8\"): Either<FsError, Option<string>> => {\n const tryResult = Try(() => fsSync.readFileSync(p, { encoding }))\n return tryResult.fold<Either<FsError, Option<string>>>(\n (err) => {\n if (err instanceof Error && \"code\" in err && err.code === \"ENOENT\") {\n return Right(Option<string>(undefined))\n }\n return Left(toFsError(p, \"readFileOptSync\", err))\n },\n (data) => Right(Option(data)),\n )\n },\n\n statSync: (p: string): Either<FsError, FileInfo> => liftSync(p, \"statSync\", () => toFileInfo(fsSync.statSync(p))),\n\n copyFileSync: (src: string, dest: string): Either<FsError, void> =>\n liftSync(src, \"copyFileSync\", () => fsSync.copyFileSync(src, dest)),\n\n renameSync: (oldPath: string, newPath: string): Either<FsError, void> =>\n liftSync(oldPath, \"renameSync\", () => fsSync.renameSync(oldPath, newPath)),\n\n readdirSync: (p: string): Either<FsError, List<string>> =>\n liftSync(p, \"readdirSync\", () => List(fsSync.readdirSync(p))),\n\n writeFileSync: (p: string, data: string, encoding: BufferEncoding = \"utf8\"): Either<FsError, void> =>\n liftSync(p, \"writeFileSync\", () => fsSync.writeFileSync(p, data, { encoding })),\n\n appendFileSync: (p: string, data: string, encoding: BufferEncoding = \"utf8\"): Either<FsError, void> =>\n liftSync(p, \"appendFileSync\", () => fsSync.appendFileSync(p, data, { encoding })),\n\n mkdirSync: (p: string, options?: { recursive?: boolean }): Either<FsError, void> => {\n if (options?.recursive && isMagicFsPath(p)) {\n return Left(\n toFsError(p, \"mkdirSync\", new Error(\"recursive mkdir refused under magic filesystem root (/proc, /sys, /dev)\")),\n )\n }\n return liftSync(p, \"mkdirSync\", () => {\n fsSync.mkdirSync(p, options)\n })\n },\n\n unlinkSync: (p: string): Either<FsError, void> => liftSync(p, \"unlinkSync\", () => fsSync.unlinkSync(p)),\n}\n"],"mappings":"sMAmBA,MAAME,EAAc,IAAmC,CACrD,KAAMC,EAAM,KACZ,OAAQA,EAAM,OAAO,EACrB,YAAaA,EAAM,YAAY,EAC/B,eAAgBA,EAAM,eAAe,EACrC,UAAWA,EAAM,UACjB,WAAYA,EAAM,MAClB,WAAYA,EAAM,MAClB,YAAaA,EAAM,IACrB,GAEMC,GAAa,EAAW,EAAY,IACxCC,EAAQC,EAAGC,EAAIC,aAAiB,MAAQA,EAAY,MAAM,OAAOA,CAAK,CAAC,CAAC,EAQpEC,EAA2C,CAAC,SAAU,QAAS,OAAO,EAEtEC,EAAiB,GAAuBD,EAAkB,KAAM,GAAWH,EAAE,WAAWK,CAAM,CAAC,EAE/FC,GAAa,EAAkB,IAA6B,CAKhE,IAAMC,EADUC,EAAQ,QAAQ,qBAAsB,MAClC,CAAC,CAClB,QAAQ,UAAW,cAAc,CAAC,CAClC,QAAQ,QAAS,cAAc,CAAC,CAChC,QAAQ,MAAO,OAAO,CAAC,CACvB,QAAQ,oBAAq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B,EAAO,aAAaM,EAAG,CAAE,UAAS,CAAC,CAChD,CAAC,CAAC,KACd,GACKc,aAAe,OAAS,SAAUA,GAAOA,EAAI,OAAS,SACjDkB,EAAMZ,EAAe,IAAA,EAAS,CAAC,EAEjCa,EAAKnC,EAAUE,EAAG,kBAAmBc,CAAG,CAAC,EAEjD,GAASkB,EAAMZ,EAAOC,CAAI,CAAC,CAC9B,EAGF,SAAW,GAAyCJ,EAASjB,EAAG,eAAkBJ,EAAWF,EAAO,SAASM,CAAC,CAAC,CAAC,EAEhH,cAAe,EAAa,IAC1BiB,EAASK,EAAK,mBAAsB5B,EAAO,aAAa4B,EAAKC,CAAI,CAAC,EAEpE,YAAa,EAAiB,IAC5BN,EAASO,EAAS,iBAAoB9B,EAAO,WAAW8B,EAASC,CAAO,CAAC,EAE3E,YAAc,GACZR,EAASjB,EAAG,kBAAqB0B,EAAKhC,EAAO,YAAYM,CAAC,CAAC,CAAC,EAE9D,eAAgB,EAAW,EAAc,EAA2B,SAClEiB,EAASjB,EAAG,oBAAuBN,EAAO,cAAcM,EAAGqB,EAAM,CAAE,UAAS,CAAC,CAAC,EAEhF,gBAAiB,EAAW,EAAc,EAA2B,SACnEJ,EAASjB,EAAG,qBAAwBN,EAAO,eAAeM,EAAGqB,EAAM,CAAE,UAAS,CAAC,CAAC,EAElF,WAAY,EAAW,IACjBU,GAAS,WAAa3B,EAAcJ,CAAC,EAChCiC,EACLnC,EAAUE,EAAG,YAAa,gBAAI,MAAM,yEAAyE,CAAC,CAChH,EAEKiB,EAASjB,EAAG,gBAAmB,CACpCN,EAAO,UAAUM,EAAG+B,CAAO,CAC7B,CAAC,EAGH,WAAa,GAAqCd,EAASjB,EAAG,iBAAoBN,EAAO,WAAWM,CAAC,CAAC,CACxG"}
@@ -1 +1 @@
1
- {"version":3,"file":"PathExpander.js","names":[],"sources":["../../src/path/PathExpander.ts"],"sourcesContent":["import * as os from \"node:os\"\nimport * as nodePath from \"node:path\"\n\nimport type { Either } from \"functype\"\nimport { Left, Option, Right } from \"functype\"\n\nimport { PathError } from \"../errors/errors\"\n\nexport const expandTilde = (p: string): string => {\n if (p === \"~\") return os.homedir()\n if (p.startsWith(\"~/\") || p.startsWith(\"~\\\\\")) return nodePath.join(os.homedir(), p.slice(2))\n return p\n}\n\nexport const expandVars = (p: string): Either<PathError, string> => {\n const unresolvedVars: string[] = []\n // Factor out the leading `$` and forbid `$` inside `${...}` so the engine\n // can't backtrack catastrophically on inputs like `${{${{${{...` (CodeQL\n // js/polynomial-redos).\n const result = p.replace(/\\$(?:\\{([^}$]+)\\}|([A-Za-z_][A-Za-z0-9_]*))/g, (_match: string, ...captures: unknown[]) => {\n const varName = Option(captures[0] as string | undefined)\n .or(Option(captures[1] as string | undefined))\n .orElse(\"\")\n const value = process.env[varName]\n if (value === undefined) {\n unresolvedVars.push(varName)\n return _match\n }\n return value\n })\n\n if (unresolvedVars.length > 0) {\n return Left(PathError(p, \"unresolved_variable\", `Unresolved variables: ${unresolvedVars.join(\", \")}`))\n }\n\n return Right(result)\n}\n\nexport const expandPath = (p: string): Either<PathError, string> => {\n const tildeExpanded = expandTilde(p)\n const varsResult = expandVars(tildeExpanded)\n if (varsResult.isLeft()) return varsResult\n return Right(nodePath.resolve(varsResult.orThrow()))\n}\n\nexport const Path = {\n expand: expandPath,\n expandTilde,\n expandVars,\n join: (...segments: string[]): string => nodePath.join(...segments),\n resolve: (...segments: string[]): string => nodePath.resolve(...segments),\n dirname: (p: string): string => nodePath.dirname(p),\n basename: (p: string, suffix?: string): string => nodePath.basename(p, suffix),\n extname: (p: string): string => nodePath.extname(p),\n isAbsolute: (p: string): boolean => nodePath.isAbsolute(p),\n}\n"],"mappings":"6JAQA,MAAa,EAAe,GACtB,IAAM,IAAY,EAAG,QAAQ,EAC7B,EAAE,WAAW,IAAI,GAAK,EAAE,WAAW,KAAK,EAAU,EAAS,KAAK,EAAG,QAAQ,EAAG,EAAE,MAAM,CAAC,CAAC,EACrF,EAGI,EAAc,GAAyC,CAClE,IAAM,EAA2B,CAAC,EAI5B,EAAS,EAAE,QAAQ,gDAAiD,EAAgB,GAAG,IAAwB,CACnH,IAAM,EAAU,EAAO,EAAS,EAAwB,CAAC,CACtD,GAAG,EAAO,EAAS,EAAwB,CAAC,CAAC,CAC7C,OAAO,EAAE,EACN,EAAQ,QAAQ,IAAI,GAK1B,OAJI,IAAU,IAAA,IACZ,EAAe,KAAK,CAAO,EACpB,GAEF,CACT,CAAC,EAMD,OAJI,EAAe,OAAS,EACnB,EAAK,EAAU,EAAG,sBAAuB,yBAAyB,EAAe,KAAK,IAAI,GAAG,CAAC,EAGhG,EAAM,CAAM,CACrB,EAEa,EAAc,GAAyC,CAClE,IAAM,EAAgB,EAAY,CAAC,EAC7B,EAAa,EAAW,CAAa,EAE3C,OADI,EAAW,OAAO,EAAU,EACzB,EAAM,EAAS,QAAQ,EAAW,QAAQ,CAAC,CAAC,CACrD,EAEa,EAAO,CAClB,OAAQ,EACR,cACA,aACA,MAAO,GAAG,IAA+B,EAAS,KAAK,GAAG,CAAQ,EAClE,SAAU,GAAG,IAA+B,EAAS,QAAQ,GAAG,CAAQ,EACxE,QAAU,GAAsB,EAAS,QAAQ,CAAC,EAClD,UAAW,EAAW,IAA4B,EAAS,SAAS,EAAG,CAAM,EAC7E,QAAU,GAAsB,EAAS,QAAQ,CAAC,EAClD,WAAa,GAAuB,EAAS,WAAW,CAAC,CAC3D"}
1
+ {"version":3,"file":"PathExpander.js","names":["os","nodePath","expandTilde","p","expandVars","unresolvedVars","result","captures","varName","Option","value","_match","Left","PathError","Right","expandPath","tildeExpanded","varsResult","Path","segments","suffix"],"sources":["../../src/path/PathExpander.ts"],"sourcesContent":["import * as os from \"node:os\"\nimport * as nodePath from \"node:path\"\n\nimport type { Either } from \"functype\"\nimport { Left, Option, Right } from \"functype\"\n\nimport { PathError } from \"../errors/errors\"\n\nexport const expandTilde = (p: string): string => {\n if (p === \"~\") return os.homedir()\n if (p.startsWith(\"~/\") || p.startsWith(\"~\\\\\")) return nodePath.join(os.homedir(), p.slice(2))\n return p\n}\n\nexport const expandVars = (p: string): Either<PathError, string> => {\n const unresolvedVars: string[] = []\n // Factor out the leading `$` and forbid `$` inside `${...}` so the engine\n // can't backtrack catastrophically on inputs like `${{${{${{...` (CodeQL\n // js/polynomial-redos).\n const result = p.replace(/\\$(?:\\{([^}$]+)\\}|([A-Za-z_][A-Za-z0-9_]*))/g, (_match: string, ...captures: unknown[]) => {\n const varName = Option(captures[0] as string | undefined)\n .or(Option(captures[1] as string | undefined))\n .orElse(\"\")\n const value = process.env[varName]\n if (value === undefined) {\n unresolvedVars.push(varName)\n return _match\n }\n return value\n })\n\n if (unresolvedVars.length > 0) {\n return Left(PathError(p, \"unresolved_variable\", `Unresolved variables: ${unresolvedVars.join(\", \")}`))\n }\n\n return Right(result)\n}\n\nexport const expandPath = (p: string): Either<PathError, string> => {\n const tildeExpanded = expandTilde(p)\n const varsResult = expandVars(tildeExpanded)\n if (varsResult.isLeft()) return varsResult\n return Right(nodePath.resolve(varsResult.orThrow()))\n}\n\nexport const Path = {\n expand: expandPath,\n expandTilde,\n expandVars,\n join: (...segments: string[]): string => nodePath.join(...segments),\n resolve: (...segments: string[]): string => nodePath.resolve(...segments),\n dirname: (p: string): string => nodePath.dirname(p),\n basename: (p: string, suffix?: string): string => nodePath.basename(p, suffix),\n extname: (p: string): string => nodePath.extname(p),\n isAbsolute: (p: string): boolean => nodePath.isAbsolute(p),\n}\n"],"mappings":"6JAQA,MAAaE,EAAe,GACtBC,IAAM,IAAYH,EAAG,QAAQ,EAC7BG,EAAE,WAAW,IAAI,GAAKA,EAAE,WAAW,KAAK,EAAUF,EAAS,KAAKD,EAAG,QAAQ,EAAGG,EAAE,MAAM,CAAC,CAAC,EACrFA,EAGIC,EAAc,GAAyC,CAClE,IAAMC,EAA2B,CAAC,EAI5BC,EAASH,EAAE,QAAQ,gDAAiD,EAAgB,GAAGI,IAAwB,CACnH,IAAMC,EAAUC,EAAOF,EAAS,EAAwB,CAAC,CACtD,GAAGE,EAAOF,EAAS,EAAwB,CAAC,CAAC,CAC7C,OAAO,EAAE,EACNG,EAAQ,QAAQ,IAAIF,GAK1B,OAJIE,IAAU,IAAA,IACZL,EAAe,KAAKG,CAAO,EACpBG,GAEFD,CACT,CAAC,EAMD,OAJIL,EAAe,OAAS,EACnBO,EAAKC,EAAUV,EAAG,sBAAuB,yBAAyBE,EAAe,KAAK,IAAI,GAAG,CAAC,EAGhGS,EAAMR,CAAM,CACrB,EAEaS,EAAc,GAAyC,CAClE,IAAMC,EAAgBd,EAAYC,CAAC,EAC7Bc,EAAab,EAAWY,CAAa,EAE3C,OADIC,EAAW,OAAO,EAAUA,EACzBH,EAAMb,EAAS,QAAQgB,EAAW,QAAQ,CAAC,CAAC,CACrD,EAEaC,EAAO,CAClB,OAAQH,EACR,cACA,aACA,MAAO,GAAGI,IAA+BlB,EAAS,KAAK,GAAGkB,CAAQ,EAClE,SAAU,GAAGA,IAA+BlB,EAAS,QAAQ,GAAGkB,CAAQ,EACxE,QAAU,GAAsBlB,EAAS,QAAQE,CAAC,EAClD,UAAW,EAAW,IAA4BF,EAAS,SAASE,EAAGiB,CAAM,EAC7E,QAAU,GAAsBnB,EAAS,QAAQE,CAAC,EAClD,WAAa,GAAuBF,EAAS,WAAWE,CAAC,CAC3D"}
@@ -1,2 +1,2 @@
1
- import{List as e,Option as t,Set as n,Try as r}from"functype";import*as i from"node:fs";import*as a from"node:os";import*as o from"node:path";import{execSync as s}from"node:child_process";const c=()=>r(()=>i.statSync(`/.dockerenv`)).isSuccess(),l=()=>r(()=>i.readFileSync(`/proc/self/cgroup`,`utf8`)).map(e=>e.includes(`docker`)).toEither(()=>!1).fold(()=>!1,e=>e),u=e=>{let t={};return()=>(`value`in t||(t.value=e()),t.value)},d=u(()=>c()||l()),f=u(()=>r(()=>i.readFileSync(`/proc/self/cgroup`,`utf8`)).map(e=>e.includes(`kube`)).fold(()=>!1,e=>e)),p=u(()=>r(()=>i.readFileSync(`/proc/version`,`utf8`)).map(e=>e.includes(`Microsoft`)||e.includes(`WSL`)).fold(()=>!1,e=>e)),m=u(()=>process.env.CI!==void 0||process.env.GITHUB_ACTIONS!==void 0||process.env.GITLAB_CI!==void 0||process.env.CIRCLECI!==void 0||process.env.JENKINS_URL!==void 0||process.env.TRAVIS!==void 0||process.env.BUILDKITE!==void 0),h=n.of(`all users`,`default`,`default user`,`public`),g=e=>{let t=e.toLowerCase();return!!(h.contains(t)||t.startsWith(`defaultuser`)||t.startsWith(`desktop.`)||t.startsWith(`wsiaccount`))},_=e=>r(()=>i.statSync(e).isDirectory()).fold(()=>!1,e=>e),v=e=>r(()=>i.readdirSync(e)).map(t=>t.filter(t=>!g(t)&&_(o.join(e,t)))).toOption(),y=(e,n)=>t(r(()=>s(`cmd.exe /c echo %USERPROFILE%`,{timeout:3e3,encoding:`utf8`}).trim()).toOption().flatMap(e=>{let n=e.match(/^([A-Za-z]):\\(.*)$/);if(!n)return t(void 0);let r=`/mnt/${n[1].toLowerCase()}/${n[2].replace(/\\/g,`/`)}`;return _(r)?t(r):t(void 0)}).orElse(n)),b=u(()=>{if(!p())return t(void 0);let e=`/mnt/c/Users`;return v(e).fold(()=>t(void 0),n=>n.length===1?t(o.join(e,n[0])):n.length>1?y(e,o.join(e,n[0])):t(void 0))}),x=e=>e===`OneDrive`||e.startsWith(`OneDrive `)||e.startsWith(`OneDrive-`)?t({provider:`onedrive`,label:e}):t(e===`Google Drive`?{provider:`gdrive`,label:e}:e===`Dropbox`?{provider:`dropbox`,label:e}:void 0),S=e=>r(()=>i.readdirSync(e)).map(t=>t.flatMap(t=>{let n=o.join(e,t);return x(t).fold(()=>[],e=>_(n)?[{provider:e.provider,path:n,label:e.label}]:[])})).fold(()=>[],e=>e),C=e=>{let t=o.join(e,`Library`,`CloudStorage`);return r(()=>i.readdirSync(t)).map(e=>e.flatMap(e=>{let n=o.join(t,e);return _(n)?e.startsWith(`OneDrive`)?[{provider:`onedrive`,path:n,label:e}]:e.startsWith(`GoogleDrive`)?[{provider:`gdrive`,path:n,label:e}]:[]:[]})).fold(()=>[],e=>e)},w=e=>{let t=o.join(e,`Library`,`Mobile Documents`,`com~apple~CloudDocs`);return _(t)?[{provider:`icloud`,path:t,label:`iCloud Drive`}]:[]},T=e=>[...S(e),...C(e),...w(e)],E={os:()=>process.platform,arch:()=>process.arch,homeDir:()=>a.homedir(),tmpDir:()=>a.tmpdir(),hostname:()=>a.hostname(),eol:()=>a.EOL,pathSep:()=>o.sep,isWindows:()=>process.platform===`win32`,isMac:()=>process.platform===`darwin`,isLinux:()=>process.platform===`linux`,userInfo:()=>r(()=>a.userInfo()).map(e=>({username:e.username,uid:e.uid,gid:e.gid,shell:t(e.shell),homedir:e.homedir})).toOption(),isDocker:()=>d(),isKubernetes:()=>f(),isWSL:()=>p(),isCI:()=>m(),isContainer:()=>E.isDocker()||E.isKubernetes(),windowsHomeDir:()=>b(),homeDirs:()=>{let t=a.homedir();return e([t,...E.windowsHomeDir().fold(()=>[],e=>e===t?[]:[e])])},cloudStorageDirs:t=>e(t===void 0?E.homeDirs().toArray().flatMap(e=>[...T(e)]).reduce((e,t)=>e.seen.includes(t.path)?e:{seen:[...e.seen,t.path],results:[...e.results,t]},{seen:[],results:[]}).results:T(t))};export{E as Platform};
1
+ import{List as e,Option as t,Set as n,Try as r}from"functype";import*as i from"node:fs";import*as a from"node:os";import*as o from"node:path";import{execSync as s}from"node:child_process";const c=()=>r(()=>i.statSync(`/.dockerenv`)).isSuccess(),l=()=>r(()=>i.readFileSync(`/proc/self/cgroup`,`utf8`)).map(e=>e.includes(`docker`)).toEither(()=>!1).fold(()=>!1,e=>e),u=e=>{let t={};return()=>(`value`in t||(t.value=e()),t.value)},d=u(()=>c()||l()),f=u(()=>r(()=>i.readFileSync(`/proc/self/cgroup`,`utf8`)).map(e=>e.includes(`kube`)).fold(()=>!1,e=>e)),p=u(()=>r(()=>i.readFileSync(`/proc/version`,`utf8`)).map(e=>e.includes(`Microsoft`)||e.includes(`WSL`)).fold(()=>!1,e=>e)),m=u(()=>process.env.CI!==void 0||process.env.GITHUB_ACTIONS!==void 0||process.env.GITLAB_CI!==void 0||process.env.CIRCLECI!==void 0||process.env.JENKINS_URL!==void 0||process.env.TRAVIS!==void 0||process.env.BUILDKITE!==void 0),h=n.of(`all users`,`default`,`default user`,`public`),g=e=>{let t=e.toLowerCase();return!!(h.contains(t)||t.startsWith(`defaultuser`)||t.startsWith(`desktop.`)||t.startsWith(`wsiaccount`))},_=e=>r(()=>i.statSync(e).isDirectory()).fold(()=>!1,e=>e),v=e=>r(()=>i.readdirSync(e)).map(t=>t.filter(t=>!g(t)&&_(o.join(e,t)))).toOption(),y=(e,n)=>{let i=r(()=>s(`cmd.exe /c echo %USERPROFILE%`,{timeout:3e3,encoding:`utf8`}).trim()).toOption().flatMap(e=>{let n=e.match(/^([A-Za-z]):\\(.*)$/);if(!n)return t(void 0);let r=`/mnt/${n[1].toLowerCase()}/${n[2].replace(/\\/g,`/`)}`;return _(r)?t(r):t(void 0)}).orElse(n);return t(i)},b=u(()=>{if(!p())return t(void 0);let e=`/mnt/c/Users`;return v(e).fold(()=>t(void 0),n=>n.length===1?t(o.join(e,n[0])):n.length>1?y(e,o.join(e,n[0])):t(void 0))}),x=e=>e===`OneDrive`||e.startsWith(`OneDrive `)||e.startsWith(`OneDrive-`)?t({provider:`onedrive`,label:e}):t(e===`Google Drive`?{provider:`gdrive`,label:e}:e===`Dropbox`?{provider:`dropbox`,label:e}:void 0),S=e=>r(()=>i.readdirSync(e)).map(t=>t.flatMap(t=>{let n=o.join(e,t);return x(t).fold(()=>[],e=>_(n)?[{provider:e.provider,path:n,label:e.label}]:[])})).fold(()=>[],e=>e),C=e=>{let t=o.join(e,`Library`,`CloudStorage`);return r(()=>i.readdirSync(t)).map(e=>e.flatMap(e=>{let n=o.join(t,e);return _(n)?e.startsWith(`OneDrive`)?[{provider:`onedrive`,path:n,label:e}]:e.startsWith(`GoogleDrive`)?[{provider:`gdrive`,path:n,label:e}]:[]:[]})).fold(()=>[],e=>e)},w=e=>{let t=o.join(e,`Library`,`Mobile Documents`,`com~apple~CloudDocs`);return _(t)?[{provider:`icloud`,path:t,label:`iCloud Drive`}]:[]},T=e=>[...S(e),...C(e),...w(e)],E={os:()=>process.platform,arch:()=>process.arch,homeDir:()=>a.homedir(),tmpDir:()=>a.tmpdir(),hostname:()=>a.hostname(),eol:()=>a.EOL,pathSep:()=>o.sep,isWindows:()=>process.platform===`win32`,isMac:()=>process.platform===`darwin`,isLinux:()=>process.platform===`linux`,userInfo:()=>r(()=>a.userInfo()).map(e=>({username:e.username,uid:e.uid,gid:e.gid,shell:t(e.shell),homedir:e.homedir})).toOption(),isDocker:()=>d(),isKubernetes:()=>f(),isWSL:()=>p(),isCI:()=>m(),isContainer:()=>E.isDocker()||E.isKubernetes(),windowsHomeDir:()=>b(),homeDirs:()=>{let t=a.homedir(),n=E.windowsHomeDir().fold(()=>[],e=>e===t?[]:[e]);return e([t,...n])},cloudStorageDirs:t=>{if(t!==void 0)return e(T(t));let n=E.homeDirs().toArray().flatMap(e=>[...T(e)]).reduce((e,t)=>e.seen.includes(t.path)?e:{seen:[...e.seen,t.path],results:[...e.results,t]},{seen:[],results:[]});return e(n.results)}};export{E as Platform};
2
2
  //# sourceMappingURL=Platform.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Platform.js","names":["FSet"],"sources":["../../src/platform/Platform.ts"],"sourcesContent":["import { execSync } from \"node:child_process\"\nimport * as fs from \"node:fs\"\nimport * as os from \"node:os\"\nimport * as path from \"node:path\"\n\nimport { List, Option, Set as FSet, Try } from \"functype\"\n\nexport type UserInfo = {\n readonly username: string\n readonly uid: number\n readonly gid: number\n readonly shell: Option<string>\n readonly homedir: string\n}\n\nexport type CloudProvider = \"onedrive\" | \"gdrive\" | \"dropbox\" | \"icloud\"\n\nexport type CloudStorageDir = {\n readonly provider: CloudProvider\n readonly path: string\n readonly label: string\n}\n\nconst hasDockerEnv = (): boolean => Try(() => fs.statSync(\"/.dockerenv\")).isSuccess()\n\nconst hasDockerCGroup = (): boolean =>\n Try(() => fs.readFileSync(\"/proc/self/cgroup\", \"utf8\"))\n .map((contents) => contents.includes(\"docker\"))\n .toEither((): boolean => false)\n .fold(\n () => false,\n (matched) => matched,\n )\n\nconst memo = <T>(fn: () => T): (() => T) => {\n const cache: { value?: T } = {}\n return () => {\n if (!(\"value\" in cache)) {\n cache.value = fn()\n }\n return cache.value as T\n }\n}\n\nconst cachedIsDocker = memo(() => hasDockerEnv() || hasDockerCGroup())\nconst cachedIsKube = memo(() =>\n Try(() => fs.readFileSync(\"/proc/self/cgroup\", \"utf8\"))\n .map((contents) => contents.includes(\"kube\"))\n .fold(\n () => false,\n (matched) => matched,\n ),\n)\nconst cachedIsWSL = memo(() =>\n Try(() => fs.readFileSync(\"/proc/version\", \"utf8\"))\n .map((version) => version.includes(\"Microsoft\") || version.includes(\"WSL\"))\n .fold(\n () => false,\n (matched) => matched,\n ),\n)\nconst cachedIsCI = memo(\n () =>\n process.env[\"CI\"] !== undefined ||\n process.env[\"GITHUB_ACTIONS\"] !== undefined ||\n process.env[\"GITLAB_CI\"] !== undefined ||\n process.env[\"CIRCLECI\"] !== undefined ||\n process.env[\"JENKINS_URL\"] !== undefined ||\n process.env[\"TRAVIS\"] !== undefined ||\n process.env[\"BUILDKITE\"] !== undefined,\n)\n\nconst SYSTEM_ACCOUNTS = FSet.of(\"all users\", \"default\", \"default user\", \"public\")\n\nconst isSystemAccount = (name: string): boolean => {\n const lower = name.toLowerCase()\n if (SYSTEM_ACCOUNTS.contains(lower)) return true\n if (lower.startsWith(\"defaultuser\") || lower.startsWith(\"desktop.\") || lower.startsWith(\"wsiaccount\")) return true\n return false\n}\n\nconst isDirectory = (p: string): boolean =>\n Try(() => fs.statSync(p).isDirectory()).fold(\n () => false,\n (isDir) => isDir,\n )\n\nconst readRealUsers = (usersDir: string): Option<readonly string[]> => {\n const filterRealUsers = (entries: readonly string[]): readonly string[] =>\n entries.filter((name) => !isSystemAccount(name) && isDirectory(path.join(usersDir, name)))\n return Try(() => fs.readdirSync(usersDir))\n .map(filterRealUsers)\n .toOption()\n}\n\nconst resolveViaCmdExe = (usersDir: string, fallback: string): Option<string> => {\n // Convert Windows path C:\\Users\\foo → /mnt/c/Users/foo if it's a directory;\n // returns None for unparseable output or non-existent directories.\n const parseCmdOutput = (raw: string): Option<string> => {\n const match = raw.match(/^([A-Za-z]):\\\\(.*)$/)\n if (!match) return Option<string>(undefined)\n const drive = (match[1] as string).toLowerCase()\n const rest = (match[2] as string).replace(/\\\\/g, \"/\")\n const wslPath = `/mnt/${drive}/${rest}`\n return isDirectory(wslPath) ? Option(wslPath) : Option<string>(undefined)\n }\n const parsed = Try(() => execSync(\"cmd.exe /c echo %USERPROFILE%\", { timeout: 3000, encoding: \"utf8\" }).trim())\n .toOption()\n .flatMap(parseCmdOutput)\n .orElse(fallback)\n return Option(parsed)\n}\n\nconst resolveWindowsHome = (): Option<string> => {\n if (!cachedIsWSL()) return Option<string>(undefined)\n\n const usersDir = \"/mnt/c/Users\"\n return readRealUsers(usersDir).fold<Option<string>>(\n () => Option<string>(undefined),\n (realUsers) => {\n if (realUsers.length === 1) return Option(path.join(usersDir, realUsers[0] as string))\n if (realUsers.length > 1) return resolveViaCmdExe(usersDir, path.join(usersDir, realUsers[0] as string))\n return Option<string>(undefined)\n },\n )\n}\n\nconst cachedWindowsHome = memo(resolveWindowsHome)\n\ntype CloudDetection = { readonly provider: CloudProvider; readonly label: string }\n\nconst detectCloudProvider = (name: string): Option<CloudDetection> => {\n if (name === \"OneDrive\" || name.startsWith(\"OneDrive \") || name.startsWith(\"OneDrive-\")) {\n return Option({ provider: \"onedrive\" as const, label: name })\n }\n if (name === \"Google Drive\") return Option({ provider: \"gdrive\" as const, label: name })\n if (name === \"Dropbox\") return Option({ provider: \"dropbox\" as const, label: name })\n return Option<CloudDetection>(undefined)\n}\n\nconst scanDirectChildren = (home: string): readonly CloudStorageDir[] =>\n Try(() => fs.readdirSync(home))\n .map((entries) =>\n entries.flatMap((name): CloudStorageDir[] => {\n const fullPath = path.join(home, name)\n return detectCloudProvider(name).fold<CloudStorageDir[]>(\n () => [],\n (detection) =>\n isDirectory(fullPath) ? [{ provider: detection.provider, path: fullPath, label: detection.label }] : [],\n )\n }),\n )\n .fold<readonly CloudStorageDir[]>(\n () => [],\n (results) => results,\n )\n\nconst scanMacCloudStorage = (home: string): readonly CloudStorageDir[] => {\n const cloudStoragePath = path.join(home, \"Library\", \"CloudStorage\")\n return Try(() => fs.readdirSync(cloudStoragePath))\n .map((entries) =>\n entries.flatMap((name): CloudStorageDir[] => {\n const fullPath = path.join(cloudStoragePath, name)\n if (!isDirectory(fullPath)) return []\n if (name.startsWith(\"OneDrive\")) return [{ provider: \"onedrive\", path: fullPath, label: name }]\n if (name.startsWith(\"GoogleDrive\")) return [{ provider: \"gdrive\", path: fullPath, label: name }]\n return []\n }),\n )\n .fold<readonly CloudStorageDir[]>(\n () => [],\n (results) => results,\n )\n}\n\nconst scanMacICloud = (home: string): readonly CloudStorageDir[] => {\n const icloudPath = path.join(home, \"Library\", \"Mobile Documents\", \"com~apple~CloudDocs\")\n return isDirectory(icloudPath) ? [{ provider: \"icloud\", path: icloudPath, label: \"iCloud Drive\" }] : []\n}\n\nconst scanCloudStorageDirs = (home: string): readonly CloudStorageDir[] => [\n ...scanDirectChildren(home),\n ...scanMacCloudStorage(home),\n ...scanMacICloud(home),\n]\n\nexport const Platform = {\n os: (): \"darwin\" | \"linux\" | \"win32\" | string => process.platform,\n arch: (): string => process.arch,\n homeDir: (): string => os.homedir(),\n tmpDir: (): string => os.tmpdir(),\n hostname: (): string => os.hostname(),\n eol: (): string => os.EOL,\n pathSep: (): string => path.sep,\n\n isWindows: (): boolean => process.platform === \"win32\",\n isMac: (): boolean => process.platform === \"darwin\",\n isLinux: (): boolean => process.platform === \"linux\",\n\n userInfo: (): Option<UserInfo> => {\n const toUserInfo = (info: os.UserInfo<string>): UserInfo => ({\n username: info.username,\n uid: info.uid,\n gid: info.gid,\n shell: Option(info.shell),\n homedir: info.homedir,\n })\n return Try(() => os.userInfo())\n .map(toUserInfo)\n .toOption()\n },\n\n isDocker: (): boolean => cachedIsDocker(),\n isKubernetes: (): boolean => cachedIsKube(),\n isWSL: (): boolean => cachedIsWSL(),\n isCI: (): boolean => cachedIsCI(),\n\n isContainer: (): boolean => Platform.isDocker() || Platform.isKubernetes(),\n\n windowsHomeDir: (): Option<string> => cachedWindowsHome(),\n\n homeDirs: (): List<string> => {\n const primary = os.homedir()\n const windowsHome = Platform.windowsHomeDir().fold<readonly string[]>(\n () => [],\n (h) => (h !== primary ? [h] : []),\n )\n return List<string>([primary, ...windowsHome])\n },\n\n cloudStorageDirs: (home?: string): List<CloudStorageDir> => {\n if (home !== undefined) return List(scanCloudStorageDirs(home))\n const allDirs = Platform.homeDirs()\n .toArray()\n .flatMap((h) => [...scanCloudStorageDirs(h)])\n // Deduplicate by path, first-wins\n const deduped = allDirs.reduce<{\n readonly seen: ReadonlyArray<string>\n readonly results: ReadonlyArray<CloudStorageDir>\n }>(\n (acc, dir) =>\n acc.seen.includes(dir.path) ? acc : { seen: [...acc.seen, dir.path], results: [...acc.results, dir] },\n { seen: [], results: [] },\n )\n return List(deduped.results)\n },\n}\n"],"mappings":"4LAuBA,MAAM,MAA8B,MAAU,EAAG,SAAS,aAAa,CAAC,CAAC,CAAC,UAAU,EAE9E,MACJ,MAAU,EAAG,aAAa,oBAAqB,MAAM,CAAC,CAAC,CACpD,IAAK,GAAa,EAAS,SAAS,QAAQ,CAAC,CAAC,CAC9C,aAAwB,EAAK,CAAC,CAC9B,SACO,GACL,GAAY,CACf,EAEE,EAAW,GAA2B,CAC1C,IAAM,EAAuB,CAAC,EAC9B,WACQ,UAAW,IACf,EAAM,MAAQ,EAAG,GAEZ,EAAM,MAEjB,EAEM,EAAiB,MAAW,EAAa,GAAK,EAAgB,CAAC,EAC/D,EAAe,MACnB,MAAU,EAAG,aAAa,o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,EAAa,EAC1C,UAAsB,EAAY,EAClC,SAAqB,EAAW,EAEhC,gBAA4B,EAAS,SAAS,GAAK,EAAS,aAAa,EAEzE,mBAAsC,EAAkB,EAExD,aAA8B,CAC5B,IAAM,EAAU,EAAG,QAAQ,EAK3B,OAAO,EAAa,CAAC,EAAS,GAJV,EAAS,eAAe,CAAC,CAAC,SACtC,CAAC,EACN,GAAO,IAAM,EAAgB,CAAC,EAAP,CAAC,CAAC,CAEe,CAAC,CAAC,CAC/C,EAEA,iBAAmB,GAcV,EAbH,IAAS,IAAA,GACG,EAAS,SAAS,CAAC,CAChC,QAAQ,CAAC,CACT,QAAS,GAAM,CAAC,GAAG,EAAqB,CAAC,CAAC,CAEvB,CAAC,CAAC,QAIrB,EAAK,IACJ,EAAI,KAAK,SAAS,EAAI,IAAI,EAAI,EAAM,CAAE,KAAM,CAAC,GAAG,EAAI,KAAM,EAAI,IAAI,EAAG,QAAS,CAAC,GAAG,EAAI,QAAS,CAAG,CAAE,EACtG,CAAE,KAAM,CAAC,EAAG,QAAS,CAAC,CAAE,CAER,CAAC,CAAC,QAbgB,EAAqB,CAAI,CAAC,CAelE"}
1
+ {"version":3,"file":"Platform.js","names":["FSet","fs","os","path","hasDockerEnv","Try","hasDockerCGroup","contents","matched","memo","cache","fn","cachedIsDocker","cachedIsKube","cachedIsWSL","version","cachedIsCI","\"CI\"","\"GITHUB_ACTIONS\"","\"GITLAB_CI\"","\"CIRCLECI\"","\"JENKINS_URL\"","\"TRAVIS\"","\"BUILDKITE\"","SYSTEM_ACCOUNTS","Set","isSystemAccount","lower","name","isDirectory","p","isDir","readRealUsers","usersDir","entries","resolveViaCmdExe","parsed","execSync","match","raw","Option","wslPath","fallback","cachedWindowsHome","realUsers","detectCloudProvider","scanDirectChildren","home","fullPath","detection","results","scanMacCloudStorage","cloudStoragePath","scanMacICloud","icloudPath","scanCloudStorageDirs","Platform","info","primary","windowsHome","h","List","deduped","acc","dir"],"sources":["../../src/platform/Platform.ts"],"sourcesContent":["import { execSync } from \"node:child_process\"\nimport * as fs from \"node:fs\"\nimport * as os from \"node:os\"\nimport * as path from \"node:path\"\n\nimport { List, Option, Set as FSet, Try } from \"functype\"\n\nexport type UserInfo = {\n readonly username: string\n readonly uid: number\n readonly gid: number\n readonly shell: Option<string>\n readonly homedir: string\n}\n\nexport type CloudProvider = \"onedrive\" | \"gdrive\" | \"dropbox\" | \"icloud\"\n\nexport type CloudStorageDir = {\n readonly provider: CloudProvider\n readonly path: string\n readonly label: string\n}\n\nconst hasDockerEnv = (): boolean => Try(() => fs.statSync(\"/.dockerenv\")).isSuccess()\n\nconst hasDockerCGroup = (): boolean =>\n Try(() => fs.readFileSync(\"/proc/self/cgroup\", \"utf8\"))\n .map((contents) => contents.includes(\"docker\"))\n .toEither((): boolean => false)\n .fold(\n () => false,\n (matched) => matched,\n )\n\nconst memo = <T>(fn: () => T): (() => T) => {\n const cache: { value?: T } = {}\n return () => {\n if (!(\"value\" in cache)) {\n cache.value = fn()\n }\n return cache.value as T\n }\n}\n\nconst cachedIsDocker = memo(() => hasDockerEnv() || hasDockerCGroup())\nconst cachedIsKube = memo(() =>\n Try(() => fs.readFileSync(\"/proc/self/cgroup\", \"utf8\"))\n .map((contents) => contents.includes(\"kube\"))\n .fold(\n () => false,\n (matched) => matched,\n ),\n)\nconst cachedIsWSL = memo(() =>\n Try(() => fs.readFileSync(\"/proc/version\", \"utf8\"))\n .map((version) => version.includes(\"Microsoft\") || version.includes(\"WSL\"))\n .fold(\n () => false,\n (matched) => matched,\n ),\n)\nconst cachedIsCI = memo(\n () =>\n process.env[\"CI\"] !== undefined ||\n process.env[\"GITHUB_ACTIONS\"] !== undefined ||\n process.env[\"GITLAB_CI\"] !== undefined ||\n process.env[\"CIRCLECI\"] !== undefined ||\n process.env[\"JENKINS_URL\"] !== undefined ||\n process.env[\"TRAVIS\"] !== undefined ||\n process.env[\"BUILDKITE\"] !== undefined,\n)\n\nconst SYSTEM_ACCOUNTS = FSet.of(\"all users\", \"default\", \"default user\", \"public\")\n\nconst isSystemAccount = (name: string): boolean => {\n const lower = name.toLowerCase()\n if (SYSTEM_ACCOUNTS.contains(lower)) return true\n if (lower.startsWith(\"defaultuser\") || lower.startsWith(\"desktop.\") || lower.startsWith(\"wsiaccount\")) return true\n return false\n}\n\nconst isDirectory = (p: string): boolean =>\n Try(() => fs.statSync(p).isDirectory()).fold(\n () => false,\n (isDir) => isDir,\n )\n\nconst readRealUsers = (usersDir: string): Option<readonly string[]> => {\n const filterRealUsers = (entries: readonly string[]): readonly string[] =>\n entries.filter((name) => !isSystemAccount(name) && isDirectory(path.join(usersDir, name)))\n return Try(() => fs.readdirSync(usersDir))\n .map(filterRealUsers)\n .toOption()\n}\n\nconst resolveViaCmdExe = (usersDir: string, fallback: string): Option<string> => {\n // Convert Windows path C:\\Users\\foo → /mnt/c/Users/foo if it's a directory;\n // returns None for unparseable output or non-existent directories.\n const parseCmdOutput = (raw: string): Option<string> => {\n const match = raw.match(/^([A-Za-z]):\\\\(.*)$/)\n if (!match) return Option<string>(undefined)\n const drive = (match[1] as string).toLowerCase()\n const rest = (match[2] as string).replace(/\\\\/g, \"/\")\n const wslPath = `/mnt/${drive}/${rest}`\n return isDirectory(wslPath) ? Option(wslPath) : Option<string>(undefined)\n }\n const parsed = Try(() => execSync(\"cmd.exe /c echo %USERPROFILE%\", { timeout: 3000, encoding: \"utf8\" }).trim())\n .toOption()\n .flatMap(parseCmdOutput)\n .orElse(fallback)\n return Option(parsed)\n}\n\nconst resolveWindowsHome = (): Option<string> => {\n if (!cachedIsWSL()) return Option<string>(undefined)\n\n const usersDir = \"/mnt/c/Users\"\n return readRealUsers(usersDir).fold<Option<string>>(\n () => Option<string>(undefined),\n (realUsers) => {\n if (realUsers.length === 1) return Option(path.join(usersDir, realUsers[0] as string))\n if (realUsers.length > 1) return resolveViaCmdExe(usersDir, path.join(usersDir, realUsers[0] as string))\n return Option<string>(undefined)\n },\n )\n}\n\nconst cachedWindowsHome = memo(resolveWindowsHome)\n\ntype CloudDetection = { readonly provider: CloudProvider; readonly label: string }\n\nconst detectCloudProvider = (name: string): Option<CloudDetection> => {\n if (name === \"OneDrive\" || name.startsWith(\"OneDrive \") || name.startsWith(\"OneDrive-\")) {\n return Option({ provider: \"onedrive\" as const, label: name })\n }\n if (name === \"Google Drive\") return Option({ provider: \"gdrive\" as const, label: name })\n if (name === \"Dropbox\") return Option({ provider: \"dropbox\" as const, label: name })\n return Option<CloudDetection>(undefined)\n}\n\nconst scanDirectChildren = (home: string): readonly CloudStorageDir[] =>\n Try(() => fs.readdirSync(home))\n .map((entries) =>\n entries.flatMap((name): CloudStorageDir[] => {\n const fullPath = path.join(home, name)\n return detectCloudProvider(name).fold<CloudStorageDir[]>(\n () => [],\n (detection) =>\n isDirectory(fullPath) ? [{ provider: detection.provider, path: fullPath, label: detection.label }] : [],\n )\n }),\n )\n .fold<readonly CloudStorageDir[]>(\n () => [],\n (results) => results,\n )\n\nconst scanMacCloudStorage = (home: string): readonly CloudStorageDir[] => {\n const cloudStoragePath = path.join(home, \"Library\", \"CloudStorage\")\n return Try(() => fs.readdirSync(cloudStoragePath))\n .map((entries) =>\n entries.flatMap((name): CloudStorageDir[] => {\n const fullPath = path.join(cloudStoragePath, name)\n if (!isDirectory(fullPath)) return []\n if (name.startsWith(\"OneDrive\")) return [{ provider: \"onedrive\", path: fullPath, label: name }]\n if (name.startsWith(\"GoogleDrive\")) return [{ provider: \"gdrive\", path: fullPath, label: name }]\n return []\n }),\n )\n .fold<readonly CloudStorageDir[]>(\n () => [],\n (results) => results,\n )\n}\n\nconst scanMacICloud = (home: string): readonly CloudStorageDir[] => {\n const icloudPath = path.join(home, \"Library\", \"Mobile Documents\", \"com~apple~CloudDocs\")\n return isDirectory(icloudPath) ? [{ provider: \"icloud\", path: icloudPath, label: \"iCloud Drive\" }] : []\n}\n\nconst scanCloudStorageDirs = (home: string): readonly CloudStorageDir[] => [\n ...scanDirectChildren(home),\n ...scanMacCloudStorage(home),\n ...scanMacICloud(home),\n]\n\nexport const Platform = {\n os: (): \"darwin\" | \"linux\" | \"win32\" | string => process.platform,\n arch: (): string => process.arch,\n homeDir: (): string => os.homedir(),\n tmpDir: (): string => os.tmpdir(),\n hostname: (): string => os.hostname(),\n eol: (): string => os.EOL,\n pathSep: (): string => path.sep,\n\n isWindows: (): boolean => process.platform === \"win32\",\n isMac: (): boolean => process.platform === \"darwin\",\n isLinux: (): boolean => process.platform === \"linux\",\n\n userInfo: (): Option<UserInfo> => {\n const toUserInfo = (info: os.UserInfo<string>): UserInfo => ({\n username: info.username,\n uid: info.uid,\n gid: info.gid,\n shell: Option(info.shell),\n homedir: info.homedir,\n })\n return Try(() => os.userInfo())\n .map(toUserInfo)\n .toOption()\n },\n\n isDocker: (): boolean => cachedIsDocker(),\n isKubernetes: (): boolean => cachedIsKube(),\n isWSL: (): boolean => cachedIsWSL(),\n isCI: (): boolean => cachedIsCI(),\n\n isContainer: (): boolean => Platform.isDocker() || Platform.isKubernetes(),\n\n windowsHomeDir: (): Option<string> => cachedWindowsHome(),\n\n homeDirs: (): List<string> => {\n const primary = os.homedir()\n const windowsHome = Platform.windowsHomeDir().fold<readonly string[]>(\n () => [],\n (h) => (h !== primary ? [h] : []),\n )\n return List<string>([primary, ...windowsHome])\n },\n\n cloudStorageDirs: (home?: string): List<CloudStorageDir> => {\n if (home !== undefined) return List(scanCloudStorageDirs(home))\n const allDirs = Platform.homeDirs()\n .toArray()\n .flatMap((h) => [...scanCloudStorageDirs(h)])\n // Deduplicate by path, first-wins\n const deduped = allDirs.reduce<{\n readonly seen: ReadonlyArray<string>\n readonly results: ReadonlyArray<CloudStorageDir>\n }>(\n (acc, dir) =>\n acc.seen.includes(dir.path) ? acc : { seen: [...acc.seen, dir.path], results: [...acc.results, dir] },\n { seen: [], results: [] },\n )\n return List(deduped.results)\n },\n}\n"],"mappings":"4LAuBA,MAAMI,MAA8BC,MAAUJ,EAAG,SAAS,aAAa,CAAC,CAAC,CAAC,UAAU,EAE9E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,IACJG,EAAI,KAAK,SAASC,EAAI,IAAI,EAAID,EAAM,CAAE,KAAM,CAAC,GAAGA,EAAI,KAAMC,EAAI,IAAI,EAAG,QAAS,CAAC,GAAGD,EAAI,QAASC,CAAG,CAAE,EACtG,CAAE,KAAM,CAAC,EAAG,QAAS,CAAC,CAAE,CAC1B,EACA,OAAOH,EAAKC,EAAQ,OAAO,CAC7B,CACF"}
@@ -1,2 +1,2 @@
1
- import{ProcessError as e}from"../errors/errors.js";import{Err as t,Ok as n,Option as r,Try as i}from"functype";import{exec as a,execSync as o}from"node:child_process";const s={exec:(i,o)=>new Promise(s=>{a(i,{timeout:o?.timeout,cwd:o?.cwd},(a,o,c)=>{s(a?t(e(i,r(typeof a.code==`number`?a.code:void 0),String(c))):n({stdout:String(o),stderr:String(c),exitCode:0}))})}),execSync:(t,n)=>i(()=>o(t,{timeout:n?.timeout,cwd:n?.cwd,encoding:`utf8`,stdio:[`pipe`,`pipe`,`pipe`]})).toEither(n=>{if(n instanceof Error&&`status`in n&&`stderr`in n){let i=n;return e(t,r(i.status),String(i.stderr))}return e(t,r(void 0),``,n instanceof Error?n.message:String(n))}).map(e=>({stdout:String(e),stderr:``,exitCode:0}))};export{s as Process};
1
+ import{ProcessError as e}from"../errors/errors.js";import{Err as t,Ok as n,Option as r,Try as i}from"functype";import{exec as a,execSync as o}from"node:child_process";const s={exec:(i,o)=>new Promise(s=>{a(i,{timeout:o?.timeout,cwd:o?.cwd},(a,o,c)=>{if(a){let n=r(typeof a.code==`number`?a.code:void 0);s(t(e(i,n,String(c))))}else s(n({stdout:String(o),stderr:String(c),exitCode:0}))})}),execSync:(t,n)=>i(()=>o(t,{timeout:n?.timeout,cwd:n?.cwd,encoding:`utf8`,stdio:[`pipe`,`pipe`,`pipe`]})).toEither(n=>{if(n instanceof Error&&`status`in n&&`stderr`in n){let i=n;return e(t,r(i.status),String(i.stderr))}return e(t,r(void 0),``,n instanceof Error?n.message:String(n))}).map(e=>({stdout:String(e),stderr:``,exitCode:0}))};export{s as Process};
2
2
  //# sourceMappingURL=Process.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Process.js","names":["nodeExecSync"],"sources":["../../src/process/Process.ts"],"sourcesContent":["import { exec as execCb, execSync as nodeExecSync } from \"node:child_process\"\n\nimport type { Either, TaskResult } from \"functype\"\nimport { Err, Ok, Option, Try } from \"functype\"\n\nimport { ProcessError } from \"../errors/errors\"\n\nexport type ExecResult = {\n readonly stdout: string\n readonly stderr: string\n readonly exitCode: number\n}\n\nexport const Process = {\n exec: (command: string, options?: { timeout?: number; cwd?: string }): TaskResult<ExecResult> => {\n return new Promise((resolve) => {\n execCb(command, { timeout: options?.timeout, cwd: options?.cwd }, (error, stdout, stderr) => {\n if (error) {\n // exec callback error has `code` as exit code (number) — distinct from Node errno `code` (string)\n const exitCode = Option(typeof error.code === \"number\" ? error.code : undefined)\n resolve(Err(ProcessError(command, exitCode, String(stderr))))\n } else {\n resolve(Ok({ stdout: String(stdout), stderr: String(stderr), exitCode: 0 }))\n }\n })\n })\n },\n\n execSync: (command: string, options?: { timeout?: number; cwd?: string }): Either<ProcessError, ExecResult> => {\n const buildProcessError = (error: unknown): ProcessError => {\n if (error instanceof Error && \"status\" in error && \"stderr\" in error) {\n const execError = error as Error & { status: number; stderr: string }\n return ProcessError(command, Option(execError.status), String(execError.stderr))\n }\n return ProcessError(\n command,\n Option<number>(undefined),\n \"\",\n error instanceof Error ? error.message : String(error),\n )\n }\n return Try(() =>\n nodeExecSync(command, {\n timeout: options?.timeout,\n cwd: options?.cwd,\n encoding: \"utf8\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n }),\n )\n .toEither(buildProcessError)\n .map((stdout): ExecResult => ({ stdout: String(stdout), stderr: \"\", exitCode: 0 }))\n },\n}\n"],"mappings":"uKAaA,MAAa,EAAU,CACrB,MAAO,EAAiB,IACf,IAAI,QAAS,GAAY,CAC9B,EAAO,EAAS,CAAE,QAAS,GAAS,QAAS,IAAK,GAAS,GAAI,GAAI,EAAO,EAAQ,IAAW,CAIzF,EAHE,EAGM,EAAI,EAAa,EADR,EAAO,OAAO,EAAM,MAAS,SAAW,EAAM,KAAO,IAAA,EAC7B,EAAG,OAAO,CAAM,CAAC,CAAC,EAEnD,EAAG,CAAE,OAAQ,OAAO,CAAM,EAAG,OAAQ,OAAO,CAAM,EAAG,SAAU,CAAE,CAAC,CAAC,CAE/E,CAAC,CACH,CAAC,EAGH,UAAW,EAAiB,IAanB,MACLA,EAAa,EAAS,CACpB,QAAS,GAAS,QAClB,IAAK,GAAS,IACd,SAAU,OACV,MAAO,CAAC,OAAQ,OAAQ,MAAM,CAChC,CAAC,CACH,CAAC,CACE,SApBwB,GAAiC,CAC1D,GAAI,aAAiB,OAAS,WAAY,GAAS,WAAY,EAAO,CACpE,IAAM,EAAY,EAClB,OAAO,EAAa,EAAS,EAAO,EAAU,MAAM,EAAG,OAAO,EAAU,MAAM,CAAC,CACjF,CACA,OAAO,EACL,EACA,EAAe,IAAA,EAAS,EACxB,GACA,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,CACvD,CACF,CAS6B,CAAC,CAC3B,IAAK,IAAwB,CAAE,OAAQ,OAAO,CAAM,EAAG,OAAQ,GAAI,SAAU,CAAE,EAAE,CAExF"}
1
+ {"version":3,"file":"Process.js","names":["nodeExecSync","Process","exec","command","options","error","exitCode","Option","resolve","Err","ProcessError","stderr","Ok","stdout","Try","execSync","execError"],"sources":["../../src/process/Process.ts"],"sourcesContent":["import { exec as execCb, execSync as nodeExecSync } from \"node:child_process\"\n\nimport type { Either, TaskResult } from \"functype\"\nimport { Err, Ok, Option, Try } from \"functype\"\n\nimport { ProcessError } from \"../errors/errors\"\n\nexport type ExecResult = {\n readonly stdout: string\n readonly stderr: string\n readonly exitCode: number\n}\n\nexport const Process = {\n exec: (command: string, options?: { timeout?: number; cwd?: string }): TaskResult<ExecResult> => {\n return new Promise((resolve) => {\n execCb(command, { timeout: options?.timeout, cwd: options?.cwd }, (error, stdout, stderr) => {\n if (error) {\n // exec callback error has `code` as exit code (number) — distinct from Node errno `code` (string)\n const exitCode = Option(typeof error.code === \"number\" ? error.code : undefined)\n resolve(Err(ProcessError(command, exitCode, String(stderr))))\n } else {\n resolve(Ok({ stdout: String(stdout), stderr: String(stderr), exitCode: 0 }))\n }\n })\n })\n },\n\n execSync: (command: string, options?: { timeout?: number; cwd?: string }): Either<ProcessError, ExecResult> => {\n const buildProcessError = (error: unknown): ProcessError => {\n if (error instanceof Error && \"status\" in error && \"stderr\" in error) {\n const execError = error as Error & { status: number; stderr: string }\n return ProcessError(command, Option(execError.status), String(execError.stderr))\n }\n return ProcessError(\n command,\n Option<number>(undefined),\n \"\",\n error instanceof Error ? error.message : String(error),\n )\n }\n return Try(() =>\n nodeExecSync(command, {\n timeout: options?.timeout,\n cwd: options?.cwd,\n encoding: \"utf8\",\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n }),\n )\n .toEither(buildProcessError)\n .map((stdout): ExecResult => ({ stdout: String(stdout), stderr: \"\", exitCode: 0 }))\n },\n}\n"],"mappings":"uKAaA,MAAaC,EAAU,CACrB,MAAO,EAAiB,IACf,IAAI,QAAS,GAAY,CAC9BC,EAAOC,EAAS,CAAE,QAASC,GAAS,QAAS,IAAKA,GAAS,GAAI,GAAI,EAAO,EAAQ,IAAW,CAC3F,GAAIC,EAAO,CAET,IAAMC,EAAWC,EAAO,OAAOF,EAAM,MAAS,SAAWA,EAAM,KAAO,IAAA,EAAS,EAC/EG,EAAQC,EAAIC,EAAaP,EAASG,EAAU,OAAOK,CAAM,CAAC,CAAC,CAAC,CAC9D,MACEH,EAAQI,EAAG,CAAE,OAAQ,OAAOC,CAAM,EAAG,OAAQ,OAAOF,CAAM,EAAG,SAAU,CAAE,CAAC,CAAC,CAE/E,CAAC,CACH,CAAC,EAGH,UAAW,EAAiB,IAanBG,MACLd,EAAaG,EAAS,CACpB,QAASC,GAAS,QAClB,IAAKA,GAAS,IACd,SAAU,OACV,MAAO,CAAC,OAAQ,OAAQ,MAAM,CAChC,CAAC,CACH,CAAC,CACE,SApBwB,GAAiC,CAC1D,GAAIC,aAAiB,OAAS,WAAYA,GAAS,WAAYA,EAAO,CACpE,IAAMW,EAAYX,EAClB,OAAOK,EAAaP,EAASI,EAAOS,EAAU,MAAM,EAAG,OAAOA,EAAU,MAAM,CAAC,CACjF,CACA,OAAON,EACLP,EACAI,EAAe,IAAA,EAAS,EACxB,GACAF,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CACvD,CACF,CAS6B,CAAC,CAC3B,IAAK,IAAwB,CAAE,OAAQ,OAAOQ,CAAM,EAAG,OAAQ,GAAI,SAAU,CAAE,EAAE,CAExF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "functype-os",
3
- "version": "1.8.0",
3
+ "version": "1.10.0",
4
4
  "description": "Functional OS utilities using functype data structures — env vars, path expansion, file ops, platform detection",
5
5
  "keywords": [
6
6
  "functype",
@@ -26,12 +26,12 @@
26
26
  "functype": ">=0.60.0"
27
27
  },
28
28
  "devDependencies": {
29
- "@types/node": "^24.13.3",
29
+ "@types/node": "^24.19.0",
30
30
  "eslint-config-prettier": "^10.1.8",
31
- "ts-builds": "^3.2.3",
32
- "tsdown": "^0.22.14",
33
- "vitest": "^4.1.10",
34
- "functype": "^1.8.0"
31
+ "functype": "^1.10.0",
32
+ "ts-builds": "^3.4.3",
33
+ "tsdown": "^0.23.0",
34
+ "vitest": "^4.1.11"
35
35
  },
36
36
  "type": "module",
37
37
  "main": "./dist/index.js",