@intellectual-frontiers/core 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Intellectual Frontiers
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,9 @@
1
- # Temporary Holding Version
1
+ # @intellectual-frontiers/core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Core: errors as values, exhaustive matching, branded types, decoders from unknown to typed values, pure text helpers, type-level tests, graphs of work and exact optional objects; no dependency, no host, the same code on Bun, Node 26 and in a browser.
4
+
5
+ ```sh
6
+ bun add @intellectual-frontiers/core # or: npm install @intellectual-frontiers/core
7
+ ```
8
+
9
+ Sources and specifications: https://github.com/intellectual-frontiers/.github/tree/main/commons/core
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Exhaustive matching: a `switch` on a union's `kind` ends with `default: return absurd(value)`, so that an alternative left out does not
3
+ * compile (0001-core FR-001). One name, `absurd`, for what erga called `absurd` and the machine setup `assertNever`.
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * import { absurd } from "./absurd.js";
8
+ * type Shape = { readonly kind: "circle"; readonly r: number } | { readonly kind: "square"; readonly side: number };
9
+ * function area(s: Shape): number {
10
+ * switch (s.kind) {
11
+ * case "circle": return Math.PI * s.r ** 2;
12
+ * case "square": return s.side ** 2;
13
+ * default: return absurd(s);
14
+ * }
15
+ * }
16
+ * ```
17
+ *
18
+ * @module
19
+ */
20
+ /** The end of an exhaustive `switch`: its argument has the type `never` only when every alternative was handled. It throws if reached. */
21
+ export declare function absurd(value: never): never;
package/dist/absurd.js ADDED
@@ -0,0 +1,24 @@
1
+ // Spec: 0001-core FR-001
2
+ /**
3
+ * Exhaustive matching: a `switch` on a union's `kind` ends with `default: return absurd(value)`, so that an alternative left out does not
4
+ * compile (0001-core FR-001). One name, `absurd`, for what erga called `absurd` and the machine setup `assertNever`.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * import { absurd } from "./absurd.ts";
9
+ * type Shape = { readonly kind: "circle"; readonly r: number } | { readonly kind: "square"; readonly side: number };
10
+ * function area(s: Shape): number {
11
+ * switch (s.kind) {
12
+ * case "circle": return Math.PI * s.r ** 2;
13
+ * case "square": return s.side ** 2;
14
+ * default: return absurd(s);
15
+ * }
16
+ * }
17
+ * ```
18
+ *
19
+ * @module
20
+ */
21
+ /** The end of an exhaustive `switch`: its argument has the type `never` only when every alternative was handled. It throws if reached. */
22
+ export function absurd(value) {
23
+ throw new Error(`an alternative was not handled: ${JSON.stringify(value)}`);
24
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Identifiers are types: a branded type is a plain value that the compiler keeps apart from others of the same shape, made only by the
3
+ * function that validates it (0001-core FR-001).
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * import type { Brand } from "./brand.js";
8
+ * type UserId = Brand<string, "UserId">;
9
+ * const userId = (s: string): UserId | undefined => /^u[0-9]+$/.test(s) ? s as UserId : undefined;
10
+ * ```
11
+ *
12
+ * @module
13
+ */
14
+ /** A value of `T` that has been validated as a `B`; the brand exists only for the compiler and costs nothing at run time. */
15
+ export type Brand<T, B extends string> = T & {
16
+ readonly "@ifc/brand": B;
17
+ };
package/dist/brand.js ADDED
@@ -0,0 +1,15 @@
1
+ // Spec: 0001-core FR-001
2
+ /**
3
+ * Identifiers are types: a branded type is a plain value that the compiler keeps apart from others of the same shape, made only by the
4
+ * function that validates it (0001-core FR-001).
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * import type { Brand } from "./brand.ts";
9
+ * type UserId = Brand<string, "UserId">;
10
+ * const userId = (s: string): UserId | undefined => /^u[0-9]+$/.test(s) ? s as UserId : undefined;
11
+ * ```
12
+ *
13
+ * @module
14
+ */
15
+ export {};
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Decoders: everything that enters a program is decoded from `unknown` into a typed value once, where it enters, and past a decoder no code
3
+ * holds `unknown` (0001-core FR-002). The type assertions a decoder needs are confined to this file. Taken from erga's
4
+ * kernel (`decode.decode.ts`), with `nullable`, `record`, `tuple` and `json` added.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * import { integer, object, string } from "./decode.js";
9
+ * const person = object({ name: string, age: integer });
10
+ * person({ name: "Ada", age: 36 }); // { kind: "ok", value: { name: "Ada", age: 36 } }
11
+ * ```
12
+ *
13
+ * @module
14
+ */
15
+ import type { Brand } from "./brand.js";
16
+ import { type Result } from "./result.js";
17
+ /** Why a value did not decode: the path of the first field that failed, what was expected there and what was found. */
18
+ export type DecodeError = {
19
+ readonly kind: "decode";
20
+ readonly path: string;
21
+ readonly expected: string;
22
+ readonly found: string;
23
+ };
24
+ /** A function from anything to a typed value, or the reason it is not one; `path` names where the value sits, `$` by default. */
25
+ export type Decoder<T> = (input: unknown, path?: string) => Result<T, DecodeError>;
26
+ /** The type a decoder gives. */
27
+ export type Decoded<D> = D extends Decoder<infer T> ? T : never;
28
+ /** A short description of a value for an error message: its type, and the start of it where it is a string. */
29
+ export declare function describe(input: unknown): string;
30
+ /** A decode error as one sentence: `$.age: expected an integer, found the string "x"`. */
31
+ export declare function formatDecodeError(e: DecodeError): string;
32
+ /** A string. */
33
+ export declare const string: Decoder<string>;
34
+ /** A finite number. */
35
+ export declare const number: Decoder<number>;
36
+ /** An integer. */
37
+ export declare const integer: Decoder<number>;
38
+ /** A boolean. */
39
+ export declare const boolean: Decoder<boolean>;
40
+ /** Any value at all, kept as `unknown`: for a field whose contents another decoder reads later. */
41
+ export declare const unknownValue: Decoder<unknown>;
42
+ /** One of the given string literals. */
43
+ export declare function literal<const L extends readonly string[]>(...values: L): Decoder<L[number]>;
44
+ /** `null`, or what `inner` decodes. */
45
+ export declare function nullable<T>(inner: Decoder<T>): Decoder<T | null>;
46
+ /** An array whose every element decodes. */
47
+ export declare function array<T>(element: Decoder<T>): Decoder<readonly T[]>;
48
+ /** An array of exactly as many elements as decoders, each decoded by its own. */
49
+ export declare function tuple<const D extends readonly Decoder<unknown>[]>(...elements: D): Decoder<{
50
+ readonly [K in keyof D]: Decoded<D[K]>;
51
+ }>;
52
+ /** An object used as a map: every own key kept, every value decoded. */
53
+ export declare function record<T>(value: Decoder<T>): Decoder<Readonly<Record<string, T>>>;
54
+ /** The decoders of an object's fields. */
55
+ export type Fields = Readonly<Record<string, Decoder<unknown>>>;
56
+ /** The value an object decoder gives: the required fields, and the optional ones that may be absent. */
57
+ export type ObjectOf<R extends Fields, O extends Fields> = {
58
+ readonly [K in keyof R]: Decoded<R[K]>;
59
+ } & {
60
+ readonly [K in keyof O]?: Decoded<O[K]>;
61
+ };
62
+ /** An object whose every required field decodes; `optional` fields may be absent (or `undefined`), and are then absent from the value. Other fields are dropped. */
63
+ export declare function object<R extends Fields, O extends Fields = Record<never, never>>(required: R, optional?: O): Decoder<ObjectOf<R, O>>;
64
+ /** A union of object types told apart by their `kind`: the decoder of the alternative the input's `kind` names. */
65
+ export declare function tagged<const D extends Readonly<Record<string, Decoder<{
66
+ readonly kind: string;
67
+ }>>>>(alternatives: D): Decoder<Decoded<D[keyof D]>>;
68
+ /** The first of several decoders that accepts the input. */
69
+ export declare function oneOf<const D extends readonly Decoder<unknown>[]>(...alternatives: D): Decoder<Decoded<D[number]>>;
70
+ /** A decoded value transformed, as a decoder of the new type. */
71
+ export declare function mapDecoder<T, U>(base: Decoder<T>, f: (value: T) => U): Decoder<U>;
72
+ /** A value of `T` validated as a `B`: the one way a branded type is made. */
73
+ export declare function refine<T, B extends string>(base: Decoder<T>, name: B, valid: (value: T) => boolean): Decoder<Brand<T, B>>;
74
+ /** Text parsed as JSON and decoded; text that is not JSON is an error at `$` that says so. */
75
+ export declare function json<T>(text: string, decoder: Decoder<T>): Result<T, DecodeError>;
package/dist/decode.js ADDED
@@ -0,0 +1,165 @@
1
+ import { err, ok } from "./result.js";
2
+ /** A short description of a value for an error message: its type, and the start of it where it is a string. */
3
+ export function describe(input) {
4
+ if (input === null)
5
+ return "null";
6
+ if (input === undefined)
7
+ return "nothing";
8
+ if (Array.isArray(input))
9
+ return "an array";
10
+ const t = typeof input;
11
+ if (t === "string")
12
+ return `the string ${JSON.stringify(input).slice(0, 60)}`;
13
+ if (t === "object")
14
+ return "an object";
15
+ if (t === "function")
16
+ return "a function";
17
+ if (typeof input === "symbol")
18
+ return "a symbol";
19
+ if (typeof input === "number" || typeof input === "bigint" || typeof input === "boolean")
20
+ return `${t} ${String(input)}`;
21
+ return t;
22
+ }
23
+ function fail(path, expected, input) {
24
+ return err({ kind: "decode", path, expected, found: describe(input) });
25
+ }
26
+ /** A decode error as one sentence: `$.age: expected an integer, found the string "x"`. */
27
+ export function formatDecodeError(e) {
28
+ return `${e.path}: expected ${e.expected}, found ${e.found}`;
29
+ }
30
+ /** A string. */
31
+ export const string = (input, path = "$") => (typeof input === "string" ? ok(input) : fail(path, "a string", input));
32
+ /** A finite number. */
33
+ export const number = (input, path = "$") => typeof input === "number" && Number.isFinite(input) ? ok(input) : fail(path, "a finite number", input);
34
+ /** An integer. */
35
+ export const integer = (input, path = "$") => typeof input === "number" && Number.isInteger(input) ? ok(input) : fail(path, "an integer", input);
36
+ /** A boolean. */
37
+ export const boolean = (input, path = "$") => (typeof input === "boolean" ? ok(input) : fail(path, "a boolean", input));
38
+ /** Any value at all, kept as `unknown`: for a field whose contents another decoder reads later. */
39
+ export const unknownValue = (input) => ok(input);
40
+ /** One of the given string literals. */
41
+ export function literal(...values) {
42
+ return (input, path = "$") => typeof input === "string" && values.includes(input) ? ok(input) : fail(path, `one of ${values.join(", ")}`, input);
43
+ }
44
+ /** `null`, or what `inner` decodes. */
45
+ export function nullable(inner) {
46
+ return (input, path = "$") => (input === null ? ok(null) : inner(input, path));
47
+ }
48
+ /** An array whose every element decodes. */
49
+ export function array(element) {
50
+ return (input, path = "$") => {
51
+ if (!Array.isArray(input))
52
+ return fail(path, "an array", input);
53
+ const out = [];
54
+ for (const [i, value] of input.entries()) {
55
+ const r = element(value, `${path}[${i}]`);
56
+ if (r.kind === "err")
57
+ return r;
58
+ out.push(r.value);
59
+ }
60
+ return ok(out);
61
+ };
62
+ }
63
+ /** An array of exactly as many elements as decoders, each decoded by its own. */
64
+ export function tuple(...elements) {
65
+ return (input, path = "$") => {
66
+ if (!Array.isArray(input) || input.length !== elements.length)
67
+ return fail(path, `an array of ${elements.length}`, input);
68
+ const out = [];
69
+ for (const [i, decoder] of elements.entries()) {
70
+ const r = decoder(input[i], `${path}[${i}]`);
71
+ if (r.kind === "err")
72
+ return r;
73
+ out.push(r.value);
74
+ }
75
+ return ok(out);
76
+ };
77
+ }
78
+ const isPlainObject = (input) => typeof input === "object" && input !== null && !Array.isArray(input);
79
+ /** An object used as a map: every own key kept, every value decoded. */
80
+ export function record(value) {
81
+ return (input, path = "$") => {
82
+ if (!isPlainObject(input))
83
+ return fail(path, "an object", input);
84
+ const out = {};
85
+ for (const key of Object.keys(input)) {
86
+ const r = value(Reflect.get(input, key), `${path}.${key}`);
87
+ if (r.kind === "err")
88
+ return r;
89
+ out[key] = r.value;
90
+ }
91
+ return ok(out);
92
+ };
93
+ }
94
+ /** An object whose every required field decodes; `optional` fields may be absent (or `undefined`), and are then absent from the value. Other fields are dropped. */
95
+ export function object(required, optional) {
96
+ return (input, path = "$") => {
97
+ if (!isPlainObject(input))
98
+ return fail(path, "an object", input);
99
+ const out = {};
100
+ for (const [key, decoder] of Object.entries(required)) {
101
+ const r = decoder(Reflect.get(input, key), `${path}.${key}`);
102
+ if (r.kind === "err")
103
+ return r;
104
+ out[key] = r.value;
105
+ }
106
+ for (const [key, decoder] of Object.entries(optional ?? {})) {
107
+ const value = Reflect.get(input, key);
108
+ if (value === undefined)
109
+ continue;
110
+ const r = decoder(value, `${path}.${key}`);
111
+ if (r.kind === "err")
112
+ return r;
113
+ out[key] = r.value;
114
+ }
115
+ return ok(out);
116
+ };
117
+ }
118
+ /** A union of object types told apart by their `kind`: the decoder of the alternative the input's `kind` names. */
119
+ export function tagged(alternatives) {
120
+ return (input, path = "$") => {
121
+ const kind = isPlainObject(input) ? Reflect.get(input, "kind") : undefined;
122
+ const decoder = typeof kind === "string" && Object.hasOwn(alternatives, kind) ? alternatives[kind] : undefined;
123
+ if (decoder === undefined)
124
+ return fail(`${path}.kind`, `one of ${Object.keys(alternatives).join(", ")}`, kind);
125
+ return decoder(input, path);
126
+ };
127
+ }
128
+ /** The first of several decoders that accepts the input. */
129
+ export function oneOf(...alternatives) {
130
+ return (input, path = "$") => {
131
+ for (const decoder of alternatives) {
132
+ const r = decoder(input, path);
133
+ if (r.kind === "ok")
134
+ return r;
135
+ }
136
+ return fail(path, `one of ${alternatives.length} alternatives`, input);
137
+ };
138
+ }
139
+ /** A decoded value transformed, as a decoder of the new type. */
140
+ export function mapDecoder(base, f) {
141
+ return (input, path = "$") => {
142
+ const r = base(input, path);
143
+ return r.kind === "ok" ? ok(f(r.value)) : r;
144
+ };
145
+ }
146
+ /** A value of `T` validated as a `B`: the one way a branded type is made. */
147
+ export function refine(base, name, valid) {
148
+ return (input, path = "$") => {
149
+ const r = base(input, path);
150
+ if (r.kind === "err")
151
+ return r;
152
+ return valid(r.value) ? ok(r.value) : fail(path, `a ${name}`, input);
153
+ };
154
+ }
155
+ /** Text parsed as JSON and decoded; text that is not JSON is an error at `$` that says so. */
156
+ export function json(text, decoder) {
157
+ let value;
158
+ try {
159
+ value = JSON.parse(text);
160
+ }
161
+ catch (e) {
162
+ return err({ kind: "decode", path: "$", expected: "JSON", found: e instanceof Error ? e.message : String(e) });
163
+ }
164
+ return decoder(value);
165
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Graphs of work: an order in which each node comes after the nodes it needs (or the cycle that makes one impossible), and a schedule
3
+ * that runs each node the moment the nodes it needs are done, as many at once as asked, skipping what depends on a failure and holding
4
+ * back nothing else (0001-core FR-005). Taken from erga's `lib/ts/graph` (the build graph), with nodes of any string
5
+ * type.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * import { order } from "./graph.js";
10
+ * order(new Map([["test", ["build"]], ["build", ["fetch"]], ["fetch", []]])); // { kind: "ok", value: ["fetch", "build", "test"] }
11
+ * ```
12
+ *
13
+ * @module
14
+ */
15
+ import { type Result } from "./result.js";
16
+ /** A graph: each node and the nodes it needs. A needed node that is not a key of the graph is outside it, and ignored. */
17
+ export type Graph<N extends string> = ReadonlyMap<N, readonly N[]>;
18
+ /** A cycle among nodes: the nodes in it, in order, the first repeated at the end. */
19
+ export type Cycle<N extends string> = {
20
+ readonly kind: "cycle";
21
+ readonly nodes: readonly N[];
22
+ };
23
+ /** The nodes in an order where each comes after every node it needs; ties broken by name, so the order is the same every time. Or the first cycle found. */
24
+ export declare function order<N extends string>(graph: Graph<N>): Result<readonly N[], Cycle<N>>;
25
+ /** How one node of a scheduled run ended. */
26
+ export type Ran = "done" | "failed" | "skipped";
27
+ /**
28
+ * Every node of an acyclic graph run, each after the nodes it needs, at most `jobs` at once: `start` runs a node and says whether it
29
+ * succeeded; a node whose needed node failed or was skipped is skipped, and `skip` is told which node it waited for. How each node ended.
30
+ * A cycle, or a `start` that rejects, rejects the schedule.
31
+ */
32
+ export declare function schedule<N extends string>(graph: Graph<N>, jobs: number, start: (n: N) => Promise<boolean>, skip?: (n: N, because: N) => void): Promise<ReadonlyMap<N, Ran>>;
package/dist/graph.js ADDED
@@ -0,0 +1,98 @@
1
+ // Spec: 0001-core FR-005
2
+ /**
3
+ * Graphs of work: an order in which each node comes after the nodes it needs (or the cycle that makes one impossible), and a schedule
4
+ * that runs each node the moment the nodes it needs are done, as many at once as asked, skipping what depends on a failure and holding
5
+ * back nothing else (0001-core FR-005). Taken from erga's `lib/ts/graph` (the build graph), with nodes of any string
6
+ * type.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * import { order } from "./graph.ts";
11
+ * order(new Map([["test", ["build"]], ["build", ["fetch"]], ["fetch", []]])); // { kind: "ok", value: ["fetch", "build", "test"] }
12
+ * ```
13
+ *
14
+ * @module
15
+ */
16
+ import { err, ok } from "./result.js";
17
+ /** The nodes in an order where each comes after every node it needs; ties broken by name, so the order is the same every time. Or the first cycle found. */
18
+ export function order(graph) {
19
+ const out = [];
20
+ const state = new Map();
21
+ const path = [];
22
+ const visit = (n) => {
23
+ const s = state.get(n);
24
+ if (s === "done")
25
+ return undefined;
26
+ if (s === "visiting")
27
+ return { kind: "cycle", nodes: [...path.slice(path.indexOf(n)), n] };
28
+ state.set(n, "visiting");
29
+ path.push(n);
30
+ for (const m of [...(graph.get(n) ?? [])].sort()) {
31
+ if (!graph.has(m))
32
+ continue;
33
+ const c = visit(m);
34
+ if (c !== undefined)
35
+ return c;
36
+ }
37
+ path.pop();
38
+ state.set(n, "done");
39
+ out.push(n);
40
+ return undefined;
41
+ };
42
+ for (const n of [...graph.keys()].sort()) {
43
+ const c = visit(n);
44
+ if (c !== undefined)
45
+ return err(c);
46
+ }
47
+ return ok(out);
48
+ }
49
+ /**
50
+ * Every node of an acyclic graph run, each after the nodes it needs, at most `jobs` at once: `start` runs a node and says whether it
51
+ * succeeded; a node whose needed node failed or was skipped is skipped, and `skip` is told which node it waited for. How each node ended.
52
+ * A cycle, or a `start` that rejects, rejects the schedule.
53
+ */
54
+ export async function schedule(graph, jobs, start, skip = () => { }) {
55
+ const ran = new Map();
56
+ const waiting = new Set(graph.keys());
57
+ const inside = (n) => (graph.get(n) ?? []).filter((m) => graph.has(m));
58
+ const limit = Math.max(1, Math.floor(jobs));
59
+ let running = 0;
60
+ let stopped = false;
61
+ return await new Promise((resolve, reject) => {
62
+ const pump = () => {
63
+ if (stopped)
64
+ return;
65
+ for (let changed = true; changed;) {
66
+ changed = false;
67
+ for (const n of [...waiting].sort()) {
68
+ const before = inside(n);
69
+ const bad = before.find((m) => ran.get(m) === "failed" || ran.get(m) === "skipped");
70
+ if (bad !== undefined) {
71
+ waiting.delete(n);
72
+ ran.set(n, "skipped");
73
+ skip(n, bad);
74
+ changed = true;
75
+ continue;
76
+ }
77
+ if (running >= limit || !before.every((m) => ran.get(m) === "done"))
78
+ continue;
79
+ waiting.delete(n);
80
+ running++;
81
+ start(n).then((good) => {
82
+ running--;
83
+ ran.set(n, good ? "done" : "failed");
84
+ pump();
85
+ }, (e) => {
86
+ stopped = true;
87
+ reject(e instanceof Error ? e : new Error(`the node ${n} failed to start`, { cause: e }));
88
+ });
89
+ }
90
+ }
91
+ if (waiting.size === 0 && running === 0)
92
+ resolve(ran);
93
+ else if (running === 0)
94
+ reject(new Error(`the graph has a cycle among ${[...waiting].sort().join(", ")}`));
95
+ };
96
+ pump();
97
+ });
98
+ }
package/dist/mod.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Core, the foundation of Intellectual Frontiers Commons (its specification 0001-core): errors as values (`Result`), exhaustive matching (`absurd`), branded types (`Brand`), decoders from `unknown`
3
+ * to typed values, the pure text helpers, type-level tests, graphs of work and objects made for `exactOptionalPropertyTypes`. It imports nothing, names no host global and runs wherever ECMAScript does
4
+ * (Bun, Node, a browser, a Worker).
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * import { absurd, err, ok, type Result } from "@intellectual-frontiers/core";
9
+ * type Stage = { readonly kind: "intake" } | { readonly kind: "review" };
10
+ * function next(s: Stage): Result<Stage, string> {
11
+ * switch (s.kind) {
12
+ * case "intake": return ok({ kind: "review" });
13
+ * case "review": return err("review is the last stage");
14
+ * default: return absurd(s);
15
+ * }
16
+ * }
17
+ * ```
18
+ *
19
+ * @module
20
+ */
21
+ export { absurd } from "./absurd.js";
22
+ export type { Brand } from "./brand.js";
23
+ export { array, boolean, describe, formatDecodeError, integer, json, literal, mapDecoder, nullable, number, object, oneOf, record, refine, string, tagged, tuple, unknownValue, } from "./decode.js";
24
+ export type { Decoded, DecodeError, Decoder, Fields, ObjectOf } from "./decode.js";
25
+ export { order, schedule } from "./graph.js";
26
+ export type { Cycle, Graph, Ran } from "./graph.js";
27
+ export { compact } from "./objects.js";
28
+ export type { Compact, Simplify } from "./objects.js";
29
+ export { all, andThen, attempt, done, err, isErr, isOk, map, mapErr, match, ok, orElse, settle, unwrapOr } from "./result.js";
30
+ export type { Err, Ok, Result } from "./result.js";
31
+ export { ANSI, lf, plain, quoteArgs, splitArgs } from "./text.js";
32
+ export { expectType } from "./types.js";
33
+ export type { Equal, Extends, Not } from "./types.js";
package/dist/mod.js ADDED
@@ -0,0 +1,28 @@
1
+ // Spec: 0001-core FR-007
2
+ /**
3
+ * Core, the foundation of Intellectual Frontiers Commons (its specification 0001-core): errors as values (`Result`), exhaustive matching (`absurd`), branded types (`Brand`), decoders from `unknown`
4
+ * to typed values, the pure text helpers, type-level tests, graphs of work and objects made for `exactOptionalPropertyTypes`. It imports nothing, names no host global and runs wherever ECMAScript does
5
+ * (Bun, Node, a browser, a Worker).
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * import { absurd, err, ok, type Result } from "@intellectual-frontiers/core";
10
+ * type Stage = { readonly kind: "intake" } | { readonly kind: "review" };
11
+ * function next(s: Stage): Result<Stage, string> {
12
+ * switch (s.kind) {
13
+ * case "intake": return ok({ kind: "review" });
14
+ * case "review": return err("review is the last stage");
15
+ * default: return absurd(s);
16
+ * }
17
+ * }
18
+ * ```
19
+ *
20
+ * @module
21
+ */
22
+ export { absurd } from "./absurd.js";
23
+ export { array, boolean, describe, formatDecodeError, integer, json, literal, mapDecoder, nullable, number, object, oneOf, record, refine, string, tagged, tuple, unknownValue, } from "./decode.js";
24
+ export { order, schedule } from "./graph.js";
25
+ export { compact } from "./objects.js";
26
+ export { all, andThen, attempt, done, err, isErr, isOk, map, mapErr, match, ok, orElse, settle, unwrapOr } from "./result.js";
27
+ export { ANSI, lf, plain, quoteArgs, splitArgs } from "./text.js";
28
+ export { expectType } from "./types.js";
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Objects made for `exactOptionalPropertyTypes` (0001-core FR-006): `compact` builds an object from fields some of
3
+ * which may be `undefined`, leaving those out, and its type says so exactly, so that a caller writes `compact({ a, b: maybe })` instead of
4
+ * `{ a, ...(maybe === undefined ? {} : { b: maybe }) }` once for each optional field.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * import { compact } from "./objects.js";
9
+ * const timeout: number | undefined = undefined;
10
+ * const options = compact({ url: "https://example.com", timeout }); // { url: string; timeout?: number }, and no `timeout` key
11
+ * ```
12
+ *
13
+ * @module
14
+ */
15
+ /** One object type with the members of an intersection, so that it reads (and compares) as one. */
16
+ export type Simplify<T> = {
17
+ [K in keyof T]: T[K];
18
+ } & {};
19
+ /** The keys of `T` whose type admits `undefined`. */
20
+ type MaybeKeys<T> = {
21
+ [K in keyof T]-?: undefined extends T[K] ? K : never;
22
+ }[keyof T];
23
+ /**
24
+ * `T` with each field whose type admits `undefined` made optional without `undefined`, and every other field kept as it is (`readonly`
25
+ * kept): the type of `compact(value)` under `exactOptionalPropertyTypes`.
26
+ */
27
+ export type Compact<T> = Simplify<{
28
+ [K in keyof T as K extends MaybeKeys<T> ? never : K]: T[K];
29
+ } & {
30
+ [K in keyof T as K extends MaybeKeys<T> ? K : never]?: Exclude<T[K], undefined>;
31
+ }>;
32
+ /**
33
+ * The object with its fields that are `undefined` left out (FR-064), typed exactly by {@link Compact}. Keys are kept in their order; a key
34
+ * named `__proto__` is kept as an own field, never as the prototype.
35
+ */
36
+ export declare function compact<T extends object>(value: T): Compact<T>;
37
+ export {};
@@ -0,0 +1,29 @@
1
+ // Spec: 0001-core FR-006
2
+ /**
3
+ * Objects made for `exactOptionalPropertyTypes` (0001-core FR-006): `compact` builds an object from fields some of
4
+ * which may be `undefined`, leaving those out, and its type says so exactly, so that a caller writes `compact({ a, b: maybe })` instead of
5
+ * `{ a, ...(maybe === undefined ? {} : { b: maybe }) }` once for each optional field.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * import { compact } from "./objects.ts";
10
+ * const timeout: number | undefined = undefined;
11
+ * const options = compact({ url: "https://example.com", timeout }); // { url: string; timeout?: number }, and no `timeout` key
12
+ * ```
13
+ *
14
+ * @module
15
+ */
16
+ /**
17
+ * The object with its fields that are `undefined` left out (FR-064), typed exactly by {@link Compact}. Keys are kept in their order; a key
18
+ * named `__proto__` is kept as an own field, never as the prototype.
19
+ */
20
+ export function compact(value) {
21
+ const out = {};
22
+ for (const [k, v] of Object.entries(value)) {
23
+ if (v !== undefined)
24
+ Object.defineProperty(out, k, { value: v, enumerable: true, writable: true, configurable: true });
25
+ }
26
+ // The loop above keeps exactly the own enumerable fields that are not `undefined`, which is what `Compact<T>` says; TypeScript cannot
27
+ // follow a loop's keys into a mapped type, so this is the one assertion.
28
+ return out;
29
+ }