0.1.0 #1
13
package.json
13
package.json
@@ -18,6 +18,16 @@
|
||||
"types": "./dist/lib.d.cts",
|
||||
"default": "./dist/lib.cjs"
|
||||
}
|
||||
},
|
||||
"./util": {
|
||||
"import": {
|
||||
"types": "./dist/util.d.mts",
|
||||
"default": "./dist/util.mjs"
|
||||
},
|
||||
"require": {
|
||||
"types": "./dist/util.d.cts",
|
||||
"default": "./dist/util.cjs"
|
||||
}
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
@@ -28,7 +38,8 @@
|
||||
"clean:node": "rm -rf node_modules"
|
||||
},
|
||||
"dependencies": {
|
||||
"type-fest": "^4.10.1"
|
||||
"hotscript": "^1.0.13",
|
||||
"type-fest": "^4.10.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rollup/plugin-node-resolve": "^15.2.3",
|
||||
|
||||
@@ -5,17 +5,20 @@ import ts from "rollup-plugin-ts"
|
||||
import pkg from "./package.json" assert { type: "json" }
|
||||
|
||||
|
||||
export default defineConfig({
|
||||
input: "src/index.ts",
|
||||
export const createBundleConfig = (
|
||||
input: string,
|
||||
name: keyof typeof pkg.exports,
|
||||
) => (
|
||||
defineConfig({
|
||||
input,
|
||||
|
||||
output: [
|
||||
{
|
||||
file: pkg.exports["."].import.default,
|
||||
file: pkg.exports[name].import.default,
|
||||
format: "esm",
|
||||
},
|
||||
|
||||
{
|
||||
file: pkg.exports["."].require.default,
|
||||
file: pkg.exports[name].require.default,
|
||||
format: "cjs",
|
||||
},
|
||||
],
|
||||
@@ -31,4 +34,11 @@ export default defineConfig({
|
||||
extensions: ["ts"],
|
||||
}),
|
||||
],
|
||||
})
|
||||
})
|
||||
)
|
||||
|
||||
|
||||
export default [
|
||||
createBundleConfig("src/lib.ts", "."),
|
||||
createBundleConfig("src/util/lib.ts", "./util"),
|
||||
]
|
||||
|
||||
153
src/Trait.ts
Normal file
153
src/Trait.ts
Normal file
@@ -0,0 +1,153 @@
|
||||
import { Fn, Pipe, Tuples } from "hotscript"
|
||||
import { AbstractClass, Class, Opaque } from "type-fest"
|
||||
import { AbstractTag, TraitExpression, emptyTraitExpression } from "."
|
||||
import { ExtendFn, SimplifyFn, StaticMembers, StaticMembersFn } from "./util"
|
||||
|
||||
|
||||
export type AddAbstractToImplClass<
|
||||
ImplClass extends Class<{}, []>,
|
||||
Abstract extends {},
|
||||
> = (
|
||||
Class<
|
||||
Abstract & InstanceType<ImplClass>,
|
||||
ConstructorParameters<ImplClass>
|
||||
> &
|
||||
StaticMembers<ImplClass>
|
||||
)
|
||||
|
||||
export type RemoveAbstractFromImplClass<
|
||||
ImplClassWithAbstract extends Class<Abstract, []>,
|
||||
Abstract extends {},
|
||||
> = (
|
||||
Class<
|
||||
Omit<InstanceType<ImplClassWithAbstract>, keyof Abstract>,
|
||||
ConstructorParameters<ImplClassWithAbstract>
|
||||
> &
|
||||
StaticMembers<ImplClassWithAbstract>
|
||||
)
|
||||
|
||||
|
||||
export class Trait<
|
||||
Supertraits extends TraitExpression<typeof TraitExpression.NullSuperclass, Trait<any, any, any>[], Trait<any, any, any>[]>,
|
||||
Abstract extends {},
|
||||
ImplClass extends Class<{}, []>,
|
||||
> {
|
||||
constructor(
|
||||
readonly supertraits: Supertraits,
|
||||
readonly abstract: Abstract,
|
||||
readonly apply: (Super: AbstractClass<{}>) => ImplClass,
|
||||
) {}
|
||||
}
|
||||
|
||||
export namespace Trait {
|
||||
export type OwnSupertraits<T> = (
|
||||
T extends Trait<infer Supertraits, any, any>
|
||||
? Supertraits
|
||||
: never
|
||||
)
|
||||
export interface OwnSupertraitsFn extends Fn {
|
||||
return: Trait.OwnSupertraits<this["arg0"]>
|
||||
}
|
||||
|
||||
export type OwnAbstract<T> = (
|
||||
T extends Trait<any, infer Abstract, any>
|
||||
? Abstract
|
||||
: never
|
||||
)
|
||||
export interface OwnAbstractFn extends Fn {
|
||||
return: Trait.OwnAbstract<this["arg0"]>
|
||||
}
|
||||
|
||||
export type OwnImplClass<T> = (
|
||||
T extends Trait<any, any, infer ImplClass>
|
||||
? ImplClass
|
||||
: never
|
||||
)
|
||||
export interface OwnImplClassFn extends Fn {
|
||||
return: Trait.OwnImplClass<this["arg0"]>
|
||||
}
|
||||
|
||||
export type OwnImplInstance<T> = (
|
||||
T extends Trait<any, any, infer ImplClass>
|
||||
? InstanceType<ImplClass>
|
||||
: never
|
||||
)
|
||||
export interface OwnImplInstanceFn extends Fn {
|
||||
return: Trait.OwnImplInstance<this["arg0"]>
|
||||
}
|
||||
|
||||
export type OwnClass<T> = (
|
||||
T extends Trait<any, infer Abstract, infer ImplClass>
|
||||
? AddAbstractToImplClass<ImplClass, Abstract>
|
||||
: never
|
||||
)
|
||||
export interface OwnClassFn extends Fn {
|
||||
return: Trait.OwnClass<this["arg0"]>
|
||||
}
|
||||
|
||||
export type OwnInstance<T> = (
|
||||
T extends Trait<any, infer Abstract, infer ImplClass>
|
||||
? InstanceType<
|
||||
AddAbstractToImplClass<ImplClass, Abstract>
|
||||
>
|
||||
: never
|
||||
)
|
||||
export interface OwnInstanceFn extends Fn {
|
||||
return: Trait.OwnInstance<this["arg0"]>
|
||||
}
|
||||
|
||||
export type Supertraits<T> = (
|
||||
T extends Trait<infer Supertraits, any, any>
|
||||
? TraitExpression.AllTraits<Supertraits>
|
||||
: never
|
||||
)
|
||||
export interface SupertraitsFn extends Fn {
|
||||
return: Trait.Supertraits<this["arg0"]>
|
||||
}
|
||||
|
||||
export type Class<T> = (
|
||||
AbstractClass<
|
||||
Trait.Instance<T>,
|
||||
any[]
|
||||
> &
|
||||
Pipe<[...Trait.Supertraits<T>, T], [
|
||||
Tuples.Map<Trait.OwnClassFn>,
|
||||
Tuples.Map<StaticMembersFn>,
|
||||
ExtendFn,
|
||||
SimplifyFn,
|
||||
]>
|
||||
)
|
||||
export interface ClassFn extends Fn {
|
||||
return: Trait.Class<this["arg0"]>
|
||||
}
|
||||
|
||||
export type Instance<T> = (
|
||||
Pipe<[...Trait.Supertraits<T>, T], [
|
||||
Tuples.Map<Trait.OwnInstanceFn>,
|
||||
ExtendFn,
|
||||
SimplifyFn,
|
||||
]>
|
||||
)
|
||||
export interface InstanceFn extends Fn {
|
||||
return: Trait.Instance<this["arg0"]>
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export type TraitApplierSuperTag = "@thilawyn/traitify-ts/TraitApplierSuper"
|
||||
|
||||
export function trait<
|
||||
Abstract extends {},
|
||||
ImplClassWithAbstract extends Class<Abstract, []>,
|
||||
>(
|
||||
abstract: Opaque<Abstract, AbstractTag>,
|
||||
apply: (Super: Opaque<AbstractClass<Abstract>, TraitApplierSuperTag>) => (
|
||||
Opaque<ImplClassWithAbstract, TraitApplierSuperTag>
|
||||
),
|
||||
) {
|
||||
return new Trait(
|
||||
emptyTraitExpression,
|
||||
abstract as Abstract,
|
||||
apply as any as (Super: AbstractClass<{}>) => RemoveAbstractFromImplClass<ImplClassWithAbstract, Abstract>,
|
||||
)
|
||||
}
|
||||
117
src/TraitExpression.ts
Normal file
117
src/TraitExpression.ts
Normal file
@@ -0,0 +1,117 @@
|
||||
import { Call, Fn, Pipe, Tuples } from "hotscript"
|
||||
import { AbstractClass, Class, Opaque } from "type-fest"
|
||||
import { AbstractTag, RemoveAbstractFromImplClass, Trait, TraitApplierSuperTag } from "."
|
||||
import { ExtendFn, SimplifyFn, StaticMembersFn } from "./util"
|
||||
|
||||
|
||||
// type RemoveSupertraitsAbstractFromAbstract<Left, Right> = {
|
||||
// [Key in Extract<keyof Left, keyof Right>]: Left[Key]
|
||||
// } & {
|
||||
// [Key in Exclude<keyof Left, keyof Right>]: Left[Key]
|
||||
// }
|
||||
|
||||
|
||||
export class TraitExpression<
|
||||
Superclass extends AbstractClass<{}>,
|
||||
OwnTraits extends Trait<any, any, any>[],
|
||||
AllTraits extends Trait<any, any, any>[],
|
||||
> {
|
||||
constructor(
|
||||
readonly superclass: Superclass,
|
||||
readonly ownTraits: OwnTraits,
|
||||
readonly allTraits: AllTraits,
|
||||
) {}
|
||||
|
||||
get extends(): (
|
||||
AbstractClass<
|
||||
Pipe<[
|
||||
InstanceType<Superclass>,
|
||||
...Call<Tuples.Map<Trait.OwnImplInstanceFn>, AllTraits>,
|
||||
], [
|
||||
ExtendFn,
|
||||
SimplifyFn,
|
||||
]>,
|
||||
|
||||
ConstructorParameters<Superclass>
|
||||
> &
|
||||
|
||||
Pipe<[
|
||||
Superclass,
|
||||
...Call<Tuples.Map<Trait.OwnImplClassFn>, AllTraits>,
|
||||
], [
|
||||
Tuples.Map<StaticMembersFn>,
|
||||
ExtendFn,
|
||||
SimplifyFn,
|
||||
]>
|
||||
) {
|
||||
return this.allTraits.reduce(
|
||||
(previous, trait) => trait.apply(previous),
|
||||
this.superclass as Opaque<Superclass, TraitApplierSuperTag>,
|
||||
) as any
|
||||
}
|
||||
|
||||
subtrait<
|
||||
SubtraitAbstract extends Implements<typeof this>,
|
||||
SubtraitImplClassWithAbstract extends Class<SubtraitAbstract, []>,
|
||||
>(
|
||||
abstract: (expression: typeof this) => Opaque<SubtraitAbstract, AbstractTag>,
|
||||
apply: (Super: Opaque<AbstractClass<SubtraitAbstract>, TraitApplierSuperTag>) => (
|
||||
Opaque<SubtraitImplClassWithAbstract, TraitApplierSuperTag>
|
||||
),
|
||||
) {
|
||||
return new Trait(
|
||||
this,
|
||||
// {} as RemoveSupertraitsAbstractFromAbstract<SubtraitAbstract, Implements<typeof this>>,
|
||||
{} as SubtraitAbstract, // TODO: find a way to cleanly substract Implements<typeof this> from this.
|
||||
apply as any as (Super: AbstractClass<{}>) => RemoveAbstractFromImplClass<SubtraitImplClassWithAbstract, SubtraitAbstract>,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export namespace TraitExpression {
|
||||
export class NullSuperclass {}
|
||||
|
||||
export type Superclass<T> = (
|
||||
T extends TraitExpression<infer Superclass, any, any>
|
||||
? Superclass
|
||||
: never
|
||||
)
|
||||
export interface SuperclassFn extends Fn {
|
||||
return: TraitExpression.Superclass<this["arg0"]>
|
||||
}
|
||||
|
||||
export type OwnTraits<T> = (
|
||||
T extends TraitExpression<any, infer OwnTraits, any>
|
||||
? OwnTraits
|
||||
: never
|
||||
)
|
||||
export interface OwnTraitsFn extends Fn {
|
||||
return: TraitExpression.OwnTraits<this["arg0"]>
|
||||
}
|
||||
|
||||
export type AllTraits<T> = (
|
||||
T extends TraitExpression<any, any, infer AllTraits>
|
||||
? AllTraits
|
||||
: never
|
||||
)
|
||||
export interface AllTraitsFn extends Fn {
|
||||
return: TraitExpression.AllTraits<this["arg0"]>
|
||||
}
|
||||
}
|
||||
|
||||
export const emptyTraitExpression = new TraitExpression(
|
||||
TraitExpression.NullSuperclass,
|
||||
[] as const,
|
||||
[] as const,
|
||||
)
|
||||
|
||||
|
||||
export type Implements<Exp extends TraitExpression<any, any, any>> = (
|
||||
Exp extends TraitExpression<any, infer AllTraits, any>
|
||||
? Pipe<AllTraits, [
|
||||
Tuples.Map<Trait.OwnAbstractFn>,
|
||||
ExtendFn,
|
||||
SimplifyFn,
|
||||
]>
|
||||
: never
|
||||
)
|
||||
131
src/TraitExpressionBuilder.ts
Normal file
131
src/TraitExpressionBuilder.ts
Normal file
@@ -0,0 +1,131 @@
|
||||
import { Call, Fn, Pipe, Tuples } from "hotscript"
|
||||
import { AbstractClass } from "type-fest"
|
||||
import { Trait, TraitExpression, emptyTraitExpression } from "."
|
||||
import { ExtendableFn, StaticMembersFn } from "./util"
|
||||
|
||||
|
||||
type SpreadSupertraits<Traits extends Trait<any, any, any>[]> = (
|
||||
Call<
|
||||
Tuples.FlatMap<PrependTraitSupertraitsFn>,
|
||||
Traits
|
||||
>
|
||||
)
|
||||
interface PrependTraitSupertraitsFn extends Fn {
|
||||
return: [...Trait.Supertraits<this["arg0"]>, this["arg0"]]
|
||||
}
|
||||
|
||||
|
||||
type AbstractMembersExtendable<
|
||||
Superclass extends AbstractClass<{}>,
|
||||
Traits extends Trait<any, any, any>[],
|
||||
> = (
|
||||
Call<ExtendableFn, [
|
||||
InstanceType<Superclass>,
|
||||
...Call<Tuples.Map<Trait.OwnAbstractFn>, Traits>,
|
||||
]>
|
||||
)
|
||||
|
||||
type ImplInstanceExtendable<
|
||||
Superclass extends AbstractClass<{}>,
|
||||
Traits extends Trait<any, any, any>[],
|
||||
> = (
|
||||
Call<ExtendableFn, [
|
||||
InstanceType<Superclass>,
|
||||
...Call<Tuples.Map<Trait.OwnImplInstanceFn>, Traits>,
|
||||
]>
|
||||
)
|
||||
|
||||
type ImplStaticMembersExtendable<
|
||||
Superclass extends AbstractClass<{}>,
|
||||
Traits extends Trait<any, any, any>[],
|
||||
> = (
|
||||
Pipe<[
|
||||
Superclass,
|
||||
...Call<Tuples.Map<Trait.OwnImplClassFn>, Traits>,
|
||||
], [
|
||||
Tuples.Map<StaticMembersFn>,
|
||||
ExtendableFn,
|
||||
]>
|
||||
)
|
||||
|
||||
type BuildTraitExpression<
|
||||
Superclass extends AbstractClass<{}>,
|
||||
OwnTraits extends Trait<any, any, any>[],
|
||||
AllTraits extends Trait<any, any, any>[],
|
||||
> = (
|
||||
Call<Tuples.IsEmpty, AllTraits> extends true
|
||||
? "Cannot express an empty list of traits."
|
||||
: AbstractMembersExtendable<Superclass, AllTraits> extends false
|
||||
? "Type conflict between the traits abstract members and/or the superclass instance."
|
||||
: ImplInstanceExtendable<Superclass, AllTraits> extends false
|
||||
? "Type conflict between the traits implementation instances and/or the superclass instance."
|
||||
: ImplStaticMembersExtendable<Superclass, AllTraits> extends false
|
||||
? "Type conflict between the traits implementation static members and/or the superclass static members."
|
||||
: TraitExpression<Superclass, OwnTraits, AllTraits>
|
||||
)
|
||||
|
||||
|
||||
class TraitExpressionBuilder<
|
||||
Super extends AbstractClass<{}>,
|
||||
OwnTraits extends Trait<any, any, any>[],
|
||||
AllTraits extends Trait<any, any, any>[],
|
||||
> {
|
||||
constructor(private expression: TraitExpression<Super, OwnTraits, AllTraits>) {}
|
||||
|
||||
extends<
|
||||
Super extends AbstractClass<any>
|
||||
>(
|
||||
superclass: Super
|
||||
) {
|
||||
return new TraitExpressionBuilder(
|
||||
new TraitExpression(
|
||||
superclass,
|
||||
this.expression.ownTraits,
|
||||
this.expression.allTraits,
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
expresses<
|
||||
Traits extends Trait<any, any, any>[]
|
||||
>(
|
||||
...traits: Traits
|
||||
): TraitExpressionBuilder<
|
||||
Super,
|
||||
[...OwnTraits, ...Traits],
|
||||
[...AllTraits, ...SpreadSupertraits<Traits>]
|
||||
> {
|
||||
return new TraitExpressionBuilder(
|
||||
new TraitExpression(
|
||||
this.expression.superclass,
|
||||
[...this.expression.ownTraits, ...traits] as const,
|
||||
[...this.expression.allTraits, ...this.spreadSupertraits(traits)] as const,
|
||||
)
|
||||
) as any
|
||||
}
|
||||
|
||||
private spreadSupertraits<
|
||||
Traits extends Trait<
|
||||
TraitExpression<any, any, Trait<any, any, any>[]>,
|
||||
any,
|
||||
any
|
||||
>[]
|
||||
>(
|
||||
traits: Traits
|
||||
) {
|
||||
return traits.flatMap(trait => [
|
||||
...trait.supertraits.allTraits,
|
||||
trait,
|
||||
]) as SpreadSupertraits<Traits>
|
||||
}
|
||||
|
||||
build() {
|
||||
return this.expression as BuildTraitExpression<Super, OwnTraits, AllTraits>
|
||||
}
|
||||
|
||||
then<V>(fn: (expression: ReturnType<typeof this.build>) => V): V {
|
||||
return fn(this.build())
|
||||
}
|
||||
}
|
||||
|
||||
export const expression = new TraitExpressionBuilder(emptyTraitExpression)
|
||||
10
src/abstract.ts
Normal file
10
src/abstract.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import { Opaque } from "type-fest"
|
||||
|
||||
|
||||
export type AbstractTag = "@thilawyn/traitify-ts/Abstract"
|
||||
|
||||
export function abstract<
|
||||
Abstract extends {} = {}
|
||||
>() {
|
||||
return {} as Opaque<Abstract, AbstractTag>
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
import { AbstractClass, Opaque } from "type-fest"
|
||||
import { Trait, TraitApplierSuperTag } from "."
|
||||
import { ClassesInstances, ClassesStaticMembers, MergeInheritanceTree, MergeInheritanceTreeWithoutOverriding, StaticMembers, TraitsClasses } from "./util"
|
||||
|
||||
|
||||
/**
|
||||
* Extends a class with the given traits and expresses their combined functionality.
|
||||
* @template C - The abstract class type.
|
||||
* @template Traits - An array of traits.
|
||||
* @param extend - The class to extend.
|
||||
* @param traits - An array of traits to apply.
|
||||
* @returns A new class type expressing the combined functionality of the base class and traits.
|
||||
* @example
|
||||
* Extends a superclass and applies traits:
|
||||
* ```ts
|
||||
* class User extends extendsAndExpresses(Entity,
|
||||
* Identifiable<bigint>(),
|
||||
* Permissible,
|
||||
* ) {
|
||||
* readonly id: bigint
|
||||
*
|
||||
* constructor(id: bigint) {
|
||||
* super()
|
||||
* this.id = id
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export function extendsAndExpresses<
|
||||
C extends AbstractClass<any>,
|
||||
Traits extends readonly Trait<any>[],
|
||||
>(
|
||||
extend: C,
|
||||
...traits: Traits
|
||||
) {
|
||||
return traits.reduce(
|
||||
(previous, trait) => trait(previous),
|
||||
extend as Opaque<C, TraitApplierSuperTag>,
|
||||
) as unknown as (
|
||||
AbstractClass<
|
||||
MergeInheritanceTreeWithoutOverriding<[
|
||||
InstanceType<C>,
|
||||
...ClassesInstances<
|
||||
TraitsClasses<Traits>
|
||||
>,
|
||||
]>,
|
||||
|
||||
ConstructorParameters<C>
|
||||
> &
|
||||
|
||||
MergeInheritanceTree<[
|
||||
StaticMembers<C>,
|
||||
...ClassesStaticMembers<
|
||||
TraitsClasses<Traits>
|
||||
>,
|
||||
]>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Expresses the combined functionality of multiple traits.
|
||||
* @template Traits - An array of trait.
|
||||
* @param traits - An array of trait to apply.
|
||||
* @returns A new class type expressing the combined functionality of the traits.
|
||||
* @example
|
||||
* Applies traits to a class:
|
||||
* ```ts
|
||||
* class User extends expresses(Identifiable<bigint>(), Permissible) {
|
||||
* readonly id: bigint
|
||||
*
|
||||
* constructor(id: bigint) {
|
||||
* super()
|
||||
* this.id = id
|
||||
* }
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
export function expresses<
|
||||
Traits extends readonly Trait<any>[],
|
||||
>(
|
||||
...traits: Traits
|
||||
) {
|
||||
return extendsAndExpresses(Object, ...traits)
|
||||
}
|
||||
@@ -1,2 +1,4 @@
|
||||
export * from "./expresses"
|
||||
export * from "./trait"
|
||||
export * from "./Trait"
|
||||
export * from "./TraitExpression"
|
||||
export * from "./TraitExpressionBuilder"
|
||||
export * from "./abstract"
|
||||
|
||||
6
src/lib.ts
Normal file
6
src/lib.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export {
|
||||
abstract, expression, trait,
|
||||
type Implements,
|
||||
type Trait,
|
||||
type TraitExpression
|
||||
} from "."
|
||||
166
src/tests.ts
166
src/tests.ts
@@ -1,131 +1,81 @@
|
||||
import { AbstractClass } from "type-fest"
|
||||
import { expresses, extendsAndExpresses, trait } from "."
|
||||
import { ClassesInstances, MergeInheritanceTree } from "./util"
|
||||
import { Simplify } from "type-fest"
|
||||
import { Implements, Trait, abstract, expression, trait } from "."
|
||||
import { Pipe } from "hotscript"
|
||||
|
||||
|
||||
const Identifiable = <ID>() =>
|
||||
trait(Super => {
|
||||
abstract class Identifiable extends Super {
|
||||
abstract readonly id: ID
|
||||
const PrintsHelloOnNew = trait(
|
||||
abstract(),
|
||||
Super => class PrintsHelloOnNew extends Super {
|
||||
constructor(...args: any[]) {
|
||||
super(...args)
|
||||
console.log("Hello!")
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
const Identifiable = <ID>() => trait(
|
||||
abstract<{ readonly id: ID }>(),
|
||||
Super => class Identifiable extends Super {
|
||||
equals(el: Identifiable) {
|
||||
return this.id === el.id
|
||||
}
|
||||
|
||||
constructor(...args: any[]) {
|
||||
super(...args)
|
||||
console.log("Identified constructor")
|
||||
}
|
||||
}
|
||||
|
||||
return Identifiable
|
||||
})
|
||||
|
||||
const ImplementsIdentifiable = <ID>(defaultID: ID) =>
|
||||
trait(Super => {
|
||||
abstract class ImplementsIdentifiable extends extendsAndExpresses(
|
||||
Super,
|
||||
Identifiable<ID>(),
|
||||
) {
|
||||
id: ID = defaultID
|
||||
|
||||
constructor(...args: any[]) {
|
||||
super(...args)
|
||||
console.log("ImplementsIdentifiable constructor")
|
||||
}
|
||||
}
|
||||
|
||||
return ImplementsIdentifiable
|
||||
})
|
||||
|
||||
|
||||
const Permissible = trait(Super => {
|
||||
abstract class Permissible extends Super {
|
||||
static readonly defaultPermissions: string[] = []
|
||||
permissions: string[] = []
|
||||
|
||||
constructor(...args: any[]) {
|
||||
super(...args)
|
||||
console.log("Permissible constructor")
|
||||
}
|
||||
}
|
||||
|
||||
return Permissible
|
||||
})
|
||||
|
||||
|
||||
const UserProto = expresses(
|
||||
// Identifiable<bigint>(),
|
||||
ImplementsIdentifiable(0n),
|
||||
Permissible,
|
||||
},
|
||||
)
|
||||
|
||||
class User extends UserProto {
|
||||
constructor(id: bigint) {
|
||||
super()
|
||||
this.id = id
|
||||
}
|
||||
}
|
||||
|
||||
const user1 = new User(1n)
|
||||
console.log(user1)
|
||||
console.log(user1.equals(user1))
|
||||
|
||||
|
||||
const Test1 = trait(Super => {
|
||||
abstract class Test1 extends Super {
|
||||
declare static name: string
|
||||
declare static testValue: (
|
||||
{ _tag: "type1", value: string } |
|
||||
{ _tag: "type2", value: number }
|
||||
)
|
||||
|
||||
abstract name: string
|
||||
|
||||
declare createdAt: Date
|
||||
declare readonly status: (
|
||||
const StatefulSubscription = trait(
|
||||
abstract<{
|
||||
readonly isStatefulSubscription: true
|
||||
readonly status: (
|
||||
{ _tag: "awaitingPayment" } |
|
||||
{ _tag: "active", activeSince: Date, expiresAt?: Date } |
|
||||
{ _tag: "expired", expiredSince: Date }
|
||||
)
|
||||
}>(),
|
||||
|
||||
Super => class StatefulSubscription extends Super {},
|
||||
)
|
||||
|
||||
const ActiveStatefulSubscription = expression
|
||||
.expresses(StatefulSubscription)
|
||||
.build()
|
||||
.subtrait(
|
||||
exp => {
|
||||
interface IActiveStatefulSubscription extends Implements<typeof exp> {
|
||||
readonly isActiveStatefulSubscription: true
|
||||
readonly status: { _tag: "active", activeSince: Date, expiresAt?: Date }
|
||||
}
|
||||
|
||||
return Test1
|
||||
})
|
||||
return abstract<IActiveStatefulSubscription>()
|
||||
},
|
||||
|
||||
const Test2 = trait(Super => {
|
||||
abstract class Test2 extends Super {
|
||||
declare readonly status: { _tag: "active", activeSince: Date, expiresAt?: Date }
|
||||
}
|
||||
Super => class ActiveStatefulSubscription extends Super {},
|
||||
)
|
||||
|
||||
return Test2
|
||||
})
|
||||
|
||||
const Test3 = trait(Super => {
|
||||
abstract class Test3 extends Super {
|
||||
declare static testValue: { _tag: "type2", value: number }
|
||||
declare lol: 10n
|
||||
}
|
||||
|
||||
return Test3
|
||||
})
|
||||
|
||||
const TestObjectProto = expresses(Test1, Test2, Test3)
|
||||
TestObjectProto.testValue
|
||||
type T = Trait.Instance<typeof ActiveStatefulSubscription>
|
||||
|
||||
|
||||
interface Gneugneu {
|
||||
ahi: string
|
||||
get adolf(): string
|
||||
class TestSuperclass {
|
||||
// id: number = 69
|
||||
// static test = 69
|
||||
}
|
||||
|
||||
class GneugneuImpl implements Gneugneu {
|
||||
ahi: string = ""
|
||||
get adolf(): string {
|
||||
throw new Error("Method not implemented.")
|
||||
}
|
||||
const exp = expression
|
||||
.extends(TestSuperclass)
|
||||
.expresses(
|
||||
PrintsHelloOnNew,
|
||||
Identifiable<bigint>(),
|
||||
// Identifiable<number>(),
|
||||
ActiveStatefulSubscription,
|
||||
)
|
||||
.build()
|
||||
|
||||
type Abs = Implements<typeof exp>
|
||||
|
||||
class User extends exp.extends implements Implements<typeof exp> {
|
||||
readonly isStatefulSubscription: true = true
|
||||
readonly isActiveStatefulSubscription: true = true
|
||||
declare status: { _tag: "active"; activeSince: Date; expiresAt?: Date | undefined }
|
||||
id: bigint = -1n
|
||||
}
|
||||
|
||||
abstract class Issou extends GneugneuImpl implements Gneugneu {
|
||||
}
|
||||
console.log(new User())
|
||||
|
||||
117
src/trait.ts
117
src/trait.ts
@@ -1,117 +0,0 @@
|
||||
import { AbstractClass, AbstractConstructor, Opaque } from "type-fest"
|
||||
|
||||
|
||||
/**
|
||||
* Represents a trait that can be applied to a class.
|
||||
* @template C - The abstract class type.
|
||||
*/
|
||||
export type Trait<
|
||||
C extends AbstractClass<any>
|
||||
> = Opaque<
|
||||
TraitApplier<C>,
|
||||
"@thilawyn/thilatrait/Trait"
|
||||
>
|
||||
|
||||
export type TraitApplierSuperTag = "@thilawyn/thilatrait/Super"
|
||||
|
||||
/**
|
||||
* Represents the function signature for applying a trait to a parent class.
|
||||
* @template C - The abstract class type.
|
||||
*/
|
||||
export type TraitApplier<
|
||||
C extends AbstractClass<any>
|
||||
> = (
|
||||
(Super: Opaque<AbstractConstructor<object>, TraitApplierSuperTag>) => Opaque<C, TraitApplierSuperTag>
|
||||
)
|
||||
|
||||
/**
|
||||
* Creates a trait using the provided trait applier function.
|
||||
* @template C - The abstract class type.
|
||||
* @param applier - The trait applier function.
|
||||
* @returns A trait.
|
||||
* @example
|
||||
* Creates a trait:
|
||||
* ```ts
|
||||
* const Permissible = trait(Super => {
|
||||
* abstract class Permissible extends Super {
|
||||
* static readonly defaultPermissions: string[] = []
|
||||
* permissions: string[] = []
|
||||
*
|
||||
* // Constructor is optional
|
||||
* // If you wish to use it, make sure it takes any[] as an args array and passes it to the super call. This is necessary for inheritance to work properly.
|
||||
* // Trait constructors cannot have typed arguments of their own, they only serve to run logic during object instantiation.
|
||||
* constructor(...args: any[]) {
|
||||
* super(...args)
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* return Permissible
|
||||
* })
|
||||
* ```
|
||||
* Creates a generic trait:
|
||||
* ```ts
|
||||
* const Identifiable = <ID>() =>
|
||||
* trait(Super => {
|
||||
* abstract class Identifiable extends Super {
|
||||
* abstract readonly id: ID
|
||||
*
|
||||
* equals(el: Identifiable) {
|
||||
* return this.id === el.id
|
||||
* }
|
||||
*
|
||||
* // Optional
|
||||
* constructor(...args: any[]) {
|
||||
* super(...args)
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* return Identifiable
|
||||
* })
|
||||
* ```
|
||||
* Creates a subtrait:
|
||||
* ```ts
|
||||
* const ImplementsIdentifiable = <ID>(defaultID: ID) =>
|
||||
* trait(Super => {
|
||||
* abstract class ImplementsIdentifiable extends extendsAndExpresses(
|
||||
* Super,
|
||||
* Identifiable<ID>(),
|
||||
* ) {
|
||||
* id: ID = defaultID
|
||||
*
|
||||
* // Optional
|
||||
* constructor(...args: any[]) {
|
||||
* super(...args)
|
||||
* }
|
||||
* }
|
||||
*
|
||||
* return ImplementsIdentifiable
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
export function trait<
|
||||
C extends AbstractClass<any>
|
||||
>(
|
||||
applier: TraitApplier<C>
|
||||
) {
|
||||
return applier as Trait<C>
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the class type of a trait.
|
||||
* @template T - The trait type.
|
||||
*/
|
||||
export type TraitClass<T> = (
|
||||
T extends Trait<infer C>
|
||||
? C
|
||||
: never
|
||||
)
|
||||
|
||||
/**
|
||||
* Returns the instance type of a trait.
|
||||
* @template T - The trait type.
|
||||
*/
|
||||
export type TraitInstance<T> = (
|
||||
T extends Trait<infer C>
|
||||
? InstanceType<C>
|
||||
: never
|
||||
)
|
||||
@@ -1,66 +0,0 @@
|
||||
import { AbstractClass } from "type-fest"
|
||||
|
||||
|
||||
/**
|
||||
* Represents an array of instances corresponding to the provided classes.
|
||||
* @template Classes - An array of classes extending AbstractClass.
|
||||
*/
|
||||
export type ClassesInstances<Classes extends readonly AbstractClass<any>[]> = (
|
||||
Classes extends [infer Class, ...infer Rest]
|
||||
? Class extends AbstractClass<any>
|
||||
? Rest extends AbstractClass<any>[]
|
||||
? [InstanceType<Class>, ...ClassesInstances<Rest>]
|
||||
: never
|
||||
: never
|
||||
: []
|
||||
)
|
||||
|
||||
/**
|
||||
* Represents an intersection of instances of the provided classes.
|
||||
* @template Classes - An array of classes extending AbstractClass.
|
||||
*/
|
||||
export type ClassesInstancesIntersection<Classes extends readonly AbstractClass<any>[]> = (
|
||||
Classes extends [infer Class, ...infer Rest]
|
||||
? Class extends AbstractClass<any>
|
||||
? Rest extends AbstractClass<any>[]
|
||||
? InstanceType<Class> & ClassesInstancesIntersection<Rest>
|
||||
: never
|
||||
: never
|
||||
: {}
|
||||
)
|
||||
|
||||
/**
|
||||
* Represents the static members of a class.
|
||||
* @template Class - A class extending AbstractClass.
|
||||
*/
|
||||
export type StaticMembers<Class extends AbstractClass<any>> = (
|
||||
Omit<Class, "prototype">
|
||||
)
|
||||
|
||||
/**
|
||||
* Represents an array of static members corresponding to the provided classes.
|
||||
* @template Classes - An array of classes extending AbstractClass.
|
||||
*/
|
||||
export type ClassesStaticMembers<Classes extends readonly AbstractClass<any>[]> = (
|
||||
Classes extends [infer Class, ...infer Rest]
|
||||
? Class extends AbstractClass<any>
|
||||
? Rest extends AbstractClass<any>[]
|
||||
? [StaticMembers<Class>, ...ClassesStaticMembers<Rest>]
|
||||
: never
|
||||
: never
|
||||
: []
|
||||
)
|
||||
|
||||
/**
|
||||
* Represents an intersection of static members of the provided classes.
|
||||
* @template Classes - An array of classes extending AbstractClass.
|
||||
*/
|
||||
export type ClassesStaticMembersIntersection<Classes extends readonly AbstractClass<any>[]> = (
|
||||
Classes extends [infer Class, ...infer Rest]
|
||||
? Class extends AbstractClass<any>
|
||||
? Rest extends AbstractClass<any>[]
|
||||
? StaticMembers<Class> & ClassesStaticMembersIntersection<Rest>
|
||||
: never
|
||||
: never
|
||||
: {}
|
||||
)
|
||||
25
src/util/extend.ts
Normal file
25
src/util/extend.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { Call, ComposeLeft, Fn, Match, Tuples } from "hotscript"
|
||||
import { CommonKeys } from "."
|
||||
|
||||
|
||||
type ExtendReducer<Super, Self> = (
|
||||
Pick<Self, CommonKeys<Self, Super>> extends Pick<Super, CommonKeys<Self, Super>>
|
||||
? Omit<Super, CommonKeys<Self, Super>> & Self
|
||||
: never
|
||||
)
|
||||
interface ExtendReducerFn extends Fn {
|
||||
return: ExtendReducer<this["arg0"], this["arg1"]>
|
||||
}
|
||||
|
||||
export type ExtendFn = Tuples.Reduce<ExtendReducerFn, {}>
|
||||
export type Extend<T extends {}[]> = Call<ExtendFn, T>
|
||||
|
||||
|
||||
export type ExtendableFn = ComposeLeft<[
|
||||
ExtendFn,
|
||||
Match<[
|
||||
Match.With<never, false>,
|
||||
Match.With<any, true>,
|
||||
]>
|
||||
]>
|
||||
export type Extendable<T extends {}[]> = Call<ExtendableFn, T>
|
||||
@@ -1,3 +1,3 @@
|
||||
export * from "./class"
|
||||
export * from "./extend"
|
||||
export * from "./inheritance"
|
||||
export * from "./trait"
|
||||
export * from "./misc"
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
/**
|
||||
* Represents the common keys between two types.
|
||||
* @template A - The first type.
|
||||
* @template B - The second type.
|
||||
*/
|
||||
export type CommonKeys<A, B> = Extract<keyof A, keyof B>
|
||||
import { CommonKeys } from "."
|
||||
|
||||
|
||||
/**
|
||||
* Merges an inheritance tree defined by an array of types, considering overrides.
|
||||
|
||||
6
src/util/lib.ts
Normal file
6
src/util/lib.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export {
|
||||
Extend,
|
||||
ExtendFn,
|
||||
Extendable,
|
||||
ExtendableFn
|
||||
} from "."
|
||||
25
src/util/misc.ts
Normal file
25
src/util/misc.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
import { Fn } from "hotscript"
|
||||
import { AbstractClass, Simplify } from "type-fest"
|
||||
|
||||
|
||||
/**
|
||||
* Represents the common keys between two types.
|
||||
* @template A - The first type.
|
||||
* @template B - The second type.
|
||||
*/
|
||||
export type CommonKeys<A, B> = Extract<keyof A, keyof B>
|
||||
|
||||
export interface SimplifyFn extends Fn {
|
||||
return: Simplify<this["arg0"]>
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents the static members of a class.
|
||||
* @template Class - A class extending AbstractClass.
|
||||
*/
|
||||
export type StaticMembers<Class extends AbstractClass<any>> = (
|
||||
Omit<Class, "prototype">
|
||||
)
|
||||
export interface StaticMembersFn extends Fn {
|
||||
return: StaticMembers<this["arg0"]>
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
import { Trait, TraitClass } from ".."
|
||||
|
||||
|
||||
/**
|
||||
* Represents an array of classes corresponding to the provided traits.
|
||||
* @template Traits - An array of traits extending Trait<any>.
|
||||
*/
|
||||
export type TraitsClasses<Traits extends readonly Trait<any>[]> = (
|
||||
Traits extends [infer T, ...infer Rest]
|
||||
? T extends Trait<any>
|
||||
? Rest extends Trait<any>[]
|
||||
? [TraitClass<T>, ...TraitsClasses<Rest>]
|
||||
: never
|
||||
: never
|
||||
: []
|
||||
)
|
||||
Reference in New Issue
Block a user