{"name":"alge","version":"0.4.2-next.2","repository":{"type":"git","url":"git+ssh://git@github.com/jasonkuhrt/alge.git"},"author":{"name":"Jason Kuhrt"},"packageManager":"pnpm@7.9.4","license":"MIT","type":"module","types":"./dist/esm/index.d.ts","exports":{".":{"require":{"default":"./dist/cjs/index.js"},"import":{"default":"./dist/esm/index.js"}}},"scripts":{"ts-node":"ts-node-esm","reflect:toc":"markdown-toc README.md -i --maxdepth 4 && prettier --write README.md","format":"pnpm format:prettier","format:prettier":"prettier --write .","format:check":"pnpm format:check:prettier","format:check:prettier":"prettier --check .","lint":"eslint . --ext .ts,.tsx --fix","lint:check":"eslint . --ext .ts,.tsx --max-warnings 0","type-check":"pnpm tsc --noEmit","dev":"pnpm clean && tsc --build --watch tsconfig.cjs.json tsconfig.esm.json","build":"pnpm clean && pnpm build:cjs && pnpm build:esm","build:cjs":"tsc --project tsconfig.cjs.json","build:esm":"tsc --project tsconfig.esm.json","test":"jest","clean":"rm -rf dist-cjs dist-esm node_modules/.cache","release:pr":"dripip pr","release:canary":"dripip preview","release:stable":"dripip stable","prepack":"pnpm build"},"dependencies":{"lodash.ismatch":"^4.4.0","remeda":"^1.0.0","zod":"^3.17.3"},"devDependencies":{"@jest/types":"28.1.3","@prisma-labs/prettier-config":"0.1.0","@swc/core":"1.2.241","@swc/helpers":"0.4.7","@swc/jest":"0.2.22","@tsconfig/node16":"1.0.3","@tsconfig/recommended":"1.0.1","@types/jest":"28.1.7","@types/lodash.ismatch":"4.4.7","@types/node":"17.0.39","@types/semver":"7.3.12","@types/semver-utils":"1.1.1","@typescript-eslint/eslint-plugin":"5.33.1","@typescript-eslint/parser":"5.33.1","dripip":"0.10.0","eslint":"8.22.0","eslint-config-prettier":"8.5.0","eslint-plugin-codegen":"0.16.1","eslint-plugin-deprecation":"1.3.2","eslint-plugin-only-warn":"1.0.3","eslint-plugin-prefer-arrow":"1.2.3","eslint-plugin-simple-import-sort":"7.0.0","eslint-plugin-tsdoc":"0.2.16","jest":"28.1.3","jest-watch-select-projects":"2.0.0","jest-watch-suspend":"1.1.2","jest-watch-typeahead":"2.0.0","konn":"0.7.0","markdown-toc":"1.2.0","prettier":"2.7.1","semver":"7.3.7","semver-utils":"1.1.4","ts-jest":"28.0.8","ts-node":"10.9.1","tsd":"0.22.0","typescript":"4.7.4"},"readme":"# alge 🌱\n\n[![trunk](https://github.com/jasonkuhrt/alge/actions/workflows/trunk.yml/badge.svg)](https://github.com/jasonkuhrt/alge/actions/workflows/trunk.yml)\n[![npm version](https://img.shields.io/npm/v/alge.svg)](https://www.npmjs.com/package/alge)\n\n## TL;DR\n\nType safe library for creating [Algebraic Data Types](https://en.wikipedia.org/wiki/Algebraic_data_type) (ADTs) in TypeScript. Pronounced \"AL GEE\" like [the plant](https://en.wikipedia.org/wiki/Algae) ([or whatever it is](https://www.indefenseofplants.com/blog/2018/2/20/are-algae-plants)). Schemas powered by [Zod](https://github.com/colinhacks/zod) <3.\n\nThere are three distinct conceptual levels in Alge. Firstly there is a builder for defining your ADT in the first place. Secondly there is a controller for working with your defined ADT such as construction, type guards, and codecs. Finally there are the actual pure-data instances of your ADT.\n\n![Alge Anatomy](docs/assets/Alge%20Anatomy.png)\n\nHere's how it looks like in code.\n\nAt its simplest you can create one off records:\n\n```ts\nimport { Alge } from 'alge'\nimport { z } from 'zod'\n\nconst Circle = Alge.record(`Circle`, { radius: z.number().positive() })\n```\n\nBut you can as easily make full blown ADTs too:\n\n```ts\nimport { Alge } from 'alge'\nimport { z } from 'zod'\n\nconst Length = z.number().positive()\n\n//           v---------- 2. ADT Controller\n//           |            v--------- 1. ADT Builder\nexport const Shape = Alge.data(`Shape`, {\n  Rectangle: {\n    width: Length,\n    height: Length,\n  },\n  Circle: {\n    radius: Length,\n  },\n  Square: {\n    size: Length,\n  },\n})\n```\n\nYou use your built Controller to create your data:\n\n```ts\n//    v--------- 3. Instance\n//    |        v--------- 2. ADT Controller\nconst circle = Shape.Circle.create({ radius: 50 })\n// { _tag: 'Circle', radius: 50 }\n\nconst square = Shape.Square.create({ size: 50 })\n// { _tag: 'Square', size: 5 }\n```\n\nThere are other utility functions on the controller:\n\n```ts\nif (Shape.Circle.is(circle)) {\n  console.log(`I Am Circle`)\n}\n\nconst circleForTheOutsideWorld = Shape.Circle.to.json(circle)\n// '{ \"_tag\": \"Circle\", \"radius\": 50 }'\n\nconst squareFromTheOutsideWorld = Shape.Square.from.json({ _tag: 'Square', size: 10 })\n// { _tag: 'Square', size: 10 }\n```\n\nYou can use Alge for pattern matching too:\n\n```ts\nconst shape = Math.random() > 0.5 ? circle : square\nconst result = Alge.match(shape)\n  .Circle({ radius: 13 }, () => `Got an unlucky circle!`)\n  .Circle((circle) => `Got a circle of radius ${circle.radius}!`)\n  .Square({ size: 13 }, () => `Got an unlucky square!`)\n  .Square((square) => `Got a square of size ${square.size}!`)\n  .done()\n```\n\nThis is just a taster. Places you can go next:\n\n1. [Install](#installation) and learn interactively (JSDoc is coming soon!)\n1. A formal [features breakdown](#features)\n1. [Code examples](/examples)\n1. A simple [introduction to Algebraic Data Types](#about-algebraic-data-types) (for those unfamiliar)\n1. ~~A admittedly rambling 😃 [video introduction](https://youtu.be/fLlVQSJx4AU) if you like that format~~ **Outdated, I need to record a new one.**\n\n   [![Video Cover](docs/assets/cover.png)](https://youtu.be/fLlVQSJx4AU)\n\n## Contents\n\n<!-- toc -->\n\n- [Installation](#installation)\n- [Roadmap](#roadmap)\n- [About Algebraic Data Types](#about-algebraic-data-types)\n  - [What?](#what)\n  - [Why?](#why)\n\n* [Features](#features)\n  - [Records](#records)\n    - [Definition (`.record`)](#definition-record)\n    - [Construction (`.create`)](#construction-create)\n    - [Input Defaults](#input-defaults)\n    - [Input Validation](#input-validation)\n    - [Metadata](#metadata)\n    - [Chaining API](#chaining-api)\n    - [Codecs](#codecs)\n      - [Definition (`.codec`)](#definition-codec)\n      - [Usage (`.to.`, `.from`)](#usage-to-from)\n      - [Built In JSON](#built-in-json)\n      - [OrThrow Decoders](#orthrow-decoders)\n  - [Data (Algebraic Data Types)](#data-algebraic-data-types)\n    - [Definition](#definition)\n      - [Referencing Records](#referencing-records)\n      - [Inline Records](#inline-records)\n      - [Referencing Zod Objects](#referencing-zod-objects)\n    - [Construction](#construction)\n    - [Chaining API](#chaining-api-1)\n    - [Identity (`.is`, `.is$`)](#identity-is-is)\n    - [Codecs](#codecs-1)\n      - [Definition (`.codec`)](#definition-codec-1)\n      - [Usage (`to`, `from`)](#usage-to-from)\n  - [Static Types](#static-types)\n    - [Namespaces](#namespaces)\n  - [Pattern Matching](#pattern-matching)\n    - [Tag Matchers](#tag-matchers)\n    - [Data Matchers](#data-matchers)\n    - [Mixing Matchers](#mixing-matchers)\n    - [Done Versus Else](#done-versus-else)\n\n<!-- tocstop -->\n\n## Installation\n\n```\nnpm add alge\n```\n\n## Roadmap\n\nThere is no timeline but there are priorities. Refer to the currently three [pinned issues](https://github.com/jasonkuhrt/alge/issues).\n\n## About Algebraic Data Types\n\nAlge is a Type Script library for creating [Algebraic Data Types](https://en.wikipedia.org/wiki/Algebraic_data_type) (ADTs). This guide will take you from not knowing what ADTs are to why you might want to use Alge for them in your code.\n\n### What?\n\nAlgebraic Data Types (ADTs for short) are a methodology of modelling data. They could appear in any context that is about defining and/or navigating the shape of data. One of their fundamental benefits is that they can express different states/inrecords/facts about/of data. They are the combination of two other concepts, _product types_ and _union types_.\n\nA product type is like:\n\n```ts\ninterface Foo {\n  bar: string\n  qux: number\n}\n```\n\nA union type is like:\n\n```ts\ntype Foo = 1 | 2 | 3\n```\n\nBasically, when the power of these two data modelling techniques are combined, we get something far greater than the sum of its parts: ADTs.\n\nADTs can particularly shine at build time. While dynamically typed programing languages (\"scripting language\", e.g. Ruby, JavaScript, Python, ...) can support ADTs at runtime, adding static type support into the mix increases the ADT value proposition. Then there are yet other more minor programing language features like pattern matching that if supporting ADTs make them feel that much more beneficial too.\n\nReferences:\n\n- [Wikipedia entry on ADTs](https://en.wikipedia.org/wiki/Algebraic_data_type)\n- [Type Script documentation on discriminated unions](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#discriminated-unions)\n\n### Why?\n\nNow that we have some understanding of _what_ ADTs are let's build some understanding about _why_ we might want to use them. To do this we'll work with an example.\n\nLet's say we want to accept some user input about an npm package dependency version pin. It might come in the form of an exact version or a range of acceptable versions. How would we model this? Let's start without ADTs and then refactor with them to appreciate the difference. Let's assume that input parsing has been taken care of and so here we're only concerned with structured data modelling.\n\n```ts\ninterface Pin {\n  isExact: boolean\n  patch?: number\n  minor?: number\n  major?: number\n  release?: string\n  build?: string\n  range?: Array<{\n    operator: `~` | `>=` | `...` // etc.\n    patch: number\n    minor: number\n    major: number\n    release?: string\n    build?: string\n  }>\n}\n```\n\nThis data modelling is flawed. There is out-of-band information about important data relationships. `release` and `build` are legitimately optional properties but `range` `patch` `minor` `major` all depend on the state of `isExact`. When `true` then `range` is undefined and the others are not, and vice-versa. In other words these configurations of the data are impossible:\n\n```ts\nconst pin = {\n  isExact: true,\n  patch: 1,\n  minor: 2,\n  major: 3,\n  range: [\n    {\n      operator: `~`,\n      patch: 1,\n      minor: 0,\n      major: 0,\n    },\n  ],\n}\n```\n\n```ts\nconst pin = {\n  isExact: false,\n  patch: 1,\n  minor: 2,\n  major: 3,\n}\n```\n\nWhile these are possible:\n\n```ts\nconst pin = {\n  isExact: true,\n  patch: 1,\n  minor: 2,\n  major: 3,\n}\n```\n\n```ts\nconst pin = {\n  isExact: true,\n  patch: 1,\n  minor: 2,\n  major: 3,\n  release: `beta`,\n}\n```\n\n```ts\nconst pin = {\n  isExact: false,\n  range: [\n    {\n      operator: `~`,\n      patch: 1,\n      minor: 0,\n      major: 0,\n    },\n  ],\n}\n```\n\nBut since our data modelling doesn't encode these _facts_ our code suffers. For example:\n\n```ts\nif (pin.isExact) {\n  doSomething(pin.major!)\n  //                       ^\n}\n```\n\nNotice the `!`. Its us telling Type Script that `major` is definitely not undefined and so the type error can be ignored. In JS its even worse, as we wouldn't even be prompted to think about such cases, unless we remember to. Seems trivial in this case, but at scale day after day often with unfamiliar code a mistake will inevitably be made. Another approach could have been this:\n\n```ts\nif (pin.isExact) {\n  if (!pin.major) throw new Error(`Bad pin data!`)\n  doSomething(pin.major)\n}\n```\n\nSo, poor data modelling affects the quality of our code by our code either needing to deal with apparently possible states that are actually impossible OR by our code carefully ignoring those impossible states. Both solutions are terrible because they make code harder to read. There is more code, and the chance that wires about impossible and possible states will cross becomes a real possibility leading to potential runtime errors.\n\nADTs solve this. Let's refactor our Pin type into an ADT to see how!\n\n```ts\ntype Pin = ExactPin | RangePin\n\ninterface ExactPin {\n  tag: `ExactPin`\n  patch: number\n  minor: number\n  major: number\n  release?: string\n  build?: string\n}\n\ninterface RangePin {\n  tag: `RangePin`\n  values: Array<{\n    operator: `~` | `>=` | `...` // etc.\n    isExact: boolean\n    patch: number\n    minor: number\n    major: number\n    release?: string\n    build?: string\n  }>\n}\n```\n\nNow we've encoded the possible states we cared about. Our code quality increases:\n\n```ts\nif (pin.tag === 'ExactPin') {\n  doSomething(pin.major) // No problem, `pin` has been narrowed from `Pin` to `ExactPin`!\n}\n```\n\nWhen a developer deals with values of `Pin` type they will have an immediately much better understanding of the possible states.\n\nIn fact every optional property in some data represents possibly different state representations and thus potentially a use case for an ADT. So for example we could go further with our above data modelling and define things like `ExactPreReleasePin` and `ExactPreReleaseBuildPin`:\n\n```ts\ninterface ExactPreReleasePin {\n  tag: `ExactPreReleasePin`\n  patch: number\n  minor: number\n  major: number\n  release: string\n}\n```\n\n```ts\ninterface ExactPreReleaseBuildPin {\n  tag: `ExactPreReleasePin`\n  patch: number\n  minor: number\n  major: number\n  release: string\n  build: string\n}\n```\n\nOf course like any technique there is a point where ADT modelling is probably overkill for your use-case. That said, that line might be further out than you think. For example while the above might seem excessive, it actually answers a question the previous data modelling left ambiguous which is the question of, is the following state possible?\n\n```ts\nconst pin = {\n  isExact: true,\n  patch: 1,\n  minor: 2,\n  major: 3,\n  build: `5`,\n}\n```\n\nThe answer is no! But without the ADT that _fact_ would have to managed by humans, rather than the machine.\n\nAt scale, having well modelled data can be a life saver. The up front verbosity pays dividends downstream for all the impossible branches removed from programs' possibility space. ADTs help you (or your consumers) focus on what _can actually happen_.\n\n</br></br>\n\n# Features\n\nAll code blocks below assume these imports:\n\n```ts\nimport { Alge } from 'alge'\nimport { z } from 'zod'\n```\n\n## Records\n\n### Definition (`.record`)\n\nUse the Record Builder to define a record. At a minimum you specify the name and schema. Names should be in [pascal case](https://techterms.com/definition/pascalcase) to avoid name collisions with the Alge API (see below).\n\n```ts\nconst Circle = Alge.record('Circle', {\n  radius: z.number().positive(),\n})\n```\n\nIf you already have a Zod Object defined from somewhere else you can just pass it in:\n\n```ts\nconst Circle = Alge.record('Circle', CircleSchema)\n```\n\n### Construction (`.create`)\n\nOnce you've defined a record with the Record Builder you get back a Record Controller. Use it to create instances of your record:\n\n```ts\nconst circle = Circle.create({ radius: 10 })\n// { _tag: 'circle', radius: 10 }\n```\n\nThe `_tag` property is present to track the name of your record. you normally shouldn't have to interact directly with it.\n\n### Input Defaults\n\nLeverage Zod to get defaults for your properties ([zod docs](https://github.com/colinhacks/zod#default)):\n\n```ts\nconst Circle = Alge.record('Circle', {\n  radius: z.number().positive().default(0),\n})\n\nconst circle = Circle.create()\n// { _tag: 'circle', radius: 0 }\n```\n\n### Input Validation\n\nInput is validated via Zod. For example a negative number where only positives are accepted.\n\n```ts\nconst circle = circle.create({ radius: -10 })\n// throws\n```\n\n### Metadata\n\nThe controller gives you access to metadata about your record:\n\n```ts\ncircle.name // 'Circle'\ncircle.schema // a Zod schema instance\n```\n\n### Chaining API\n\nThere is a chaining API available which is more verbose but also affords more features (see further down).\n\n```ts\nconst Circle = Alge.record('Circle')\n  .schema({\n    radius: z.number().positive(),\n  })\n  .done()\n```\n\nLike in the shorthand form, if you already have a Zod Object defined from somewhere else you can just pass it in:\n\n```ts\nconst Circle = Alge.record('Circle').schema(CircleSchema).done()\n```\n\n### Codecs\n\n#### Definition (`.codec`)\n\nYou can define a named codec which allows your record to be encoded to/decoded from another representation.\n\nThe encoder (`to`) transforms your record into a string.\n\nThe decoder (`from`) transforms a string into your record, or `null` if the string is invalid.\n\n```ts\nconst Circle = Alge.record('Circle')\n  .schema({\n    radius: z.number().positive().default(1),\n  })\n  .codec('graphic', {\n    //    ^[1]\n    to: (circle) => `(${circle.radius})`,\n    from (string) => {\n      const match = string.match(^/\\((\\d+)\\)/$)\n      return match ? { radius: radius[1]! } : null\n    //               ^[2]\n    }\n  })\n  .done()\n```\n\nNotes:\n\n1. We give our codec a _name_. This name is used for the derived API (see \"usage\" below).\n2. When returning the parsed data for our record we do _not_ need to deal with the `_tag` property.\n\n#### Usage (`.to.`, `.from`)\n\nCodecs are exposed under the `.from` and `.to` (decoders/encoders) properties:\n\n```ts\nconst circle = Circle.create()\n// { _tag: 'Circle', radius: 1 }\n\nCircle.to.graphic(circle)\n// (1)\n\nCircle.from.graphic(`(1)`)\n// { _tag: 'Circle', radius: 1 }\n\nCircle.from.graphic(`()`)\n// null\n```\n\n#### Built In JSON\n\nAll records have a JSON codec:\n\n```ts\nCircle.to.json(circle)\n// '{ \"_tag\": \"Circle\", \"radius\": 1 }'\n\nCircle.from.json('{ \"_tag\": \"Circle\", \"radius\": 1 }')\n// { _tag: 'Circle', radius: 1 }\n```\n\n#### OrThrow Decoders\n\nAll decoders, JSON or your custom ones, have a variant of decode that will throw an `Error` when decoding fails:\n\n```ts\nCircle.from.graphicOrThrow(`()`)\n// throws\n\nCircle.from.jsonOrThrow(`bad`)\n// throws\n```\n\n## Data (Algebraic Data Types)\n\nThe ADT Builder is an extension of the Record Builder and the ADT Controller it returns is an extension of the Record Controller.\n\n### Definition\n\n#### Referencing Records\n\nRecords can be passes into the Data Builder:\n\n```ts\nconst Circle = Alge.record('Circle', { radius: z.number() })\nconst Square = Alge.record('Square', { size: z.number() })\n\nconst Shape = Alge.data('Shape', { Circle, Square })\n```\n\n#### Inline Records\n\nRecords can also be defined inline:\n\n```ts\nconst Shape = Alge.data('Shape', {\n  Circle: { radius: z.number() },\n  Square: { size: z.number() },\n})\n```\n\n#### Referencing Zod Objects\n\nExisting Zod object schemas are also accepted:\n\n```ts\nconst Circle = z.object({ radius: z.number() })\nconst Square = z.object({ size: z.number() })\nconst Shape = Alge.data('Shape', { Circle, Square })\n```\n\n### Construction\n\nThe ADT Controller contains one Record Controller for every record defined under a property of that records name. Use it just like you did before:\n\n```ts\nconst circle = Shape.Circle.create({ radius: 1 })\n// { _tag: 'Circle', radius: 1 }\nconst square = Shape.Square.create({ size: 2 })\n// { _tag: 'Square', size: 2 }\n```\n\n### Chaining API\n\nAs with records before there is a chaining API for ADTs that is more verbose but has additional features.\n\n```ts\nconst Shape = Alge.data('shape').record(Circle).record(Square).done()\n```\n\nAs with the shorthand your existing Zod objects can be passed in:\n\n```ts\nconst CircleSchema = z.object({ radius: z.number() })\nconst SquareSchema = z.object({ size: z.number() })\nconst Shape = Alge.data('shape')\n  .record('Circle')\n  .schema(CircleSchema)\n  .record('Square')\n  .schema(SquareSchema)\n  .done()\n```\n\n### Identity (`.is`, `.is$`)\n\nUse the `.is` Record Controller method as a TypeScript type guard. It checks if the given value is that record or not:\n\n```ts\nconst onlyCircle = (shape: Shape): null | Shape.Circle => {\n  return Shape.Circle.is(shape) ? shape : null\n}\n```\n\nWhen you're working with unknown values there is the `.$is` method which takes `unknown` input. It is less type safe than `.is` so avoid `.is$` when you can:\n\n```ts\nconst onlyCircle = (someValue: unknown): null | Shape.Circle => {\n  return Shape.Circle.$is(someValue) ? someValue : null\n}\n```\n\n### Codecs\n\nWhen a codec of some name is defined for every record in an ADT then something special happens. The ADT gets access to a generalized version of the codec with these features:\n\n1. A generalized decoder that will take a string and return a record instance of the first record decoder to return non-null. The static type is a union of all the records in the ADT (plus `null`).\n2. A generalized encoder that will dispatch automatically to the correct Record encoder based on the passed in record's `_tag` value.\n\n#### Definition (`.codec`)\n\nHere is an example of defining a custom codec for each record in an ADT.\n\n```ts\nconst circlePattern = /^\\(( *)\\)$/\nconst squarePattern = /^\\[( *)\\]$/\n\nconst shape = Alge.data('Shape')\n  .record(`Circle`)\n  .schema({\n    radius: z.number(),\n  })\n  .codec('graphic', {\n    to: (circle) => `(${' '.repeat(circle.radius)})`,\n    from: (string) => {\n      const match = string.exec(circleString)\n      return match ? { radius: match[1]!.length } : null\n    },\n  })\n  .record(`square`)\n  .schema({\n    size: z.number(),\n  })\n  .codec('graphic', {\n    to: (square) => `[${' '.repeat(square.size)}]`,\n    from: (string) => {\n      const match = squarePattern.exec(string)\n      return match ? { size: match[1]!.length } : null\n    },\n  })\n  .done()\n```\n\n#### Usage (`to`, `from`)\n\n```ts\nconst circle = Shape.Circle.create({ radius: 3 })\n// { _tag: 'circle', radius: 3 }\nconst circleString = Shape.Circle.to.graphic(circle)\n// '(   )'\nconst circle2 = Shape.Circle.from.graphic(circleString)\n// { _tag: 'circle', radius: 3 }\nconst circle3 = Shape.Circle.from.graphic('(]')\n// null\nconst shape1 = shape.from.graphic('()')\n// type: circle | square | null\n// value: { _tag: 'circle', radius: 0 }\nconst shape2 = Shape.from.graphic('[]')\n// type: circle | square | null\n// value: { _tag: 'square', size: 0 }\nconst shape3 = Shape.from.graphic('!')\n// type: circle | square | null\n// value: null\nconst shape4 = Shape.from.graphicOrThrow('!')\n// type: circle | square\n// value: throws\n```\n\nAs mentioned all records have a JSON codec, thus all ADTs have a generalized one.\n\n```ts\nconst circleJson = Shape.to.json(circle)\n// '{ \"_tag\": \"circle\", \"radius\": 50 }'\nconst circle2 = shape.from.json(circleJson)\n// { \"_tag\": \"circle\", \"radius\": 50 }\n```\n\n## Static Types\n\nOften you will write code (e.g. your own functions) that need to be typed with your adt. alge has \"type functions\" for this which leverages typescript inference.\n\nFor adts there is `alge.Infer`. it return an object with a property _per_ record of the adt _as well as_ a special property `*` which is _a union of all records_.\n\n```ts\ntype Shape = Alge.Infer<typeof shape>\n/*\n{\n  Circle: { _tag: 'Circle', radius: number }\n  Square: { _tag: 'Square', size: number }\n  '*':    | { _tag: 'Circle', radius: number }\n          | { _tag: 'Square', size: number }\n}\n*/\n\nconst doSomething = (shape: Shape['*']): null | Shape['circle'] => {\n  // todo\n}\n```\n\nFor lone records there is `alge.InferRecord`.\n\n```ts\ntype Circle = Alge.InferRecord<typeof Circle>\n\nconst doSomething = (circle: Circle) => {\n  // todo\n}\n```\n\n### Namespaces\n\nWhen working with inferred adt types, if you prefer to work with namespaces rather than objects to reference types you can use the following pattern:\n\n```ts\ntype ShapeInferred = Alge.Infer<typeof Shape>\n\ntype Shape = ShapeInferred['*']\n\nnamespace Shape {\n  export type Circle = ShapeInferred['Circle']\n  export type Square = ShapeInferred['Square']\n}\n\nconst doSomething = (shape: Shape): null | Shape.Circle => {\n  // todo\n}\n```\n\n## Pattern Matching\n\nUse `.match` to branch on your ADT's variants or even branch multiple ways among a single variant based on different data patterns.\n\n- Pass your value to `Alge.match(yourValue)` to begin the pattern matching.\n- Use tag or data or both matchers (see below)\n- Finish the chain with `.done()` to statically verify variant exhaustiveness or `.else(...)` if you want to specify a fallback value.\n\n### Tag Matchers\n\nTag Matchers simply branch based on the variant's tag (`_tag`). You call `.done()` to perform the exhaustiveness check. If you can't call this (because of static type error) then your pattern matching is not exhaustive. This catches bugs!\n\n```ts\nconst result = Alge.match(shape)\n  .Circle((circle) => `Got a circle of radius ${circle.radius}!`)\n  .Square((square) => `Got a square of size ${square.size}!`)\n  .done()\n```\n\n### Data Matchers\n\nData Matchers allow you to specify that the branch only matches when the actually data of the variant also matches your criteria.\n\nSince these kinds of matchers are dynamic you cannot use `.done` with them but instead must use `.else` to specify a fallback value in case they do not match.\n\n```ts\nconst result = Alge.match(shape)\n  .Circle({ radius: 13 }, () => `Got an unlucky circle!`)\n  .Square({ size: 13 }, () => `Got an unlucky square!`)\n  .else({ ok: true })\n```\n\n### Mixing Matchers\n\nYou can mix matchers. Order matters. More specific matchers must come before more general matchers. Alge automates these checks for you:\n\n- Cannot specify a data matcher _after_ a tag matcher (static & runtime enforcement)\n- Future Feature (#todo-issue)[https://github.com/jasonkuhrt/alge/issues/todo]: Cannot specify a more specific data matcher after a less specific one\n\n```ts\nconst result = Alge.match(shape)\n  .Circle({ radius: 13 }, () => `Got an unlucky circle!`)\n  .Circle((circle) => `Got a circle of radius ${circle.radius}!`)\n  .Square({ size: 13 }, () => `Got an unlucky square!`)\n  .Square((square) => `Got a square of size ${square.size}!`)\n  .done()\n```\n\n### Done Versus Else\n\nWhen you don't want to be exhaustive, use `else` instead of `done`. The value you specify in `else` will be used if no matcher matches.\n\n```ts\nconst result = Alge.match(shape)\n  .Circle((circle) => `Got a circle of radius ${circle.radius}!`)\n  .else(null)\n```\n\nIf you don't want your else to be an eager value, make it lazy with a function:\n\n```ts\nconst result = Alge.match(shape)\n  .Circle((circle) => `Got a circle of radius ${circle.radius}!`)\n  .else(() => (Math.random() > 0.5 ? 1 : 2))\n```\n\n</br></br>\n\n![alt](https://repobeats.axiom.co/api/embed/3c932f1cb76da4ad21328bfdd0ad1c6fbbe76a0b.svg 'repobeats analytics image')\n","readmeFilename":"README.md","gitHead":"68ccb52d1d3a08fcdf6f5e895125606b14fc53f1","description":"[![trunk](https://github.com/jasonkuhrt/alge/actions/workflows/trunk.yml/badge.svg)](https://github.com/jasonkuhrt/alge/actions/workflows/trunk.yml) [![npm version](https://img.shields.io/npm/v/alge.svg)](https://www.npmjs.com/package/alge)","bugs":{"url":"https://github.com/jasonkuhrt/alge/issues"},"homepage":"https://github.com/jasonkuhrt/alge#readme","_id":"alge@0.4.2-next.2","_nodeVersion":"16.16.0","_npmVersion":"8.11.0","dist":{"integrity":"sha512-R+suSHERMI+rn9AD0VSQu0BAhhauhBsYJOHhlhpxzX47lbDorFFKhe+OKSYZ/NWV1LEda9flHigudIUMHjMzGg==","shasum":"6bc1a58647842416df7591b787584e583b3c2312","tarball":"http://registry-npm.ywwl.com/alge/download/alge-0.4.2-next.2.tgz","fileCount":210,"unpackedSize":278942,"signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEQCIDg0eRKyUa3XgvU+Psc5lI9x9WIqVA+IOcrEs/lj4Et7AiBapUt5Y8rf/PJhFR4OqogBgzrDoVu61n0D8ouLdwRNkg=="}],"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v4.10.10\r\nComment: https://openpgpjs.org\r\n\r\nwsFzBAEBCAAGBQJjBZbLACEJED1NWxICdlZqFiEECWMYAoorWMhJKdjhPU1b\r\nEgJ2Vmq4SA/9G75u6F1BeTcV2/E25A6xCpL7Bz9vv0jF4VnUnGKKKe7+YHmG\r\n/oIbexqyube/1KAXNbszJD8lGrbm+ULHDBhzullrhGgLAU/ysLzPlvSBKoFX\r\n+dxVVmMnk/iZLAqfPDbdTUtABXQDQFOS19Iu3o6u9ZBAIhNCfEVF90bZi8A/\r\nQvYdhlkK6q/Znz1lnEOedx70WygC/I9U7F0f2tJTsgAH5Phj6yF7suUuTNrv\r\n0vilILVlp5YOOLU4L9LTSqaTs5NPu9moOfJ1liMWik9JYDcxANK/Bybiq/MQ\r\nTfq2koZPP2hs+0iAqEb4szcr/Jj6jjECRgyIiUL/B15wkeKLN0BozDpt3yth\r\n4D5pHlCgDR2+fAST2voS0sZXdkV1zJy0FM5aibIpFFsQbosVOR63LGBVq+LO\r\nreT32ZMwxd45tyeWhEyYLuhUzlHp4OxJ+LaBIL5KDWbnNfFnfYvkVJhz5+fK\r\nw/yPD7fNhjFcFZ07LVdaSNBeXZDpo/eSW6sX0fOs55NCwmbQl8Vsn+4HmyXU\r\nOIM2QRC1y1UvQHxgksLXJrbeAia/k9cbU19iXyE9tv2fIORIpUT6rlWtBKvX\r\nThWhCZMCKvv9R4MtFSYi3mp8fwK7HK4o4bNBGLlLxP4nINtKiHjfSh7igxlY\r\nReUTL2S7oKyW6Z0aEbGvC8UgrAsUXGQ0XTs=\r\n=mey/\r\n-----END PGP SIGNATURE-----\r\n","size":43281,"noattachment":false,"key":"/alge/-/alge-0.4.2-next.2.tgz"},"_npmUser":{"name":"jasonkuhrt","email":"jasonkuhrt@me.com"},"directories":{},"maintainers":[{"name":"jasonkuhrt","email":"jasonkuhrt@me.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/alge_0.4.2-next.2_1661310667260_0.587027026116959"},"_hasShrinkwrap":false,"publish_time":1661310667520,"_cnpm_publish_time":1661310667520,"dist-tags":{"latest":"0.8.1","next":"0.8.1"}}