diff --git a/.codex/config.toml b/.codex/config.toml index 5522f6a..7d2d3e0 100644 --- a/.codex/config.toml +++ b/.codex/config.toml @@ -1,5 +1,5 @@ -model = "gpt-5.4" -review_model = "gpt-5.4" +model = "gpt-5.5" +review_model = "gpt-5.5" model_provider = "openai" approval_policy = "untrusted" diff --git a/.commands/test-lint.sh b/.commands/test-lint.sh new file mode 100755 index 0000000..2352b8c --- /dev/null +++ b/.commands/test-lint.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +set -e + +ARGUMENTS="$@" + +eslint --quiet $ARGUMENTS \ No newline at end of file diff --git a/.commands/test-tu.sh b/.commands/test-tu.sh new file mode 100755 index 0000000..dcbb299 --- /dev/null +++ b/.commands/test-tu.sh @@ -0,0 +1,7 @@ +#!/bin/bash + +set -e + +ARGUMENTS="$@" + +vitest --coverage $ARGUMENTS \ No newline at end of file diff --git a/.commands/test-types.sh b/.commands/test-types.sh new file mode 100755 index 0000000..1b22ad4 --- /dev/null +++ b/.commands/test-types.sh @@ -0,0 +1,8 @@ +#!/bin/bash + +set -e + +tsc -p tsconfig.test.json + +# docs +npm -w docs run test:types \ No newline at end of file diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 1d0d9a8..a2bb71e 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -16,7 +16,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: - node-version: '24.x' + node-version: '22.15.1' registry-url: 'https://registry.npmjs.org/' - run: npm install -g npm@latest - run: npm ci diff --git a/.vscode/settings.json b/.vscode/settings.json index a51c5f5..e9e816a 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -18,11 +18,12 @@ "editor.codeActionsOnSave": { "source.fixAll.eslint": "explicit" }, - - "typescript.tsdk": "node_modules/typescript/lib", - "deno.enable": true, "deno.enablePaths": ["integration/deno"], "deno.disablePaths": ["dist", "node_modules"], - "deno.config": "./integration/deno/deno.json" + "deno.config": "./integration/deno/deno.json", + "js/ts.tsdk.path": "node_modules/typescript/lib", + "cSpell.words": [ + "vitest" + ] } \ No newline at end of file diff --git a/docs/.commands/test-types.sh b/docs/.commands/test-types.sh new file mode 100755 index 0000000..ef0a496 --- /dev/null +++ b/docs/.commands/test-types.sh @@ -0,0 +1,6 @@ +#!/bin/bash + +set -e + +tsc -p tsconfig.app.json +tsc -p tsconfig.v0.json \ No newline at end of file diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index ae5fe26..4d3e714 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -95,25 +95,25 @@ export default defineConfig({ ({ namedGroups }) => A.join( [ "// @filename: @duplojs/server-utils.ts", - `export * from "@v${namedGroups?.version ?? ""}";`, + `export * from "@server-utils/v${namedGroups?.version ?? ""}";`, "// @filename: @duplojs/server-utils/file.ts", - `export * from "@v${namedGroups?.version ?? ""}/file";`, + `export * from "@server-utils/v${namedGroups?.version ?? ""}/file";`, "// @filename: @duplojs/server-utils/common.ts", - `export * from "@v${namedGroups?.version ?? ""}/common";`, + `export * from "@server-utils/v${namedGroups?.version ?? ""}/common";`, "// @filename: @duplojs/server-utils/dataParser.ts", - `export * from "@v${namedGroups?.version ?? ""}/dataParser";`, + `export * from "@server-utils/v${namedGroups?.version ?? ""}/dataParser";`, "// @filename: @duplojs/server-utils/dataParserCoerce.ts", - `export * from "@v${namedGroups?.version ?? ""}/dataParserCoerce";`, + `export * from "@server-utils/v${namedGroups?.version ?? ""}/dataParserCoerce";`, "// @filename: @duplojs/server-utils/dataParserExtended.ts", - `export * from "@v${namedGroups?.version ?? ""}/dataParserExtended";`, + `export * from "@server-utils/v${namedGroups?.version ?? ""}/dataParserExtended";`, "// @filename: @duplojs/server-utils/command.ts", - `export * from "@v${namedGroups?.version ?? ""}/command";`, + `export * from "@server-utils/v${namedGroups?.version ?? ""}/command";`, "// @filename: index.ts", "// ---cut---", @@ -134,13 +134,13 @@ export default defineConfig({ moduleResolution: ModuleResolutionKind.Bundler, moduleDetection: ModuleDetectionKind.Force, paths: { - "@v0": ["libs/v0/index"], - "@v0/common": ["libs/v0/common/index"], - "@v0/file": ["libs/v0/file/index"], - "@v0/dataParser": ["libs/v0/dataParser/index"], - "@v0/dataParserCoerce": ["libs/v0/dataParser/parsers/coerce/index"], - "@v0/dataParserExtended": ["libs/v0/dataParser/extended/index"], - "@v0/command": ["libs/v0/command/index"], + "@server-utils/v0": ["libs/v0/index"], + "@server-utils/v0/common": ["libs/v0/common/index"], + "@server-utils/v0/file": ["libs/v0/file/index"], + "@server-utils/v0/dataParser": ["libs/v0/dataParser/index"], + "@server-utils/v0/dataParserCoerce": ["libs/v0/dataParser/parsers/coerce/index"], + "@server-utils/v0/dataParserExtended": ["libs/v0/dataParser/extended/index"], + "@server-utils/v0/command": ["libs/v0/command/index"], }, }, }, diff --git a/docs/en/v0/api/command/create.md b/docs/en/v0/api/command/create.md index db32d98..7da283c 100644 --- a/docs/en/v0/api/command/create.md +++ b/docs/en/v0/api/command/create.md @@ -6,14 +6,13 @@ prev: next: text: "createBooleanOption" link: "/en/v0/api/command/createBooleanOption" -description: "Creates a CLI command with a name, an execute handler, and optional configuration." +description: "Creates a CLI command with a name, optional options/subject, and an execute handler." --- # create -`create` is used to declare a CLI command. -You provide a name and an execute function. -You can also add options, a subject (positional arguments), or sub-commands. +`create` declares a CLI command. +You provide a name and an execute function, and you can also add options, a subject for positional arguments, or child commands. ## Example @@ -48,12 +47,12 @@ function create< - `params` (`CreateCommandParams`, optional) : command configuration. - `params.description` (`string`, optional) : help description. - `params.options` (`Option[]`, optional) : option parsers. -- `params.subject` (`Subject | Command[]`, optional) : parser for positional data or sub-commands list. -- `execute` : command handler. Receives typed `options` and optional typed `subject`. +- `params.subject` (`Subject | Command[]`, optional) : parser-like contract for positional data or sub-commands list. +- `execute` : command handler. Receives typed `options` and, when present, a typed `subject`. ## Return value -- `Command` : executable command object with `execute(args)`. +- `Command` : command definition object meant to be attached to a command tree and executed through [`exec`](/en/v0/api/command/exec). ## Others examples diff --git a/docs/en/v0/api/command/createArrayOption.md b/docs/en/v0/api/command/createArrayOption.md index 14c3cd3..8a9914b 100644 --- a/docs/en/v0/api/command/createArrayOption.md +++ b/docs/en/v0/api/command/createArrayOption.md @@ -6,7 +6,7 @@ prev: next: text: "API Reference" link: "/en/v0/api/" -description: "Creates an option that parses a delimited list into a typed array." +description: "Creates an option that parses a delimited list into a typed array from a DataParser or clean contract." --- # createArrayOption @@ -25,11 +25,11 @@ Creates an option that parses a delimited list into a typed array. ```typescript function createArrayOption< GenericName extends string, - GenericSchema extends EligibleDataParser, + GenericContract extends EligibleContract, GenericMinValues extends number >( name: GenericName, - schema: GenericSchema, + contract: GenericContract, params: { description?: string aliases?: readonly string[] @@ -41,18 +41,18 @@ function createArrayOption< ): Option< GenericName, [ - ...A.CreateTuple, GenericMinValues>, - ...DP.Output[] + ...A.CreateTuple, GenericMinValues>, + ...ComputeOptionContract[] ] > function createArrayOption< GenericName extends string, - GenericSchema extends EligibleDataParser, + GenericContract extends EligibleContract, GenericMinValues extends number >( name: GenericName, - schema: GenericSchema, + contract: GenericContract, params?: { description?: string aliases?: readonly string[] @@ -63,8 +63,8 @@ function createArrayOption< ): Option< GenericName, | [ - ...A.CreateTuple, GenericMinValues>, - ...DP.Output[] + ...A.CreateTuple, GenericMinValues>, + ...ComputeOptionContract[] ] | undefined > @@ -73,7 +73,7 @@ function createArrayOption< ## Parameters - `name` (`string`) : option name used as `--name`. -- `schema` (`EligibleDataParser`) : parser for each array element. +- `contract` (`EligibleContract`) : parser or clean contract for each array element. - `params` (optional) : option metadata and array constraints. - `params.required` (`true`, optional) : throws when option is missing. - `params.min` (`number`, optional) : minimum number of values. @@ -87,6 +87,10 @@ function createArrayOption< - Required mode: `Option`. - Optional mode: `Option`. +## Notes + +- Primitive parsers and clean primitive contracts are coerced from CLI string input automatically. + ## See also - [`createOption`](/en/v0/api/command/createOption) - Builds a single-value option. diff --git a/docs/en/v0/api/command/createOption.md b/docs/en/v0/api/command/createOption.md index 2afc8d8..95a2ada 100644 --- a/docs/en/v0/api/command/createOption.md +++ b/docs/en/v0/api/command/createOption.md @@ -6,12 +6,12 @@ prev: next: text: "createArrayOption" link: "/en/v0/api/command/createArrayOption" -description: "Creates an option with a single parsed value from a DataParser schema." +description: "Creates an option with a single parsed value from a DataParser or clean contract." --- # createOption -Creates an option with a single parsed value from a DataParser schema. +Creates an option with a single parsed value from a DataParser or clean contract. ## Example @@ -25,34 +25,36 @@ Creates an option with a single parsed value from a DataParser schema. ```typescript function createOption< GenericName extends string, - GenericSchema extends EligibleDataParser + GenericContract extends EligibleContract, + GenericOutput extends ComputeOptionContract = ComputeOptionContract >( name: GenericName, - schema: GenericSchema, + contract: GenericContract, params: { description?: string aliases?: readonly string[] required: true } -): Option> +): Option function createOption< GenericName extends string, - GenericSchema extends EligibleDataParser + GenericContract extends EligibleContract, + GenericOutput extends ComputeOptionContract = ComputeOptionContract >( name: GenericName, - schema: GenericSchema, + contract: GenericContract, params?: { description?: string aliases?: readonly string[] } -): Option | undefined> +): Option ``` ## Parameters - `name` (`string`) : option name used as `--name`. -- `schema` (`EligibleDataParser`) : parser used to validate/transform the value. +- `contract` (`EligibleContract`) : parser or clean contract used to validate/transform the value. - `params` (optional) : option metadata and requirement behavior. - `params.required` (`true`, optional) : throws when option is missing. - `params.description` (`string`, optional) : help description. @@ -60,8 +62,12 @@ function createOption< ## Return value -- `Option>` when `required: true`. -- `Option | undefined>` otherwise. +- `Option` when `required: true`. +- `Option` otherwise. + +## Notes + +- Primitive parsers and clean primitive contracts are coerced from CLI string input automatically. ## See also diff --git a/docs/en/v0/api/command/execOptions.md b/docs/en/v0/api/command/execOptions.md index e5cedfd..e3f6724 100644 --- a/docs/en/v0/api/command/execOptions.md +++ b/docs/en/v0/api/command/execOptions.md @@ -11,7 +11,7 @@ description: "Parses CLI options from runtime arguments." # execOptions -`execOptions` parses CLI options and returns the result as a `{ [optionName]: resultOption }` record. +`execOptions` parses CLI options and resolves the result as a `{ [optionName]: resultOption }` record. If parsing fails, a detailed error is printed to the console. The `--help` / `-h` output is generated automatically from the declared options. @@ -29,7 +29,7 @@ function execOptions< GenericOptions extends [Option, ...Option[]] >( ...options: GenericOptions -): ComputeResult +): Promise> ``` ## Parameters @@ -38,7 +38,7 @@ function execOptions< ## Return value -- `ComputeResult` : object whose keys are option names and whose values are the typed result of each parser. +- `Promise>` : promise resolving to an object whose keys are option names and whose values are the typed result of each parser. ## See also diff --git a/docs/examples/v0/api/command/createArrayOption/main.ts b/docs/examples/v0/api/command/createArrayOption/main.ts index 64b6b0f..ac277db 100644 --- a/docs/examples/v0/api/command/createArrayOption/main.ts +++ b/docs/examples/v0/api/command/createArrayOption/main.ts @@ -1,38 +1,35 @@ import { SC } from "@duplojs/server-utils"; -import { DP, type ExpectType } from "@duplojs/utils"; +import { C, DP, type ExpectType } from "@duplojs/utils"; -const command = SC.create( - "batch", - { - options: [ - SC.createArrayOption( - "tags", - DP.string(), - ), - SC.createArrayOption( - "files", - DP.string(), - { - required: true, - min: 1, - separator: ";", - }, - ), - ], - }, - ({ options }) => { - type check = ExpectType< - typeof options, +const UserId = C.createNewType("user-id", DP.number(), C.Positive); + +await SC.exec({ + options: [ + SC.createArrayOption( + "tags", + DP.string(), + ), + SC.createArrayOption( + "files", + DP.string(), { - tags: string[] | undefined; - files: [string, ...string[]]; + required: true, + min: 1, + separator: ";", }, - "strict" - >; - }, -); - -await command.execute([ - "--tags=api,docs", - "--files=src/a.ts;src/b.ts", -]); + ), + SC.createArrayOption("emails", C.Email), + SC.createArrayOption("userIds", UserId), + ], +}, ({ options }) => { + type check = ExpectType< + typeof options, + { + tags: string[] | undefined; + files: [string, ...string[]]; + emails: C.Email[] | undefined; + userIds: C.GetNewType[] | undefined; + }, + "strict" + >; +}); diff --git a/docs/examples/v0/api/command/createBooleanOption/main.ts b/docs/examples/v0/api/command/createBooleanOption/main.ts index 05a9903..c99e8f0 100644 --- a/docs/examples/v0/api/command/createBooleanOption/main.ts +++ b/docs/examples/v0/api/command/createBooleanOption/main.ts @@ -11,21 +11,15 @@ const verboseOption = SC.createBooleanOption( const forceOption = SC.createBooleanOption("force"); -const command = SC.create( - "cleanup", - { - options: [verboseOption, forceOption], - }, - ({ options }) => { - type check = ExpectType< - typeof options, - { - verbose: boolean; - force: boolean; - }, - "strict" - >; - }, -); - -await command.execute(["--verbose", "--force"]); +await SC.exec({ + options: [verboseOption, forceOption], +}, ({ options }) => { + type check = ExpectType< + typeof options, + { + verbose: boolean; + force: boolean; + }, + "strict" + >; +}); diff --git a/docs/examples/v0/api/command/createOption/main.ts b/docs/examples/v0/api/command/createOption/main.ts index 58525c5..30863ff 100644 --- a/docs/examples/v0/api/command/createOption/main.ts +++ b/docs/examples/v0/api/command/createOption/main.ts @@ -1,38 +1,33 @@ import { SC } from "@duplojs/server-utils"; -import { DP, type ExpectType } from "@duplojs/utils"; +import { C, DP, type ExpectType } from "@duplojs/utils"; -const command = SC.create( - "serve", - { - options: [ - SC.createOption("host", DP.string()), - SC.createOption( - "port", - DP.coerce.number(), - { required: true }, - ), - SC.createOption( - "environment", - DP.literal(["dev", "prod"]), - ), - ], - }, - ({ options }) => { - type check = ExpectType< - typeof options, - { - host: string | undefined; - port: number; - environment: "dev" | "prod" | undefined; - }, - "strict" - >; - }, -); +const UserId = C.createNewType("user-id", DP.number(), C.Positive); -await command.execute([ - "--host", - "0.0.0.0", - "--port=8080", - "--environment=prod", -]); +await SC.exec({ + options: [ + SC.createOption("host", DP.string()), + SC.createOption( + "port", + DP.number(), + { required: true }, + ), + SC.createOption( + "environment", + DP.literal(["dev", "prod"]), + ), + SC.createOption("email", C.Email), + SC.createOption("userId", UserId), + ], +}, ({ options }) => { + type check = ExpectType< + typeof options, + { + host: string | undefined; + port: number; + environment: "dev" | "prod" | undefined; + email: C.Email | undefined; + userId: C.GetNewType | undefined; + }, + "strict" + >; +}); diff --git a/docs/examples/v0/api/command/execOptions/main.ts b/docs/examples/v0/api/command/execOptions/main.ts index 34d65f2..f40115b 100644 --- a/docs/examples/v0/api/command/execOptions/main.ts +++ b/docs/examples/v0/api/command/execOptions/main.ts @@ -18,7 +18,7 @@ const verboseOption = SC.createBooleanOption( }, ); -const options = SC.execOptions(portOption, verboseOption); +const options = await SC.execOptions(portOption, verboseOption); // ^? diff --git a/docs/fr/v0/api/command/create.md b/docs/fr/v0/api/command/create.md index 13eda2e..714f210 100644 --- a/docs/fr/v0/api/command/create.md +++ b/docs/fr/v0/api/command/create.md @@ -6,14 +6,13 @@ prev: next: text: "createBooleanOption" link: "/fr/v0/api/command/createBooleanOption" -description: "Crée une commande CLI avec son nom, son comportement, et une configuration optionnelle." +description: "Crée une commande CLI avec un nom, des options/sujets optionnels et un handler d'exécution." --- # create `create` sert à déclarer une commande CLI. -Vous donnez un nom et une fonction à exécuter. -Vous pouvez aussi ajouter des options, un sujet (arguments positionnels), ou des sous-commandes. +Vous fournissez un nom et une fonction d'exécution, et vous pouvez aussi ajouter des options, un sujet pour les arguments positionnels, ou des sous-commandes. ## Exemple @@ -48,12 +47,12 @@ function create< - `params` (`CreateCommandParams`, optionnel) : configuration de la commande. - `params.description` (`string`, optionnel) : description affichée dans le help. - `params.options` (`Option[]`, optionnel) : parseurs d'options. -- `params.subject` (`Subject | Command[]`, optionnel) : parser de données positionnelles ou liste de sous-commandes. -- `execute` : handler de commande. Reçoit `options` typées et `subject` typé optionnel. +- `params.subject` (`Subject | Command[]`, optionnel) : contrat de parsing pour les données positionnelles ou liste de sous-commandes. +- `execute` : handler de commande. Reçoit des `options` typées et, si présent, un `subject` typé. ## Valeur de retour -- `Command` : objet commande exécutable avec `execute(args)`. +- `Command` : objet de définition de commande destiné à être accroché à un arbre de commandes et exécuté via [`exec`](/fr/v0/api/command/exec). ## Autres exemples diff --git a/docs/fr/v0/api/command/createArrayOption.md b/docs/fr/v0/api/command/createArrayOption.md index 8681c15..707b157 100644 --- a/docs/fr/v0/api/command/createArrayOption.md +++ b/docs/fr/v0/api/command/createArrayOption.md @@ -6,7 +6,7 @@ prev: next: text: "Référence API" link: "/fr/v0/api/" -description: "Crée une option qui parse une liste séparée en tableau typé." +description: "Crée une option qui parse une liste délimitée vers un tableau typé depuis un DataParser ou un contrat clean." --- # createArrayOption @@ -25,11 +25,11 @@ Crée une option qui parse une liste séparée en tableau typé. ```typescript function createArrayOption< GenericName extends string, - GenericSchema extends EligibleDataParser, + GenericContract extends EligibleContract, GenericMinValues extends number >( name: GenericName, - schema: GenericSchema, + contract: GenericContract, params: { description?: string aliases?: readonly string[] @@ -41,18 +41,18 @@ function createArrayOption< ): Option< GenericName, [ - ...A.CreateTuple, GenericMinValues>, - ...DP.Output[] + ...A.CreateTuple, GenericMinValues>, + ...ComputeOptionContract[] ] > function createArrayOption< GenericName extends string, - GenericSchema extends EligibleDataParser, + GenericContract extends EligibleContract, GenericMinValues extends number >( name: GenericName, - schema: GenericSchema, + contract: GenericContract, params?: { description?: string aliases?: readonly string[] @@ -63,8 +63,8 @@ function createArrayOption< ): Option< GenericName, | [ - ...A.CreateTuple, GenericMinValues>, - ...DP.Output[] + ...A.CreateTuple, GenericMinValues>, + ...ComputeOptionContract[] ] | undefined > @@ -73,7 +73,7 @@ function createArrayOption< ## Paramètres - `name` (`string`) : nom de l'option utilisé comme `--name`. -- `schema` (`EligibleDataParser`) : parseur de chaque élément du tableau. +- `contract` (`EligibleContract`) : parseur ou contrat clean pour chaque élément du tableau. - `params` (optionnel) : métadonnées et contraintes de tableau. - `params.required` (`true`, optionnel) : déclenche une erreur si l'option est absente. - `params.min` (`number`, optionnel) : nombre minimal de valeurs. @@ -87,6 +87,10 @@ function createArrayOption< - Mode requis: `Option`. - Mode optionnel: `Option`. +## Notes + +- Les parsers primitifs et les contrats clean primitifs sont coercés automatiquement depuis l'entrée CLI en chaîne. + ## Voir aussi - [`createOption`](/fr/v0/api/command/createOption) - Construit une option à valeur unique. diff --git a/docs/fr/v0/api/command/createOption.md b/docs/fr/v0/api/command/createOption.md index 49f7f0a..20bc87d 100644 --- a/docs/fr/v0/api/command/createOption.md +++ b/docs/fr/v0/api/command/createOption.md @@ -6,12 +6,12 @@ prev: next: text: "createArrayOption" link: "/fr/v0/api/command/createArrayOption" -description: "Crée une option avec une valeur unique parsée via un schéma DataParser." +description: "Crée une option à valeur unique depuis un DataParser ou un contrat clean." --- # createOption -Crée une option avec une valeur unique parsée via un schéma DataParser. +Crée une option à valeur unique depuis un DataParser ou un contrat clean. ## Exemple @@ -25,34 +25,36 @@ Crée une option avec une valeur unique parsée via un schéma DataParser. ```typescript function createOption< GenericName extends string, - GenericSchema extends EligibleDataParser + GenericContract extends EligibleContract, + GenericOutput extends ComputeOptionContract = ComputeOptionContract >( name: GenericName, - schema: GenericSchema, + contract: GenericContract, params: { description?: string aliases?: readonly string[] required: true } -): Option> +): Option function createOption< GenericName extends string, - GenericSchema extends EligibleDataParser + GenericContract extends EligibleContract, + GenericOutput extends ComputeOptionContract = ComputeOptionContract >( name: GenericName, - schema: GenericSchema, + contract: GenericContract, params?: { description?: string aliases?: readonly string[] } -): Option | undefined> +): Option ``` ## Paramètres - `name` (`string`) : nom de l'option utilisé comme `--name`. -- `schema` (`EligibleDataParser`) : parseur utilisé pour valider/transformer la valeur. +- `contract` (`EligibleContract`) : parseur ou contrat clean utilisé pour valider/transformer la valeur. - `params` (optionnel) : métadonnées d'option et comportement d'obligation. - `params.required` (`true`, optionnel) : déclenche une erreur si l'option est absente. - `params.description` (`string`, optionnel) : description dans le help. @@ -60,8 +62,12 @@ function createOption< ## Valeur de retour -- `Option>` quand `required: true`. -- `Option | undefined>` sinon. +- `Option` quand `required: true`. +- `Option` sinon. + +## Notes + +- Les parsers primitifs et les contrats clean primitifs sont coercés automatiquement depuis l'entrée CLI en chaîne. ## Voir aussi diff --git a/docs/fr/v0/api/command/execOptions.md b/docs/fr/v0/api/command/execOptions.md index 9000837..402434b 100644 --- a/docs/fr/v0/api/command/execOptions.md +++ b/docs/fr/v0/api/command/execOptions.md @@ -11,7 +11,7 @@ description: "Parse les options CLI depuis les arguments du runtime." # execOptions -`execOptions` parse les options CLI et retourne le résultat sous forme de record `{ [optionName]: resultOption }`. +`execOptions` parse les options CLI et résout le résultat sous forme de record `{ [optionName]: resultOption }`. Si le parsing échoue, une erreur détaillée est affichée dans la console. Le `--help` / `-h` est généré automatiquement depuis les options déclarées. @@ -29,7 +29,7 @@ function execOptions< GenericOptions extends [Option, ...Option[]] >( ...options: GenericOptions -): ComputeResult +): Promise> ``` ## Paramètres @@ -38,7 +38,7 @@ function execOptions< ## Valeur de retour -- `ComputeResult` : objet dont les clés sont les noms d'options et les valeurs sont les résultats typés de chaque parser. +- `Promise>` : promesse qui résout un objet dont les clés sont les noms d'options et les valeurs sont les résultats typés de chaque parser. ## Voir aussi diff --git a/docs/libs/.gitignore b/docs/libs/.gitignore new file mode 100644 index 0000000..586e3d7 --- /dev/null +++ b/docs/libs/.gitignore @@ -0,0 +1 @@ +!dist \ No newline at end of file diff --git a/docs/libs/v0/command/create.cjs b/docs/libs/v0/command/create.cjs deleted file mode 100644 index 90d3033..0000000 --- a/docs/libs/v0/command/create.cjs +++ /dev/null @@ -1,150 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var AA = require('@duplojs/utils/array'); -var OO = require('@duplojs/utils/object'); -var DDP = require('@duplojs/utils/dataParser'); -var EE = require('@duplojs/utils/either'); -var kind = require('../kind.cjs'); -var exitProcess = require('../common/exitProcess.cjs'); -var error = require('./error.cjs'); -var help = require('./help.cjs'); -var boolean = require('./options/boolean.cjs'); - -function _interopNamespaceDefault(e) { - var n = Object.create(null); - if (e) { - Object.keys(e).forEach(function (k) { - if (k !== 'default') { - var d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: function () { return e[k]; } - }); - } - }); - } - n.default = e; - return Object.freeze(n); -} - -var AA__namespace = /*#__PURE__*/_interopNamespaceDefault(AA); -var OO__namespace = /*#__PURE__*/_interopNamespaceDefault(OO); -var DDP__namespace = /*#__PURE__*/_interopNamespaceDefault(DDP); -var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); - -function printError(commandError, error$1) { - if (!error$1) { - // eslint-disable-next-line no-console - console.error(error.interpretCommandError(commandError)); - exitProcess.exitProcess(1); - } - return error.SymbolCommandError; -} -const commandKind = kind.createDuplojsServerUtilsKind("command"); -const helpOption = boolean.createBooleanOption("help", { aliases: ["h"] }); -function create(...args) { - const [name, params, execute] = args.length === 2 - ? [args[0], {}, args[1]] - : args; - const self = commandKind.setTo({ - name, - description: params.description ?? null, - options: params.options ?? [], - subject: params.subject ?? null, - execute: async (args, error$1) => { - const commandError = error$1 ?? error.createError(self.name); - const pathIndex = commandError.currentCommandPath.length; - if (self.subject instanceof Array) { - for (const command of self.subject) { - if (args[0] === command.name) { - let result = undefined; - error.setErrorPath(commandError, command.name, pathIndex); - try { - result = await command.execute(AA__namespace.shift(args), commandError); - } - finally { - error.popErrorPath(commandError); - } - if (result === error.SymbolCommandError) { - return printError(commandError, error$1); - } - return result; - } - } - } - const help$1 = helpOption.execute(args, commandError); - if (help$1 === error.SymbolCommandError) { - return printError(commandError, error$1); - } - else if (help$1.result) { - help.logCommandHelp(self); - return void exitProcess.exitProcess(0); - } - const commandOptions = AA__namespace.reduce(self.options, AA__namespace.reduceFrom({ - options: {}, - restArgs: args, - }), ({ element: option, lastValue, next, exit }) => { - const optionResult = option.execute(lastValue.restArgs, commandError); - if (optionResult === error.SymbolCommandError) { - return exit(error.SymbolCommandError); - } - return next({ - options: OO__namespace.override(lastValue.options, { - [option.name]: optionResult.result, - }), - restArgs: optionResult.argumentRest, - }); - }); - if (commandOptions === error.SymbolCommandError) { - return printError(commandError, error$1); - } - if (self.subject === null) { - await execute({ options: commandOptions.options }); - } - else if (DDP__namespace.identifier(self.subject, DDP__namespace.arrayKind) - || DDP__namespace.identifier(self.subject, DDP__namespace.tupleKind)) { - const subjectResult = self.subject.parse(commandOptions.restArgs); - if (EE__namespace.isLeft(subjectResult)) { - error.addDataParserError(commandError, utils.unwrap(subjectResult), { - type: "subject", - }); - return printError(commandError, error$1); - } - await execute({ - options: commandOptions.options, - subject: utils.unwrap(subjectResult), - }); - } - else if (DDP__namespace.identifier(self.subject, DDP__namespace.dataParserKind)) { - if (commandOptions.restArgs.length > 1) { - error.addIssue(commandError, { - type: "command", - expected: "exactly one subject argument", - received: commandOptions.restArgs, - message: `Expected exactly one subject argument, received ${commandOptions.restArgs.length}.`, - }); - return printError(commandError, error$1); - } - const subjectResult = self.subject.parse(commandOptions.restArgs); - if (EE__namespace.isLeft(subjectResult)) { - error.addDataParserError(commandError, utils.unwrap(subjectResult), { - type: "subject", - }); - return printError(commandError, error$1); - } - await execute({ - options: commandOptions.options, - subject: utils.unwrap(subjectResult), - }); - } - else { - await execute({}); - } - return void exitProcess.exitProcess(0); - }, - }); - return self; -} - -exports.create = create; diff --git a/docs/libs/v0/command/create.d.ts b/docs/libs/v0/command/create.d.ts deleted file mode 100644 index 3abc03d..0000000 --- a/docs/libs/v0/command/create.d.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { type SimplifyTopLevel, type Kind, type MaybePromise } from "@duplojs/utils"; -import * as DDP from "@duplojs/utils/dataParser"; -import { type Option } from "./options"; -import type { EligibleDataParser } from "./types"; -import { SymbolCommandError, type CommandError } from "./error"; -export type Subject = (EligibleDataParser | DDP.DataParserArray & { - readonly element: EligibleDataParser; -}>> | DDP.AdvancedContract & { - readonly shape: readonly [ - EligibleDataParser, - ...EligibleDataParser[] - ]; - readonly rest: EligibleDataParser | undefined; -}>>>); -declare const commandKind: import("@duplojs/utils").KindHandler>; -export interface Command extends Kind { - readonly name: string; - readonly description: string | null; - readonly subject: Subject | null | readonly Command[]; - readonly options: readonly Option[]; - execute(args: readonly string[], error?: CommandError): Promise; -} -export interface CreateCommandParams { - description?: string; - options?: GenericOptions; - subject?: GenericSubject | readonly Command[]; -} -export interface CreateCommandExecuteParams { - options: { - [GenericOptionName in GenericOptions[number]["name"]]: Exclude["execute"]>, SymbolCommandError>["result"]; - }; - subject: DDP.Output; -} -/** - * Create a command node. - * - * Use this builder to define a command name, its optional options/subject, and the execute handler called after parsing. - * - * ```ts - * const ping = SC.create( - * "ping", - * () => { - * // run ping action - * }, - * ); - * - * const greet = SC.create( - * "greet", - * { - * options: [SC.createOption("name", DP.string(), { required: true })], - * }, - * ({ options: { name } }) => { - * // name: string - * }, - * ); - * - * const projectCreate = SC.create( - * "create", - * () => { - * // create project - * }, - * ); - * - * const project = SC.create( - * "project", - * { - * subject: [projectCreate], - * }, - * () => { - * // parent command fallback - * }, - * ); - * ``` - * - * @remarks - * `create` supports child commands by setting `subject` to an array of commands. - * - * @see https://server-utils.duplojs.dev/en/v0/api/command/create - * @namespace SC - * - */ -export declare function create(name: string, execute: () => void): Command; -export declare function create(name: string, params: CreateCommandParams, execute: (params: CreateCommandExecuteParams) => MaybePromise): Command; -export {}; diff --git a/docs/libs/v0/command/create.mjs b/docs/libs/v0/command/create.mjs deleted file mode 100644 index e632047..0000000 --- a/docs/libs/v0/command/create.mjs +++ /dev/null @@ -1,126 +0,0 @@ -import { unwrap } from '@duplojs/utils'; -import * as AA from '@duplojs/utils/array'; -import * as OO from '@duplojs/utils/object'; -import * as DDP from '@duplojs/utils/dataParser'; -import * as EE from '@duplojs/utils/either'; -import { createDuplojsServerUtilsKind } from '../kind.mjs'; -import { exitProcess } from '../common/exitProcess.mjs'; -import { createError, setErrorPath, popErrorPath, SymbolCommandError, addDataParserError, addIssue, interpretCommandError } from './error.mjs'; -import { logCommandHelp } from './help.mjs'; -import { createBooleanOption } from './options/boolean.mjs'; - -function printError(commandError, error) { - if (!error) { - // eslint-disable-next-line no-console - console.error(interpretCommandError(commandError)); - exitProcess(1); - } - return SymbolCommandError; -} -const commandKind = createDuplojsServerUtilsKind("command"); -const helpOption = createBooleanOption("help", { aliases: ["h"] }); -function create(...args) { - const [name, params, execute] = args.length === 2 - ? [args[0], {}, args[1]] - : args; - const self = commandKind.setTo({ - name, - description: params.description ?? null, - options: params.options ?? [], - subject: params.subject ?? null, - execute: async (args, error) => { - const commandError = error ?? createError(self.name); - const pathIndex = commandError.currentCommandPath.length; - if (self.subject instanceof Array) { - for (const command of self.subject) { - if (args[0] === command.name) { - let result = undefined; - setErrorPath(commandError, command.name, pathIndex); - try { - result = await command.execute(AA.shift(args), commandError); - } - finally { - popErrorPath(commandError); - } - if (result === SymbolCommandError) { - return printError(commandError, error); - } - return result; - } - } - } - const help = helpOption.execute(args, commandError); - if (help === SymbolCommandError) { - return printError(commandError, error); - } - else if (help.result) { - logCommandHelp(self); - return void exitProcess(0); - } - const commandOptions = AA.reduce(self.options, AA.reduceFrom({ - options: {}, - restArgs: args, - }), ({ element: option, lastValue, next, exit }) => { - const optionResult = option.execute(lastValue.restArgs, commandError); - if (optionResult === SymbolCommandError) { - return exit(SymbolCommandError); - } - return next({ - options: OO.override(lastValue.options, { - [option.name]: optionResult.result, - }), - restArgs: optionResult.argumentRest, - }); - }); - if (commandOptions === SymbolCommandError) { - return printError(commandError, error); - } - if (self.subject === null) { - await execute({ options: commandOptions.options }); - } - else if (DDP.identifier(self.subject, DDP.arrayKind) - || DDP.identifier(self.subject, DDP.tupleKind)) { - const subjectResult = self.subject.parse(commandOptions.restArgs); - if (EE.isLeft(subjectResult)) { - addDataParserError(commandError, unwrap(subjectResult), { - type: "subject", - }); - return printError(commandError, error); - } - await execute({ - options: commandOptions.options, - subject: unwrap(subjectResult), - }); - } - else if (DDP.identifier(self.subject, DDP.dataParserKind)) { - if (commandOptions.restArgs.length > 1) { - addIssue(commandError, { - type: "command", - expected: "exactly one subject argument", - received: commandOptions.restArgs, - message: `Expected exactly one subject argument, received ${commandOptions.restArgs.length}.`, - }); - return printError(commandError, error); - } - const subjectResult = self.subject.parse(commandOptions.restArgs); - if (EE.isLeft(subjectResult)) { - addDataParserError(commandError, unwrap(subjectResult), { - type: "subject", - }); - return printError(commandError, error); - } - await execute({ - options: commandOptions.options, - subject: unwrap(subjectResult), - }); - } - else { - await execute({}); - } - return void exitProcess(0); - }, - }); - return self; -} - -export { create }; diff --git a/docs/libs/v0/command/exec.cjs b/docs/libs/v0/command/exec.cjs deleted file mode 100644 index f233be4..0000000 --- a/docs/libs/v0/command/exec.cjs +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -var create = require('./create.cjs'); -var getProcessArguments = require('../common/getProcessArguments.cjs'); - -async function exec(...args) { - const [params, execute] = args.length === 1 - ? [{}, args[0]] - : args; - await create.create("root", params, execute).execute(getProcessArguments.getProcessArguments()); -} - -exports.exec = exec; diff --git a/docs/libs/v0/command/exec.mjs b/docs/libs/v0/command/exec.mjs deleted file mode 100644 index 8518730..0000000 --- a/docs/libs/v0/command/exec.mjs +++ /dev/null @@ -1,11 +0,0 @@ -import { create } from './create.mjs'; -import { getProcessArguments } from '../common/getProcessArguments.mjs'; - -async function exec(...args) { - const [params, execute] = args.length === 1 - ? [{}, args[0]] - : args; - await create("root", params, execute).execute(getProcessArguments()); -} - -export { exec }; diff --git a/docs/libs/v0/command/help.d.ts b/docs/libs/v0/command/help.d.ts deleted file mode 100644 index e8dc2c5..0000000 --- a/docs/libs/v0/command/help.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { Command } from "./create"; -import type { Option } from "./options"; -export declare function logCommandHelp(command: Command, depth?: number): void; -export declare function logExecOptionHelp(options: readonly Option[], depth?: number): void; diff --git a/docs/libs/v0/command/index.cjs b/docs/libs/v0/command/index.cjs deleted file mode 100644 index cda7ff9..0000000 --- a/docs/libs/v0/command/index.cjs +++ /dev/null @@ -1,37 +0,0 @@ -'use strict'; - -var create = require('./create.cjs'); -var exec = require('./exec.cjs'); -var help = require('./help.cjs'); -var error = require('./error.cjs'); -var execOptions = require('./execOptions.cjs'); -var base = require('./options/base.cjs'); -var boolean = require('./options/boolean.cjs'); -var simple = require('./options/simple.cjs'); -var array = require('./options/array.cjs'); - -/** - * {@include command/index.md} - */ - -exports.create = create.create; -exports.exec = exec.exec; -exports.formatSubject = help.formatSubject; -exports.logCommandHelp = help.logCommandHelp; -exports.logExecOptionHelp = help.logExecOptionHelp; -exports.renderCommandHelp = help.renderCommandHelp; -exports.renderExecOptionHelp = help.renderExecOptionHelp; -exports.renderOptionsHelp = help.renderOptionsHelp; -exports.SymbolCommandError = error.SymbolCommandError; -exports.addDataParserError = error.addDataParserError; -exports.addIssue = error.addIssue; -exports.createError = error.createError; -exports.interpretCommandError = error.interpretCommandError; -exports.interpretExecOptionError = error.interpretExecOptionError; -exports.popErrorPath = error.popErrorPath; -exports.setErrorPath = error.setErrorPath; -exports.execOptions = execOptions.execOptions; -exports.initOption = base.initOption; -exports.createBooleanOption = boolean.createBooleanOption; -exports.createOption = simple.createOption; -exports.createArrayOption = array.createArrayOption; diff --git a/docs/libs/v0/command/index.mjs b/docs/libs/v0/command/index.mjs deleted file mode 100644 index e5d2ca1..0000000 --- a/docs/libs/v0/command/index.mjs +++ /dev/null @@ -1,13 +0,0 @@ -export { create } from './create.mjs'; -export { exec } from './exec.mjs'; -export { formatSubject, logCommandHelp, logExecOptionHelp, renderCommandHelp, renderExecOptionHelp, renderOptionsHelp } from './help.mjs'; -export { SymbolCommandError, addDataParserError, addIssue, createError, interpretCommandError, interpretExecOptionError, popErrorPath, setErrorPath } from './error.mjs'; -export { execOptions } from './execOptions.mjs'; -export { initOption } from './options/base.mjs'; -export { createBooleanOption } from './options/boolean.mjs'; -export { createOption } from './options/simple.mjs'; -export { createArrayOption } from './options/array.mjs'; - -/** - * {@include command/index.md} - */ diff --git a/docs/libs/v0/command/options/simple.d.ts b/docs/libs/v0/command/options/simple.d.ts deleted file mode 100644 index 99e0477..0000000 --- a/docs/libs/v0/command/options/simple.d.ts +++ /dev/null @@ -1,51 +0,0 @@ -import * as DDP from "@duplojs/utils/dataParser"; -import { type Option } from "./base"; -import type { EligibleDataParser } from "../types"; -/** - * Create an option with a single parsed value. - * - * Use a DataParser schema to parse and validate the option value from `--name=value` or `--name value`. - * - * ```ts - * const port = SC.createOption("port", DP.string()); - * - * const name = SC.createOption( - * "name", - * DP.string(), - * { - * required: true, - * aliases: ["n"], - * }, - * ); - * - * const mode = SC.createOption( - * "mode", - * DP.literal(["dev", "prod"]), - * ); - * - * SC.create( - * "serve", - * { - * options: [port, name, mode], - * }, - * ({ options: { port, name, mode } }) => { - * // port: string | undefined - * // name: string - * ``` - * - * @remarks - * Set `required: true` to throw when the option is missing. - * - * @see https://server-utils.duplojs.dev/en/v0/api/command/createOption - * @namespace SC - * - */ -export declare function createOption(name: GenericName, schema: GenericSchema, params: { - description?: string; - aliases?: readonly string[]; - required: true; -}): Option>; -export declare function createOption(name: GenericName, schema: GenericSchema, params?: { - description?: string; - aliases?: readonly string[]; -}): Option | undefined>; diff --git a/docs/libs/v0/command/options/simple.mjs b/docs/libs/v0/command/options/simple.mjs deleted file mode 100644 index b557d72..0000000 --- a/docs/libs/v0/command/options/simple.mjs +++ /dev/null @@ -1,36 +0,0 @@ -import { unwrap } from '@duplojs/utils'; -import * as EE from '@duplojs/utils/either'; -import * as DDP from '@duplojs/utils/dataParser'; -import { initOption } from './base.mjs'; -import { addIssue, addDataParserError } from '../error.mjs'; - -function createOption(name, schema, params) { - const dataParser = params?.required - ? schema - : DDP.optional(schema); - return initOption(name, ({ isHere, value }, error) => { - if (!isHere && params?.required) { - return addIssue(error, { - type: "option", - target: name, - expected: `required option --${name}`, - received: value, - message: `Option "${name}" is required.`, - }); - } - const result = dataParser.parse(value); - if (EE.isLeft(result)) { - return addDataParserError(error, unwrap(result), { - type: "option", - target: name, - }); - } - return unwrap(result); - }, { - description: params?.description, - aliases: params?.aliases, - hasValue: true, - }); -} - -export { createOption }; diff --git a/docs/libs/v0/command/types/eligibleDataParser.d.ts b/docs/libs/v0/command/types/eligibleDataParser.d.ts deleted file mode 100644 index ff584e3..0000000 --- a/docs/libs/v0/command/types/eligibleDataParser.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -import type { DP, SimplifyTopLevel } from "@duplojs/utils"; -export type EligibleDataParser = (DP.DataParserString | DP.DataParserNumber & { - readonly coerce: true; -}>> | DP.DataParserBigInt & { - readonly coerce: true; -}>> | DP.DataParserDate & { - readonly coerce: true; -}>> | DP.DataParserTime & { - readonly coerce: true; -}>> | DP.DataParserLiteral & { - readonly value: readonly string[]; -}>> | DP.DataParserNil & { - readonly coerce: true; -}>> | DP.DataParserTemplateLiteral | DP.DataParserUnion & { - readonly options: readonly [ - EligibleDataParser, - ...EligibleDataParser[] - ]; -}>> | DP.DataParserTransform & { - readonly inner: EligibleDataParser; -}>> | DP.DataParserPipe & { - readonly input: EligibleDataParser; - readonly output: EligibleDataParser; -}>> | DP.DataParserOptional & { - readonly inner: EligibleDataParser; -}>>); diff --git a/docs/libs/v0/command/types/index.d.ts b/docs/libs/v0/command/types/index.d.ts deleted file mode 100644 index 9ef3554..0000000 --- a/docs/libs/v0/command/types/index.d.ts +++ /dev/null @@ -1 +0,0 @@ -export * from "./eligibleDataParser"; diff --git a/docs/libs/v0/common/environmentVariable/expandEnvironmentVariables.cjs b/docs/libs/v0/common/environmentVariable/expandEnvironmentVariables.cjs deleted file mode 100644 index 114eb4a..0000000 --- a/docs/libs/v0/common/environmentVariable/expandEnvironmentVariables.cjs +++ /dev/null @@ -1,27 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); - -const envVarRegex = /(?[^{}]+)}/g; -const escapedDollarRegex = /\\\$/g; -function expandValue(value, env, stack = new Set()) { - return utils.S.replace(value, envVarRegex, ({ namedGroups }) => { - const value = namedGroups.value; - const rawEnvValue = env[value]; - if (rawEnvValue === undefined || stack.has(value)) { - return ""; - } - stack.add(value); - const resolved = expandValue(rawEnvValue, env, stack); - stack.delete(value); - return resolved; - }); -} -function expandEnvironmentVariables(env) { - return utils.G.reduce(utils.O.entries(env), utils.G.reduceFrom(env), ({ element: [key, value], lastValue, nextWithObject }) => nextWithObject(lastValue, { - [key]: utils.S.replaceAll(expandValue(value, lastValue), escapedDollarRegex, "$"), - })); -} - -exports.expandEnvironmentVariables = expandEnvironmentVariables; -exports.expandValue = expandValue; diff --git a/docs/libs/v0/common/environmentVariable/overrideEnvironmentVariables.cjs b/docs/libs/v0/common/environmentVariable/overrideEnvironmentVariables.cjs deleted file mode 100644 index 64cb1b0..0000000 --- a/docs/libs/v0/common/environmentVariable/overrideEnvironmentVariables.cjs +++ /dev/null @@ -1,11 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); - -function overrideEnvironmentVariables(arrayEnv, override) { - return utils.pipe(arrayEnv, utils.A.map(utils.O.entries), utils.A.flat, (entries) => override - ? entries - : utils.A.reverse(entries), utils.O.fromEntries); -} - -exports.overrideEnvironmentVariables = overrideEnvironmentVariables; diff --git a/docs/libs/v0/common/environmentVariable/overrideEnvironmentVariables.mjs b/docs/libs/v0/common/environmentVariable/overrideEnvironmentVariables.mjs deleted file mode 100644 index 6d56502..0000000 --- a/docs/libs/v0/common/environmentVariable/overrideEnvironmentVariables.mjs +++ /dev/null @@ -1,9 +0,0 @@ -import { pipe, A, O } from '@duplojs/utils'; - -function overrideEnvironmentVariables(arrayEnv, override) { - return pipe(arrayEnv, A.map(O.entries), A.flat, (entries) => override - ? entries - : A.reverse(entries), O.fromEntries); -} - -export { overrideEnvironmentVariables }; diff --git a/docs/libs/v0/common/environmentVariable/parseEnvironmentFiles.cjs b/docs/libs/v0/common/environmentVariable/parseEnvironmentFiles.cjs deleted file mode 100644 index 4108f2f..0000000 --- a/docs/libs/v0/common/environmentVariable/parseEnvironmentFiles.cjs +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var readTextFile = require('../../file/readTextFile.cjs'); - -const lineRegex = /^(?:export\s+)?(?[A-Z_][A-Z0-9_]*)=(?'(?:\\'|[^'])*'|"(?:\\"|[^"])*"|`(?:\\`|[^`])*`|[^\s#\r\n][^#\r\n]*|)\s*(?:#.*)?$/mg; -const endLineBreakerRegex = /\r\n?/mg; -const surroundingQuoteRegex = /^(['"`])([\s\S]*)\1$/mg; -const backCartRegex = /\\r/g; -const newLineRegex = /\\n/g; -function parseEnvironmentLine(line) { - return utils.pipe(line, utils.S.replace(endLineBreakerRegex, "\n"), utils.S.extractAll(lineRegex), utils.G.reduce(utils.G.reduceFrom({}), ({ element, nextWithObject, lastValue, next }) => { - if (element.namedGroups?.key && element.namedGroups?.value) { - return nextWithObject(lastValue, { - [element.namedGroups.key]: utils.pipe(element.namedGroups.value, (value) => { - const surroundingValue = utils.S.replace(value, surroundingQuoteRegex, "$2"); - if (utils.S.startsWith(value, "\"")) { - return utils.pipe(surroundingValue, utils.S.replace(newLineRegex, "\n"), utils.S.replace(backCartRegex, "\r")); - } - return surroundingValue; - }), - }); - } - return next(lastValue); - })); -} -function parseEnvironmentFiles(baseEnv, paths) { - return utils.G.asyncReduce(paths, utils.G.reduceFrom([baseEnv]), ({ lastValue, element, nextPush, exit }) => readTextFile.readTextFile(element) - .then(utils.innerPipe(utils.E.whenIsRight(utils.innerPipe(parseEnvironmentLine, (value) => nextPush(lastValue, value))), utils.when(utils.E.isLeft, exit)))); -} - -exports.parseEnvironmentFiles = parseEnvironmentFiles; -exports.parseEnvironmentLine = parseEnvironmentLine; diff --git a/docs/libs/v0/common/environmentVariable/parseEnvironmentFiles.mjs b/docs/libs/v0/common/environmentVariable/parseEnvironmentFiles.mjs deleted file mode 100644 index cf2a193..0000000 --- a/docs/libs/v0/common/environmentVariable/parseEnvironmentFiles.mjs +++ /dev/null @@ -1,30 +0,0 @@ -import { G, innerPipe, E, when, pipe, S } from '@duplojs/utils'; -import { readTextFile } from '../../file/readTextFile.mjs'; - -const lineRegex = /^(?:export\s+)?(?[A-Z_][A-Z0-9_]*)=(?'(?:\\'|[^'])*'|"(?:\\"|[^"])*"|`(?:\\`|[^`])*`|[^\s#\r\n][^#\r\n]*|)\s*(?:#.*)?$/mg; -const endLineBreakerRegex = /\r\n?/mg; -const surroundingQuoteRegex = /^(['"`])([\s\S]*)\1$/mg; -const backCartRegex = /\\r/g; -const newLineRegex = /\\n/g; -function parseEnvironmentLine(line) { - return pipe(line, S.replace(endLineBreakerRegex, "\n"), S.extractAll(lineRegex), G.reduce(G.reduceFrom({}), ({ element, nextWithObject, lastValue, next }) => { - if (element.namedGroups?.key && element.namedGroups?.value) { - return nextWithObject(lastValue, { - [element.namedGroups.key]: pipe(element.namedGroups.value, (value) => { - const surroundingValue = S.replace(value, surroundingQuoteRegex, "$2"); - if (S.startsWith(value, "\"")) { - return pipe(surroundingValue, S.replace(newLineRegex, "\n"), S.replace(backCartRegex, "\r")); - } - return surroundingValue; - }), - }); - } - return next(lastValue); - })); -} -function parseEnvironmentFiles(baseEnv, paths) { - return G.asyncReduce(paths, G.reduceFrom([baseEnv]), ({ lastValue, element, nextPush, exit }) => readTextFile(element) - .then(innerPipe(E.whenIsRight(innerPipe(parseEnvironmentLine, (value) => nextPush(lastValue, value))), when(E.isLeft, exit)))); -} - -export { parseEnvironmentFiles, parseEnvironmentLine }; diff --git a/docs/libs/v0/common/getCurrentWorkDirectory.cjs b/docs/libs/v0/common/getCurrentWorkDirectory.cjs deleted file mode 100644 index fc25889..0000000 --- a/docs/libs/v0/common/getCurrentWorkDirectory.cjs +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include common/getCurrentWorkDirectory/index.md} - */ -const getCurrentWorkDirectory = implementor.implementFunction("getCurrentWorkDirectory", { - NODE: () => utils.pipe(utils.E.safeCallback(() => utils.E.success(process.cwd())), utils.E.whenIsLeft(utils.E.error)), - DENO: () => utils.pipe(utils.E.safeCallback(() => utils.E.success(Deno.cwd())), utils.E.whenIsLeft(utils.E.error)), -}); - -exports.getCurrentWorkDirectory = getCurrentWorkDirectory; diff --git a/docs/libs/v0/common/getCurrentWorkDirectory.mjs b/docs/libs/v0/common/getCurrentWorkDirectory.mjs deleted file mode 100644 index d2d165f..0000000 --- a/docs/libs/v0/common/getCurrentWorkDirectory.mjs +++ /dev/null @@ -1,12 +0,0 @@ -import { pipe, E } from '@duplojs/utils'; -import { implementFunction } from '../implementor.mjs'; - -/** - * {@include common/getCurrentWorkDirectory/index.md} - */ -const getCurrentWorkDirectory = implementFunction("getCurrentWorkDirectory", { - NODE: () => pipe(E.safeCallback(() => E.success(process.cwd())), E.whenIsLeft(E.error)), - DENO: () => pipe(E.safeCallback(() => E.success(Deno.cwd())), E.whenIsLeft(E.error)), -}); - -export { getCurrentWorkDirectory }; diff --git a/docs/libs/v0/common/setCurrentWorkingDirectory.cjs b/docs/libs/v0/common/setCurrentWorkingDirectory.cjs deleted file mode 100644 index e8889b9..0000000 --- a/docs/libs/v0/common/setCurrentWorkingDirectory.cjs +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include common/setCurrentWorkingDirectory/index.md} - */ -const setCurrentWorkingDirectory = implementor.implementFunction("setCurrentWorkingDirectory", { - NODE: (path) => utils.pipe(path, utils.when(utils.instanceOf(URL), ({ pathname }) => decodeURIComponent(pathname)), (path) => utils.E.safeCallback(() => void process.chdir(path)), utils.P.when(utils.E.isLeft, utils.E.fail), utils.P.otherwise(utils.E.ok)), - DENO: (path) => utils.pipe(path, utils.when(utils.instanceOf(URL), ({ pathname }) => decodeURIComponent(pathname)), (path) => utils.E.safeCallback(() => void Deno.chdir(path)), utils.P.when(utils.E.isLeft, utils.E.fail), utils.P.otherwise(utils.E.ok)), -}); - -exports.setCurrentWorkingDirectory = setCurrentWorkingDirectory; diff --git a/docs/libs/v0/common/setCurrentWorkingDirectory.mjs b/docs/libs/v0/common/setCurrentWorkingDirectory.mjs deleted file mode 100644 index fc372a0..0000000 --- a/docs/libs/v0/common/setCurrentWorkingDirectory.mjs +++ /dev/null @@ -1,12 +0,0 @@ -import { pipe, when, instanceOf, E, P } from '@duplojs/utils'; -import { implementFunction } from '../implementor.mjs'; - -/** - * {@include common/setCurrentWorkingDirectory/index.md} - */ -const setCurrentWorkingDirectory = implementFunction("setCurrentWorkingDirectory", { - NODE: (path) => pipe(path, when(instanceOf(URL), ({ pathname }) => decodeURIComponent(pathname)), (path) => E.safeCallback(() => void process.chdir(path)), P.when(E.isLeft, E.fail), P.otherwise(E.ok)), - DENO: (path) => pipe(path, when(instanceOf(URL), ({ pathname }) => decodeURIComponent(pathname)), (path) => E.safeCallback(() => void Deno.chdir(path)), P.when(E.isLeft, E.fail), P.otherwise(E.ok)), -}); - -export { setCurrentWorkingDirectory }; diff --git a/docs/libs/v0/dist/command/create/index.cjs b/docs/libs/v0/dist/command/create/index.cjs new file mode 100644 index 0000000..9f30011 --- /dev/null +++ b/docs/libs/v0/dist/command/create/index.cjs @@ -0,0 +1,149 @@ +'use strict'; + +var utils = require('@duplojs/utils'); +var AA = require('@duplojs/utils/array'); +var GG = require('@duplojs/utils/generator'); +var OO = require('@duplojs/utils/object'); +var EE = require('@duplojs/utils/either'); +var kind = require('../../kind.cjs'); +var exitProcess = require('../../common/exitProcess.cjs'); +var error = require('../error.cjs'); +var help = require('../help.cjs'); +var subject = require('./subject.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var AA__namespace = /*#__PURE__*/_interopNamespaceDefault(AA); +var GG__namespace = /*#__PURE__*/_interopNamespaceDefault(GG); +var OO__namespace = /*#__PURE__*/_interopNamespaceDefault(OO); +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +const commandKind = kind.createDuplojsServerUtilsKind("command"); +function isCommand(input) { + return input instanceof Array + ? input.every(commandKind.has) + : commandKind.has(input); +} +function create(...args) { + const [name, params, execute] = args.length === 2 + ? [args[0], {}, args[1]] + : args; + const self = commandKind.setTo({ + name, + description: params.description ?? null, + options: params.options ?? [], + children: utils.justExec(() => { + if (isCommand(params.subject)) { + return { + type: "subCommand", + subCommands: AA__namespace.coalescing(params.subject), + }; + } + else if (params.subject) { + return { + type: "subject", + subject: params.subject, + dataParser: subject.subjectToDataParser(params.subject), + }; + } + return null; + }), + execute: async (args, error$1) => { + if (self.children?.type === "subCommand") { + for (const command of self.children.subCommands) { + if (args[0] === command.name) { + error$1.currentCommandPath[error$1.currentCommandPath.length] = command.name; + return command.execute(AA__namespace.shift(args), error$1); + } + } + } + const help$1 = await help.helpOption.execute(args, error$1); + if (help$1 === error.SymbolCommandError) { + return error.SymbolCommandError; + } + else if (help$1.result) { + help.logCommandHelp(self); + return void exitProcess.exitProcess(0); + } + const commandOptions = await GG__namespace.asyncReduce(self.options, GG__namespace.reduceFrom({ + options: {}, + restArgs: args, + }), async ({ element: option, lastValue, next, exit }) => { + const optionResult = await option.execute(lastValue.restArgs, error$1); + if (optionResult === error.SymbolCommandError) { + return exit(error.SymbolCommandError); + } + return next({ + options: OO__namespace.override(lastValue.options, { + [option.name]: optionResult.result, + }), + restArgs: optionResult.argumentRest, + }); + }); + if (commandOptions === error.SymbolCommandError) { + return error.SymbolCommandError; + } + if (self.children?.type === "subject") { + const hasMultiSubject = subject.isMultiSubject(self.children.subject); + if (!hasMultiSubject + && commandOptions.restArgs.length > 1) { + error.addIssue(error$1, { + type: "command", + expected: "exactly one subject argument", + received: commandOptions.restArgs, + message: `Expected exactly one subject argument, received ${commandOptions.restArgs.length}.`, + }); + return error.SymbolCommandError; + } + const subjectInput = hasMultiSubject + ? commandOptions.restArgs + : commandOptions.restArgs[0]; + const subjectResult = self.children.dataParser.isAsynchronous() + ? await self.children.dataParser.asyncParse(subjectInput) + : self.children.dataParser.parse(subjectInput); + if (EE__namespace.isLeft(subjectResult)) { + error.addIssueDataParser(error$1, utils.unwrap(subjectResult), { + type: "subject", + }); + return error.SymbolCommandError; + } + await execute({ + options: commandOptions.options, + subject: utils.unwrap(subjectResult), + }); + } + else { + if (commandOptions.restArgs.length > 0) { + error.addIssue(error$1, { + type: "command", + expected: "existing child command", + received: commandOptions.restArgs[0], + message: `Unknown child command "${commandOptions.restArgs[0]}".`, + }); + return error.SymbolCommandError; + } + await execute({ options: commandOptions.options }); + } + return void exitProcess.exitProcess(0); + }, + }); + return self; +} + +exports.create = create; +exports.isCommand = isCommand; diff --git a/docs/libs/v0/dist/command/create/index.d.ts b/docs/libs/v0/dist/command/create/index.d.ts new file mode 100644 index 0000000..12b3ea5 --- /dev/null +++ b/docs/libs/v0/dist/command/create/index.d.ts @@ -0,0 +1,91 @@ +import { type Kind, type MaybePromise, type AnyTuple, type IsEqual } from "@duplojs/utils"; +import type * as DDP from "@duplojs/utils/dataParser"; +import type { Option } from "../options"; +import { SymbolCommandError, type CommandError } from "../error"; +import { type ComputeSubject, type Subject } from "./subject"; +export type { Subject } from "./subject"; +declare const commandKind: import("@duplojs/utils").KindHandler>; +export declare function isCommand(input: unknown): input is Command | AnyTuple; +export type CommandChildren = { + type: "subCommand"; + subCommands: readonly Command[]; +} | { + type: "subject"; + subject: Subject; + dataParser: DDP.DataParser; +}; +export interface Command extends Kind { + readonly name: string; + readonly description: string | null; + readonly children: CommandChildren | null; + readonly options: readonly Option[]; + execute(args: readonly string[], error: CommandError): Promise; +} +export interface CreateCommandParams | undefined = undefined> { + description?: string; + options?: GenericOptions; + subject?: GenericSubject; +} +export type CreateCommandExecuteParams | undefined = undefined> = ((IsEqual extends true ? {} : { + options: { + [GenericOption in GenericOptions[number] as GenericOption["name"]]: Exclude>, SymbolCommandError>["result"]; + }; +}) & ([ + GenericSubject +] extends [Subject] ? { + subject: ComputeSubject; +} : {})); +/** + * Create a command node. + * + * Use this builder to define a command name, optional options, an optional subject, and the execute handler called after parsing. + * + * ```ts + * const ping = SC.create( + * "ping", + * () => { + * // run ping action + * }, + * ); + * + * const UserId = C.createNewType("user-id", DP.number(), C.Positive); + * + * const greet = SC.create( + * "greet", + * { + * options: [SC.createOption("email", C.Email)], + * subject: UserId, + * }, + * ({ options: { email }, subject }) => { + * // email: C.Email | undefined + * // subject: C.GetNewType + * }, + * ); + * + * const projectCreate = SC.create( + * "create", + * () => { + * // create project + * }, + * ); + * + * const project = SC.create( + * "project", + * { + * subject: [projectCreate], + * }, + * () => { + * // parent command fallback + * }, + * ); + * ``` + * + * @remarks + * `subject` can be a parser-like contract for positional arguments, or an array of child commands for nested command trees. + * + * @see https://server-utils.duplojs.dev/en/v0/api/command/create + * @namespace SC + * + */ +export declare function create(name: string, execute: () => void): Command; +export declare function create | undefined = undefined>(name: string, params: CreateCommandParams, execute: (params: CreateCommandExecuteParams) => MaybePromise): Command; diff --git a/docs/libs/v0/dist/command/create/index.mjs b/docs/libs/v0/dist/command/create/index.mjs new file mode 100644 index 0000000..d3010c0 --- /dev/null +++ b/docs/libs/v0/dist/command/create/index.mjs @@ -0,0 +1,124 @@ +import { justExec, unwrap } from '@duplojs/utils'; +import * as AA from '@duplojs/utils/array'; +import * as GG from '@duplojs/utils/generator'; +import * as OO from '@duplojs/utils/object'; +import * as EE from '@duplojs/utils/either'; +import { createDuplojsServerUtilsKind } from '../../kind.mjs'; +import { exitProcess } from '../../common/exitProcess.mjs'; +import { SymbolCommandError, addIssue, addIssueDataParser } from '../error.mjs'; +import { helpOption, logCommandHelp } from '../help.mjs'; +import { isMultiSubject, subjectToDataParser } from './subject.mjs'; + +const commandKind = createDuplojsServerUtilsKind("command"); +function isCommand(input) { + return input instanceof Array + ? input.every(commandKind.has) + : commandKind.has(input); +} +function create(...args) { + const [name, params, execute] = args.length === 2 + ? [args[0], {}, args[1]] + : args; + const self = commandKind.setTo({ + name, + description: params.description ?? null, + options: params.options ?? [], + children: justExec(() => { + if (isCommand(params.subject)) { + return { + type: "subCommand", + subCommands: AA.coalescing(params.subject), + }; + } + else if (params.subject) { + return { + type: "subject", + subject: params.subject, + dataParser: subjectToDataParser(params.subject), + }; + } + return null; + }), + execute: async (args, error) => { + if (self.children?.type === "subCommand") { + for (const command of self.children.subCommands) { + if (args[0] === command.name) { + error.currentCommandPath[error.currentCommandPath.length] = command.name; + return command.execute(AA.shift(args), error); + } + } + } + const help = await helpOption.execute(args, error); + if (help === SymbolCommandError) { + return SymbolCommandError; + } + else if (help.result) { + logCommandHelp(self); + return void exitProcess(0); + } + const commandOptions = await GG.asyncReduce(self.options, GG.reduceFrom({ + options: {}, + restArgs: args, + }), async ({ element: option, lastValue, next, exit }) => { + const optionResult = await option.execute(lastValue.restArgs, error); + if (optionResult === SymbolCommandError) { + return exit(SymbolCommandError); + } + return next({ + options: OO.override(lastValue.options, { + [option.name]: optionResult.result, + }), + restArgs: optionResult.argumentRest, + }); + }); + if (commandOptions === SymbolCommandError) { + return SymbolCommandError; + } + if (self.children?.type === "subject") { + const hasMultiSubject = isMultiSubject(self.children.subject); + if (!hasMultiSubject + && commandOptions.restArgs.length > 1) { + addIssue(error, { + type: "command", + expected: "exactly one subject argument", + received: commandOptions.restArgs, + message: `Expected exactly one subject argument, received ${commandOptions.restArgs.length}.`, + }); + return SymbolCommandError; + } + const subjectInput = hasMultiSubject + ? commandOptions.restArgs + : commandOptions.restArgs[0]; + const subjectResult = self.children.dataParser.isAsynchronous() + ? await self.children.dataParser.asyncParse(subjectInput) + : self.children.dataParser.parse(subjectInput); + if (EE.isLeft(subjectResult)) { + addIssueDataParser(error, unwrap(subjectResult), { + type: "subject", + }); + return SymbolCommandError; + } + await execute({ + options: commandOptions.options, + subject: unwrap(subjectResult), + }); + } + else { + if (commandOptions.restArgs.length > 0) { + addIssue(error, { + type: "command", + expected: "existing child command", + received: commandOptions.restArgs[0], + message: `Unknown child command "${commandOptions.restArgs[0]}".`, + }); + return SymbolCommandError; + } + await execute({ options: commandOptions.options }); + } + return void exitProcess(0); + }, + }); + return self; +} + +export { create, isCommand }; diff --git a/docs/libs/v0/dist/command/create/subject.cjs b/docs/libs/v0/dist/command/create/subject.cjs new file mode 100644 index 0000000..55ca778 --- /dev/null +++ b/docs/libs/v0/dist/command/create/subject.cjs @@ -0,0 +1,82 @@ +'use strict'; + +var utils = require('@duplojs/utils'); +var DDP = require('@duplojs/utils/dataParser'); +var AA = require('@duplojs/utils/array'); +var CC = require('@duplojs/utils/clean'); +var file = require('../../dataParser/parsers/file.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var DDP__namespace = /*#__PURE__*/_interopNamespaceDefault(DDP); +var AA__namespace = /*#__PURE__*/_interopNamespaceDefault(AA); +var CC__namespace = /*#__PURE__*/_interopNamespaceDefault(CC); + +function subjectToDataParser(contract) { + if (utils.hasSomeKinds(contract, [ + DDP__namespace.numberKind, + DDP__namespace.bigIntKind, + DDP__namespace.dateKind, + DDP__namespace.timeKind, + DDP__namespace.nilKind, + file.fileKind, + ])) { + const clone = contract.clone(); + clone.definition.coerce = true; + return clone; + } + else if (DDP__namespace.identifier(contract, DDP__namespace.arrayKind)) { + return DDP__namespace.array(subjectToDataParser(contract.definition.element), contract.definition); + } + else if (DDP__namespace.identifier(contract, DDP__namespace.tupleKind)) { + return DDP__namespace.tuple(AA__namespace.mapTuple(contract.definition.shape, (part) => subjectToDataParser(part)), { + ...contract.definition, + rest: contract.definition.rest + ? subjectToDataParser(contract.definition.rest) + : undefined, + }); + } + else if (contract instanceof Array) { + return DDP__namespace.tuple(AA__namespace.mapTuple(contract, subjectToDataParser)); + } + else if (utils.hasSomeKinds(contract, [ + DDP__namespace.unionKind, + DDP__namespace.pipeKind, + DDP__namespace.optionalKind, + DDP__namespace.literalKind, + DDP__namespace.transformKind, + DDP__namespace.templateLiteralKind, + DDP__namespace.stringKind, + ])) { + return contract; + } + else { + return CC__namespace.toMapDataParser(contract, { coerce: true }); + } +} +function isMultiSubject(subject) { + return subject instanceof Array + || utils.hasSomeKinds(subject, [ + DDP__namespace.tupleKind, + DDP__namespace.arrayKind, + CC__namespace.entityPropertyArrayKind, + ]); +} + +exports.isMultiSubject = isMultiSubject; +exports.subjectToDataParser = subjectToDataParser; diff --git a/docs/libs/v0/dist/command/create/subject.d.ts b/docs/libs/v0/dist/command/create/subject.d.ts new file mode 100644 index 0000000..b1c0d76 --- /dev/null +++ b/docs/libs/v0/dist/command/create/subject.d.ts @@ -0,0 +1,17 @@ +import { type AnyTuple, type SimplifyTopLevel } from "@duplojs/utils"; +import * as DDP from "@duplojs/utils/dataParser"; +import type { ComputeEligibleCleanType, EligibleCleanType, EligibleDataParser } from "../types"; +export type Subject = (EligibleDataParser | DDP.DataParserArray & { + readonly element: EligibleDataParser; +}>> | DDP.AdvancedContract & { + readonly shape: readonly [ + EligibleDataParser, + ...EligibleDataParser[] + ]; + readonly rest: EligibleDataParser | undefined; +}>>> | EligibleCleanType | AnyTuple); +export type ComputeSubject = [GenericSubject] extends [DDP.DataParser] ? DDP.Output : [GenericSubject] extends [EligibleCleanType] ? ComputeEligibleCleanType : [GenericSubject] extends [AnyTuple] ? { + [GenericKey in keyof GenericSubject]: GenericSubject[GenericKey] extends EligibleCleanType | EligibleDataParser ? ComputeSubject : never; +} : never; +export declare function subjectToDataParser(contract: Subject): DDP.DataParser; +export declare function isMultiSubject(subject: Subject): boolean; diff --git a/docs/libs/v0/dist/command/create/subject.mjs b/docs/libs/v0/dist/command/create/subject.mjs new file mode 100644 index 0000000..16ee82d --- /dev/null +++ b/docs/libs/v0/dist/command/create/subject.mjs @@ -0,0 +1,58 @@ +import { hasSomeKinds } from '@duplojs/utils'; +import * as DDP from '@duplojs/utils/dataParser'; +import * as AA from '@duplojs/utils/array'; +import * as CC from '@duplojs/utils/clean'; +import { fileKind } from '../../dataParser/parsers/file.mjs'; + +function subjectToDataParser(contract) { + if (hasSomeKinds(contract, [ + DDP.numberKind, + DDP.bigIntKind, + DDP.dateKind, + DDP.timeKind, + DDP.nilKind, + fileKind, + ])) { + const clone = contract.clone(); + clone.definition.coerce = true; + return clone; + } + else if (DDP.identifier(contract, DDP.arrayKind)) { + return DDP.array(subjectToDataParser(contract.definition.element), contract.definition); + } + else if (DDP.identifier(contract, DDP.tupleKind)) { + return DDP.tuple(AA.mapTuple(contract.definition.shape, (part) => subjectToDataParser(part)), { + ...contract.definition, + rest: contract.definition.rest + ? subjectToDataParser(contract.definition.rest) + : undefined, + }); + } + else if (contract instanceof Array) { + return DDP.tuple(AA.mapTuple(contract, subjectToDataParser)); + } + else if (hasSomeKinds(contract, [ + DDP.unionKind, + DDP.pipeKind, + DDP.optionalKind, + DDP.literalKind, + DDP.transformKind, + DDP.templateLiteralKind, + DDP.stringKind, + ])) { + return contract; + } + else { + return CC.toMapDataParser(contract, { coerce: true }); + } +} +function isMultiSubject(subject) { + return subject instanceof Array + || hasSomeKinds(subject, [ + DDP.tupleKind, + DDP.arrayKind, + CC.entityPropertyArrayKind, + ]); +} + +export { isMultiSubject, subjectToDataParser }; diff --git a/docs/libs/v0/command/error.cjs b/docs/libs/v0/dist/command/error.cjs similarity index 90% rename from docs/libs/v0/command/error.cjs rename to docs/libs/v0/dist/command/error.cjs index a029461..129a6d8 100644 --- a/docs/libs/v0/command/error.cjs +++ b/docs/libs/v0/dist/command/error.cjs @@ -16,15 +16,7 @@ function addIssue(error, issue) { }); return SymbolCommandError; } -function setErrorPath(error, value, index) { - error.currentCommandPath[index] = value; - return error; -} -function popErrorPath(error) { - error.currentCommandPath.pop(); - return error; -} -function addDataParserError(error, parseError, params) { +function addIssueDataParser(error, parseError, params) { for (const issue of parseError.issues) { error.issues.push({ type: params.type, @@ -100,10 +92,8 @@ function interpretExecOptionError(error) { } exports.SymbolCommandError = SymbolCommandError; -exports.addDataParserError = addDataParserError; exports.addIssue = addIssue; +exports.addIssueDataParser = addIssueDataParser; exports.createError = createError; exports.interpretCommandError = interpretCommandError; exports.interpretExecOptionError = interpretExecOptionError; -exports.popErrorPath = popErrorPath; -exports.setErrorPath = setErrorPath; diff --git a/docs/libs/v0/command/error.d.ts b/docs/libs/v0/dist/command/error.d.ts similarity index 76% rename from docs/libs/v0/command/error.d.ts rename to docs/libs/v0/dist/command/error.d.ts index b7d9879..41ac130 100644 --- a/docs/libs/v0/command/error.d.ts +++ b/docs/libs/v0/dist/command/error.d.ts @@ -15,10 +15,8 @@ export interface CommandError { export declare const SymbolCommandError: unique symbol; export type SymbolCommandError = typeof SymbolCommandError; export declare function createError(commandName: string): CommandError; -export declare function addIssue(error: CommandError, issue: Omit): typeof SymbolCommandError; -export declare function setErrorPath(error: CommandError, value: string, index: number): CommandError; -export declare function popErrorPath(error: CommandError): CommandError; -export declare function addDataParserError(error: CommandError, parseError: DDP.DataParserError, params: { +export declare function addIssue(error: CommandError, issue: Omit): SymbolCommandError; +export declare function addIssueDataParser(error: CommandError, parseError: DDP.DataParserError, params: { type: "option" | "subject"; target?: string; }): SymbolCommandError; diff --git a/docs/libs/v0/command/error.mjs b/docs/libs/v0/dist/command/error.mjs similarity index 89% rename from docs/libs/v0/command/error.mjs rename to docs/libs/v0/dist/command/error.mjs index 3acfd24..8de3232 100644 --- a/docs/libs/v0/command/error.mjs +++ b/docs/libs/v0/dist/command/error.mjs @@ -14,15 +14,7 @@ function addIssue(error, issue) { }); return SymbolCommandError; } -function setErrorPath(error, value, index) { - error.currentCommandPath[index] = value; - return error; -} -function popErrorPath(error) { - error.currentCommandPath.pop(); - return error; -} -function addDataParserError(error, parseError, params) { +function addIssueDataParser(error, parseError, params) { for (const issue of parseError.issues) { error.issues.push({ type: params.type, @@ -97,4 +89,4 @@ function interpretExecOptionError(error) { ]); } -export { SymbolCommandError, addDataParserError, addIssue, createError, interpretCommandError, interpretExecOptionError, popErrorPath, setErrorPath }; +export { SymbolCommandError, addIssue, addIssueDataParser, createError, interpretCommandError, interpretExecOptionError }; diff --git a/docs/libs/v0/dist/command/exec.cjs b/docs/libs/v0/dist/command/exec.cjs new file mode 100644 index 0000000..5f0847d --- /dev/null +++ b/docs/libs/v0/dist/command/exec.cjs @@ -0,0 +1,21 @@ +'use strict'; + +var index = require('./create/index.cjs'); +var error = require('./error.cjs'); +var getProcessArguments = require('../common/getProcessArguments.cjs'); +var exitProcess = require('../common/exitProcess.cjs'); + +async function exec(...args) { + const [params, execute] = args.length === 1 + ? [{}, args[0]] + : args; + const error$1 = error.createError("root"); + const result = await index.create("root", params, execute).execute(getProcessArguments.getProcessArguments(), error$1); + if (result === error.SymbolCommandError) { + // eslint-disable-next-line no-console + console.error(error.interpretCommandError(error$1)); + return void exitProcess.exitProcess(1); + } +} + +exports.exec = exec; diff --git a/docs/libs/v0/command/exec.d.ts b/docs/libs/v0/dist/command/exec.d.ts similarity index 69% rename from docs/libs/v0/command/exec.d.ts rename to docs/libs/v0/dist/command/exec.d.ts index 3dca9e0..2c404d7 100644 --- a/docs/libs/v0/command/exec.d.ts +++ b/docs/libs/v0/dist/command/exec.d.ts @@ -1,5 +1,5 @@ -import type { MaybePromise } from "@duplojs/utils"; -import { type CreateCommandExecuteParams, type CreateCommandParams, type Subject } from "./create"; +import type { MaybePromise, AnyTuple } from "@duplojs/utils"; +import { type Command, type Subject, type CreateCommandExecuteParams, type CreateCommandParams } from "./create"; import type { Option } from "./options"; /** * Execute a root command from process arguments. @@ -43,4 +43,4 @@ import type { Option } from "./options"; * */ export declare function exec(execute: () => void): Promise; -export declare function exec(params: CreateCommandParams, execute: (params: CreateCommandExecuteParams) => MaybePromise): Promise; +export declare function exec | undefined>(params: CreateCommandParams, execute: (params: CreateCommandExecuteParams) => MaybePromise): Promise; diff --git a/docs/libs/v0/dist/command/exec.mjs b/docs/libs/v0/dist/command/exec.mjs new file mode 100644 index 0000000..ced0042 --- /dev/null +++ b/docs/libs/v0/dist/command/exec.mjs @@ -0,0 +1,19 @@ +import { create } from './create/index.mjs'; +import { createError, SymbolCommandError, interpretCommandError } from './error.mjs'; +import { getProcessArguments } from '../common/getProcessArguments.mjs'; +import { exitProcess } from '../common/exitProcess.mjs'; + +async function exec(...args) { + const [params, execute] = args.length === 1 + ? [{}, args[0]] + : args; + const error = createError("root"); + const result = await create("root", params, execute).execute(getProcessArguments(), error); + if (result === SymbolCommandError) { + // eslint-disable-next-line no-console + console.error(interpretCommandError(error)); + return void exitProcess(1); + } +} + +export { exec }; diff --git a/docs/libs/v0/command/execOptions.cjs b/docs/libs/v0/dist/command/execOptions.cjs similarity index 78% rename from docs/libs/v0/command/execOptions.cjs rename to docs/libs/v0/dist/command/execOptions.cjs index 6c0e0ad..2377c0c 100644 --- a/docs/libs/v0/command/execOptions.cjs +++ b/docs/libs/v0/dist/command/execOptions.cjs @@ -1,12 +1,11 @@ 'use strict'; -var AA = require('@duplojs/utils/array'); +var GG = require('@duplojs/utils/generator'); var OO = require('@duplojs/utils/object'); var error = require('./error.cjs'); var help = require('./help.cjs'); -var exitProcess = require('../common/exitProcess.cjs'); var getProcessArguments = require('../common/getProcessArguments.cjs'); -var boolean = require('./options/boolean.cjs'); +var exitProcess = require('../common/exitProcess.cjs'); function _interopNamespaceDefault(e) { var n = Object.create(null); @@ -25,14 +24,13 @@ function _interopNamespaceDefault(e) { return Object.freeze(n); } -var AA__namespace = /*#__PURE__*/_interopNamespaceDefault(AA); +var GG__namespace = /*#__PURE__*/_interopNamespaceDefault(GG); var OO__namespace = /*#__PURE__*/_interopNamespaceDefault(OO); -const helpOption = boolean.createBooleanOption("help", { aliases: ["h"] }); -function execOptions(...options) { +async function execOptions(...options) { const processArguments = getProcessArguments.getProcessArguments(); const error$1 = error.createError("root"); - const help$1 = helpOption.execute(processArguments, error$1); + const help$1 = await help.helpOption.execute(processArguments, error$1); if (help$1 === error.SymbolCommandError) { // eslint-disable-next-line no-console console.error(error.interpretExecOptionError(error$1)); @@ -42,11 +40,11 @@ function execOptions(...options) { help.logExecOptionHelp(options); return void exitProcess.exitProcess(0); } - const result = AA__namespace.reduce(options, AA__namespace.reduceFrom({ + const result = await GG__namespace.asyncReduce(options, GG__namespace.reduceFrom({ options: {}, restArgs: processArguments, - }), ({ element: option, lastValue, next, exit }) => { - const optionResult = option.execute(lastValue.restArgs, error$1); + }), async ({ element: option, lastValue, next, exit }) => { + const optionResult = await option.execute(lastValue.restArgs, error$1); if (optionResult === error.SymbolCommandError) { return exit(error.SymbolCommandError); } diff --git a/docs/libs/v0/command/execOptions.d.ts b/docs/libs/v0/dist/command/execOptions.d.ts similarity index 67% rename from docs/libs/v0/command/execOptions.d.ts rename to docs/libs/v0/dist/command/execOptions.d.ts index 9847981..cc8a943 100644 --- a/docs/libs/v0/command/execOptions.d.ts +++ b/docs/libs/v0/dist/command/execOptions.d.ts @@ -1,12 +1,12 @@ -import type { SimplifyTopLevel } from "@duplojs/utils"; -import { type Option } from "./options"; -type ComputeResult = SimplifyTopLevel<{ +import type { AnyTuple, SimplifyTopLevel } from "@duplojs/utils"; +import type { Option } from "./options"; +type ComputeResult> = SimplifyTopLevel<{ [GenericOption in GenericOptions[number] as GenericOption extends Option ? GenericName : never]: GenericOption extends Option ? GenericResult : never; }>; /** * Execute command options from process arguments. * - * `execOptions` reads runtime arguments, executes each option parser, and returns an object keyed by option name. + * `execOptions` reads runtime arguments, executes each option parser, and resolves to an object keyed by option name. * It also adds an automatic `--help` / `-h` manual generated from the declared options. * * ```ts @@ -18,7 +18,7 @@ type ComputeResult = SimplifyTopLe * required: true, * }, * ); - * const portResult = SC.execOptions(portOption); + * const portResult = await SC.execOptions(portOption); * // portResult.port: number * * const tagOption = SC.createArrayOption( @@ -31,7 +31,7 @@ type ComputeResult = SimplifyTopLe * ); * const forceOption = SC.createBooleanOption("force"); * - * const options = SC.execOptions(tagOption, forceOption); + * const options = await SC.execOptions(tagOption, forceOption); * // options.tag: string[] | undefined * ``` * @@ -42,5 +42,5 @@ type ComputeResult = SimplifyTopLe * @namespace SC * */ -export declare function execOptions(...options: GenericOptions): ComputeResult; +export declare function execOptions>(...options: GenericOptions): Promise>; export {}; diff --git a/docs/libs/v0/command/execOptions.mjs b/docs/libs/v0/dist/command/execOptions.mjs similarity index 71% rename from docs/libs/v0/command/execOptions.mjs rename to docs/libs/v0/dist/command/execOptions.mjs index 66065e7..6b77f6c 100644 --- a/docs/libs/v0/command/execOptions.mjs +++ b/docs/libs/v0/dist/command/execOptions.mjs @@ -1,16 +1,14 @@ -import * as AA from '@duplojs/utils/array'; +import * as GG from '@duplojs/utils/generator'; import * as OO from '@duplojs/utils/object'; import { createError, SymbolCommandError, interpretExecOptionError } from './error.mjs'; -import { logExecOptionHelp } from './help.mjs'; -import { exitProcess } from '../common/exitProcess.mjs'; +import { helpOption, logExecOptionHelp } from './help.mjs'; import { getProcessArguments } from '../common/getProcessArguments.mjs'; -import { createBooleanOption } from './options/boolean.mjs'; +import { exitProcess } from '../common/exitProcess.mjs'; -const helpOption = createBooleanOption("help", { aliases: ["h"] }); -function execOptions(...options) { +async function execOptions(...options) { const processArguments = getProcessArguments(); const error = createError("root"); - const help = helpOption.execute(processArguments, error); + const help = await helpOption.execute(processArguments, error); if (help === SymbolCommandError) { // eslint-disable-next-line no-console console.error(interpretExecOptionError(error)); @@ -20,11 +18,11 @@ function execOptions(...options) { logExecOptionHelp(options); return void exitProcess(0); } - const result = AA.reduce(options, AA.reduceFrom({ + const result = await GG.asyncReduce(options, GG.reduceFrom({ options: {}, restArgs: processArguments, - }), ({ element: option, lastValue, next, exit }) => { - const optionResult = option.execute(lastValue.restArgs, error); + }), async ({ element: option, lastValue, next, exit }) => { + const optionResult = await option.execute(lastValue.restArgs, error); if (optionResult === SymbolCommandError) { return exit(SymbolCommandError); } diff --git a/docs/libs/v0/command/help.cjs b/docs/libs/v0/dist/command/help.cjs similarity index 81% rename from docs/libs/v0/command/help.cjs rename to docs/libs/v0/dist/command/help.cjs index f5657c5..18bf6a7 100644 --- a/docs/libs/v0/command/help.cjs +++ b/docs/libs/v0/dist/command/help.cjs @@ -4,6 +4,8 @@ var utils = require('@duplojs/utils'); var AA = require('@duplojs/utils/array'); var PP = require('@duplojs/utils/pattern'); var DDP = require('@duplojs/utils/dataParser'); +var boolean = require('./options/boolean.cjs'); +var file = require('../dataParser/parsers/file.cjs'); function _interopNamespaceDefault(e) { var n = Object.create(null); @@ -26,9 +28,7 @@ var AA__namespace = /*#__PURE__*/_interopNamespaceDefault(AA); var PP__namespace = /*#__PURE__*/_interopNamespaceDefault(PP); var DDP__namespace = /*#__PURE__*/_interopNamespaceDefault(DDP); -/** - * @internal - */ +const helpOption = boolean.createBooleanOption("help", { aliases: ["h"] }); function formatSubject(subject) { return PP__namespace.match(subject) .when(DDP__namespace.identifier(DDP__namespace.stringKind), utils.justReturn("string")) @@ -37,11 +37,15 @@ function formatSubject(subject) { .when(DDP__namespace.identifier(DDP__namespace.dateKind), utils.justReturn("date")) .when(DDP__namespace.identifier(DDP__namespace.timeKind), utils.justReturn("time")) .when(DDP__namespace.identifier(DDP__namespace.nilKind), utils.justReturn("null")) + .when(file.fileKind.has, utils.justReturn("file")) .when(DDP__namespace.identifier(DDP__namespace.literalKind), (subject) => utils.pipe(subject.definition.value, AA__namespace.map(String), AA__namespace.join(" | "))) .when(DDP__namespace.identifier(DDP__namespace.templateLiteralKind), (subject) => utils.pipe(subject.definition.template, AA__namespace.map((part) => DDP__namespace.identifier(part, DDP__namespace.dataParserKind) ? `\${${formatSubject(part)}}` : String(part)), AA__namespace.join(""))) .when(DDP__namespace.identifier(DDP__namespace.unionKind), (subject) => utils.pipe(subject.definition.options, AA__namespace.map(formatSubject), AA__namespace.join(" | "))) + .when(DDP__namespace.identifier(DDP__namespace.transformKind), (subject) => formatSubject(subject.definition.inner)) + .when(DDP__namespace.identifier(DDP__namespace.pipeKind), (subject) => formatSubject(subject.definition.input)) + .when(DDP__namespace.identifier(DDP__namespace.optionalKind), (subject) => `${formatSubject(subject.definition.inner)}?`) .when(DDP__namespace.identifier(DDP__namespace.arrayKind), (subject) => `${formatSubject(subject.definition.element)}[]`) .when(DDP__namespace.identifier(DDP__namespace.tupleKind), (subject) => { const parts = utils.pipe(subject.definition.shape, AA__namespace.map(formatSubject), AA__namespace.join(", ")); @@ -52,9 +56,6 @@ function formatSubject(subject) { }) .otherwise(utils.justReturn("unknown")); } -/** - * @internal - */ function renderOptionsHelp(options, depth) { return utils.Printer.renderParagraph([ `${utils.Printer.indent(depth)}${utils.Printer.colorizedBold("OPTIONS:", "blue")}`, @@ -70,9 +71,6 @@ function renderOptionsHelp(options, depth) { ])), ]); } -/** - * @internal - */ function renderCommandHelp(command, depth) { const logs = []; logs.push(`${utils.Printer.indent(depth)}${utils.Printer.colorizedBold("NAME:", "green")}${command.name}`); @@ -85,42 +83,40 @@ function renderCommandHelp(command, depth) { if (AA__namespace.minElements(command.options, 1)) { logs.push(renderOptionsHelp(command.options, depth + 1)); } - if (utils.isType(command.subject, "array")) { - for (const childCommand of command.subject) { - logs.push(...renderCommandHelp(childCommand, depth + 1)); + if (command.children?.type === "subCommand") { + for (const subCommand of command.children.subCommands) { + logs.push(...renderCommandHelp(subCommand, depth + 1)); } } - else if (DDP__namespace.identifier(command.subject, DDP__namespace.dataParserKind)) { - const formattedSubject = formatSubject(command.subject); + else if (command.children?.type === "subject") { + const formattedSubject = formatSubject(command.children.dataParser); logs.push(AA__namespace.join([ utils.Printer.indent(depth + 1), utils.Printer.colorizedBold("SUBJECT:", "magenta"), - utils.hasSomeKinds(command.subject, [DDP__namespace.tupleKind, DDP__namespace.arrayKind]) + utils.hasSomeKinds(command.children.dataParser, [DDP__namespace.tupleKind, DDP__namespace.arrayKind]) ? formattedSubject : `<${formattedSubject}>`, ], "")); } return logs; } -function logCommandHelp(command, depth = 0) { +function logCommandHelp(command) { // eslint-disable-next-line no-console - console.log(utils.Printer.renderParagraph(renderCommandHelp(command, depth))); + console.log(utils.Printer.renderParagraph(renderCommandHelp(command, 0))); } -/** - * @internal - */ function renderExecOptionHelp(options, depth) { return [ `${utils.Printer.indent(depth)}${utils.Printer.colorizedBold("OPTION HELP", "green")}`, renderOptionsHelp(options, depth + 1), ]; } -function logExecOptionHelp(options, depth = 0) { +function logExecOptionHelp(options) { // eslint-disable-next-line no-console - console.log(utils.Printer.renderParagraph(renderExecOptionHelp(options, depth))); + console.log(utils.Printer.renderParagraph(renderExecOptionHelp(options, 0))); } exports.formatSubject = formatSubject; +exports.helpOption = helpOption; exports.logCommandHelp = logCommandHelp; exports.logExecOptionHelp = logExecOptionHelp; exports.renderCommandHelp = renderCommandHelp; diff --git a/docs/libs/v0/dist/command/help.d.ts b/docs/libs/v0/dist/command/help.d.ts new file mode 100644 index 0000000..fcf1c21 --- /dev/null +++ b/docs/libs/v0/dist/command/help.d.ts @@ -0,0 +1,10 @@ +import * as DDP from "@duplojs/utils/dataParser"; +import type { Command } from "./create"; +import { type Option } from "./options"; +export declare const helpOption: Option<"help", boolean>; +export declare function formatSubject(subject: DDP.DataParser): string; +export declare function renderOptionsHelp(options: readonly Option[], depth: number): string; +export declare function renderCommandHelp(command: Command, depth: number): string[]; +export declare function logCommandHelp(command: Command): void; +export declare function renderExecOptionHelp(options: readonly Option[], depth: number): string[]; +export declare function logExecOptionHelp(options: readonly Option[]): void; diff --git a/docs/libs/v0/command/help.mjs b/docs/libs/v0/dist/command/help.mjs similarity index 73% rename from docs/libs/v0/command/help.mjs rename to docs/libs/v0/dist/command/help.mjs index ec6a46d..6b5812c 100644 --- a/docs/libs/v0/command/help.mjs +++ b/docs/libs/v0/dist/command/help.mjs @@ -1,11 +1,11 @@ -import { justReturn, pipe, Printer, isType, hasSomeKinds } from '@duplojs/utils'; +import { Printer, hasSomeKinds, pipe, justReturn } from '@duplojs/utils'; import * as AA from '@duplojs/utils/array'; import * as PP from '@duplojs/utils/pattern'; import * as DDP from '@duplojs/utils/dataParser'; +import { createBooleanOption } from './options/boolean.mjs'; +import { fileKind } from '../dataParser/parsers/file.mjs'; -/** - * @internal - */ +const helpOption = createBooleanOption("help", { aliases: ["h"] }); function formatSubject(subject) { return PP.match(subject) .when(DDP.identifier(DDP.stringKind), justReturn("string")) @@ -14,11 +14,15 @@ function formatSubject(subject) { .when(DDP.identifier(DDP.dateKind), justReturn("date")) .when(DDP.identifier(DDP.timeKind), justReturn("time")) .when(DDP.identifier(DDP.nilKind), justReturn("null")) + .when(fileKind.has, justReturn("file")) .when(DDP.identifier(DDP.literalKind), (subject) => pipe(subject.definition.value, AA.map(String), AA.join(" | "))) .when(DDP.identifier(DDP.templateLiteralKind), (subject) => pipe(subject.definition.template, AA.map((part) => DDP.identifier(part, DDP.dataParserKind) ? `\${${formatSubject(part)}}` : String(part)), AA.join(""))) .when(DDP.identifier(DDP.unionKind), (subject) => pipe(subject.definition.options, AA.map(formatSubject), AA.join(" | "))) + .when(DDP.identifier(DDP.transformKind), (subject) => formatSubject(subject.definition.inner)) + .when(DDP.identifier(DDP.pipeKind), (subject) => formatSubject(subject.definition.input)) + .when(DDP.identifier(DDP.optionalKind), (subject) => `${formatSubject(subject.definition.inner)}?`) .when(DDP.identifier(DDP.arrayKind), (subject) => `${formatSubject(subject.definition.element)}[]`) .when(DDP.identifier(DDP.tupleKind), (subject) => { const parts = pipe(subject.definition.shape, AA.map(formatSubject), AA.join(", ")); @@ -29,9 +33,6 @@ function formatSubject(subject) { }) .otherwise(justReturn("unknown")); } -/** - * @internal - */ function renderOptionsHelp(options, depth) { return Printer.renderParagraph([ `${Printer.indent(depth)}${Printer.colorizedBold("OPTIONS:", "blue")}`, @@ -47,9 +48,6 @@ function renderOptionsHelp(options, depth) { ])), ]); } -/** - * @internal - */ function renderCommandHelp(command, depth) { const logs = []; logs.push(`${Printer.indent(depth)}${Printer.colorizedBold("NAME:", "green")}${command.name}`); @@ -62,39 +60,36 @@ function renderCommandHelp(command, depth) { if (AA.minElements(command.options, 1)) { logs.push(renderOptionsHelp(command.options, depth + 1)); } - if (isType(command.subject, "array")) { - for (const childCommand of command.subject) { - logs.push(...renderCommandHelp(childCommand, depth + 1)); + if (command.children?.type === "subCommand") { + for (const subCommand of command.children.subCommands) { + logs.push(...renderCommandHelp(subCommand, depth + 1)); } } - else if (DDP.identifier(command.subject, DDP.dataParserKind)) { - const formattedSubject = formatSubject(command.subject); + else if (command.children?.type === "subject") { + const formattedSubject = formatSubject(command.children.dataParser); logs.push(AA.join([ Printer.indent(depth + 1), Printer.colorizedBold("SUBJECT:", "magenta"), - hasSomeKinds(command.subject, [DDP.tupleKind, DDP.arrayKind]) + hasSomeKinds(command.children.dataParser, [DDP.tupleKind, DDP.arrayKind]) ? formattedSubject : `<${formattedSubject}>`, ], "")); } return logs; } -function logCommandHelp(command, depth = 0) { +function logCommandHelp(command) { // eslint-disable-next-line no-console - console.log(Printer.renderParagraph(renderCommandHelp(command, depth))); + console.log(Printer.renderParagraph(renderCommandHelp(command, 0))); } -/** - * @internal - */ function renderExecOptionHelp(options, depth) { return [ `${Printer.indent(depth)}${Printer.colorizedBold("OPTION HELP", "green")}`, renderOptionsHelp(options, depth + 1), ]; } -function logExecOptionHelp(options, depth = 0) { +function logExecOptionHelp(options) { // eslint-disable-next-line no-console - console.log(Printer.renderParagraph(renderExecOptionHelp(options, depth))); + console.log(Printer.renderParagraph(renderExecOptionHelp(options, 0))); } -export { formatSubject, logCommandHelp, logExecOptionHelp, renderCommandHelp, renderExecOptionHelp, renderOptionsHelp }; +export { formatSubject, helpOption, logCommandHelp, logExecOptionHelp, renderCommandHelp, renderExecOptionHelp, renderOptionsHelp }; diff --git a/docs/libs/v0/dist/command/index.cjs b/docs/libs/v0/dist/command/index.cjs new file mode 100644 index 0000000..628e47c --- /dev/null +++ b/docs/libs/v0/dist/command/index.cjs @@ -0,0 +1,22 @@ +'use strict'; + +var index = require('./create/index.cjs'); +var exec = require('./exec.cjs'); +var execOptions = require('./execOptions.cjs'); +var base = require('./options/base.cjs'); +var boolean = require('./options/boolean.cjs'); +var simple = require('./options/simple.cjs'); +var array = require('./options/array.cjs'); + +/** + * {@include command/index.md} + */ + +exports.create = index.create; +exports.isCommand = index.isCommand; +exports.exec = exec.exec; +exports.execOptions = execOptions.execOptions; +exports.initOption = base.initOption; +exports.createBooleanOption = boolean.createBooleanOption; +exports.createOption = simple.createOption; +exports.createArrayOption = array.createArrayOption; diff --git a/docs/libs/v0/command/index.d.ts b/docs/libs/v0/dist/command/index.d.ts similarity index 95% rename from docs/libs/v0/command/index.d.ts rename to docs/libs/v0/dist/command/index.d.ts index 4d3beee..fd491ad 100644 --- a/docs/libs/v0/command/index.d.ts +++ b/docs/libs/v0/dist/command/index.d.ts @@ -26,6 +26,4 @@ export * from "./types"; export * from "./options"; export * from "./create"; export * from "./exec"; -export * from "./help"; -export * from "./error"; export * from "./execOptions"; diff --git a/docs/libs/v0/dist/command/index.mjs b/docs/libs/v0/dist/command/index.mjs new file mode 100644 index 0000000..30f97c3 --- /dev/null +++ b/docs/libs/v0/dist/command/index.mjs @@ -0,0 +1,11 @@ +export { create, isCommand } from './create/index.mjs'; +export { exec } from './exec.mjs'; +export { execOptions } from './execOptions.mjs'; +export { initOption } from './options/base.mjs'; +export { createBooleanOption } from './options/boolean.mjs'; +export { createOption } from './options/simple.mjs'; +export { createArrayOption } from './options/array.mjs'; + +/** + * {@include command/index.md} + */ diff --git a/docs/libs/v0/command/options/array.cjs b/docs/libs/v0/dist/command/options/array.cjs similarity index 62% rename from docs/libs/v0/command/options/array.cjs rename to docs/libs/v0/dist/command/options/array.cjs index 71625bb..d384237 100644 --- a/docs/libs/v0/command/options/array.cjs +++ b/docs/libs/v0/dist/command/options/array.cjs @@ -4,8 +4,10 @@ var utils = require('@duplojs/utils'); var SS = require('@duplojs/utils/string'); var DDP = require('@duplojs/utils/dataParser'); var EE = require('@duplojs/utils/either'); +var CC = require('@duplojs/utils/clean'); var base = require('./base.cjs'); var error = require('../error.cjs'); +var file = require('../../dataParser/parsers/file.cjs'); function _interopNamespaceDefault(e) { var n = Object.create(null); @@ -27,17 +29,38 @@ function _interopNamespaceDefault(e) { var SS__namespace = /*#__PURE__*/_interopNamespaceDefault(SS); var DDP__namespace = /*#__PURE__*/_interopNamespaceDefault(DDP); var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); +var CC__namespace = /*#__PURE__*/_interopNamespaceDefault(CC); const defaultSeparator = ","; -function createArrayOption(name, schema, params) { - const dataParser = utils.pipe(schema, DDP__namespace.array, (schema) => params?.min +function createArrayOption(name, contract, params) { + let computeDataParser = undefined; + if (utils.hasSomeKinds(contract, [ + DDP__namespace.stringKind, + DDP__namespace.numberKind, + DDP__namespace.bigIntKind, + DDP__namespace.dateKind, + DDP__namespace.timeKind, + DDP__namespace.nilKind, + file.fileKind, + ])) { + const clone = contract.clone(); + clone.definition.coerce = true; + computeDataParser = clone; + } + else if (DDP__namespace.identifier(contract, DDP__namespace.dataParserKind)) { + computeDataParser = contract; + } + else { + computeDataParser = CC__namespace.toMapDataParser(contract, { coerce: true }); + } + const dataParser = utils.pipe(computeDataParser, DDP__namespace.array, (schema) => params?.min ? schema.addChecker(DDP__namespace.checkerArrayMin(params.min)) : schema, (schema) => params?.max ? schema.addChecker(DDP__namespace.checkerArrayMax(params.max)) : schema, (schema) => params?.required ? schema : DDP__namespace.optional(schema)); - return base.initOption(name, ({ isHere, value }, error$1) => { + return base.initOption(name, async ({ isHere, value }, error$1) => { if (!isHere && params?.required) { return error.addIssue(error$1, { type: "option", @@ -50,9 +73,11 @@ function createArrayOption(name, schema, params) { const values = value !== undefined ? SS__namespace.split(value, params?.separator ?? defaultSeparator) : undefined; - const result = dataParser.parse(values); + const result = dataParser.isAsynchronous() + ? await dataParser.asyncParse(values) + : dataParser.parse(values); if (EE__namespace.isLeft(result)) { - return error.addDataParserError(error$1, utils.unwrap(result), { + return error.addIssueDataParser(error$1, utils.unwrap(result), { type: "option", target: name, }); diff --git a/docs/libs/v0/command/options/array.d.ts b/docs/libs/v0/dist/command/options/array.d.ts similarity index 51% rename from docs/libs/v0/command/options/array.d.ts rename to docs/libs/v0/dist/command/options/array.d.ts index 751ae0d..3e8e6e3 100644 --- a/docs/libs/v0/command/options/array.d.ts +++ b/docs/libs/v0/dist/command/options/array.d.ts @@ -1,18 +1,16 @@ -import * as DDP from "@duplojs/utils/dataParser"; import type * as AA from "@duplojs/utils/array"; import { type Option } from "./base"; -import type { EligibleDataParser } from "../types"; +import type { EligibleContract } from "../types"; +import type { ComputeOptionContract } from "./types"; /** * Create an option that parses an array of values. * - * This option parses a delimited string value into an array and validates each element with the provided DataParser schema. + * This option parses a delimited string value into an array and validates each element with the provided DataParser or clean contract. * * ```ts - * const tags = SC.createArrayOption("tags", DP.string()); - * * const ids = SC.createArrayOption( * "ids", - * DP.string(), + * DP.number(), * { * required: true, * min: 1, @@ -25,27 +23,35 @@ import type { EligibleDataParser } from "../types"; * { separator: ";" }, * ); * + * const UserId = C.createNewType("user-id", DP.number(), C.Positive); + * const userIds = SC.createArrayOption("userIds", UserId); + * + * const tags = SC.createArrayOption("tags", DP.string()); + * const emails = SC.createArrayOption("emails", C.Email); + * * SC.create( * "batch", * { - * options: [tags, ids, paths], + * options: [tags, ids, paths, emails, userIds], * }, - * ({ options: { ids, tags, paths } }) => { - * // ids: [string, ...string[]] + * ({ options: { ids, tags, paths, emails, userIds } }) => { + * // ids: [number, ...number[]] * // tags: string[] | undefined * // paths: string[] | undefined + * // emails: C.Email[] | undefined + * // userIds: C.GetNewType[] | undefined * }, * ); * ``` * * @remarks - * The default separator is `,`. You can customize it with `separator`. + * The default separator is `,`. You can customize it with `separator`, and primitive elements are coerced from CLI string input. * * @see https://server-utils.duplojs.dev/en/v0/api/command/createArrayOption * @namespace SC * */ -export declare function createArrayOption(name: GenericName, schema: GenericSchema, params: { +export declare function createArrayOption(name: GenericName, contract: GenericContract, params: { description?: string; aliases?: readonly string[]; min?: GenericMinValues; @@ -53,16 +59,16 @@ export declare function createArrayOption, GenericMinValues>, - ...DDP.Output[] + ...AA.CreateTuple, GenericMinValues>, + ...ComputeOptionContract[] ]>; -export declare function createArrayOption(name: GenericName, schema: GenericSchema, params?: { +export declare function createArrayOption(name: GenericName, contract: GenericContract, params?: { description?: string; aliases?: readonly string[]; min?: GenericMinValues; max?: number; separator?: string; }): Option, GenericMinValues>, - ...DDP.Output[] + ...AA.CreateTuple, GenericMinValues>, + ...ComputeOptionContract[] ] | undefined>; diff --git a/docs/libs/v0/command/options/array.mjs b/docs/libs/v0/dist/command/options/array.mjs similarity index 50% rename from docs/libs/v0/command/options/array.mjs rename to docs/libs/v0/dist/command/options/array.mjs index a776309..b26ad23 100644 --- a/docs/libs/v0/command/options/array.mjs +++ b/docs/libs/v0/dist/command/options/array.mjs @@ -1,20 +1,42 @@ -import { pipe, unwrap } from '@duplojs/utils'; +import { hasSomeKinds, pipe, unwrap } from '@duplojs/utils'; import * as SS from '@duplojs/utils/string'; import * as DDP from '@duplojs/utils/dataParser'; import * as EE from '@duplojs/utils/either'; +import * as CC from '@duplojs/utils/clean'; import { initOption } from './base.mjs'; -import { addIssue, addDataParserError } from '../error.mjs'; +import { addIssue, addIssueDataParser } from '../error.mjs'; +import { fileKind } from '../../dataParser/parsers/file.mjs'; const defaultSeparator = ","; -function createArrayOption(name, schema, params) { - const dataParser = pipe(schema, DDP.array, (schema) => params?.min +function createArrayOption(name, contract, params) { + let computeDataParser = undefined; + if (hasSomeKinds(contract, [ + DDP.stringKind, + DDP.numberKind, + DDP.bigIntKind, + DDP.dateKind, + DDP.timeKind, + DDP.nilKind, + fileKind, + ])) { + const clone = contract.clone(); + clone.definition.coerce = true; + computeDataParser = clone; + } + else if (DDP.identifier(contract, DDP.dataParserKind)) { + computeDataParser = contract; + } + else { + computeDataParser = CC.toMapDataParser(contract, { coerce: true }); + } + const dataParser = pipe(computeDataParser, DDP.array, (schema) => params?.min ? schema.addChecker(DDP.checkerArrayMin(params.min)) : schema, (schema) => params?.max ? schema.addChecker(DDP.checkerArrayMax(params.max)) : schema, (schema) => params?.required ? schema : DDP.optional(schema)); - return initOption(name, ({ isHere, value }, error) => { + return initOption(name, async ({ isHere, value }, error) => { if (!isHere && params?.required) { return addIssue(error, { type: "option", @@ -27,9 +49,11 @@ function createArrayOption(name, schema, params) { const values = value !== undefined ? SS.split(value, params?.separator ?? defaultSeparator) : undefined; - const result = dataParser.parse(values); + const result = dataParser.isAsynchronous() + ? await dataParser.asyncParse(values) + : dataParser.parse(values); if (EE.isLeft(result)) { - return addDataParserError(error, unwrap(result), { + return addIssueDataParser(error, unwrap(result), { type: "option", target: name, }); diff --git a/docs/libs/v0/command/options/base.cjs b/docs/libs/v0/dist/command/options/base.cjs similarity index 95% rename from docs/libs/v0/command/options/base.cjs rename to docs/libs/v0/dist/command/options/base.cjs index a185c5e..aa48583 100644 --- a/docs/libs/v0/command/options/base.cjs +++ b/docs/libs/v0/dist/command/options/base.cjs @@ -30,7 +30,7 @@ const regexOption = /^(?-{1,2})(?[A-Za-z0-9][A-Za-z0-9_-]*)(?:=(? { + execute: async (args, error$1) => { const result = AA__namespace.reduce(args, AA__namespace.reduceFrom(null), ({ element, next, exit, index }) => { const extractResult = SS__namespace.extract(element, regexOption); if (!extractResult) { @@ -47,7 +47,7 @@ function initOption(name, execute, params) { return exit(result); }); if (!result) { - const executeResult = execute({ + const executeResult = await execute({ isHere: false, value: undefined, }, error$1); @@ -71,7 +71,7 @@ function initOption(name, execute, params) { message: `Missing value for option "${self.name}": received another option token instead of a value.`, }); } - const executeResult = execute({ + const executeResult = await execute({ isHere: true, value, }, error$1); @@ -94,7 +94,7 @@ function initOption(name, execute, params) { message: `Option "${self.name}" does not accept a value.`, }); } - const executeResult = execute({ + const executeResult = await execute({ isHere: true, value: undefined, }, error$1); diff --git a/docs/libs/v0/command/options/base.d.ts b/docs/libs/v0/dist/command/options/base.d.ts similarity index 82% rename from docs/libs/v0/command/options/base.d.ts rename to docs/libs/v0/dist/command/options/base.d.ts index f7b13cd..1b75d04 100644 --- a/docs/libs/v0/command/options/base.d.ts +++ b/docs/libs/v0/dist/command/options/base.d.ts @@ -1,4 +1,4 @@ -import type { Kind } from "@duplojs/utils"; +import type { Kind, MaybePromise } from "@duplojs/utils"; import { type CommandError, SymbolCommandError } from "../error"; declare const optionKind: import("@duplojs/utils").KindHandler>; export interface Option extends Kind { @@ -6,16 +6,16 @@ export interface Option; } export interface InitOptionExecuteParams { isHere: boolean; value: string | undefined; } -export declare function initOption(name: GenericName, execute: (params: InitOptionExecuteParams, error: CommandError) => GenericExecuteOutputValue | SymbolCommandError, params?: { +export declare function initOption(name: GenericName, execute: (params: InitOptionExecuteParams, error: CommandError) => MaybePromise, params?: { description?: string; aliases?: readonly string[]; hasValue?: boolean; diff --git a/docs/libs/v0/command/options/base.mjs b/docs/libs/v0/dist/command/options/base.mjs similarity index 94% rename from docs/libs/v0/command/options/base.mjs rename to docs/libs/v0/dist/command/options/base.mjs index 8ce7343..24021f5 100644 --- a/docs/libs/v0/command/options/base.mjs +++ b/docs/libs/v0/dist/command/options/base.mjs @@ -8,7 +8,7 @@ const regexOption = /^(?-{1,2})(?[A-Za-z0-9][A-Za-z0-9_-]*)(?:=(? { + execute: async (args, error) => { const result = AA.reduce(args, AA.reduceFrom(null), ({ element, next, exit, index }) => { const extractResult = SS.extract(element, regexOption); if (!extractResult) { @@ -25,7 +25,7 @@ function initOption(name, execute, params) { return exit(result); }); if (!result) { - const executeResult = execute({ + const executeResult = await execute({ isHere: false, value: undefined, }, error); @@ -49,7 +49,7 @@ function initOption(name, execute, params) { message: `Missing value for option "${self.name}": received another option token instead of a value.`, }); } - const executeResult = execute({ + const executeResult = await execute({ isHere: true, value, }, error); @@ -72,7 +72,7 @@ function initOption(name, execute, params) { message: `Option "${self.name}" does not accept a value.`, }); } - const executeResult = execute({ + const executeResult = await execute({ isHere: true, value: undefined, }, error); diff --git a/docs/libs/v0/command/options/boolean.cjs b/docs/libs/v0/dist/command/options/boolean.cjs similarity index 100% rename from docs/libs/v0/command/options/boolean.cjs rename to docs/libs/v0/dist/command/options/boolean.cjs diff --git a/docs/libs/v0/command/options/boolean.d.ts b/docs/libs/v0/dist/command/options/boolean.d.ts similarity index 100% rename from docs/libs/v0/command/options/boolean.d.ts rename to docs/libs/v0/dist/command/options/boolean.d.ts diff --git a/docs/libs/v0/command/options/boolean.mjs b/docs/libs/v0/dist/command/options/boolean.mjs similarity index 100% rename from docs/libs/v0/command/options/boolean.mjs rename to docs/libs/v0/dist/command/options/boolean.mjs diff --git a/docs/libs/v0/command/options/index.d.ts b/docs/libs/v0/dist/command/options/index.d.ts similarity index 80% rename from docs/libs/v0/command/options/index.d.ts rename to docs/libs/v0/dist/command/options/index.d.ts index ea2ddbf..82bf9de 100644 --- a/docs/libs/v0/command/options/index.d.ts +++ b/docs/libs/v0/dist/command/options/index.d.ts @@ -1,4 +1,5 @@ export * from "./base"; +export * from "./types"; export * from "./boolean"; export * from "./simple"; export * from "./array"; diff --git a/docs/libs/v0/command/options/simple.cjs b/docs/libs/v0/dist/command/options/simple.cjs similarity index 55% rename from docs/libs/v0/command/options/simple.cjs rename to docs/libs/v0/dist/command/options/simple.cjs index 4b2eea5..67f3b0d 100644 --- a/docs/libs/v0/command/options/simple.cjs +++ b/docs/libs/v0/dist/command/options/simple.cjs @@ -1,10 +1,12 @@ 'use strict'; var utils = require('@duplojs/utils'); -var EE = require('@duplojs/utils/either'); var DDP = require('@duplojs/utils/dataParser'); +var EE = require('@duplojs/utils/either'); +var CC = require('@duplojs/utils/clean'); var base = require('./base.cjs'); var error = require('../error.cjs'); +var file = require('../../dataParser/parsers/file.cjs'); function _interopNamespaceDefault(e) { var n = Object.create(null); @@ -23,14 +25,35 @@ function _interopNamespaceDefault(e) { return Object.freeze(n); } -var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); var DDP__namespace = /*#__PURE__*/_interopNamespaceDefault(DDP); +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); +var CC__namespace = /*#__PURE__*/_interopNamespaceDefault(CC); -function createOption(name, schema, params) { +function createOption(name, contract, params) { + let computeDataParser = undefined; + if (utils.hasSomeKinds(contract, [ + DDP__namespace.stringKind, + DDP__namespace.numberKind, + DDP__namespace.bigIntKind, + DDP__namespace.dateKind, + DDP__namespace.timeKind, + DDP__namespace.nilKind, + file.fileKind, + ])) { + const clone = contract.clone(); + clone.definition.coerce = true; + computeDataParser = clone; + } + else if (DDP__namespace.identifier(contract, DDP__namespace.dataParserKind)) { + computeDataParser = contract; + } + else { + computeDataParser = CC__namespace.toMapDataParser(contract, { coerce: true }); + } const dataParser = params?.required - ? schema - : DDP__namespace.optional(schema); - return base.initOption(name, ({ isHere, value }, error$1) => { + ? computeDataParser + : DDP__namespace.optional(computeDataParser); + return base.initOption(name, async ({ isHere, value }, error$1) => { if (!isHere && params?.required) { return error.addIssue(error$1, { type: "option", @@ -40,9 +63,11 @@ function createOption(name, schema, params) { message: `Option "${name}" is required.`, }); } - const result = dataParser.parse(value); + const result = dataParser.isAsynchronous() + ? await dataParser.asyncParse(value) + : dataParser.parse(value); if (EE__namespace.isLeft(result)) { - return error.addDataParserError(error$1, utils.unwrap(result), { + return error.addIssueDataParser(error$1, utils.unwrap(result), { type: "option", target: name, }); diff --git a/docs/libs/v0/dist/command/options/simple.d.ts b/docs/libs/v0/dist/command/options/simple.d.ts new file mode 100644 index 0000000..b63bd7d --- /dev/null +++ b/docs/libs/v0/dist/command/options/simple.d.ts @@ -0,0 +1,60 @@ +import { type Option } from "./base"; +import type { EligibleContract } from "../types"; +import type { ComputeOptionContract } from "./types"; +/** + * Create an option with a single parsed value. + * + * Use a DataParser or a clean contract to parse and validate the option value from `--name=value` or `--name value`. + * + * ```ts + * const name = SC.createOption( + * "name", + * DP.string(), + * { + * required: true, + * aliases: ["n"], + * }, + * ); + * + * const mode = SC.createOption( + * "mode", + * DP.literal(["dev", "prod"]), + * ); + * + * const UserId = C.createNewType("user-id", DP.number(), C.Positive); + * const userId = SC.createOption("userId", UserId); + * + * const port = SC.createOption("port", DP.number()); + * const email = SC.createOption("email", C.Email); + * + * SC.create( + * "serve", + * { + * options: [port, name, mode, email, userId], + * }, + * ({ options: { port, name, mode, email, userId } }) => { + * // port: number | undefined + * // name: string + * // mode: "dev" | "prod" | undefined + * // email: C.Email | undefined + * // userId: C.GetNewType | undefined + * }, + * ); + * ``` + * + * @remarks + * Primitive parsers and clean primitive contracts are coerced from CLI string input automatically. + * + * @see https://server-utils.duplojs.dev/en/v0/api/command/createOption + * @namespace SC + * + */ +export declare function createOption = ComputeOptionContract>(name: GenericName, contract: GenericContract, params: { + description?: string; + aliases?: readonly string[]; + required: true; +}): Option; +export declare function createOption = ComputeOptionContract>(name: GenericName, contract: GenericContract, params?: { + description?: string; + aliases?: readonly string[]; +}): Option; diff --git a/docs/libs/v0/dist/command/options/simple.mjs b/docs/libs/v0/dist/command/options/simple.mjs new file mode 100644 index 0000000..4fd7d57 --- /dev/null +++ b/docs/libs/v0/dist/command/options/simple.mjs @@ -0,0 +1,60 @@ +import { hasSomeKinds, unwrap } from '@duplojs/utils'; +import * as DDP from '@duplojs/utils/dataParser'; +import * as EE from '@duplojs/utils/either'; +import * as CC from '@duplojs/utils/clean'; +import { initOption } from './base.mjs'; +import { addIssue, addIssueDataParser } from '../error.mjs'; +import { fileKind } from '../../dataParser/parsers/file.mjs'; + +function createOption(name, contract, params) { + let computeDataParser = undefined; + if (hasSomeKinds(contract, [ + DDP.stringKind, + DDP.numberKind, + DDP.bigIntKind, + DDP.dateKind, + DDP.timeKind, + DDP.nilKind, + fileKind, + ])) { + const clone = contract.clone(); + clone.definition.coerce = true; + computeDataParser = clone; + } + else if (DDP.identifier(contract, DDP.dataParserKind)) { + computeDataParser = contract; + } + else { + computeDataParser = CC.toMapDataParser(contract, { coerce: true }); + } + const dataParser = params?.required + ? computeDataParser + : DDP.optional(computeDataParser); + return initOption(name, async ({ isHere, value }, error) => { + if (!isHere && params?.required) { + return addIssue(error, { + type: "option", + target: name, + expected: `required option --${name}`, + received: value, + message: `Option "${name}" is required.`, + }); + } + const result = dataParser.isAsynchronous() + ? await dataParser.asyncParse(value) + : dataParser.parse(value); + if (EE.isLeft(result)) { + return addIssueDataParser(error, unwrap(result), { + type: "option", + target: name, + }); + } + return unwrap(result); + }, { + description: params?.description, + aliases: params?.aliases, + hasValue: true, + }); +} + +export { createOption }; diff --git a/docs/libs/v0/dist/command/options/types/computeOptionContract.d.ts b/docs/libs/v0/dist/command/options/types/computeOptionContract.d.ts new file mode 100644 index 0000000..b92203c --- /dev/null +++ b/docs/libs/v0/dist/command/options/types/computeOptionContract.d.ts @@ -0,0 +1,3 @@ +import type * as DDP from "@duplojs/utils/dataParser"; +import type { ComputeEligibleCleanType, EligibleCleanType, EligibleContract } from "../../types"; +export type ComputeOptionContract = [GenericContract] extends [DDP.DataParser] ? DDP.Output : [GenericContract] extends [EligibleCleanType] ? ComputeEligibleCleanType : never; diff --git a/docs/libs/v0/dist/command/options/types/index.d.ts b/docs/libs/v0/dist/command/options/types/index.d.ts new file mode 100644 index 0000000..7f7edc8 --- /dev/null +++ b/docs/libs/v0/dist/command/options/types/index.d.ts @@ -0,0 +1 @@ +export * from "./computeOptionContract"; diff --git a/docs/libs/v0/dist/command/types/eligibleCleanType.d.ts b/docs/libs/v0/dist/command/types/eligibleCleanType.d.ts new file mode 100644 index 0000000..e7048ec --- /dev/null +++ b/docs/libs/v0/dist/command/types/eligibleCleanType.d.ts @@ -0,0 +1,7 @@ +import type { AnyTuple } from "@duplojs/utils"; +import type * as CC from "@duplojs/utils/clean"; +import type * as DD from "@duplojs/utils/date"; +export type EligiblePrimitive = string | number | boolean | bigint | DD.TheDate | DD.TheTime; +export type EligibleEntityProperty = (CC.NewTypeHandler | CC.EntityPropertyDefinitionUnion> | CC.EntityPropertyDefinitionNullable | CC.EntityPropertyDefinitionArray | CC.EntityPropertyDefinitionIdentifier); +export type EligibleCleanType = (CC.ConstraintHandler | CC.ConstraintsSetHandler | CC.PrimitiveHandler | EligibleEntityProperty); +export type ComputeEligibleCleanType = [GenericCleanType] extends [CC.ConstraintHandler] ? CC.GetConstraint : [GenericCleanType] extends [CC.ConstraintsSetHandler] ? CC.GetConstraints : [GenericCleanType] extends [CC.PrimitiveHandler] ? ReturnType : [GenericCleanType] extends [EligibleEntityProperty] ? CC.EntityProperty : never; diff --git a/docs/libs/v0/dist/command/types/eligibleContract.d.ts b/docs/libs/v0/dist/command/types/eligibleContract.d.ts new file mode 100644 index 0000000..79ea269 --- /dev/null +++ b/docs/libs/v0/dist/command/types/eligibleContract.d.ts @@ -0,0 +1,3 @@ +import type { EligibleCleanType } from "./eligibleCleanType"; +import type { EligibleDataParser } from "./eligibleDataParser"; +export type EligibleContract = (EligibleDataParser | EligibleCleanType); diff --git a/docs/libs/v0/dist/command/types/eligibleDataParser.d.ts b/docs/libs/v0/dist/command/types/eligibleDataParser.d.ts new file mode 100644 index 0000000..19f0bd4 --- /dev/null +++ b/docs/libs/v0/dist/command/types/eligibleDataParser.d.ts @@ -0,0 +1,18 @@ +import type { SimplifyTopLevel } from "@duplojs/utils"; +import type * as DDP from "@duplojs/utils/dataParser"; +import type * as SDP from "../../dataParser"; +export type EligibleDataParser = (DDP.DataParserString | DDP.DataParserNumber | DDP.DataParserBigInt | DDP.DataParserDate | DDP.DataParserTime | DDP.DataParserNil | DDP.DataParserTemplateLiteral | DDP.DataParserLiteral & { + readonly value: readonly string[]; +}>> | DDP.DataParserUnion & { + readonly options: readonly [ + EligibleDataParser, + ...EligibleDataParser[] + ]; +}>> | DDP.DataParserTransform & { + readonly inner: EligibleDataParser; +}>> | DDP.DataParserPipe & { + readonly input: EligibleDataParser; + readonly output: DDP.DataParser; +}>> | DDP.DataParserOptional & { + readonly inner: EligibleDataParser; +}>> | SDP.DataParserFile); diff --git a/docs/libs/v0/dist/command/types/index.d.ts b/docs/libs/v0/dist/command/types/index.d.ts new file mode 100644 index 0000000..d02bdc3 --- /dev/null +++ b/docs/libs/v0/dist/command/types/index.d.ts @@ -0,0 +1,3 @@ +export * from "./eligibleDataParser"; +export * from "./eligibleCleanType"; +export * from "./eligibleContract"; diff --git a/docs/libs/v0/dist/common/environmentVariable/expandEnvironmentVariables.cjs b/docs/libs/v0/dist/common/environmentVariable/expandEnvironmentVariables.cjs new file mode 100644 index 0000000..73ec89f --- /dev/null +++ b/docs/libs/v0/dist/common/environmentVariable/expandEnvironmentVariables.cjs @@ -0,0 +1,50 @@ +'use strict'; + +var GG = require('@duplojs/utils/generator'); +var OO = require('@duplojs/utils/object'); +var SS = require('@duplojs/utils/string'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var GG__namespace = /*#__PURE__*/_interopNamespaceDefault(GG); +var OO__namespace = /*#__PURE__*/_interopNamespaceDefault(OO); +var SS__namespace = /*#__PURE__*/_interopNamespaceDefault(SS); + +const envVarRegex = /(?[^{}]+)}/g; +const escapedDollarRegex = /\\\$/g; +function expandValue(value, env, stack = new Set()) { + return SS__namespace.replace(value, envVarRegex, ({ namedGroups }) => { + const value = namedGroups.value; + const rawEnvValue = env[value]; + if (rawEnvValue === undefined || stack.has(value)) { + return ""; + } + stack.add(value); + const resolved = expandValue(rawEnvValue, env, stack); + stack.delete(value); + return resolved; + }); +} +function expandEnvironmentVariables(env) { + return GG__namespace.reduce(OO__namespace.entries(env), GG__namespace.reduceFrom(env), ({ element: [key, value], lastValue, nextWithObject }) => nextWithObject(lastValue, { + [key]: SS__namespace.replaceAll(expandValue(value, lastValue), escapedDollarRegex, "$"), + })); +} + +exports.expandEnvironmentVariables = expandEnvironmentVariables; +exports.expandValue = expandValue; diff --git a/docs/libs/v0/common/environmentVariable/expandEnvironmentVariables.d.ts b/docs/libs/v0/dist/common/environmentVariable/expandEnvironmentVariables.d.ts similarity index 100% rename from docs/libs/v0/common/environmentVariable/expandEnvironmentVariables.d.ts rename to docs/libs/v0/dist/common/environmentVariable/expandEnvironmentVariables.d.ts diff --git a/docs/libs/v0/common/environmentVariable/expandEnvironmentVariables.mjs b/docs/libs/v0/dist/common/environmentVariable/expandEnvironmentVariables.mjs similarity index 57% rename from docs/libs/v0/common/environmentVariable/expandEnvironmentVariables.mjs rename to docs/libs/v0/dist/common/environmentVariable/expandEnvironmentVariables.mjs index 8776b33..9913efa 100644 --- a/docs/libs/v0/common/environmentVariable/expandEnvironmentVariables.mjs +++ b/docs/libs/v0/dist/common/environmentVariable/expandEnvironmentVariables.mjs @@ -1,9 +1,11 @@ -import { G, O, S } from '@duplojs/utils'; +import * as GG from '@duplojs/utils/generator'; +import * as OO from '@duplojs/utils/object'; +import * as SS from '@duplojs/utils/string'; const envVarRegex = /(?[^{}]+)}/g; const escapedDollarRegex = /\\\$/g; function expandValue(value, env, stack = new Set()) { - return S.replace(value, envVarRegex, ({ namedGroups }) => { + return SS.replace(value, envVarRegex, ({ namedGroups }) => { const value = namedGroups.value; const rawEnvValue = env[value]; if (rawEnvValue === undefined || stack.has(value)) { @@ -16,8 +18,8 @@ function expandValue(value, env, stack = new Set()) { }); } function expandEnvironmentVariables(env) { - return G.reduce(O.entries(env), G.reduceFrom(env), ({ element: [key, value], lastValue, nextWithObject }) => nextWithObject(lastValue, { - [key]: S.replaceAll(expandValue(value, lastValue), escapedDollarRegex, "$"), + return GG.reduce(OO.entries(env), GG.reduceFrom(env), ({ element: [key, value], lastValue, nextWithObject }) => nextWithObject(lastValue, { + [key]: SS.replaceAll(expandValue(value, lastValue), escapedDollarRegex, "$"), })); } diff --git a/docs/libs/v0/common/environmentVariable/index.cjs b/docs/libs/v0/dist/common/environmentVariable/index.cjs similarity index 100% rename from docs/libs/v0/common/environmentVariable/index.cjs rename to docs/libs/v0/dist/common/environmentVariable/index.cjs diff --git a/docs/libs/v0/common/environmentVariable/index.d.ts b/docs/libs/v0/dist/common/environmentVariable/index.d.ts similarity index 100% rename from docs/libs/v0/common/environmentVariable/index.d.ts rename to docs/libs/v0/dist/common/environmentVariable/index.d.ts diff --git a/docs/libs/v0/common/environmentVariable/index.mjs b/docs/libs/v0/dist/common/environmentVariable/index.mjs similarity index 100% rename from docs/libs/v0/common/environmentVariable/index.mjs rename to docs/libs/v0/dist/common/environmentVariable/index.mjs diff --git a/docs/libs/v0/dist/common/environmentVariable/overrideEnvironmentVariables.cjs b/docs/libs/v0/dist/common/environmentVariable/overrideEnvironmentVariables.cjs new file mode 100644 index 0000000..878f17b --- /dev/null +++ b/docs/libs/v0/dist/common/environmentVariable/overrideEnvironmentVariables.cjs @@ -0,0 +1,33 @@ +'use strict'; + +var utils = require('@duplojs/utils'); +var OO = require('@duplojs/utils/object'); +var AA = require('@duplojs/utils/array'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var OO__namespace = /*#__PURE__*/_interopNamespaceDefault(OO); +var AA__namespace = /*#__PURE__*/_interopNamespaceDefault(AA); + +function overrideEnvironmentVariables(arrayEnv, override) { + return utils.pipe(arrayEnv, AA__namespace.map(OO__namespace.entries), AA__namespace.flat, (entries) => override + ? entries + : AA__namespace.reverse(entries), OO__namespace.fromEntries); +} + +exports.overrideEnvironmentVariables = overrideEnvironmentVariables; diff --git a/docs/libs/v0/common/environmentVariable/overrideEnvironmentVariables.d.ts b/docs/libs/v0/dist/common/environmentVariable/overrideEnvironmentVariables.d.ts similarity index 100% rename from docs/libs/v0/common/environmentVariable/overrideEnvironmentVariables.d.ts rename to docs/libs/v0/dist/common/environmentVariable/overrideEnvironmentVariables.d.ts diff --git a/docs/libs/v0/dist/common/environmentVariable/overrideEnvironmentVariables.mjs b/docs/libs/v0/dist/common/environmentVariable/overrideEnvironmentVariables.mjs new file mode 100644 index 0000000..53cbd4a --- /dev/null +++ b/docs/libs/v0/dist/common/environmentVariable/overrideEnvironmentVariables.mjs @@ -0,0 +1,11 @@ +import { pipe } from '@duplojs/utils'; +import * as OO from '@duplojs/utils/object'; +import * as AA from '@duplojs/utils/array'; + +function overrideEnvironmentVariables(arrayEnv, override) { + return pipe(arrayEnv, AA.map(OO.entries), AA.flat, (entries) => override + ? entries + : AA.reverse(entries), OO.fromEntries); +} + +export { overrideEnvironmentVariables }; diff --git a/docs/libs/v0/dist/common/environmentVariable/parseEnvironmentFiles.cjs b/docs/libs/v0/dist/common/environmentVariable/parseEnvironmentFiles.cjs new file mode 100644 index 0000000..d066dba --- /dev/null +++ b/docs/libs/v0/dist/common/environmentVariable/parseEnvironmentFiles.cjs @@ -0,0 +1,57 @@ +'use strict'; + +var utils = require('@duplojs/utils'); +var GG = require('@duplojs/utils/generator'); +var SS = require('@duplojs/utils/string'); +var EE = require('@duplojs/utils/either'); +var readTextFile = require('../../file/readTextFile.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var GG__namespace = /*#__PURE__*/_interopNamespaceDefault(GG); +var SS__namespace = /*#__PURE__*/_interopNamespaceDefault(SS); +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +const lineRegex = /^(?:export\s+)?(?[A-Z_][A-Z0-9_]*)=(?'(?:\\'|[^'])*'|"(?:\\"|[^"])*"|`(?:\\`|[^`])*`|[^\s#\r\n][^#\r\n]*|)\s*(?:#.*)?$/mg; +const endLineBreakerRegex = /\r\n?/mg; +const surroundingQuoteRegex = /^(['"`])([\s\S]*)\1$/mg; +const backCartRegex = /\\r/g; +const newLineRegex = /\\n/g; +function parseEnvironmentLine(line) { + return utils.pipe(line, SS__namespace.replace(endLineBreakerRegex, "\n"), SS__namespace.extractAll(lineRegex), GG__namespace.reduce(GG__namespace.reduceFrom({}), ({ element, nextWithObject, lastValue, next }) => { + if (element.namedGroups?.key && element.namedGroups?.value) { + return nextWithObject(lastValue, { + [element.namedGroups.key]: utils.pipe(element.namedGroups.value, (value) => { + const surroundingValue = SS__namespace.replace(value, surroundingQuoteRegex, "$2"); + if (SS__namespace.startsWith(value, "\"")) { + return utils.pipe(surroundingValue, SS__namespace.replace(newLineRegex, "\n"), SS__namespace.replace(backCartRegex, "\r")); + } + return surroundingValue; + }), + }); + } + return next(lastValue); + })); +} +function parseEnvironmentFiles(baseEnv, paths) { + return GG__namespace.asyncReduce(paths, GG__namespace.reduceFrom([baseEnv]), ({ lastValue, element, nextPush, exit }) => readTextFile.readTextFile(element) + .then(utils.innerPipe(EE__namespace.whenIsRight(utils.innerPipe(parseEnvironmentLine, (value) => nextPush(lastValue, value))), utils.when(EE__namespace.isLeft, exit)))); +} + +exports.parseEnvironmentFiles = parseEnvironmentFiles; +exports.parseEnvironmentLine = parseEnvironmentLine; diff --git a/docs/libs/v0/common/environmentVariable/parseEnvironmentFiles.d.ts b/docs/libs/v0/dist/common/environmentVariable/parseEnvironmentFiles.d.ts similarity index 100% rename from docs/libs/v0/common/environmentVariable/parseEnvironmentFiles.d.ts rename to docs/libs/v0/dist/common/environmentVariable/parseEnvironmentFiles.d.ts diff --git a/docs/libs/v0/dist/common/environmentVariable/parseEnvironmentFiles.mjs b/docs/libs/v0/dist/common/environmentVariable/parseEnvironmentFiles.mjs new file mode 100644 index 0000000..14e6984 --- /dev/null +++ b/docs/libs/v0/dist/common/environmentVariable/parseEnvironmentFiles.mjs @@ -0,0 +1,33 @@ +import { innerPipe, when, pipe } from '@duplojs/utils'; +import * as GG from '@duplojs/utils/generator'; +import * as SS from '@duplojs/utils/string'; +import * as EE from '@duplojs/utils/either'; +import { readTextFile } from '../../file/readTextFile.mjs'; + +const lineRegex = /^(?:export\s+)?(?[A-Z_][A-Z0-9_]*)=(?'(?:\\'|[^'])*'|"(?:\\"|[^"])*"|`(?:\\`|[^`])*`|[^\s#\r\n][^#\r\n]*|)\s*(?:#.*)?$/mg; +const endLineBreakerRegex = /\r\n?/mg; +const surroundingQuoteRegex = /^(['"`])([\s\S]*)\1$/mg; +const backCartRegex = /\\r/g; +const newLineRegex = /\\n/g; +function parseEnvironmentLine(line) { + return pipe(line, SS.replace(endLineBreakerRegex, "\n"), SS.extractAll(lineRegex), GG.reduce(GG.reduceFrom({}), ({ element, nextWithObject, lastValue, next }) => { + if (element.namedGroups?.key && element.namedGroups?.value) { + return nextWithObject(lastValue, { + [element.namedGroups.key]: pipe(element.namedGroups.value, (value) => { + const surroundingValue = SS.replace(value, surroundingQuoteRegex, "$2"); + if (SS.startsWith(value, "\"")) { + return pipe(surroundingValue, SS.replace(newLineRegex, "\n"), SS.replace(backCartRegex, "\r")); + } + return surroundingValue; + }), + }); + } + return next(lastValue); + })); +} +function parseEnvironmentFiles(baseEnv, paths) { + return GG.asyncReduce(paths, GG.reduceFrom([baseEnv]), ({ lastValue, element, nextPush, exit }) => readTextFile(element) + .then(innerPipe(EE.whenIsRight(innerPipe(parseEnvironmentLine, (value) => nextPush(lastValue, value))), when(EE.isLeft, exit)))); +} + +export { parseEnvironmentFiles, parseEnvironmentLine }; diff --git a/docs/libs/v0/common/environmentVariableOrThrow.cjs b/docs/libs/v0/dist/common/environmentVariableOrThrow.cjs similarity index 59% rename from docs/libs/v0/common/environmentVariableOrThrow.cjs rename to docs/libs/v0/dist/common/environmentVariableOrThrow.cjs index d6eb757..b45c1f5 100644 --- a/docs/libs/v0/common/environmentVariableOrThrow.cjs +++ b/docs/libs/v0/dist/common/environmentVariableOrThrow.cjs @@ -1,9 +1,29 @@ 'use strict'; var utils = require('@duplojs/utils'); +var EE = require('@duplojs/utils/either'); var kind = require('../kind.cjs'); var index = require('./environmentVariable/index.cjs'); +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + class EnvironmentVariableError extends utils.kindHeritage("environment-variable-error", kind.createDuplojsServerUtilsKind("environment-variable-error"), Error) { error; constructor(error) { @@ -16,7 +36,7 @@ class EnvironmentVariableError extends utils.kindHeritage("environment-variable- */ async function environmentVariableOrThrow(shape, params) { const result = await index.environmentVariable(shape, params); - if (utils.E.isLeft(result)) { + if (EE__namespace.isLeft(result)) { throw new EnvironmentVariableError(result); } return utils.unwrap(result); diff --git a/docs/libs/v0/common/environmentVariableOrThrow.d.ts b/docs/libs/v0/dist/common/environmentVariableOrThrow.d.ts similarity index 82% rename from docs/libs/v0/common/environmentVariableOrThrow.d.ts rename to docs/libs/v0/dist/common/environmentVariableOrThrow.d.ts index 7b8e9e4..c0a5513 100644 --- a/docs/libs/v0/common/environmentVariableOrThrow.d.ts +++ b/docs/libs/v0/dist/common/environmentVariableOrThrow.d.ts @@ -1,12 +1,13 @@ -import { type DP, E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; +import type * as DDP from "@duplojs/utils/dataParser"; import type * as SF from "../file"; import { type EnvironmentVariableParams } from "./environmentVariable"; declare const EnvironmentVariableError_base: new (params: { "@DuplojsServerUtils/environment-variable-error"?: unknown; }, parentParams: readonly [message?: string | undefined, options?: ErrorOptions | undefined]) => Error & import("@duplojs/utils").Kind, unknown> & import("@duplojs/utils").Kind, unknown>; export declare class EnvironmentVariableError extends EnvironmentVariableError_base { - error: SF.FileSystemLeft<"read-text-file"> | E.Error; - constructor(error: SF.FileSystemLeft<"read-text-file"> | E.Error); + error: SF.FileSystemLeft<"read-text-file"> | EE.Error; + constructor(error: SF.FileSystemLeft<"read-text-file"> | EE.Error); } /** * Load and validate environment variables or throw. @@ -55,5 +56,5 @@ export declare class EnvironmentVariableError extends EnvironmentVariableError_b * @see https://server-utils.duplojs.dev/en/v0/api/common/environmentVariableOrThrow * @see https://server-utils.duplojs.dev/en/v0/api/common/environmentVariable */ -export declare function environmentVariableOrThrow(shape: GenericShape, params?: EnvironmentVariableParams): Promise>; +export declare function environmentVariableOrThrow(shape: GenericShape, params?: EnvironmentVariableParams): Promise>; export {}; diff --git a/docs/libs/v0/common/environmentVariableOrThrow.mjs b/docs/libs/v0/dist/common/environmentVariableOrThrow.mjs similarity index 86% rename from docs/libs/v0/common/environmentVariableOrThrow.mjs rename to docs/libs/v0/dist/common/environmentVariableOrThrow.mjs index e3af1a2..b45efb5 100644 --- a/docs/libs/v0/common/environmentVariableOrThrow.mjs +++ b/docs/libs/v0/dist/common/environmentVariableOrThrow.mjs @@ -1,4 +1,5 @@ -import { kindHeritage, E, unwrap } from '@duplojs/utils'; +import { kindHeritage, unwrap } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { createDuplojsServerUtilsKind } from '../kind.mjs'; import { environmentVariable } from './environmentVariable/index.mjs'; @@ -14,7 +15,7 @@ class EnvironmentVariableError extends kindHeritage("environment-variable-error" */ async function environmentVariableOrThrow(shape, params) { const result = await environmentVariable(shape, params); - if (E.isLeft(result)) { + if (EE.isLeft(result)) { throw new EnvironmentVariableError(result); } return unwrap(result); diff --git a/docs/libs/v0/common/exitProcess.cjs b/docs/libs/v0/dist/common/exitProcess.cjs similarity index 100% rename from docs/libs/v0/common/exitProcess.cjs rename to docs/libs/v0/dist/common/exitProcess.cjs diff --git a/docs/libs/v0/common/exitProcess.d.ts b/docs/libs/v0/dist/common/exitProcess.d.ts similarity index 100% rename from docs/libs/v0/common/exitProcess.d.ts rename to docs/libs/v0/dist/common/exitProcess.d.ts diff --git a/docs/libs/v0/common/exitProcess.mjs b/docs/libs/v0/dist/common/exitProcess.mjs similarity index 100% rename from docs/libs/v0/common/exitProcess.mjs rename to docs/libs/v0/dist/common/exitProcess.mjs diff --git a/docs/libs/v0/dist/common/getCurrentWorkDirectory.cjs b/docs/libs/v0/dist/common/getCurrentWorkDirectory.cjs new file mode 100644 index 0000000..1444367 --- /dev/null +++ b/docs/libs/v0/dist/common/getCurrentWorkDirectory.cjs @@ -0,0 +1,34 @@ +'use strict'; + +var utils = require('@duplojs/utils'); +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include common/getCurrentWorkDirectory/index.md} + */ +const getCurrentWorkDirectory = implementor.implementFunction("getCurrentWorkDirectory", { + NODE: () => utils.pipe(EE__namespace.safeCallback(() => EE__namespace.success(process.cwd())), EE__namespace.whenIsLeft(EE__namespace.error)), + DENO: () => utils.pipe(EE__namespace.safeCallback(() => EE__namespace.success(Deno.cwd())), EE__namespace.whenIsLeft(EE__namespace.error)), +}); + +exports.getCurrentWorkDirectory = getCurrentWorkDirectory; diff --git a/docs/libs/v0/common/getCurrentWorkDirectory.d.ts b/docs/libs/v0/dist/common/getCurrentWorkDirectory.d.ts similarity index 77% rename from docs/libs/v0/common/getCurrentWorkDirectory.d.ts rename to docs/libs/v0/dist/common/getCurrentWorkDirectory.d.ts index 71ea30f..1948523 100644 --- a/docs/libs/v0/common/getCurrentWorkDirectory.d.ts +++ b/docs/libs/v0/dist/common/getCurrentWorkDirectory.d.ts @@ -1,7 +1,7 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; declare module "../implementor" { interface ServerUtilsFunction { - getCurrentWorkDirectory(): E.Error | E.Success; + getCurrentWorkDirectory(): EE.Error | EE.Success; getCurrentWorkDirectoryOrThrow(): string; } } @@ -26,4 +26,4 @@ declare module "../implementor" { * @see https://server-utils.duplojs.dev/en/v0/api/common/getCurrentWorkDirectory * */ -export declare const getCurrentWorkDirectory: () => E.Error | E.Success; +export declare const getCurrentWorkDirectory: () => EE.Error | EE.Success; diff --git a/docs/libs/v0/dist/common/getCurrentWorkDirectory.mjs b/docs/libs/v0/dist/common/getCurrentWorkDirectory.mjs new file mode 100644 index 0000000..a917d9f --- /dev/null +++ b/docs/libs/v0/dist/common/getCurrentWorkDirectory.mjs @@ -0,0 +1,13 @@ +import { pipe } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; +import { implementFunction } from '../implementor.mjs'; + +/** + * {@include common/getCurrentWorkDirectory/index.md} + */ +const getCurrentWorkDirectory = implementFunction("getCurrentWorkDirectory", { + NODE: () => pipe(EE.safeCallback(() => EE.success(process.cwd())), EE.whenIsLeft(EE.error)), + DENO: () => pipe(EE.safeCallback(() => EE.success(Deno.cwd())), EE.whenIsLeft(EE.error)), +}); + +export { getCurrentWorkDirectory }; diff --git a/docs/libs/v0/common/getCurrentWorkDirectoryOrThrow.cjs b/docs/libs/v0/dist/common/getCurrentWorkDirectoryOrThrow.cjs similarity index 100% rename from docs/libs/v0/common/getCurrentWorkDirectoryOrThrow.cjs rename to docs/libs/v0/dist/common/getCurrentWorkDirectoryOrThrow.cjs diff --git a/docs/libs/v0/common/getCurrentWorkDirectoryOrThrow.d.ts b/docs/libs/v0/dist/common/getCurrentWorkDirectoryOrThrow.d.ts similarity index 100% rename from docs/libs/v0/common/getCurrentWorkDirectoryOrThrow.d.ts rename to docs/libs/v0/dist/common/getCurrentWorkDirectoryOrThrow.d.ts diff --git a/docs/libs/v0/common/getCurrentWorkDirectoryOrThrow.mjs b/docs/libs/v0/dist/common/getCurrentWorkDirectoryOrThrow.mjs similarity index 100% rename from docs/libs/v0/common/getCurrentWorkDirectoryOrThrow.mjs rename to docs/libs/v0/dist/common/getCurrentWorkDirectoryOrThrow.mjs diff --git a/docs/libs/v0/common/getProcessArguments.cjs b/docs/libs/v0/dist/common/getProcessArguments.cjs similarity index 100% rename from docs/libs/v0/common/getProcessArguments.cjs rename to docs/libs/v0/dist/common/getProcessArguments.cjs diff --git a/docs/libs/v0/common/getProcessArguments.d.ts b/docs/libs/v0/dist/common/getProcessArguments.d.ts similarity index 100% rename from docs/libs/v0/common/getProcessArguments.d.ts rename to docs/libs/v0/dist/common/getProcessArguments.d.ts diff --git a/docs/libs/v0/common/getProcessArguments.mjs b/docs/libs/v0/dist/common/getProcessArguments.mjs similarity index 100% rename from docs/libs/v0/common/getProcessArguments.mjs rename to docs/libs/v0/dist/common/getProcessArguments.mjs diff --git a/docs/libs/v0/common/index.d.ts b/docs/libs/v0/dist/common/index.d.ts similarity index 100% rename from docs/libs/v0/common/index.d.ts rename to docs/libs/v0/dist/common/index.d.ts diff --git a/docs/libs/v0/dist/common/setCurrentWorkingDirectory.cjs b/docs/libs/v0/dist/common/setCurrentWorkingDirectory.cjs new file mode 100644 index 0000000..8e1405d --- /dev/null +++ b/docs/libs/v0/dist/common/setCurrentWorkingDirectory.cjs @@ -0,0 +1,36 @@ +'use strict'; + +var utils = require('@duplojs/utils'); +var EE = require('@duplojs/utils/either'); +var PP = require('@duplojs/utils/pattern'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); +var PP__namespace = /*#__PURE__*/_interopNamespaceDefault(PP); + +/** + * {@include common/setCurrentWorkingDirectory/index.md} + */ +const setCurrentWorkingDirectory = implementor.implementFunction("setCurrentWorkingDirectory", { + NODE: (path) => utils.pipe(path, utils.when(utils.instanceOf(URL), ({ pathname }) => decodeURIComponent(pathname)), (path) => EE__namespace.safeCallback(() => void process.chdir(path)), PP__namespace.when(EE__namespace.isLeft, EE__namespace.fail), PP__namespace.otherwise(EE__namespace.ok)), + DENO: (path) => utils.pipe(path, utils.when(utils.instanceOf(URL), ({ pathname }) => decodeURIComponent(pathname)), (path) => EE__namespace.safeCallback(() => void Deno.chdir(path)), PP__namespace.when(EE__namespace.isLeft, EE__namespace.fail), PP__namespace.otherwise(EE__namespace.ok)), +}); + +exports.setCurrentWorkingDirectory = setCurrentWorkingDirectory; diff --git a/docs/libs/v0/common/setCurrentWorkingDirectory.d.ts b/docs/libs/v0/dist/common/setCurrentWorkingDirectory.d.ts similarity index 86% rename from docs/libs/v0/common/setCurrentWorkingDirectory.d.ts rename to docs/libs/v0/dist/common/setCurrentWorkingDirectory.d.ts index a15decd..094b49b 100644 --- a/docs/libs/v0/common/setCurrentWorkingDirectory.d.ts +++ b/docs/libs/v0/dist/common/setCurrentWorkingDirectory.d.ts @@ -1,7 +1,7 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; declare module "../implementor" { interface ServerUtilsFunction { - setCurrentWorkingDirectory(path: GenericPath): E.Fail | E.Ok; + setCurrentWorkingDirectory(path: GenericPath): EE.Fail | EE.Ok; } } /** @@ -26,4 +26,4 @@ declare module "../implementor" { * @see https://server-utils.duplojs.dev/en/v0/api/common/setCurrentWorkingDirectory * */ -export declare const setCurrentWorkingDirectory: (path: GenericPath) => E.Fail | E.Ok; +export declare const setCurrentWorkingDirectory: (path: GenericPath) => EE.Fail | EE.Ok; diff --git a/docs/libs/v0/dist/common/setCurrentWorkingDirectory.mjs b/docs/libs/v0/dist/common/setCurrentWorkingDirectory.mjs new file mode 100644 index 0000000..159ea4f --- /dev/null +++ b/docs/libs/v0/dist/common/setCurrentWorkingDirectory.mjs @@ -0,0 +1,14 @@ +import { pipe, when, instanceOf } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; +import * as PP from '@duplojs/utils/pattern'; +import { implementFunction } from '../implementor.mjs'; + +/** + * {@include common/setCurrentWorkingDirectory/index.md} + */ +const setCurrentWorkingDirectory = implementFunction("setCurrentWorkingDirectory", { + NODE: (path) => pipe(path, when(instanceOf(URL), ({ pathname }) => decodeURIComponent(pathname)), (path) => EE.safeCallback(() => void process.chdir(path)), PP.when(EE.isLeft, EE.fail), PP.otherwise(EE.ok)), + DENO: (path) => pipe(path, when(instanceOf(URL), ({ pathname }) => decodeURIComponent(pathname)), (path) => EE.safeCallback(() => void Deno.chdir(path)), PP.when(EE.isLeft, EE.fail), PP.otherwise(EE.ok)), +}); + +export { setCurrentWorkingDirectory }; diff --git a/docs/libs/v0/common/setCurrentWorkingDirectoryOrThrow.cjs b/docs/libs/v0/dist/common/setCurrentWorkingDirectoryOrThrow.cjs similarity index 57% rename from docs/libs/v0/common/setCurrentWorkingDirectoryOrThrow.cjs rename to docs/libs/v0/dist/common/setCurrentWorkingDirectoryOrThrow.cjs index 381a5af..a928a77 100644 --- a/docs/libs/v0/common/setCurrentWorkingDirectoryOrThrow.cjs +++ b/docs/libs/v0/dist/common/setCurrentWorkingDirectoryOrThrow.cjs @@ -1,9 +1,29 @@ 'use strict'; var utils = require('@duplojs/utils'); +var EE = require('@duplojs/utils/either'); var kind = require('../kind.cjs'); var setCurrentWorkingDirectory = require('./setCurrentWorkingDirectory.cjs'); +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + class SetCurrentWorkingDirectoryError extends utils.kindHeritage("set-working-directory-error", kind.createDuplojsServerUtilsKind("set-working-directory-error"), Error) { constructor() { super({}, ["Failed to set current working directory"]); @@ -14,7 +34,7 @@ class SetCurrentWorkingDirectoryError extends utils.kindHeritage("set-working-di */ function setCurrentWorkingDirectoryOrThrow(path) { const result = setCurrentWorkingDirectory.setCurrentWorkingDirectory(path); - if (utils.E.isLeft(result)) { + if (EE__namespace.isLeft(result)) { throw new SetCurrentWorkingDirectoryError(); } return; diff --git a/docs/libs/v0/common/setCurrentWorkingDirectoryOrThrow.d.ts b/docs/libs/v0/dist/common/setCurrentWorkingDirectoryOrThrow.d.ts similarity index 100% rename from docs/libs/v0/common/setCurrentWorkingDirectoryOrThrow.d.ts rename to docs/libs/v0/dist/common/setCurrentWorkingDirectoryOrThrow.d.ts diff --git a/docs/libs/v0/common/setCurrentWorkingDirectoryOrThrow.mjs b/docs/libs/v0/dist/common/setCurrentWorkingDirectoryOrThrow.mjs similarity index 85% rename from docs/libs/v0/common/setCurrentWorkingDirectoryOrThrow.mjs rename to docs/libs/v0/dist/common/setCurrentWorkingDirectoryOrThrow.mjs index 89fbd9e..5ef9876 100644 --- a/docs/libs/v0/common/setCurrentWorkingDirectoryOrThrow.mjs +++ b/docs/libs/v0/dist/common/setCurrentWorkingDirectoryOrThrow.mjs @@ -1,4 +1,5 @@ -import { kindHeritage, E } from '@duplojs/utils'; +import { kindHeritage } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { createDuplojsServerUtilsKind } from '../kind.mjs'; import { setCurrentWorkingDirectory } from './setCurrentWorkingDirectory.mjs'; @@ -12,7 +13,7 @@ class SetCurrentWorkingDirectoryError extends kindHeritage("set-working-director */ function setCurrentWorkingDirectoryOrThrow(path) { const result = setCurrentWorkingDirectory(path); - if (E.isLeft(result)) { + if (EE.isLeft(result)) { throw new SetCurrentWorkingDirectoryError(); } return; diff --git a/docs/libs/v0/dataParser/extended/coerce/file.cjs b/docs/libs/v0/dist/dataParser/extended/coerce/file.cjs similarity index 100% rename from docs/libs/v0/dataParser/extended/coerce/file.cjs rename to docs/libs/v0/dist/dataParser/extended/coerce/file.cjs diff --git a/docs/libs/v0/dataParser/extended/coerce/file.d.ts b/docs/libs/v0/dist/dataParser/extended/coerce/file.d.ts similarity index 60% rename from docs/libs/v0/dataParser/extended/coerce/file.d.ts rename to docs/libs/v0/dist/dataParser/extended/coerce/file.d.ts index 091136f..ebcc177 100644 --- a/docs/libs/v0/dataParser/extended/coerce/file.d.ts +++ b/docs/libs/v0/dist/dataParser/extended/coerce/file.d.ts @@ -1,6 +1,7 @@ +import type { NeverCoalescing } from "@duplojs/utils"; +import type * as DDP from "@duplojs/utils/dataParser"; import type * as dataParsers from "../../parsers"; import * as dataParsersExtended from ".."; -import { type DP, type NeverCoalescing } from "@duplojs/utils"; -export declare function file, "mimeType" | "minSize" | "maxSize" | "coerce"> = never>(params?: dataParsers.DataParserFileParams, definition?: GenericDefinition): dataParsersExtended.DataParserFileExtended & { +export declare function file, "mimeType" | "minSize" | "maxSize" | "coerce"> = never>(params?: dataParsers.DataParserFileParams, definition?: GenericDefinition): dataParsersExtended.DataParserFileExtended & { coerce: true; }>>; diff --git a/docs/libs/v0/dataParser/extended/coerce/file.mjs b/docs/libs/v0/dist/dataParser/extended/coerce/file.mjs similarity index 100% rename from docs/libs/v0/dataParser/extended/coerce/file.mjs rename to docs/libs/v0/dist/dataParser/extended/coerce/file.mjs diff --git a/docs/libs/v0/dataParser/extended/coerce/index.cjs b/docs/libs/v0/dist/dataParser/extended/coerce/index.cjs similarity index 100% rename from docs/libs/v0/dataParser/extended/coerce/index.cjs rename to docs/libs/v0/dist/dataParser/extended/coerce/index.cjs diff --git a/docs/libs/v0/dataParser/extended/coerce/index.d.ts b/docs/libs/v0/dist/dataParser/extended/coerce/index.d.ts similarity index 100% rename from docs/libs/v0/dataParser/extended/coerce/index.d.ts rename to docs/libs/v0/dist/dataParser/extended/coerce/index.d.ts diff --git a/docs/libs/v0/dataParser/extended/coerce/index.mjs b/docs/libs/v0/dist/dataParser/extended/coerce/index.mjs similarity index 100% rename from docs/libs/v0/dataParser/extended/coerce/index.mjs rename to docs/libs/v0/dist/dataParser/extended/coerce/index.mjs diff --git a/docs/libs/v0/dataParser/extended/file.cjs b/docs/libs/v0/dist/dataParser/extended/file.cjs similarity index 75% rename from docs/libs/v0/dataParser/extended/file.cjs rename to docs/libs/v0/dist/dataParser/extended/file.cjs index ce4efab..6bd3a7d 100644 --- a/docs/libs/v0/dataParser/extended/file.cjs +++ b/docs/libs/v0/dist/dataParser/extended/file.cjs @@ -1,13 +1,33 @@ 'use strict'; var utils = require('@duplojs/utils'); +var DDP = require('@duplojs/utils/dataParser'); var file$1 = require('../parsers/file.cjs'); +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var DDP__namespace = /*#__PURE__*/_interopNamespaceDefault(DDP); + /** * {@include dataParserExtended/file/index.md} */ function file(params, definition) { - const self = utils.DP.dataParserExtendedInit(file$1.file(params, definition), { + const self = DDP__namespace.dataParserExtendedInit(file$1.file(params, definition), { mimeType(self, value) { return file({ mimeType: value, diff --git a/docs/libs/v0/dataParser/extended/file.d.ts b/docs/libs/v0/dist/dataParser/extended/file.d.ts similarity index 79% rename from docs/libs/v0/dataParser/extended/file.d.ts rename to docs/libs/v0/dist/dataParser/extended/file.d.ts index 703b7a6..932e7a6 100644 --- a/docs/libs/v0/dataParser/extended/file.d.ts +++ b/docs/libs/v0/dist/dataParser/extended/file.d.ts @@ -1,7 +1,8 @@ -import { type AnyTuple, type BytesInString, DP, type FixDeepFunctionInfer, type Kind, type NeverCoalescing } from "@duplojs/utils"; +import { type AnyTuple, type BytesInString, type FixDeepFunctionInfer, type Kind, type NeverCoalescing } from "@duplojs/utils"; +import * as DDP from "@duplojs/utils/dataParser"; import * as dataParsers from "../parsers"; import { type FileInterface } from "../../file"; -type _DataParserFileExtended = (Kind & DP.DataParserExtended); +type _DataParserFileExtended = (Kind & DDP.DataParserExtended); export interface DataParserFileExtended extends _DataParserFileExtended { addChecker(...args: FixDeepFunctionInfer): DataParserFileExtended>; - refine(theFunction: (input: DP.Output) => boolean, definition?: Partial>): DataParserFileExtended>]>>; + ], GenericChecker>): DataParserFileExtended>; + refine(theFunction: (input: DDP.Output) => boolean, definition?: Partial>): DataParserFileExtended>]>>; /** Set a mime type constraint on the parsed file. */ mimeType(value: string | AnyTuple | RegExp): DataParserFileExtended; /** @@ -61,7 +62,7 @@ export interface DataParserFileExtended, "mimeType" | "minSize" | "maxSize"> = never>(params?: dataParsers.DataParserFileParams, definition?: GenericDefinition): DataParserFileExtended>>; +export declare function file, "mimeType" | "minSize" | "maxSize"> = never>(params?: dataParsers.DataParserFileParams, definition?: GenericDefinition): DataParserFileExtended>>; export declare namespace file { var overrideHandler: import("@duplojs/utils").OverrideHandler>; } diff --git a/docs/libs/v0/dataParser/extended/file.mjs b/docs/libs/v0/dist/dataParser/extended/file.mjs similarity index 92% rename from docs/libs/v0/dataParser/extended/file.mjs rename to docs/libs/v0/dist/dataParser/extended/file.mjs index b6e78c9..540d28c 100644 --- a/docs/libs/v0/dataParser/extended/file.mjs +++ b/docs/libs/v0/dist/dataParser/extended/file.mjs @@ -1,11 +1,12 @@ -import { DP, createOverride } from '@duplojs/utils'; +import { createOverride } from '@duplojs/utils'; +import * as DDP from '@duplojs/utils/dataParser'; import { file as file$1 } from '../parsers/file.mjs'; /** * {@include dataParserExtended/file/index.md} */ function file(params, definition) { - const self = DP.dataParserExtendedInit(file$1(params, definition), { + const self = DDP.dataParserExtendedInit(file$1(params, definition), { mimeType(self, value) { return file({ mimeType: value, diff --git a/docs/libs/v0/dataParser/extended/index.cjs b/docs/libs/v0/dist/dataParser/extended/index.cjs similarity index 100% rename from docs/libs/v0/dataParser/extended/index.cjs rename to docs/libs/v0/dist/dataParser/extended/index.cjs diff --git a/docs/libs/v0/dataParser/extended/index.d.ts b/docs/libs/v0/dist/dataParser/extended/index.d.ts similarity index 100% rename from docs/libs/v0/dataParser/extended/index.d.ts rename to docs/libs/v0/dist/dataParser/extended/index.d.ts diff --git a/docs/libs/v0/dataParser/extended/index.mjs b/docs/libs/v0/dist/dataParser/extended/index.mjs similarity index 100% rename from docs/libs/v0/dataParser/extended/index.mjs rename to docs/libs/v0/dist/dataParser/extended/index.mjs diff --git a/docs/libs/v0/dataParser/index.cjs b/docs/libs/v0/dist/dataParser/index.cjs similarity index 100% rename from docs/libs/v0/dataParser/index.cjs rename to docs/libs/v0/dist/dataParser/index.cjs diff --git a/docs/libs/v0/dataParser/index.d.ts b/docs/libs/v0/dist/dataParser/index.d.ts similarity index 100% rename from docs/libs/v0/dataParser/index.d.ts rename to docs/libs/v0/dist/dataParser/index.d.ts diff --git a/docs/libs/v0/dataParser/index.mjs b/docs/libs/v0/dist/dataParser/index.mjs similarity index 100% rename from docs/libs/v0/dataParser/index.mjs rename to docs/libs/v0/dist/dataParser/index.mjs diff --git a/docs/libs/v0/dataParser/kind.cjs b/docs/libs/v0/dist/dataParser/kind.cjs similarity index 100% rename from docs/libs/v0/dataParser/kind.cjs rename to docs/libs/v0/dist/dataParser/kind.cjs diff --git a/docs/libs/v0/dataParser/kind.d.ts b/docs/libs/v0/dist/dataParser/kind.d.ts similarity index 100% rename from docs/libs/v0/dataParser/kind.d.ts rename to docs/libs/v0/dist/dataParser/kind.d.ts diff --git a/docs/libs/v0/dataParser/kind.mjs b/docs/libs/v0/dist/dataParser/kind.mjs similarity index 100% rename from docs/libs/v0/dataParser/kind.mjs rename to docs/libs/v0/dist/dataParser/kind.mjs diff --git a/docs/libs/v0/dataParser/override.d.ts b/docs/libs/v0/dist/dataParser/override.d.ts similarity index 100% rename from docs/libs/v0/dataParser/override.d.ts rename to docs/libs/v0/dist/dataParser/override.d.ts diff --git a/docs/libs/v0/dataParser/parsers/coerce/file.cjs b/docs/libs/v0/dist/dataParser/parsers/coerce/file.cjs similarity index 100% rename from docs/libs/v0/dataParser/parsers/coerce/file.cjs rename to docs/libs/v0/dist/dataParser/parsers/coerce/file.cjs diff --git a/docs/libs/v0/dataParser/parsers/coerce/file.d.ts b/docs/libs/v0/dist/dataParser/parsers/coerce/file.d.ts similarity index 58% rename from docs/libs/v0/dataParser/parsers/coerce/file.d.ts rename to docs/libs/v0/dist/dataParser/parsers/coerce/file.d.ts index ce82f09..3970fb7 100644 --- a/docs/libs/v0/dataParser/parsers/coerce/file.d.ts +++ b/docs/libs/v0/dist/dataParser/parsers/coerce/file.d.ts @@ -1,5 +1,6 @@ +import type { NeverCoalescing } from "@duplojs/utils"; +import type * as DDP from "@duplojs/utils/dataParser"; import * as dataParsers from "../../parsers"; -import { type DP, type NeverCoalescing } from "@duplojs/utils"; -export declare function file, "mimeType" | "minSize" | "maxSize" | "coerce"> = never>(params?: dataParsers.DataParserFileParams, definition?: GenericDefinition): dataParsers.DataParserFile & { +export declare function file, "mimeType" | "minSize" | "maxSize" | "coerce"> = never>(params?: dataParsers.DataParserFileParams, definition?: GenericDefinition): dataParsers.DataParserFile & { coerce: true; }>>; diff --git a/docs/libs/v0/dataParser/parsers/coerce/file.mjs b/docs/libs/v0/dist/dataParser/parsers/coerce/file.mjs similarity index 100% rename from docs/libs/v0/dataParser/parsers/coerce/file.mjs rename to docs/libs/v0/dist/dataParser/parsers/coerce/file.mjs diff --git a/docs/libs/v0/dataParser/parsers/coerce/index.cjs b/docs/libs/v0/dist/dataParser/parsers/coerce/index.cjs similarity index 100% rename from docs/libs/v0/dataParser/parsers/coerce/index.cjs rename to docs/libs/v0/dist/dataParser/parsers/coerce/index.cjs diff --git a/docs/libs/v0/dataParser/parsers/coerce/index.d.ts b/docs/libs/v0/dist/dataParser/parsers/coerce/index.d.ts similarity index 100% rename from docs/libs/v0/dataParser/parsers/coerce/index.d.ts rename to docs/libs/v0/dist/dataParser/parsers/coerce/index.d.ts diff --git a/docs/libs/v0/dataParser/parsers/coerce/index.mjs b/docs/libs/v0/dist/dataParser/parsers/coerce/index.mjs similarity index 100% rename from docs/libs/v0/dataParser/parsers/coerce/index.mjs rename to docs/libs/v0/dist/dataParser/parsers/coerce/index.mjs diff --git a/docs/libs/v0/dataParser/parsers/file.cjs b/docs/libs/v0/dist/dataParser/parsers/file.cjs similarity index 62% rename from docs/libs/v0/dataParser/parsers/file.cjs rename to docs/libs/v0/dist/dataParser/parsers/file.cjs index 3a222f0..1f966bc 100644 --- a/docs/libs/v0/dataParser/parsers/file.cjs +++ b/docs/libs/v0/dist/dataParser/parsers/file.cjs @@ -1,15 +1,37 @@ 'use strict'; var utils = require('@duplojs/utils'); +var DDP = require('@duplojs/utils/dataParser'); +var EE = require('@duplojs/utils/either'); var kind = require('../kind.cjs'); var fileInterface = require('../../file/fileInterface.cjs'); +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var DDP__namespace = /*#__PURE__*/_interopNamespaceDefault(DDP); +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + const fileKind = kind.createDataParserKind("file"); /** * {@include dataParser/file/index.md} */ function file(params, definition) { - const self = utils.DP.dataParserInit(fileKind, { + const self = DDP__namespace.dataParserInit(fileKind, { errorMessage: definition?.errorMessage, checkers: definition?.checkers ?? [], coerce: definition?.coerce ?? false, @@ -28,21 +50,21 @@ function file(params, definition) { if (self.definition.checkExist || self.definition.maxSize !== undefined || self.definition.minSize !== undefined) { - return utils.DP.addIssue(error, "async data parser", data, self.definition.errorMessage); + return DDP__namespace.addIssue(error, "async data parser", data, self.definition.errorMessage); } let fileInterface$1 = data; if (self.definition.coerce && typeof fileInterface$1 === "string") { fileInterface$1 = fileInterface.createFileInterface(fileInterface$1); } if (!fileInterface.isFileInterface(fileInterface$1)) { - return utils.DP.addIssue(error, "file", data, self.definition.errorMessage); + return DDP__namespace.addIssue(error, "file", data, self.definition.errorMessage); } if (self.definition.mimeType && !self .definition .mimeType .test(fileInterface$1.getMimeType() ?? "")) { - return utils.DP.addIssue(error, `file with mime type matching ${self.definition.mimeType.source}`, data, "Wrong mimeType."); + return DDP__namespace.addIssue(error, `file with mime type matching ${self.definition.mimeType.source}`, data, "Wrong mimeType."); } return fileInterface$1; }, @@ -52,33 +74,33 @@ function file(params, definition) { fileInterface$1 = fileInterface.createFileInterface(fileInterface$1); } if (!fileInterface.isFileInterface(fileInterface$1)) { - return utils.DP.addIssue(error, "file", data, self.definition.errorMessage); + return DDP__namespace.addIssue(error, "file", data, self.definition.errorMessage); } if (self.definition.mimeType && !self .definition .mimeType .test(fileInterface$1.getMimeType() ?? "")) { - return utils.DP.addIssue(error, `file with mime type matching ${self.definition.mimeType.source}`, fileInterface$1, "Wrong mimeType."); + return DDP__namespace.addIssue(error, `file with mime type matching ${self.definition.mimeType.source}`, fileInterface$1, "Wrong mimeType."); } if (self.definition.checkExist || self.definition.maxSize !== undefined || self.definition.minSize !== undefined) { const resultStats = await fileInterface$1.stat(); - if (utils.E.isLeft(resultStats)) { - return utils.DP.addIssue(error, "existing file", fileInterface$1, "File not exist."); + if (EE__namespace.isLeft(resultStats)) { + return DDP__namespace.addIssue(error, "existing file", fileInterface$1, "File not exist."); } const stat = utils.unwrap(resultStats); if (!stat.isFile) { - return utils.DP.addIssue(error, "file", stat, "Is not file."); + return DDP__namespace.addIssue(error, "file", stat, "Is not file."); } if (self.definition.maxSize !== undefined && stat.sizeBytes > self.definition.maxSize) { - return utils.DP.addIssue(error, `file with sizeBytes <= ${self.definition.maxSize}`, stat.sizeBytes, "File is to large."); + return DDP__namespace.addIssue(error, `file with sizeBytes <= ${self.definition.maxSize}`, stat.sizeBytes, "File is to large."); } if (self.definition.minSize !== undefined && stat.sizeBytes < self.definition.minSize) { - return utils.DP.addIssue(error, `file with sizeBytes >= ${self.definition.minSize}`, stat.sizeBytes, "File is to small."); + return DDP__namespace.addIssue(error, `file with sizeBytes >= ${self.definition.minSize}`, stat.sizeBytes, "File is to small."); } } return fileInterface$1; diff --git a/docs/libs/v0/dataParser/parsers/file.d.ts b/docs/libs/v0/dist/dataParser/parsers/file.d.ts similarity index 76% rename from docs/libs/v0/dataParser/parsers/file.d.ts rename to docs/libs/v0/dist/dataParser/parsers/file.d.ts index 291a617..8ceab7c 100644 --- a/docs/libs/v0/dataParser/parsers/file.d.ts +++ b/docs/libs/v0/dist/dataParser/parsers/file.d.ts @@ -1,9 +1,11 @@ -import { type BytesInString, DP, type FixDeepFunctionInfer, type Kind, type O, type NeverCoalescing, type AnyTuple } from "@duplojs/utils"; +import { type BytesInString, type FixDeepFunctionInfer, type Kind, type NeverCoalescing, type AnyTuple } from "@duplojs/utils"; +import * as DDP from "@duplojs/utils/dataParser"; +import type * as OO from "@duplojs/utils/object"; import { type FileInterface } from "../../file"; export interface DataParserFileCheckerCustom { } -export type DataParserFileCheckers = (DataParserFileCheckerCustom[O.GetPropsWithValueExtends] | DP.CheckerRefineImplementation); -export interface DataParserDefinitionFile extends DP.DataParserDefinition { +export type DataParserFileCheckers = (DataParserFileCheckerCustom[OO.GetPropsWithValueExtends] | DDP.CheckerRefineImplementation); +export interface DataParserDefinitionFile extends DDP.DataParserDefinition { readonly coerce: boolean; readonly mimeType?: RegExp; readonly minSize?: number; @@ -11,7 +13,7 @@ export interface DataParserDefinitionFile extends DP.DataParserDefinition>; -type _DataParserFile = (DP.DataParser & Kind); +type _DataParserFile = (DDP.DataParser & Kind); export interface DataParserFile extends _DataParserFile { addChecker(...args: FixDeepFunctionInfer): DataParserFile>; + ], GenericChecker>): DataParserFile>; } export interface DataParserFileParams { readonly mimeType?: string | AnyTuple | RegExp; @@ -61,7 +63,7 @@ export interface DataParserFileParams { * @namespace SDP * */ -export declare function file, "mimeType" | "minSize" | "maxSize" | "checkExist"> = never>(params?: DataParserFileParams, definition?: GenericDefinition): DataParserFile>>; +export declare function file, "mimeType" | "minSize" | "maxSize" | "checkExist"> = never>(params?: DataParserFileParams, definition?: GenericDefinition): DataParserFile>>; export declare namespace file { var overrideHandler: import("@duplojs/utils").OverrideHandler>; } diff --git a/docs/libs/v0/dataParser/parsers/file.mjs b/docs/libs/v0/dist/dataParser/parsers/file.mjs similarity index 70% rename from docs/libs/v0/dataParser/parsers/file.mjs rename to docs/libs/v0/dist/dataParser/parsers/file.mjs index 78cf49a..cc4fc77 100644 --- a/docs/libs/v0/dataParser/parsers/file.mjs +++ b/docs/libs/v0/dist/dataParser/parsers/file.mjs @@ -1,4 +1,6 @@ -import { DP, toRegExp, stringToBytes, E, unwrap, createOverride } from '@duplojs/utils'; +import { toRegExp, stringToBytes, unwrap, createOverride } from '@duplojs/utils'; +import * as DDP from '@duplojs/utils/dataParser'; +import * as EE from '@duplojs/utils/either'; import { createDataParserKind } from '../kind.mjs'; import { createFileInterface, isFileInterface } from '../../file/fileInterface.mjs'; @@ -7,7 +9,7 @@ const fileKind = createDataParserKind("file"); * {@include dataParser/file/index.md} */ function file(params, definition) { - const self = DP.dataParserInit(fileKind, { + const self = DDP.dataParserInit(fileKind, { errorMessage: definition?.errorMessage, checkers: definition?.checkers ?? [], coerce: definition?.coerce ?? false, @@ -26,21 +28,21 @@ function file(params, definition) { if (self.definition.checkExist || self.definition.maxSize !== undefined || self.definition.minSize !== undefined) { - return DP.addIssue(error, "async data parser", data, self.definition.errorMessage); + return DDP.addIssue(error, "async data parser", data, self.definition.errorMessage); } let fileInterface = data; if (self.definition.coerce && typeof fileInterface === "string") { fileInterface = createFileInterface(fileInterface); } if (!isFileInterface(fileInterface)) { - return DP.addIssue(error, "file", data, self.definition.errorMessage); + return DDP.addIssue(error, "file", data, self.definition.errorMessage); } if (self.definition.mimeType && !self .definition .mimeType .test(fileInterface.getMimeType() ?? "")) { - return DP.addIssue(error, `file with mime type matching ${self.definition.mimeType.source}`, data, "Wrong mimeType."); + return DDP.addIssue(error, `file with mime type matching ${self.definition.mimeType.source}`, data, "Wrong mimeType."); } return fileInterface; }, @@ -50,33 +52,33 @@ function file(params, definition) { fileInterface = createFileInterface(fileInterface); } if (!isFileInterface(fileInterface)) { - return DP.addIssue(error, "file", data, self.definition.errorMessage); + return DDP.addIssue(error, "file", data, self.definition.errorMessage); } if (self.definition.mimeType && !self .definition .mimeType .test(fileInterface.getMimeType() ?? "")) { - return DP.addIssue(error, `file with mime type matching ${self.definition.mimeType.source}`, fileInterface, "Wrong mimeType."); + return DDP.addIssue(error, `file with mime type matching ${self.definition.mimeType.source}`, fileInterface, "Wrong mimeType."); } if (self.definition.checkExist || self.definition.maxSize !== undefined || self.definition.minSize !== undefined) { const resultStats = await fileInterface.stat(); - if (E.isLeft(resultStats)) { - return DP.addIssue(error, "existing file", fileInterface, "File not exist."); + if (EE.isLeft(resultStats)) { + return DDP.addIssue(error, "existing file", fileInterface, "File not exist."); } const stat = unwrap(resultStats); if (!stat.isFile) { - return DP.addIssue(error, "file", stat, "Is not file."); + return DDP.addIssue(error, "file", stat, "Is not file."); } if (self.definition.maxSize !== undefined && stat.sizeBytes > self.definition.maxSize) { - return DP.addIssue(error, `file with sizeBytes <= ${self.definition.maxSize}`, stat.sizeBytes, "File is to large."); + return DDP.addIssue(error, `file with sizeBytes <= ${self.definition.maxSize}`, stat.sizeBytes, "File is to large."); } if (self.definition.minSize !== undefined && stat.sizeBytes < self.definition.minSize) { - return DP.addIssue(error, `file with sizeBytes >= ${self.definition.minSize}`, stat.sizeBytes, "File is to small."); + return DDP.addIssue(error, `file with sizeBytes >= ${self.definition.minSize}`, stat.sizeBytes, "File is to small."); } } return fileInterface; diff --git a/docs/libs/v0/dataParser/parsers/index.d.ts b/docs/libs/v0/dist/dataParser/parsers/index.d.ts similarity index 100% rename from docs/libs/v0/dataParser/parsers/index.d.ts rename to docs/libs/v0/dist/dataParser/parsers/index.d.ts diff --git a/docs/libs/v0/dist/file/appendFile.cjs b/docs/libs/v0/dist/file/appendFile.cjs new file mode 100644 index 0000000..eaf9161 --- /dev/null +++ b/docs/libs/v0/dist/file/appendFile.cjs @@ -0,0 +1,40 @@ +'use strict'; + +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/appendFile/index.md} + */ +const appendFile = implementor.implementFunction("appendFile", { + NODE: async (path, data) => { + const fs = await implementor.nodeFileSystem.value; + return fs.appendFile(path, data) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-append-file", value)); + }, + DENO: (path, data) => Deno.writeFile(path, data, { append: true }) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-append-file", value)), +}); + +exports.appendFile = appendFile; diff --git a/docs/libs/v0/file/appendFile.d.ts b/docs/libs/v0/dist/file/appendFile.d.ts similarity index 85% rename from docs/libs/v0/file/appendFile.d.ts rename to docs/libs/v0/dist/file/appendFile.d.ts index 1848bb1..52b2007 100644 --- a/docs/libs/v0/file/appendFile.d.ts +++ b/docs/libs/v0/dist/file/appendFile.d.ts @@ -1,8 +1,8 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; declare module "../implementor" { interface ServerUtilsFunction { - appendFile(path: string, data: Uint8Array): Promise | E.Ok>; + appendFile(path: string, data: Uint8Array): Promise | EE.Ok>; } } /** @@ -28,4 +28,4 @@ declare module "../implementor" { * @namespace SF * */ -export declare const appendFile: (path: string, data: Uint8Array) => Promise | E.Ok>; +export declare const appendFile: (path: string, data: Uint8Array) => Promise | EE.Ok>; diff --git a/docs/libs/v0/file/appendFile.mjs b/docs/libs/v0/dist/file/appendFile.mjs similarity index 63% rename from docs/libs/v0/file/appendFile.mjs rename to docs/libs/v0/dist/file/appendFile.mjs index 33f86ab..1d9e8d6 100644 --- a/docs/libs/v0/file/appendFile.mjs +++ b/docs/libs/v0/dist/file/appendFile.mjs @@ -1,4 +1,4 @@ -import { E } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; /** @@ -8,12 +8,12 @@ const appendFile = implementFunction("appendFile", { NODE: async (path, data) => { const fs = await nodeFileSystem.value; return fs.appendFile(path, data) - .then(E.ok) - .catch((value) => E.left("file-system-append-file", value)); + .then(EE.ok) + .catch((value) => EE.left("file-system-append-file", value)); }, DENO: (path, data) => Deno.writeFile(path, data, { append: true }) - .then(E.ok) - .catch((value) => E.left("file-system-append-file", value)), + .then(EE.ok) + .catch((value) => EE.left("file-system-append-file", value)), }); export { appendFile }; diff --git a/docs/libs/v0/dist/file/appendTextFile.cjs b/docs/libs/v0/dist/file/appendTextFile.cjs new file mode 100644 index 0000000..cc68bbf --- /dev/null +++ b/docs/libs/v0/dist/file/appendTextFile.cjs @@ -0,0 +1,40 @@ +'use strict'; + +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/appendTextFile/index.md} + */ +const appendTextFile = implementor.implementFunction("appendTextFile", { + NODE: async (path, data) => { + const fs = await implementor.nodeFileSystem.value; + return fs.appendFile(path, data) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-append-text-file", value)); + }, + DENO: (path, data) => Deno.writeTextFile(path, data, { append: true }) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-append-text-file", value)), +}); + +exports.appendTextFile = appendTextFile; diff --git a/docs/libs/v0/file/appendTextFile.d.ts b/docs/libs/v0/dist/file/appendTextFile.d.ts similarity index 84% rename from docs/libs/v0/file/appendTextFile.d.ts rename to docs/libs/v0/dist/file/appendTextFile.d.ts index 094241a..06bfde5 100644 --- a/docs/libs/v0/file/appendTextFile.d.ts +++ b/docs/libs/v0/dist/file/appendTextFile.d.ts @@ -1,8 +1,8 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; declare module "../implementor" { interface ServerUtilsFunction { - appendTextFile(path: string, data: string): Promise | E.Ok>; + appendTextFile(path: string, data: string): Promise | EE.Ok>; } } /** @@ -26,4 +26,4 @@ declare module "../implementor" { * @namespace SF * */ -export declare const appendTextFile: (path: string, data: string) => Promise | E.Ok>; +export declare const appendTextFile: (path: string, data: string) => Promise | EE.Ok>; diff --git a/docs/libs/v0/file/appendTextFile.mjs b/docs/libs/v0/dist/file/appendTextFile.mjs similarity index 63% rename from docs/libs/v0/file/appendTextFile.mjs rename to docs/libs/v0/dist/file/appendTextFile.mjs index 60f6460..d1b0f85 100644 --- a/docs/libs/v0/file/appendTextFile.mjs +++ b/docs/libs/v0/dist/file/appendTextFile.mjs @@ -1,4 +1,4 @@ -import { E } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; /** @@ -8,12 +8,12 @@ const appendTextFile = implementFunction("appendTextFile", { NODE: async (path, data) => { const fs = await nodeFileSystem.value; return fs.appendFile(path, data) - .then(E.ok) - .catch((value) => E.left("file-system-append-text-file", value)); + .then(EE.ok) + .catch((value) => EE.left("file-system-append-text-file", value)); }, DENO: (path, data) => Deno.writeTextFile(path, data, { append: true }) - .then(E.ok) - .catch((value) => E.left("file-system-append-text-file", value)), + .then(EE.ok) + .catch((value) => EE.left("file-system-append-text-file", value)), }); export { appendTextFile }; diff --git a/docs/libs/v0/dist/file/copy.cjs b/docs/libs/v0/dist/file/copy.cjs new file mode 100644 index 0000000..947e9ed --- /dev/null +++ b/docs/libs/v0/dist/file/copy.cjs @@ -0,0 +1,37 @@ +'use strict'; + +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/copy/index.md} + */ +const copy = implementor.implementFunction("copy", { + NODE: async (fromPath, toPath) => { + const fs = await implementor.nodeFileSystem.value; + return fs.cp(fromPath, toPath, { recursive: true }) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-copy", value)); + }, +}); + +exports.copy = copy; diff --git a/docs/libs/v0/file/copy.d.ts b/docs/libs/v0/dist/file/copy.d.ts similarity index 85% rename from docs/libs/v0/file/copy.d.ts rename to docs/libs/v0/dist/file/copy.d.ts index a150455..e0f17c9 100644 --- a/docs/libs/v0/file/copy.d.ts +++ b/docs/libs/v0/dist/file/copy.d.ts @@ -1,8 +1,8 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; declare module "../implementor" { interface ServerUtilsFunction { - copy(fromPath: string, toPath: string): Promise | E.Ok>; + copy(fromPath: string, toPath: string): Promise | EE.Ok>; } } /** @@ -21,4 +21,4 @@ declare module "../implementor" { * @namespace SF * */ -export declare const copy: (fromPath: string, toPath: string) => Promise | E.Ok>; +export declare const copy: (fromPath: string, toPath: string) => Promise | EE.Ok>; diff --git a/docs/libs/v0/file/copy.mjs b/docs/libs/v0/dist/file/copy.mjs similarity index 70% rename from docs/libs/v0/file/copy.mjs rename to docs/libs/v0/dist/file/copy.mjs index b114e7f..3c2af58 100644 --- a/docs/libs/v0/file/copy.mjs +++ b/docs/libs/v0/dist/file/copy.mjs @@ -1,4 +1,4 @@ -import { E } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; /** @@ -8,8 +8,8 @@ const copy = implementFunction("copy", { NODE: async (fromPath, toPath) => { const fs = await nodeFileSystem.value; return fs.cp(fromPath, toPath, { recursive: true }) - .then(E.ok) - .catch((value) => E.left("file-system-copy", value)); + .then(EE.ok) + .catch((value) => EE.left("file-system-copy", value)); }, }); diff --git a/docs/libs/v0/dist/file/ensureDirectory.cjs b/docs/libs/v0/dist/file/ensureDirectory.cjs new file mode 100644 index 0000000..08bf674 --- /dev/null +++ b/docs/libs/v0/dist/file/ensureDirectory.cjs @@ -0,0 +1,44 @@ +'use strict'; + +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/ensureDirectory/index.md} + */ +const ensureDirectory = implementor.implementFunction("ensureDirectory", { + NODE: async (path) => { + const fs = await implementor.nodeFileSystem.value; + return fs.mkdir(path, { + recursive: true, + }) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-ensure-directory", value)); + }, + DENO: (path) => Deno.mkdir(path, { + recursive: true, + }) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-ensure-directory", value)), +}); + +exports.ensureDirectory = ensureDirectory; diff --git a/docs/libs/v0/file/ensureDirectory.d.ts b/docs/libs/v0/dist/file/ensureDirectory.d.ts similarity index 85% rename from docs/libs/v0/file/ensureDirectory.d.ts rename to docs/libs/v0/dist/file/ensureDirectory.d.ts index 8af96cc..fceaf5c 100644 --- a/docs/libs/v0/file/ensureDirectory.d.ts +++ b/docs/libs/v0/dist/file/ensureDirectory.d.ts @@ -1,8 +1,8 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; declare module "../implementor" { interface ServerUtilsFunction { - ensureDirectory(path: GenericPath): Promise | E.Ok>; + ensureDirectory(path: GenericPath): Promise | EE.Ok>; } } /** @@ -21,4 +21,4 @@ declare module "../implementor" { * @namespace SF * */ -export declare const ensureDirectory: (path: GenericPath) => Promise | E.Ok>; +export declare const ensureDirectory: (path: GenericPath) => Promise | EE.Ok>; diff --git a/docs/libs/v0/file/ensureDirectory.mjs b/docs/libs/v0/dist/file/ensureDirectory.mjs similarity index 64% rename from docs/libs/v0/file/ensureDirectory.mjs rename to docs/libs/v0/dist/file/ensureDirectory.mjs index 576fb4b..ac6185b 100644 --- a/docs/libs/v0/file/ensureDirectory.mjs +++ b/docs/libs/v0/dist/file/ensureDirectory.mjs @@ -1,4 +1,4 @@ -import { E } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; /** @@ -10,14 +10,14 @@ const ensureDirectory = implementFunction("ensureDirectory", { return fs.mkdir(path, { recursive: true, }) - .then(E.ok) - .catch((value) => E.left("file-system-ensure-directory", value)); + .then(EE.ok) + .catch((value) => EE.left("file-system-ensure-directory", value)); }, DENO: (path) => Deno.mkdir(path, { recursive: true, }) - .then(E.ok) - .catch((value) => E.left("file-system-ensure-directory", value)), + .then(EE.ok) + .catch((value) => EE.left("file-system-ensure-directory", value)), }); export { ensureDirectory }; diff --git a/docs/libs/v0/dist/file/ensureFile.cjs b/docs/libs/v0/dist/file/ensureFile.cjs new file mode 100644 index 0000000..9c7d8a2 --- /dev/null +++ b/docs/libs/v0/dist/file/ensureFile.cjs @@ -0,0 +1,46 @@ +'use strict'; + +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/ensureFile/index.md} + */ +const ensureFile = implementor.implementFunction("ensureFile", { + NODE: async (path) => { + const fs = await implementor.nodeFileSystem.value; + return fs.open(path, "a") + .then((fh) => fh.close()) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-ensure-file", value)); + }, + DENO: (path) => Deno.open(path, { + write: true, + create: true, + append: true, + }) + .then((fh) => void fh.close()) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-ensure-file", value)), +}); + +exports.ensureFile = ensureFile; diff --git a/docs/libs/v0/file/ensureFile.d.ts b/docs/libs/v0/dist/file/ensureFile.d.ts similarity index 79% rename from docs/libs/v0/file/ensureFile.d.ts rename to docs/libs/v0/dist/file/ensureFile.d.ts index 01d5405..afebdcc 100644 --- a/docs/libs/v0/file/ensureFile.d.ts +++ b/docs/libs/v0/dist/file/ensureFile.d.ts @@ -1,8 +1,8 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; declare module "../implementor" { interface ServerUtilsFunction { - ensureFile(path: GenericPath): Promise | E.Ok>; + ensureFile(path: GenericPath): Promise | EE.Ok>; } } /** @@ -21,4 +21,4 @@ declare module "../implementor" { * @namespace SF * */ -export declare const ensureFile: (path: GenericPath) => Promise | E.Ok>; +export declare const ensureFile: (path: GenericPath) => Promise | EE.Ok>; diff --git a/docs/libs/v0/file/ensureFile.mjs b/docs/libs/v0/dist/file/ensureFile.mjs similarity index 68% rename from docs/libs/v0/file/ensureFile.mjs rename to docs/libs/v0/dist/file/ensureFile.mjs index a3c8e9d..a9bf2b2 100644 --- a/docs/libs/v0/file/ensureFile.mjs +++ b/docs/libs/v0/dist/file/ensureFile.mjs @@ -1,4 +1,4 @@ -import { E } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; /** @@ -9,8 +9,8 @@ const ensureFile = implementFunction("ensureFile", { const fs = await nodeFileSystem.value; return fs.open(path, "a") .then((fh) => fh.close()) - .then(E.ok) - .catch((value) => E.left("file-system-ensure-file", value)); + .then(EE.ok) + .catch((value) => EE.left("file-system-ensure-file", value)); }, DENO: (path) => Deno.open(path, { write: true, @@ -18,8 +18,8 @@ const ensureFile = implementFunction("ensureFile", { append: true, }) .then((fh) => void fh.close()) - .then(E.ok) - .catch((value) => E.left("file-system-ensure-file", value)), + .then(EE.ok) + .catch((value) => EE.left("file-system-ensure-file", value)), }); export { ensureFile }; diff --git a/docs/libs/v0/dist/file/exists.cjs b/docs/libs/v0/dist/file/exists.cjs new file mode 100644 index 0000000..dfef156 --- /dev/null +++ b/docs/libs/v0/dist/file/exists.cjs @@ -0,0 +1,47 @@ +'use strict'; + +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/exists/index.md} + */ +const exists = implementor.implementFunction("exists", { + NODE: async (path) => { + const fs = await implementor.nodeFileSystem.value; + return fs.access(path) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-exists", value)); + }, + DENO: (path) => Deno + .stat(path) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-exists", value)), + BUN: (path) => Bun.file(path) + .exists() + .then((value) => value + ? EE__namespace.ok() + : EE__namespace.left("file-system-exists", new Error("Path does not exist"))) + .catch((value) => EE__namespace.left("file-system-exists", value)), +}); + +exports.exists = exists; diff --git a/docs/libs/v0/file/exists.d.ts b/docs/libs/v0/dist/file/exists.d.ts similarity index 81% rename from docs/libs/v0/file/exists.d.ts rename to docs/libs/v0/dist/file/exists.d.ts index 7fffa5d..bdd60b7 100644 --- a/docs/libs/v0/file/exists.d.ts +++ b/docs/libs/v0/dist/file/exists.d.ts @@ -1,8 +1,8 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; declare module "../implementor" { interface ServerUtilsFunction { - exists(path: GenericPath): Promise | E.Ok>; + exists(path: GenericPath): Promise | EE.Ok>; } } /** @@ -21,4 +21,4 @@ declare module "../implementor" { * @namespace SF * */ -export declare const exists: (path: GenericPath) => Promise | E.Ok>; +export declare const exists: (path: GenericPath) => Promise | EE.Ok>; diff --git a/docs/libs/v0/file/exists.mjs b/docs/libs/v0/dist/file/exists.mjs similarity index 52% rename from docs/libs/v0/file/exists.mjs rename to docs/libs/v0/dist/file/exists.mjs index 3ef3ed3..83588a1 100644 --- a/docs/libs/v0/file/exists.mjs +++ b/docs/libs/v0/dist/file/exists.mjs @@ -1,4 +1,4 @@ -import { E } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; /** @@ -8,19 +8,19 @@ const exists = implementFunction("exists", { NODE: async (path) => { const fs = await nodeFileSystem.value; return fs.access(path) - .then(E.ok) - .catch((value) => E.left("file-system-exists", value)); + .then(EE.ok) + .catch((value) => EE.left("file-system-exists", value)); }, DENO: (path) => Deno .stat(path) - .then(E.ok) - .catch((value) => E.left("file-system-exists", value)), + .then(EE.ok) + .catch((value) => EE.left("file-system-exists", value)), BUN: (path) => Bun.file(path) .exists() .then((value) => value - ? E.ok() - : E.left("file-system-exists", new Error("Path does not exist"))) - .catch((value) => E.left("file-system-exists", value)), + ? EE.ok() + : EE.left("file-system-exists", new Error("Path does not exist"))) + .catch((value) => EE.left("file-system-exists", value)), }); export { exists }; diff --git a/docs/libs/v0/file/fileInterface.cjs b/docs/libs/v0/dist/file/fileInterface.cjs similarity index 65% rename from docs/libs/v0/file/fileInterface.cjs rename to docs/libs/v0/dist/file/fileInterface.cjs index 63d532c..c92e1f3 100644 --- a/docs/libs/v0/file/fileInterface.cjs +++ b/docs/libs/v0/dist/file/fileInterface.cjs @@ -1,7 +1,8 @@ 'use strict'; -var kind = require('../kind.cjs'); var utils = require('@duplojs/utils'); +var EE = require('@duplojs/utils/either'); +var kind = require('../kind.cjs'); var rename = require('./rename.cjs'); var exists = require('./exists.cjs'); var move = require('./move.cjs'); @@ -9,6 +10,25 @@ var remove = require('./remove.cjs'); var stat = require('./stat.cjs'); var relocate = require('./relocate.cjs'); +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + const fileInterfaceKind = kind.createDuplojsServerUtilsKind("fileInterface"); /** * {@include file/createFileInterface/index.md} @@ -34,13 +54,13 @@ function createFileInterface(path) { return exists.exists(path); } function localRename(newName) { - return utils.asyncPipe(rename.rename(path, newName), utils.E.whenIsRight(utils.innerPipe(createFileInterface, utils.E.success))); + return utils.asyncPipe(rename.rename(path, newName), EE__namespace.whenIsRight(utils.innerPipe(createFileInterface, EE__namespace.success))); } function localRelocate(newParentPath) { - return utils.asyncPipe(relocate.relocate(path, newParentPath), utils.E.whenIsRight(utils.innerPipe(createFileInterface, utils.E.success))); + return utils.asyncPipe(relocate.relocate(path, newParentPath), EE__namespace.whenIsRight(utils.innerPipe(createFileInterface, EE__namespace.success))); } function localMove(newPath) { - return utils.asyncPipe(move.move(path, newPath), utils.E.whenIsRight(() => utils.E.success(createFileInterface(newPath)))); + return utils.asyncPipe(move.move(path, newPath), EE__namespace.whenIsRight(() => EE__namespace.success(createFileInterface(newPath)))); } function localRemove() { return remove.remove(path); diff --git a/docs/libs/v0/file/fileInterface.d.ts b/docs/libs/v0/dist/file/fileInterface.d.ts similarity index 82% rename from docs/libs/v0/file/fileInterface.d.ts rename to docs/libs/v0/dist/file/fileInterface.d.ts index 3f92cc4..43de70a 100644 --- a/docs/libs/v0/file/fileInterface.d.ts +++ b/docs/libs/v0/dist/file/fileInterface.d.ts @@ -1,4 +1,5 @@ -import { type Kind, E, Path } from "@duplojs/utils"; +import { type Kind, Path } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import { type StatInfo } from "./stat"; import type { FileSystemLeft } from "./types"; declare const fileInterfaceKind: import("@duplojs/utils").KindHandler>; @@ -8,12 +9,12 @@ export interface FileInterface extends Kind getMimeType(): string | null; getExtension(params?: Path.GetExtensionNameParams): string | null; getParentPath(): string | null; - rename(newName: string): Promise | E.Success>; - relocate(parentPath: string): Promise | E.Success>; - move(newPath: string): Promise | E.Success>; - exists(): Promise | E.Ok>; - remove(): Promise | E.Ok>; - stat(): Promise | E.Success>; + rename(newName: string): Promise | EE.Success>; + relocate(parentPath: string): Promise | EE.Success>; + move(newPath: string): Promise | EE.Success>; + exists(): Promise | EE.Ok>; + remove(): Promise | EE.Ok>; + stat(): Promise | EE.Success>; } /** * Create a file interface with helper methods. diff --git a/docs/libs/v0/file/fileInterface.mjs b/docs/libs/v0/dist/file/fileInterface.mjs similarity index 78% rename from docs/libs/v0/file/fileInterface.mjs rename to docs/libs/v0/dist/file/fileInterface.mjs index 980e043..d9983af 100644 --- a/docs/libs/v0/file/fileInterface.mjs +++ b/docs/libs/v0/dist/file/fileInterface.mjs @@ -1,5 +1,6 @@ +import { asyncPipe, innerPipe, Path, mimeType } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { createDuplojsServerUtilsKind } from '../kind.mjs'; -import { asyncPipe, E, innerPipe, Path, mimeType } from '@duplojs/utils'; import { rename } from './rename.mjs'; import { exists } from './exists.mjs'; import { move } from './move.mjs'; @@ -32,13 +33,13 @@ function createFileInterface(path) { return exists(path); } function localRename(newName) { - return asyncPipe(rename(path, newName), E.whenIsRight(innerPipe(createFileInterface, E.success))); + return asyncPipe(rename(path, newName), EE.whenIsRight(innerPipe(createFileInterface, EE.success))); } function localRelocate(newParentPath) { - return asyncPipe(relocate(path, newParentPath), E.whenIsRight(innerPipe(createFileInterface, E.success))); + return asyncPipe(relocate(path, newParentPath), EE.whenIsRight(innerPipe(createFileInterface, EE.success))); } function localMove(newPath) { - return asyncPipe(move(path, newPath), E.whenIsRight(() => E.success(createFileInterface(newPath)))); + return asyncPipe(move(path, newPath), EE.whenIsRight(() => EE.success(createFileInterface(newPath)))); } function localRemove() { return remove(path); diff --git a/docs/libs/v0/file/folderInterface.cjs b/docs/libs/v0/dist/file/folderInterface.cjs similarity index 65% rename from docs/libs/v0/file/folderInterface.cjs rename to docs/libs/v0/dist/file/folderInterface.cjs index 76a7d42..9576e80 100644 --- a/docs/libs/v0/file/folderInterface.cjs +++ b/docs/libs/v0/dist/file/folderInterface.cjs @@ -1,6 +1,7 @@ 'use strict'; var utils = require('@duplojs/utils'); +var EE = require('@duplojs/utils/either'); var kind = require('../kind.cjs'); var move = require('./move.cjs'); var exists = require('./exists.cjs'); @@ -11,6 +12,25 @@ var stat = require('./stat.cjs'); var walkDirectory = require('./walkDirectory.cjs'); var relocate = require('./relocate.cjs'); +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + const folderInterfaceKind = kind.createDuplojsServerUtilsKind("folderInterface"); /** * {@include file/createFolderInterface/index.md} @@ -23,13 +43,13 @@ function createFolderInterface(path) { return utils.Path.getParentFolderPath(path); } function localRename(newName) { - return utils.asyncPipe(rename.rename(path, newName), utils.E.whenIsRight(utils.innerPipe(createFolderInterface, utils.E.success))); + return utils.asyncPipe(rename.rename(path, newName), EE__namespace.whenIsRight(utils.innerPipe(createFolderInterface, EE__namespace.success))); } function localRelocate(newParentPath) { - return utils.asyncPipe(relocate.relocate(path, newParentPath), utils.E.whenIsRight(utils.innerPipe(createFolderInterface, utils.E.success))); + return utils.asyncPipe(relocate.relocate(path, newParentPath), EE__namespace.whenIsRight(utils.innerPipe(createFolderInterface, EE__namespace.success))); } function localMove(newPath) { - return utils.asyncPipe(move.move(path, newPath), utils.E.whenIsRight(() => utils.E.success(createFolderInterface(newPath)))); + return utils.asyncPipe(move.move(path, newPath), EE__namespace.whenIsRight(() => EE__namespace.success(createFolderInterface(newPath)))); } function localExists() { return exists.exists(path); diff --git a/docs/libs/v0/file/folderInterface.d.ts b/docs/libs/v0/dist/file/folderInterface.d.ts similarity index 75% rename from docs/libs/v0/file/folderInterface.d.ts rename to docs/libs/v0/dist/file/folderInterface.d.ts index f2f1912..2bdc610 100644 --- a/docs/libs/v0/file/folderInterface.d.ts +++ b/docs/libs/v0/dist/file/folderInterface.d.ts @@ -1,4 +1,5 @@ -import { E, type Kind } from "@duplojs/utils"; +import { type Kind } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import { type StatInfo } from "./stat"; import type { FileInterface } from "./fileInterface"; import type { UnknownInterface } from "./unknownInterface"; @@ -8,14 +9,14 @@ export interface FolderInterface extends Kind | E.Success>; - exists(): Promise | E.Ok>; - relocate(parentPath: string): Promise | E.Success>; - move(newPath: string): Promise | E.Success>; - remove(): Promise | E.Ok>; - getChildren(): Promise | E.Success>; - stat(): Promise | E.Success>; - walk(): Promise | E.Success>>; + rename(newName: string): Promise | EE.Success>; + exists(): Promise | EE.Ok>; + relocate(parentPath: string): Promise | EE.Success>; + move(newPath: string): Promise | EE.Success>; + remove(): Promise | EE.Ok>; + getChildren(): Promise | EE.Success>; + stat(): Promise | EE.Success>; + walk(): Promise | EE.Success>>; } /** * Create a folder interface with helper methods. diff --git a/docs/libs/v0/file/folderInterface.mjs b/docs/libs/v0/dist/file/folderInterface.mjs similarity index 78% rename from docs/libs/v0/file/folderInterface.mjs rename to docs/libs/v0/dist/file/folderInterface.mjs index 332c1c2..f5deb73 100644 --- a/docs/libs/v0/file/folderInterface.mjs +++ b/docs/libs/v0/dist/file/folderInterface.mjs @@ -1,4 +1,5 @@ -import { asyncPipe, E, innerPipe, Path } from '@duplojs/utils'; +import { asyncPipe, innerPipe, Path } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { createDuplojsServerUtilsKind } from '../kind.mjs'; import { move } from './move.mjs'; import { exists } from './exists.mjs'; @@ -21,13 +22,13 @@ function createFolderInterface(path) { return Path.getParentFolderPath(path); } function localRename(newName) { - return asyncPipe(rename(path, newName), E.whenIsRight(innerPipe(createFolderInterface, E.success))); + return asyncPipe(rename(path, newName), EE.whenIsRight(innerPipe(createFolderInterface, EE.success))); } function localRelocate(newParentPath) { - return asyncPipe(relocate(path, newParentPath), E.whenIsRight(innerPipe(createFolderInterface, E.success))); + return asyncPipe(relocate(path, newParentPath), EE.whenIsRight(innerPipe(createFolderInterface, EE.success))); } function localMove(newPath) { - return asyncPipe(move(path, newPath), E.whenIsRight(() => E.success(createFolderInterface(newPath)))); + return asyncPipe(move(path, newPath), EE.whenIsRight(() => EE.success(createFolderInterface(newPath)))); } function localExists() { return exists(path); diff --git a/docs/libs/v0/file/index.cjs b/docs/libs/v0/dist/file/index.cjs similarity index 100% rename from docs/libs/v0/file/index.cjs rename to docs/libs/v0/dist/file/index.cjs diff --git a/docs/libs/v0/file/index.d.ts b/docs/libs/v0/dist/file/index.d.ts similarity index 100% rename from docs/libs/v0/file/index.d.ts rename to docs/libs/v0/dist/file/index.d.ts diff --git a/docs/libs/v0/file/index.mjs b/docs/libs/v0/dist/file/index.mjs similarity index 100% rename from docs/libs/v0/file/index.mjs rename to docs/libs/v0/dist/file/index.mjs diff --git a/docs/libs/v0/dist/file/link.cjs b/docs/libs/v0/dist/file/link.cjs new file mode 100644 index 0000000..b07f58f --- /dev/null +++ b/docs/libs/v0/dist/file/link.cjs @@ -0,0 +1,41 @@ +'use strict'; + +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/link/index.md} + */ +const link = implementor.implementFunction("link", { + NODE: async (existingPath, newPath) => { + const fs = await implementor.nodeFileSystem.value; + return fs.link(existingPath, newPath) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-link", value)); + }, + DENO: (existingPath, newPath) => Deno + .link(existingPath, newPath) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-link", value)), +}); + +exports.link = link; diff --git a/docs/libs/v0/file/link.d.ts b/docs/libs/v0/dist/file/link.d.ts similarity index 83% rename from docs/libs/v0/file/link.d.ts rename to docs/libs/v0/dist/file/link.d.ts index b085550..1687a75 100644 --- a/docs/libs/v0/file/link.d.ts +++ b/docs/libs/v0/dist/file/link.d.ts @@ -1,8 +1,8 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; declare module "../implementor" { interface ServerUtilsFunction { - link(existingPath: string, newPath: string): Promise | E.Ok>; + link(existingPath: string, newPath: string): Promise | EE.Ok>; } } /** @@ -21,4 +21,4 @@ declare module "../implementor" { * @namespace SF * */ -export declare const link: (existingPath: string, newPath: string) => Promise | E.Ok>; +export declare const link: (existingPath: string, newPath: string) => Promise | EE.Ok>; diff --git a/docs/libs/v0/file/link.mjs b/docs/libs/v0/dist/file/link.mjs similarity index 64% rename from docs/libs/v0/file/link.mjs rename to docs/libs/v0/dist/file/link.mjs index 4df1911..df9aac5 100644 --- a/docs/libs/v0/file/link.mjs +++ b/docs/libs/v0/dist/file/link.mjs @@ -1,4 +1,4 @@ -import { E } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; /** @@ -8,13 +8,13 @@ const link = implementFunction("link", { NODE: async (existingPath, newPath) => { const fs = await nodeFileSystem.value; return fs.link(existingPath, newPath) - .then(E.ok) - .catch((value) => E.left("file-system-link", value)); + .then(EE.ok) + .catch((value) => EE.left("file-system-link", value)); }, DENO: (existingPath, newPath) => Deno .link(existingPath, newPath) - .then(E.ok) - .catch((value) => E.left("file-system-link", value)), + .then(EE.ok) + .catch((value) => EE.left("file-system-link", value)), }); export { link }; diff --git a/docs/libs/v0/dist/file/linkStat.cjs b/docs/libs/v0/dist/file/linkStat.cjs new file mode 100644 index 0000000..c54cd5b --- /dev/null +++ b/docs/libs/v0/dist/file/linkStat.cjs @@ -0,0 +1,106 @@ +'use strict'; + +var utils = require('@duplojs/utils'); +var EE = require('@duplojs/utils/either'); +var DD = require('@duplojs/utils/date'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); +var DD__namespace = /*#__PURE__*/_interopNamespaceDefault(DD); + +function createStatInfoWithFsSource(source) { + return { + isFile: source.isFile(), + isDirectory: source.isDirectory(), + isSymlink: source.isSymbolicLink(), + sizeBytes: source.size, + modifiedAt: DD__namespace.isSafeTimestamp(source.mtime.getTime()) ? DD__namespace.createOrThrow(source.mtime) : null, + accessedAt: DD__namespace.isSafeTimestamp(source.atime.getTime()) ? DD__namespace.createOrThrow(source.atime) : null, + createdAt: DD__namespace.isSafeTimestamp(source.birthtime.getTime()) ? DD__namespace.createOrThrow(source.birthtime) : null, + changedAt: DD__namespace.isSafeTimestamp(source.ctime.getTime()) ? DD__namespace.createOrThrow(source.ctime) : null, + deviceId: source.dev, + inode: source.ino, + permissionsMode: source.mode, + hardLinkCount: source.nlink, + ownerUserId: source.uid, + ownerGroupId: source.gid, + specialDeviceId: source.rdev, + ioBlockSize: source.blksize, + allocatedBlockCount: source.blocks, + isBlockDevice: source.isBlockDevice(), + isCharacterDevice: source.isCharacterDevice(), + isFifo: source.isFIFO(), + isSocket: source.isSocket(), + }; +} +function createStatInfoWithDeno(source) { + return { + isFile: source.isFile, + isDirectory: source.isDirectory, + isSymlink: source.isSymlink, + sizeBytes: source.size, + modifiedAt: source.mtime + && DD__namespace.isSafeTimestamp(source.mtime.getTime()) + ? DD__namespace.createOrThrow(source.mtime) + : null, + accessedAt: source.atime + && DD__namespace.isSafeTimestamp(source.atime.getTime()) + ? DD__namespace.createOrThrow(source.atime) + : null, + createdAt: source.birthtime + && DD__namespace.isSafeTimestamp(source.birthtime.getTime()) + ? DD__namespace.createOrThrow(source.birthtime) + : null, + changedAt: source.ctime + && DD__namespace.isSafeTimestamp(source.ctime.getTime()) + ? DD__namespace.createOrThrow(source.ctime) + : null, + deviceId: source.dev, + inode: source.ino, + permissionsMode: source.mode, + hardLinkCount: source.nlink, + ownerUserId: source.uid, + ownerGroupId: source.gid, + specialDeviceId: source.rdev, + ioBlockSize: source.blksize, + allocatedBlockCount: source.blocks, + isBlockDevice: source.isBlockDevice, + isCharacterDevice: source.isCharDevice, + isFifo: source.isFifo, + isSocket: source.isSocket, + }; +} +/** + * {@include file/linkStat/index.md} + */ +const linkStat = implementor.implementFunction("linkStat", { + NODE: async (path) => { + const fs = await implementor.nodeFileSystem.value; + return fs.lstat(path) + .then(utils.innerPipe(createStatInfoWithFsSource, EE__namespace.success)) + .catch((value) => EE__namespace.left("file-system-link-stat", value)); + }, + DENO: (path) => Deno + .lstat(path) + .then(utils.innerPipe(createStatInfoWithDeno, EE__namespace.success)) + .catch((value) => EE__namespace.left("file-system-link-stat", value)), +}); + +exports.linkStat = linkStat; diff --git a/docs/libs/v0/file/linkStat.d.ts b/docs/libs/v0/dist/file/linkStat.d.ts similarity index 78% rename from docs/libs/v0/file/linkStat.d.ts rename to docs/libs/v0/dist/file/linkStat.d.ts index 9f4c3ce..e8c1a71 100644 --- a/docs/libs/v0/file/linkStat.d.ts +++ b/docs/libs/v0/dist/file/linkStat.d.ts @@ -1,9 +1,9 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { StatInfo } from "./stat"; import type { FileSystemLeft } from "./types"; declare module "../implementor" { interface ServerUtilsFunction { - linkStat(path: GenericPath): Promise | E.Success>; + linkStat(path: GenericPath): Promise | EE.Success>; } } /** @@ -22,4 +22,4 @@ declare module "../implementor" { * @namespace SF * */ -export declare const linkStat: (path: GenericPath) => Promise | E.Success>; +export declare const linkStat: (path: GenericPath) => Promise | EE.Success>; diff --git a/docs/libs/v0/file/linkStat.mjs b/docs/libs/v0/dist/file/linkStat.mjs similarity index 61% rename from docs/libs/v0/file/linkStat.mjs rename to docs/libs/v0/dist/file/linkStat.mjs index 80e24ee..1163e2a 100644 --- a/docs/libs/v0/file/linkStat.mjs +++ b/docs/libs/v0/dist/file/linkStat.mjs @@ -1,4 +1,6 @@ -import { innerPipe, E, D } from '@duplojs/utils'; +import { innerPipe } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; +import * as DD from '@duplojs/utils/date'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; function createStatInfoWithFsSource(source) { @@ -7,10 +9,10 @@ function createStatInfoWithFsSource(source) { isDirectory: source.isDirectory(), isSymlink: source.isSymbolicLink(), sizeBytes: source.size, - modifiedAt: D.isSafeTimestamp(source.mtime.getTime()) ? D.createOrThrow(source.mtime) : null, - accessedAt: D.isSafeTimestamp(source.atime.getTime()) ? D.createOrThrow(source.atime) : null, - createdAt: D.isSafeTimestamp(source.birthtime.getTime()) ? D.createOrThrow(source.birthtime) : null, - changedAt: D.isSafeTimestamp(source.ctime.getTime()) ? D.createOrThrow(source.ctime) : null, + modifiedAt: DD.isSafeTimestamp(source.mtime.getTime()) ? DD.createOrThrow(source.mtime) : null, + accessedAt: DD.isSafeTimestamp(source.atime.getTime()) ? DD.createOrThrow(source.atime) : null, + createdAt: DD.isSafeTimestamp(source.birthtime.getTime()) ? DD.createOrThrow(source.birthtime) : null, + changedAt: DD.isSafeTimestamp(source.ctime.getTime()) ? DD.createOrThrow(source.ctime) : null, deviceId: source.dev, inode: source.ino, permissionsMode: source.mode, @@ -33,20 +35,20 @@ function createStatInfoWithDeno(source) { isSymlink: source.isSymlink, sizeBytes: source.size, modifiedAt: source.mtime - && D.isSafeTimestamp(source.mtime.getTime()) - ? D.createOrThrow(source.mtime) + && DD.isSafeTimestamp(source.mtime.getTime()) + ? DD.createOrThrow(source.mtime) : null, accessedAt: source.atime - && D.isSafeTimestamp(source.atime.getTime()) - ? D.createOrThrow(source.atime) + && DD.isSafeTimestamp(source.atime.getTime()) + ? DD.createOrThrow(source.atime) : null, createdAt: source.birthtime - && D.isSafeTimestamp(source.birthtime.getTime()) - ? D.createOrThrow(source.birthtime) + && DD.isSafeTimestamp(source.birthtime.getTime()) + ? DD.createOrThrow(source.birthtime) : null, changedAt: source.ctime - && D.isSafeTimestamp(source.ctime.getTime()) - ? D.createOrThrow(source.ctime) + && DD.isSafeTimestamp(source.ctime.getTime()) + ? DD.createOrThrow(source.ctime) : null, deviceId: source.dev, inode: source.ino, @@ -70,13 +72,13 @@ const linkStat = implementFunction("linkStat", { NODE: async (path) => { const fs = await nodeFileSystem.value; return fs.lstat(path) - .then(innerPipe(createStatInfoWithFsSource, E.success)) - .catch((value) => E.left("file-system-link-stat", value)); + .then(innerPipe(createStatInfoWithFsSource, EE.success)) + .catch((value) => EE.left("file-system-link-stat", value)); }, DENO: (path) => Deno .lstat(path) - .then(innerPipe(createStatInfoWithDeno, E.success)) - .catch((value) => E.left("file-system-link-stat", value)), + .then(innerPipe(createStatInfoWithDeno, EE.success)) + .catch((value) => EE.left("file-system-link-stat", value)), }); export { linkStat }; diff --git a/docs/libs/v0/dist/file/makeDirectory.cjs b/docs/libs/v0/dist/file/makeDirectory.cjs new file mode 100644 index 0000000..b1055d5 --- /dev/null +++ b/docs/libs/v0/dist/file/makeDirectory.cjs @@ -0,0 +1,44 @@ +'use strict'; + +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/makeDirectory/index.md} + */ +const makeDirectory = implementor.implementFunction("makeDirectory", { + NODE: async (path, params) => { + const fs = await implementor.nodeFileSystem.value; + return fs.mkdir(path, { + recursive: params?.recursive, + }) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-make-directory", value)); + }, + DENO: (path, params) => Deno.mkdir(path, { + recursive: params?.recursive, + }) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-make-directory", value)), +}); + +exports.makeDirectory = makeDirectory; diff --git a/docs/libs/v0/file/makeDirectory.d.ts b/docs/libs/v0/dist/file/makeDirectory.d.ts similarity index 88% rename from docs/libs/v0/file/makeDirectory.d.ts rename to docs/libs/v0/dist/file/makeDirectory.d.ts index a22dccb..ff75cd9 100644 --- a/docs/libs/v0/file/makeDirectory.d.ts +++ b/docs/libs/v0/dist/file/makeDirectory.d.ts @@ -1,11 +1,11 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; interface MakeDirectoryParams { recursive?: boolean; } declare module "../implementor" { interface ServerUtilsFunction { - makeDirectory(path: GenericPath, params?: MakeDirectoryParams): Promise | E.Ok>; + makeDirectory(path: GenericPath, params?: MakeDirectoryParams): Promise | EE.Ok>; } } /** @@ -24,5 +24,5 @@ declare module "../implementor" { * @namespace SF * */ -export declare const makeDirectory: (path: GenericPath, params?: MakeDirectoryParams) => Promise | E.Ok>; +export declare const makeDirectory: (path: GenericPath, params?: MakeDirectoryParams) => Promise | EE.Ok>; export {}; diff --git a/docs/libs/v0/file/makeDirectory.mjs b/docs/libs/v0/dist/file/makeDirectory.mjs similarity index 66% rename from docs/libs/v0/file/makeDirectory.mjs rename to docs/libs/v0/dist/file/makeDirectory.mjs index 73a331e..8c5bff6 100644 --- a/docs/libs/v0/file/makeDirectory.mjs +++ b/docs/libs/v0/dist/file/makeDirectory.mjs @@ -1,4 +1,4 @@ -import { E } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; /** @@ -10,14 +10,14 @@ const makeDirectory = implementFunction("makeDirectory", { return fs.mkdir(path, { recursive: params?.recursive, }) - .then(E.ok) - .catch((value) => E.left("file-system-make-directory", value)); + .then(EE.ok) + .catch((value) => EE.left("file-system-make-directory", value)); }, DENO: (path, params) => Deno.mkdir(path, { recursive: params?.recursive, }) - .then(E.ok) - .catch((value) => E.left("file-system-make-directory", value)), + .then(EE.ok) + .catch((value) => EE.left("file-system-make-directory", value)), }); export { makeDirectory }; diff --git a/docs/libs/v0/dist/file/makeTemporaryDirectory.cjs b/docs/libs/v0/dist/file/makeTemporaryDirectory.cjs new file mode 100644 index 0000000..f2804ff --- /dev/null +++ b/docs/libs/v0/dist/file/makeTemporaryDirectory.cjs @@ -0,0 +1,40 @@ +'use strict'; + +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/makeTemporaryDirectory/index.md} + */ +const makeTemporaryDirectory = implementor.implementFunction("makeTemporaryDirectory", { + NODE: async (prefix) => { + const fs = await implementor.nodeFileSystem.value; + return fs.mkdtemp(prefix) + .then(EE__namespace.success) + .catch((value) => EE__namespace.left("file-system-make-temporary-directory", value)); + }, + DENO: (prefix) => Deno.makeTempDir({ prefix }) + .then(EE__namespace.success) + .catch((value) => EE__namespace.left("file-system-make-temporary-directory", value)), +}); + +exports.makeTemporaryDirectory = makeTemporaryDirectory; diff --git a/docs/libs/v0/file/makeTemporaryDirectory.d.ts b/docs/libs/v0/dist/file/makeTemporaryDirectory.d.ts similarity index 79% rename from docs/libs/v0/file/makeTemporaryDirectory.d.ts rename to docs/libs/v0/dist/file/makeTemporaryDirectory.d.ts index ea21d7d..4445018 100644 --- a/docs/libs/v0/file/makeTemporaryDirectory.d.ts +++ b/docs/libs/v0/dist/file/makeTemporaryDirectory.d.ts @@ -1,8 +1,8 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; declare module "../implementor" { interface ServerUtilsFunction { - makeTemporaryDirectory(prefix: string): Promise | E.Success>; + makeTemporaryDirectory(prefix: string): Promise | EE.Success>; } } /** @@ -21,4 +21,4 @@ declare module "../implementor" { * @namespace SF * */ -export declare const makeTemporaryDirectory: (prefix: string) => Promise | E.Success>; +export declare const makeTemporaryDirectory: (prefix: string) => Promise | EE.Success>; diff --git a/docs/libs/v0/file/makeTemporaryDirectory.mjs b/docs/libs/v0/dist/file/makeTemporaryDirectory.mjs similarity index 60% rename from docs/libs/v0/file/makeTemporaryDirectory.mjs rename to docs/libs/v0/dist/file/makeTemporaryDirectory.mjs index 327f69a..ec41f54 100644 --- a/docs/libs/v0/file/makeTemporaryDirectory.mjs +++ b/docs/libs/v0/dist/file/makeTemporaryDirectory.mjs @@ -1,4 +1,4 @@ -import { E } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; /** @@ -8,12 +8,12 @@ const makeTemporaryDirectory = implementFunction("makeTemporaryDirectory", { NODE: async (prefix) => { const fs = await nodeFileSystem.value; return fs.mkdtemp(prefix) - .then(E.success) - .catch((value) => E.left("file-system-make-temporary-directory", value)); + .then(EE.success) + .catch((value) => EE.left("file-system-make-temporary-directory", value)); }, DENO: (prefix) => Deno.makeTempDir({ prefix }) - .then(E.success) - .catch((value) => E.left("file-system-make-temporary-directory", value)), + .then(EE.success) + .catch((value) => EE.left("file-system-make-temporary-directory", value)), }); export { makeTemporaryDirectory }; diff --git a/docs/libs/v0/dist/file/makeTemporaryFile.cjs b/docs/libs/v0/dist/file/makeTemporaryFile.cjs new file mode 100644 index 0000000..37a0655 --- /dev/null +++ b/docs/libs/v0/dist/file/makeTemporaryFile.cjs @@ -0,0 +1,51 @@ +'use strict'; + +var utils = require('@duplojs/utils'); +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/makeTemporaryFile/index.md} + */ +const makeTemporaryFile = implementor.implementFunction("makeTemporaryFile", { + NODE: async (prefix, suffix) => { + const fs = await implementor.nodeFileSystem.value; + const os = await implementor.nodeOs.value; + const crypto = await implementor.nodeCrypto.value; + const fileTemporaryPath = utils.Path.resolveRelative([ + os.tmpdir(), + `${prefix}${crypto.randomUUID()}${suffix ?? ""}`, + ]); + return fs.open(fileTemporaryPath, "wx") + .then((fh) => fh.close()) + .then(() => EE__namespace.success(fileTemporaryPath)) + .catch((value) => EE__namespace.left("file-system-make-temporary-file", value)); + }, + DENO: (prefix, suffix) => Deno.makeTempFile({ + prefix, + suffix, + }) + .then(EE__namespace.success) + .catch((value) => EE__namespace.left("file-system-make-temporary-file", value)), +}); + +exports.makeTemporaryFile = makeTemporaryFile; diff --git a/docs/libs/v0/file/makeTemporaryFile.d.ts b/docs/libs/v0/dist/file/makeTemporaryFile.d.ts similarity index 78% rename from docs/libs/v0/file/makeTemporaryFile.d.ts rename to docs/libs/v0/dist/file/makeTemporaryFile.d.ts index 3e47231..2fdfd69 100644 --- a/docs/libs/v0/file/makeTemporaryFile.d.ts +++ b/docs/libs/v0/dist/file/makeTemporaryFile.d.ts @@ -1,8 +1,8 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; declare module "../implementor" { interface ServerUtilsFunction { - makeTemporaryFile(prefix: string, suffix?: string): Promise | E.Success>; + makeTemporaryFile(prefix: string, suffix?: string): Promise | EE.Success>; } } /** @@ -21,4 +21,4 @@ declare module "../implementor" { * @namespace SF * */ -export declare const makeTemporaryFile: (prefix: string, suffix?: string) => Promise | E.Success>; +export declare const makeTemporaryFile: (prefix: string, suffix?: string) => Promise | EE.Success>; diff --git a/docs/libs/v0/file/makeTemporaryFile.mjs b/docs/libs/v0/dist/file/makeTemporaryFile.mjs similarity index 69% rename from docs/libs/v0/file/makeTemporaryFile.mjs rename to docs/libs/v0/dist/file/makeTemporaryFile.mjs index 98a3927..a213fd9 100644 --- a/docs/libs/v0/file/makeTemporaryFile.mjs +++ b/docs/libs/v0/dist/file/makeTemporaryFile.mjs @@ -1,4 +1,5 @@ -import { E, Path } from '@duplojs/utils'; +import { Path } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem, nodeOs, nodeCrypto } from '../implementor.mjs'; /** @@ -15,15 +16,15 @@ const makeTemporaryFile = implementFunction("makeTemporaryFile", { ]); return fs.open(fileTemporaryPath, "wx") .then((fh) => fh.close()) - .then(() => E.success(fileTemporaryPath)) - .catch((value) => E.left("file-system-make-temporary-file", value)); + .then(() => EE.success(fileTemporaryPath)) + .catch((value) => EE.left("file-system-make-temporary-file", value)); }, DENO: (prefix, suffix) => Deno.makeTempFile({ prefix, suffix, }) - .then(E.success) - .catch((value) => E.left("file-system-make-temporary-file", value)), + .then(EE.success) + .catch((value) => EE.left("file-system-make-temporary-file", value)), }); export { makeTemporaryFile }; diff --git a/docs/libs/v0/dist/file/move.cjs b/docs/libs/v0/dist/file/move.cjs new file mode 100644 index 0000000..9c31f82 --- /dev/null +++ b/docs/libs/v0/dist/file/move.cjs @@ -0,0 +1,40 @@ +'use strict'; + +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/move/index.md} + */ +const move = implementor.implementFunction("move", { + NODE: async (fromPath, toPath) => { + const fs = await implementor.nodeFileSystem.value; + return fs.rename(fromPath, toPath) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-move", value)); + }, + DENO: (fromPath, toPath) => Deno.rename(fromPath, toPath) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-move", value)), +}); + +exports.move = move; diff --git a/docs/libs/v0/file/move.d.ts b/docs/libs/v0/dist/file/move.d.ts similarity index 84% rename from docs/libs/v0/file/move.d.ts rename to docs/libs/v0/dist/file/move.d.ts index 654f0a7..118aaeb 100644 --- a/docs/libs/v0/file/move.d.ts +++ b/docs/libs/v0/dist/file/move.d.ts @@ -1,8 +1,8 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; declare module "../implementor" { interface ServerUtilsFunction { - move(fromPath: string, toPath: string): Promise | E.Ok>; + move(fromPath: string, toPath: string): Promise | EE.Ok>; } } /** @@ -21,4 +21,4 @@ declare module "../implementor" { * @namespace SF * */ -export declare const move: (fromPath: string, toPath: string) => Promise | E.Ok>; +export declare const move: (fromPath: string, toPath: string) => Promise | EE.Ok>; diff --git a/docs/libs/v0/file/move.mjs b/docs/libs/v0/dist/file/move.mjs similarity index 62% rename from docs/libs/v0/file/move.mjs rename to docs/libs/v0/dist/file/move.mjs index 5a4dda6..771988f 100644 --- a/docs/libs/v0/file/move.mjs +++ b/docs/libs/v0/dist/file/move.mjs @@ -1,4 +1,4 @@ -import { E } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; /** @@ -8,12 +8,12 @@ const move = implementFunction("move", { NODE: async (fromPath, toPath) => { const fs = await nodeFileSystem.value; return fs.rename(fromPath, toPath) - .then(E.ok) - .catch((value) => E.left("file-system-move", value)); + .then(EE.ok) + .catch((value) => EE.left("file-system-move", value)); }, DENO: (fromPath, toPath) => Deno.rename(fromPath, toPath) - .then(E.ok) - .catch((value) => E.left("file-system-move", value)), + .then(EE.ok) + .catch((value) => EE.left("file-system-move", value)), }); export { move }; diff --git a/docs/libs/v0/dist/file/readDirectory.cjs b/docs/libs/v0/dist/file/readDirectory.cjs new file mode 100644 index 0000000..6d868f5 --- /dev/null +++ b/docs/libs/v0/dist/file/readDirectory.cjs @@ -0,0 +1,37 @@ +'use strict'; + +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/readDirectory/index.md} + */ +const readDirectory = implementor.implementFunction("readDirectory", { + NODE: async (path, params) => { + const fs = await implementor.nodeFileSystem.value; + return fs.readdir(path, { recursive: params?.recursive }) + .then(EE__namespace.success) + .catch((value) => EE__namespace.left("file-system-read-directory", value)); + }, +}); + +exports.readDirectory = readDirectory; diff --git a/docs/libs/v0/file/readDirectory.d.ts b/docs/libs/v0/dist/file/readDirectory.d.ts similarity index 86% rename from docs/libs/v0/file/readDirectory.d.ts rename to docs/libs/v0/dist/file/readDirectory.d.ts index 7d06c2e..76c7a5a 100644 --- a/docs/libs/v0/file/readDirectory.d.ts +++ b/docs/libs/v0/dist/file/readDirectory.d.ts @@ -1,11 +1,11 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; interface ReadDirectoryParams { recursive?: boolean; } declare module "../implementor" { interface ServerUtilsFunction { - readDirectory(path: GenericPath, params?: ReadDirectoryParams): Promise | E.Success>; + readDirectory(path: GenericPath, params?: ReadDirectoryParams): Promise | EE.Success>; } } /** @@ -24,5 +24,5 @@ declare module "../implementor" { * @namespace SF * */ -export declare const readDirectory: (path: GenericPath, params?: ReadDirectoryParams) => Promise | E.Success>; +export declare const readDirectory: (path: GenericPath, params?: ReadDirectoryParams) => Promise | EE.Success>; export {}; diff --git a/docs/libs/v0/file/readDirectory.mjs b/docs/libs/v0/dist/file/readDirectory.mjs similarity index 70% rename from docs/libs/v0/file/readDirectory.mjs rename to docs/libs/v0/dist/file/readDirectory.mjs index 71e6fee..e6848c6 100644 --- a/docs/libs/v0/file/readDirectory.mjs +++ b/docs/libs/v0/dist/file/readDirectory.mjs @@ -1,4 +1,4 @@ -import { E } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; /** @@ -8,8 +8,8 @@ const readDirectory = implementFunction("readDirectory", { NODE: async (path, params) => { const fs = await nodeFileSystem.value; return fs.readdir(path, { recursive: params?.recursive }) - .then(E.success) - .catch((value) => E.left("file-system-read-directory", value)); + .then(EE.success) + .catch((value) => EE.left("file-system-read-directory", value)); }, }); diff --git a/docs/libs/v0/dist/file/readFile.cjs b/docs/libs/v0/dist/file/readFile.cjs new file mode 100644 index 0000000..95378d2 --- /dev/null +++ b/docs/libs/v0/dist/file/readFile.cjs @@ -0,0 +1,45 @@ +'use strict'; + +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/readFile/index.md} + */ +const readFile = implementor.implementFunction("readFile", { + NODE: async (path) => { + const fs = await implementor.nodeFileSystem.value; + return fs.readFile(path) + .then(EE__namespace.success) + .catch((value) => EE__namespace.left("file-system-read-file", value)); + }, + DENO: (path) => Deno + .readFile(path) + .then(EE__namespace.success) + .catch((value) => EE__namespace.left("file-system-read-file", value)), + BUN: (path) => Bun.file(path) + .bytes() + .then(EE__namespace.success) + .catch((value) => EE__namespace.left("file-system-read-file", value)), +}); + +exports.readFile = readFile; diff --git a/docs/libs/v0/file/readFile.d.ts b/docs/libs/v0/dist/file/readFile.d.ts similarity index 77% rename from docs/libs/v0/file/readFile.d.ts rename to docs/libs/v0/dist/file/readFile.d.ts index 84ef0cc..64f904f 100644 --- a/docs/libs/v0/file/readFile.d.ts +++ b/docs/libs/v0/dist/file/readFile.d.ts @@ -1,8 +1,8 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; declare module "../implementor" { interface ServerUtilsFunction { - readFile(path: GenericPath): Promise | E.Success>; + readFile(path: GenericPath): Promise | EE.Success>; } } /** @@ -21,4 +21,4 @@ declare module "../implementor" { * @namespace SF * */ -export declare const readFile: (path: GenericPath) => Promise | E.Success>; +export declare const readFile: (path: GenericPath) => Promise | EE.Success>; diff --git a/docs/libs/v0/file/readFile.mjs b/docs/libs/v0/dist/file/readFile.mjs similarity index 54% rename from docs/libs/v0/file/readFile.mjs rename to docs/libs/v0/dist/file/readFile.mjs index 9998b3a..8b31966 100644 --- a/docs/libs/v0/file/readFile.mjs +++ b/docs/libs/v0/dist/file/readFile.mjs @@ -1,4 +1,4 @@ -import { E } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; /** @@ -8,17 +8,17 @@ const readFile = implementFunction("readFile", { NODE: async (path) => { const fs = await nodeFileSystem.value; return fs.readFile(path) - .then(E.success) - .catch((value) => E.left("file-system-read-file", value)); + .then(EE.success) + .catch((value) => EE.left("file-system-read-file", value)); }, DENO: (path) => Deno .readFile(path) - .then(E.success) - .catch((value) => E.left("file-system-read-file", value)), + .then(EE.success) + .catch((value) => EE.left("file-system-read-file", value)), BUN: (path) => Bun.file(path) .bytes() - .then(E.success) - .catch((value) => E.left("file-system-read-file", value)), + .then(EE.success) + .catch((value) => EE.left("file-system-read-file", value)), }); export { readFile }; diff --git a/docs/libs/v0/dist/file/readJsonFile.cjs b/docs/libs/v0/dist/file/readJsonFile.cjs new file mode 100644 index 0000000..1f79b86 --- /dev/null +++ b/docs/libs/v0/dist/file/readJsonFile.cjs @@ -0,0 +1,47 @@ +'use strict'; + +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/readJsonFile/index.md} + */ +const readJsonFile = implementor.implementFunction("readJsonFile", { + NODE: async (path) => { + const fs = await implementor.nodeFileSystem.value; + return fs.readFile(path, { encoding: "utf-8" }) + .then(JSON.parse) + .then(EE__namespace.success) + .catch((value) => EE__namespace.left("file-system-read-json-file", value)); + }, + DENO: (path) => Deno.readTextFile(path) + .then(JSON.parse) + .then(EE__namespace.success) + .catch((value) => EE__namespace.left("file-system-read-json-file", value)), + BUN: (path) => Bun.file(path) + .text() + .then(JSON.parse) + .then(EE__namespace.success) + .catch((value) => EE__namespace.left("file-system-read-json-file", value)), +}); + +exports.readJsonFile = readJsonFile; diff --git a/docs/libs/v0/file/readJsonFile.d.ts b/docs/libs/v0/dist/file/readJsonFile.d.ts similarity index 82% rename from docs/libs/v0/file/readJsonFile.d.ts rename to docs/libs/v0/dist/file/readJsonFile.d.ts index 4da8a74..2500960 100644 --- a/docs/libs/v0/file/readJsonFile.d.ts +++ b/docs/libs/v0/dist/file/readJsonFile.d.ts @@ -1,8 +1,8 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; declare module "../implementor" { interface ServerUtilsFunction { - readJsonFile(path: GenericPath): Promise | E.Success>; + readJsonFile(path: GenericPath): Promise | EE.Success>; } } /** @@ -21,4 +21,4 @@ declare module "../implementor" { * @namespace SF * */ -export declare const readJsonFile: (path: GenericPath) => Promise | E.Success>; +export declare const readJsonFile: (path: GenericPath) => Promise | EE.Success>; diff --git a/docs/libs/v0/file/readJsonFile.mjs b/docs/libs/v0/dist/file/readJsonFile.mjs similarity index 59% rename from docs/libs/v0/file/readJsonFile.mjs rename to docs/libs/v0/dist/file/readJsonFile.mjs index 05b3b5e..8adc4f4 100644 --- a/docs/libs/v0/file/readJsonFile.mjs +++ b/docs/libs/v0/dist/file/readJsonFile.mjs @@ -1,4 +1,4 @@ -import { E } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; /** @@ -9,18 +9,18 @@ const readJsonFile = implementFunction("readJsonFile", { const fs = await nodeFileSystem.value; return fs.readFile(path, { encoding: "utf-8" }) .then(JSON.parse) - .then(E.success) - .catch((value) => E.left("file-system-read-json-file", value)); + .then(EE.success) + .catch((value) => EE.left("file-system-read-json-file", value)); }, DENO: (path) => Deno.readTextFile(path) .then(JSON.parse) - .then(E.success) - .catch((value) => E.left("file-system-read-json-file", value)), + .then(EE.success) + .catch((value) => EE.left("file-system-read-json-file", value)), BUN: (path) => Bun.file(path) .text() .then(JSON.parse) - .then(E.success) - .catch((value) => E.left("file-system-read-json-file", value)), + .then(EE.success) + .catch((value) => EE.left("file-system-read-json-file", value)), }); export { readJsonFile }; diff --git a/docs/libs/v0/dist/file/readLink.cjs b/docs/libs/v0/dist/file/readLink.cjs new file mode 100644 index 0000000..3f91d1a --- /dev/null +++ b/docs/libs/v0/dist/file/readLink.cjs @@ -0,0 +1,41 @@ +'use strict'; + +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/readLink/index.md} + */ +const readLink = implementor.implementFunction("readLink", { + NODE: async (path) => { + const fs = await implementor.nodeFileSystem.value; + return fs.readlink(path, { encoding: "utf-8" }) + .then(EE__namespace.success) + .catch((value) => EE__namespace.left("file-system-read-link", value)); + }, + DENO: (path) => Deno + .readLink(path) + .then(EE__namespace.success) + .catch((value) => EE__namespace.left("file-system-read-link", value)), +}); + +exports.readLink = readLink; diff --git a/docs/libs/v0/file/readLink.d.ts b/docs/libs/v0/dist/file/readLink.d.ts similarity index 77% rename from docs/libs/v0/file/readLink.d.ts rename to docs/libs/v0/dist/file/readLink.d.ts index 1804b72..aac8fce 100644 --- a/docs/libs/v0/file/readLink.d.ts +++ b/docs/libs/v0/dist/file/readLink.d.ts @@ -1,8 +1,8 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; declare module "../implementor" { interface ServerUtilsFunction { - readLink(path: GenericPath): Promise | E.Success>; + readLink(path: GenericPath): Promise | EE.Success>; } } /** @@ -21,4 +21,4 @@ declare module "../implementor" { * @namespace SF * */ -export declare const readLink: (path: GenericPath) => Promise | E.Success>; +export declare const readLink: (path: GenericPath) => Promise | EE.Success>; diff --git a/docs/libs/v0/file/readLink.mjs b/docs/libs/v0/dist/file/readLink.mjs similarity index 61% rename from docs/libs/v0/file/readLink.mjs rename to docs/libs/v0/dist/file/readLink.mjs index 9a33f39..ee9a52f 100644 --- a/docs/libs/v0/file/readLink.mjs +++ b/docs/libs/v0/dist/file/readLink.mjs @@ -1,4 +1,4 @@ -import { E } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; /** @@ -8,13 +8,13 @@ const readLink = implementFunction("readLink", { NODE: async (path) => { const fs = await nodeFileSystem.value; return fs.readlink(path, { encoding: "utf-8" }) - .then(E.success) - .catch((value) => E.left("file-system-read-link", value)); + .then(EE.success) + .catch((value) => EE.left("file-system-read-link", value)); }, DENO: (path) => Deno .readLink(path) - .then(E.success) - .catch((value) => E.left("file-system-read-link", value)), + .then(EE.success) + .catch((value) => EE.left("file-system-read-link", value)), }); export { readLink }; diff --git a/docs/libs/v0/dist/file/readTextFile.cjs b/docs/libs/v0/dist/file/readTextFile.cjs new file mode 100644 index 0000000..2145798 --- /dev/null +++ b/docs/libs/v0/dist/file/readTextFile.cjs @@ -0,0 +1,45 @@ +'use strict'; + +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/readTextFile/index.md} + */ +const readTextFile = implementor.implementFunction("readTextFile", { + NODE: async (path) => { + const fs = await implementor.nodeFileSystem.value; + return fs.readFile(path, { encoding: "utf-8" }) + .then(EE__namespace.success) + .catch((value) => EE__namespace.left("file-system-read-text-file", value)); + }, + DENO: (path) => Deno + .readTextFile(path) + .then(EE__namespace.success) + .catch((value) => EE__namespace.left("file-system-read-text-file", value)), + BUN: (path) => Bun.file(path) + .text() + .then(EE__namespace.success) + .catch((value) => EE__namespace.left("file-system-read-text-file", value)), +}); + +exports.readTextFile = readTextFile; diff --git a/docs/libs/v0/file/readTextFile.d.ts b/docs/libs/v0/dist/file/readTextFile.d.ts similarity index 84% rename from docs/libs/v0/file/readTextFile.d.ts rename to docs/libs/v0/dist/file/readTextFile.d.ts index aa8b48f..59d54cf 100644 --- a/docs/libs/v0/file/readTextFile.d.ts +++ b/docs/libs/v0/dist/file/readTextFile.d.ts @@ -1,8 +1,8 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; declare module "../implementor" { interface ServerUtilsFunction { - readTextFile(path: GenericPath): Promise | E.Success>; + readTextFile(path: GenericPath): Promise | EE.Success>; } } /** @@ -21,4 +21,4 @@ declare module "../implementor" { * @namespace SF * */ -export declare const readTextFile: (path: GenericPath) => Promise | E.Success>; +export declare const readTextFile: (path: GenericPath) => Promise | EE.Success>; diff --git a/docs/libs/v0/file/readTextFile.mjs b/docs/libs/v0/dist/file/readTextFile.mjs similarity index 56% rename from docs/libs/v0/file/readTextFile.mjs rename to docs/libs/v0/dist/file/readTextFile.mjs index 239b84b..c6d5be2 100644 --- a/docs/libs/v0/file/readTextFile.mjs +++ b/docs/libs/v0/dist/file/readTextFile.mjs @@ -1,4 +1,4 @@ -import { E } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; /** @@ -8,17 +8,17 @@ const readTextFile = implementFunction("readTextFile", { NODE: async (path) => { const fs = await nodeFileSystem.value; return fs.readFile(path, { encoding: "utf-8" }) - .then(E.success) - .catch((value) => E.left("file-system-read-text-file", value)); + .then(EE.success) + .catch((value) => EE.left("file-system-read-text-file", value)); }, DENO: (path) => Deno .readTextFile(path) - .then(E.success) - .catch((value) => E.left("file-system-read-text-file", value)), + .then(EE.success) + .catch((value) => EE.left("file-system-read-text-file", value)), BUN: (path) => Bun.file(path) .text() - .then(E.success) - .catch((value) => E.left("file-system-read-text-file", value)), + .then(EE.success) + .catch((value) => EE.left("file-system-read-text-file", value)), }); export { readTextFile }; diff --git a/docs/libs/v0/dist/file/realPath.cjs b/docs/libs/v0/dist/file/realPath.cjs new file mode 100644 index 0000000..5cdb609 --- /dev/null +++ b/docs/libs/v0/dist/file/realPath.cjs @@ -0,0 +1,41 @@ +'use strict'; + +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/realPath/index.md} + */ +const realPath = implementor.implementFunction("realPath", { + NODE: async (path) => { + const fs = await implementor.nodeFileSystem.value; + return fs.realpath(path) + .then(EE__namespace.success) + .catch((value) => EE__namespace.left("file-system-real-path", value)); + }, + DENO: (path) => Deno + .realPath(path) + .then(EE__namespace.success) + .catch((value) => EE__namespace.left("file-system-real-path", value)), +}); + +exports.realPath = realPath; diff --git a/docs/libs/v0/file/realPath.d.ts b/docs/libs/v0/dist/file/realPath.d.ts similarity index 78% rename from docs/libs/v0/file/realPath.d.ts rename to docs/libs/v0/dist/file/realPath.d.ts index 765acfc..f668abf 100644 --- a/docs/libs/v0/file/realPath.d.ts +++ b/docs/libs/v0/dist/file/realPath.d.ts @@ -1,8 +1,8 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; declare module "../implementor" { interface ServerUtilsFunction { - realPath(path: GenericPath): Promise | E.Success>; + realPath(path: GenericPath): Promise | EE.Success>; } } /** @@ -21,4 +21,4 @@ declare module "../implementor" { * @namespace SF * */ -export declare const realPath: (path: GenericPath) => Promise | E.Success>; +export declare const realPath: (path: GenericPath) => Promise | EE.Success>; diff --git a/docs/libs/v0/file/realPath.mjs b/docs/libs/v0/dist/file/realPath.mjs similarity index 59% rename from docs/libs/v0/file/realPath.mjs rename to docs/libs/v0/dist/file/realPath.mjs index db257b6..e46ea63 100644 --- a/docs/libs/v0/file/realPath.mjs +++ b/docs/libs/v0/dist/file/realPath.mjs @@ -1,4 +1,4 @@ -import { E } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; /** @@ -8,13 +8,13 @@ const realPath = implementFunction("realPath", { NODE: async (path) => { const fs = await nodeFileSystem.value; return fs.realpath(path) - .then(E.success) - .catch((value) => E.left("file-system-real-path", value)); + .then(EE.success) + .catch((value) => EE.left("file-system-real-path", value)); }, DENO: (path) => Deno .realPath(path) - .then(E.success) - .catch((value) => E.left("file-system-real-path", value)), + .then(EE.success) + .catch((value) => EE.left("file-system-real-path", value)), }); export { realPath }; diff --git a/docs/libs/v0/dist/file/relocate.cjs b/docs/libs/v0/dist/file/relocate.cjs new file mode 100644 index 0000000..7878813 --- /dev/null +++ b/docs/libs/v0/dist/file/relocate.cjs @@ -0,0 +1,53 @@ +'use strict'; + +var utils = require('@duplojs/utils'); +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/relocate/index.md} + */ +const relocate = implementor.implementFunction("relocate", { + NODE: async (fromPath, newParentPath) => { + const fs = await implementor.nodeFileSystem.value; + const baseName = utils.Path.getBaseName(fromPath); + if (!baseName) { + return EE__namespace.left("file-system-relocate", new Error(`Invalid base name ${fromPath}`)); + } + const newPath = utils.Path.resolveRelative([newParentPath, baseName]); + return fs.rename(fromPath, newPath) + .then(() => EE__namespace.success(newPath)) + .catch((value) => EE__namespace.left("file-system-relocate", value)); + }, + DENO: (fromPath, newParentPath) => { + const baseName = utils.Path.getBaseName(fromPath); + if (!baseName) { + return Promise.resolve(EE__namespace.left("file-system-relocate", new Error(`Invalid base name ${fromPath}`))); + } + const newPath = utils.Path.resolveRelative([newParentPath, baseName]); + return Deno.rename(fromPath, newPath) + .then(() => EE__namespace.success(newPath)) + .catch((value) => EE__namespace.left("file-system-relocate", value)); + }, +}); + +exports.relocate = relocate; diff --git a/docs/libs/v0/file/relocate.d.ts b/docs/libs/v0/dist/file/relocate.d.ts similarity index 86% rename from docs/libs/v0/file/relocate.d.ts rename to docs/libs/v0/dist/file/relocate.d.ts index a0c8524..77c0f45 100644 --- a/docs/libs/v0/file/relocate.d.ts +++ b/docs/libs/v0/dist/file/relocate.d.ts @@ -1,8 +1,8 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; declare module "../implementor" { interface ServerUtilsFunction { - relocate(fromPath: string, toPath: string): Promise | E.Success>; + relocate(fromPath: string, toPath: string): Promise | EE.Success>; } } /** @@ -31,4 +31,4 @@ declare module "../implementor" { * @namespace SF * */ -export declare const relocate: (fromPath: string, toPath: string) => Promise | E.Success>; +export declare const relocate: (fromPath: string, toPath: string) => Promise | EE.Success>; diff --git a/docs/libs/v0/file/relocate.mjs b/docs/libs/v0/dist/file/relocate.mjs similarity index 58% rename from docs/libs/v0/file/relocate.mjs rename to docs/libs/v0/dist/file/relocate.mjs index bdb72b2..8586a9f 100644 --- a/docs/libs/v0/file/relocate.mjs +++ b/docs/libs/v0/dist/file/relocate.mjs @@ -1,4 +1,5 @@ -import { Path, E } from '@duplojs/utils'; +import { Path } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; /** @@ -9,22 +10,22 @@ const relocate = implementFunction("relocate", { const fs = await nodeFileSystem.value; const baseName = Path.getBaseName(fromPath); if (!baseName) { - return E.left("file-system-relocate", new Error(`Invalid base name ${fromPath}`)); + return EE.left("file-system-relocate", new Error(`Invalid base name ${fromPath}`)); } const newPath = Path.resolveRelative([newParentPath, baseName]); return fs.rename(fromPath, newPath) - .then(() => E.success(newPath)) - .catch((value) => E.left("file-system-relocate", value)); + .then(() => EE.success(newPath)) + .catch((value) => EE.left("file-system-relocate", value)); }, DENO: (fromPath, newParentPath) => { const baseName = Path.getBaseName(fromPath); if (!baseName) { - return Promise.resolve(E.left("file-system-relocate", new Error(`Invalid base name ${fromPath}`))); + return Promise.resolve(EE.left("file-system-relocate", new Error(`Invalid base name ${fromPath}`))); } const newPath = Path.resolveRelative([newParentPath, baseName]); return Deno.rename(fromPath, newPath) - .then(() => E.success(newPath)) - .catch((value) => E.left("file-system-relocate", value)); + .then(() => EE.success(newPath)) + .catch((value) => EE.left("file-system-relocate", value)); }, }); diff --git a/docs/libs/v0/dist/file/remove.cjs b/docs/libs/v0/dist/file/remove.cjs new file mode 100644 index 0000000..38c3bb7 --- /dev/null +++ b/docs/libs/v0/dist/file/remove.cjs @@ -0,0 +1,45 @@ +'use strict'; + +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/remove/index.md} + */ +const remove = implementor.implementFunction("remove", { + NODE: async (path, params) => { + const fs = await implementor.nodeFileSystem.value; + return fs.rm(path, { + recursive: params?.recursive ?? false, + force: true, + }) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-remove", value)); + }, + DENO: (path, params) => Deno.remove(path, { + recursive: params?.recursive, + }) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-remove", value)), +}); + +exports.remove = remove; diff --git a/docs/libs/v0/file/remove.d.ts b/docs/libs/v0/dist/file/remove.d.ts similarity index 91% rename from docs/libs/v0/file/remove.d.ts rename to docs/libs/v0/dist/file/remove.d.ts index 6829c8d..685566b 100644 --- a/docs/libs/v0/file/remove.d.ts +++ b/docs/libs/v0/dist/file/remove.d.ts @@ -1,11 +1,11 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; interface RemoveDirectoryParams { recursive?: boolean; } declare module "../implementor" { interface ServerUtilsFunction { - remove(path: GenericPath, params?: RemoveDirectoryParams): Promise | E.Ok>; + remove(path: GenericPath, params?: RemoveDirectoryParams): Promise | EE.Ok>; } } /** @@ -24,5 +24,5 @@ declare module "../implementor" { * @namespace SF * */ -export declare const remove: (path: GenericPath, params?: RemoveDirectoryParams) => Promise | E.Ok>; +export declare const remove: (path: GenericPath, params?: RemoveDirectoryParams) => Promise | EE.Ok>; export {}; diff --git a/docs/libs/v0/file/remove.mjs b/docs/libs/v0/dist/file/remove.mjs similarity index 68% rename from docs/libs/v0/file/remove.mjs rename to docs/libs/v0/dist/file/remove.mjs index fd39353..4028b58 100644 --- a/docs/libs/v0/file/remove.mjs +++ b/docs/libs/v0/dist/file/remove.mjs @@ -1,4 +1,4 @@ -import { E } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; /** @@ -11,14 +11,14 @@ const remove = implementFunction("remove", { recursive: params?.recursive ?? false, force: true, }) - .then(E.ok) - .catch((value) => E.left("file-system-remove", value)); + .then(EE.ok) + .catch((value) => EE.left("file-system-remove", value)); }, DENO: (path, params) => Deno.remove(path, { recursive: params?.recursive, }) - .then(E.ok) - .catch((value) => E.left("file-system-remove", value)), + .then(EE.ok) + .catch((value) => EE.left("file-system-remove", value)), }); export { remove }; diff --git a/docs/libs/v0/dist/file/rename.cjs b/docs/libs/v0/dist/file/rename.cjs new file mode 100644 index 0000000..3d9fec9 --- /dev/null +++ b/docs/libs/v0/dist/file/rename.cjs @@ -0,0 +1,59 @@ +'use strict'; + +var utils = require('@duplojs/utils'); +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/rename/index.md} + */ +const rename = implementor.implementFunction("rename", { + NODE: async (path, newName) => { + const fs = await implementor.nodeFileSystem.value; + const parentPath = utils.Path.getParentFolderPath(path); + if (!parentPath) { + return EE__namespace.left("file-system-rename", new Error(`Invalid parent path ${parentPath}.`)); + } + if (newName.includes("/")) { + return EE__namespace.left("file-system-rename", new Error(`Invalid new name ${newName}.`)); + } + const newPath = utils.Path.resolveRelative([parentPath, newName]); + return fs.rename(path, newPath) + .then(() => EE__namespace.success(newPath)) + .catch((value) => EE__namespace.left("file-system-rename", value)); + }, + DENO: (path, newName) => { + const parentPath = utils.Path.getParentFolderPath(path); + if (!parentPath) { + return Promise.resolve(EE__namespace.left("file-system-rename", new Error(`Invalid parent path ${parentPath}.`))); + } + if (newName.includes("/")) { + return Promise.resolve(EE__namespace.left("file-system-rename", new Error(`Invalid new name ${newName}.`))); + } + const newPath = utils.Path.resolveRelative([parentPath, newName]); + return Deno.rename(path, newPath) + .then(() => EE__namespace.success(newPath)) + .catch((value) => EE__namespace.left("file-system-rename", value)); + }, +}); + +exports.rename = rename; diff --git a/docs/libs/v0/file/rename.d.ts b/docs/libs/v0/dist/file/rename.d.ts similarity index 85% rename from docs/libs/v0/file/rename.d.ts rename to docs/libs/v0/dist/file/rename.d.ts index 512b49b..ac08853 100644 --- a/docs/libs/v0/file/rename.d.ts +++ b/docs/libs/v0/dist/file/rename.d.ts @@ -1,8 +1,8 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; declare module "../implementor" { interface ServerUtilsFunction { - rename(path: string, newName: string): Promise | E.Success>; + rename(path: string, newName: string): Promise | EE.Success>; } } /** @@ -26,4 +26,4 @@ declare module "../implementor" { * @namespace SF * */ -export declare const rename: (path: string, newName: string) => Promise | E.Success>; +export declare const rename: (path: string, newName: string) => Promise | EE.Success>; diff --git a/docs/libs/v0/file/rename.mjs b/docs/libs/v0/dist/file/rename.mjs similarity index 52% rename from docs/libs/v0/file/rename.mjs rename to docs/libs/v0/dist/file/rename.mjs index 35b23c3..b64a284 100644 --- a/docs/libs/v0/file/rename.mjs +++ b/docs/libs/v0/dist/file/rename.mjs @@ -1,4 +1,5 @@ -import { Path, E } from '@duplojs/utils'; +import { Path } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; /** @@ -9,28 +10,28 @@ const rename = implementFunction("rename", { const fs = await nodeFileSystem.value; const parentPath = Path.getParentFolderPath(path); if (!parentPath) { - return E.left("file-system-rename", new Error(`Invalid parent path ${parentPath}.`)); + return EE.left("file-system-rename", new Error(`Invalid parent path ${parentPath}.`)); } if (newName.includes("/")) { - return E.left("file-system-rename", new Error(`Invalid new name ${newName}.`)); + return EE.left("file-system-rename", new Error(`Invalid new name ${newName}.`)); } const newPath = Path.resolveRelative([parentPath, newName]); return fs.rename(path, newPath) - .then(() => E.success(newPath)) - .catch((value) => E.left("file-system-rename", value)); + .then(() => EE.success(newPath)) + .catch((value) => EE.left("file-system-rename", value)); }, DENO: (path, newName) => { const parentPath = Path.getParentFolderPath(path); if (!parentPath) { - return Promise.resolve(E.left("file-system-rename", new Error(`Invalid parent path ${parentPath}.`))); + return Promise.resolve(EE.left("file-system-rename", new Error(`Invalid parent path ${parentPath}.`))); } if (newName.includes("/")) { - return Promise.resolve(E.left("file-system-rename", new Error(`Invalid new name ${newName}.`))); + return Promise.resolve(EE.left("file-system-rename", new Error(`Invalid new name ${newName}.`))); } const newPath = Path.resolveRelative([parentPath, newName]); return Deno.rename(path, newPath) - .then(() => E.success(newPath)) - .catch((value) => E.left("file-system-rename", value)); + .then(() => EE.success(newPath)) + .catch((value) => EE.left("file-system-rename", value)); }, }); diff --git a/docs/libs/v0/file/setMode.cjs b/docs/libs/v0/dist/file/setMode.cjs similarity index 57% rename from docs/libs/v0/file/setMode.cjs rename to docs/libs/v0/dist/file/setMode.cjs index 29adefc..af02b8a 100644 --- a/docs/libs/v0/file/setMode.cjs +++ b/docs/libs/v0/dist/file/setMode.cjs @@ -1,8 +1,28 @@ 'use strict'; var utils = require('@duplojs/utils'); +var EE = require('@duplojs/utils/either'); var implementor = require('../implementor.cjs'); +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + function calculatePermissions(permissions) { if (!permissions) { return 0; @@ -30,13 +50,13 @@ const setMode = implementor.implementFunction("setMode", { NODE: async (path, mode) => { const fs = await implementor.nodeFileSystem.value; return fs.chmod(path, toMode(mode)) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-set-mode", value)); + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-set-mode", value)); }, DENO: (path, mode) => Deno .chmod(path, toMode(mode)) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-set-mode", value)), + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-set-mode", value)), }); exports.setMode = setMode; diff --git a/docs/libs/v0/file/setMode.d.ts b/docs/libs/v0/dist/file/setMode.d.ts similarity index 90% rename from docs/libs/v0/file/setMode.d.ts rename to docs/libs/v0/dist/file/setMode.d.ts index a613d9a..2e41a95 100644 --- a/docs/libs/v0/file/setMode.d.ts +++ b/docs/libs/v0/dist/file/setMode.d.ts @@ -1,4 +1,4 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; interface Permissions { read?: boolean; @@ -16,7 +16,7 @@ interface ModeObject { type SetMode = ModeObject | number; declare module "../implementor" { interface ServerUtilsFunction { - setMode(path: string, mode: SetMode): Promise | E.Ok>; + setMode(path: string, mode: SetMode): Promise | EE.Ok>; } } /** @@ -42,5 +42,5 @@ declare module "../implementor" { * @namespace SF * */ -export declare const setMode: (path: string, mode: SetMode) => Promise | E.Ok>; +export declare const setMode: (path: string, mode: SetMode) => Promise | EE.Ok>; export {}; diff --git a/docs/libs/v0/file/setMode.mjs b/docs/libs/v0/dist/file/setMode.mjs similarity index 78% rename from docs/libs/v0/file/setMode.mjs rename to docs/libs/v0/dist/file/setMode.mjs index 6271f46..24af8d6 100644 --- a/docs/libs/v0/file/setMode.mjs +++ b/docs/libs/v0/dist/file/setMode.mjs @@ -1,4 +1,5 @@ -import { E, isType } from '@duplojs/utils'; +import { isType } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; function calculatePermissions(permissions) { @@ -28,13 +29,13 @@ const setMode = implementFunction("setMode", { NODE: async (path, mode) => { const fs = await nodeFileSystem.value; return fs.chmod(path, toMode(mode)) - .then(E.ok) - .catch((value) => E.left("file-system-set-mode", value)); + .then(EE.ok) + .catch((value) => EE.left("file-system-set-mode", value)); }, DENO: (path, mode) => Deno .chmod(path, toMode(mode)) - .then(E.ok) - .catch((value) => E.left("file-system-set-mode", value)), + .then(EE.ok) + .catch((value) => EE.left("file-system-set-mode", value)), }); export { setMode }; diff --git a/docs/libs/v0/dist/file/setOwner.cjs b/docs/libs/v0/dist/file/setOwner.cjs new file mode 100644 index 0000000..d18fb60 --- /dev/null +++ b/docs/libs/v0/dist/file/setOwner.cjs @@ -0,0 +1,41 @@ +'use strict'; + +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/setOwner/index.md} + */ +const setOwner = implementor.implementFunction("setOwner", { + NODE: async (path, { userId, groupId }) => { + const fs = await implementor.nodeFileSystem.value; + return fs.chown(path, userId, groupId) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-set-owner", value)); + }, + DENO: (path, { userId, groupId }) => Deno + .chown(path, userId, groupId) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-set-owner", value)), +}); + +exports.setOwner = setOwner; diff --git a/docs/libs/v0/file/setOwner.d.ts b/docs/libs/v0/dist/file/setOwner.d.ts similarity index 84% rename from docs/libs/v0/file/setOwner.d.ts rename to docs/libs/v0/dist/file/setOwner.d.ts index 18cb623..857e761 100644 --- a/docs/libs/v0/file/setOwner.d.ts +++ b/docs/libs/v0/dist/file/setOwner.d.ts @@ -1,4 +1,4 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; interface SetOwnerParams { userId: number; @@ -6,7 +6,7 @@ interface SetOwnerParams { } declare module "../implementor" { interface ServerUtilsFunction { - setOwner(path: string, params: SetOwnerParams): Promise | E.Ok>; + setOwner(path: string, params: SetOwnerParams): Promise | EE.Ok>; } } /** @@ -31,5 +31,5 @@ declare module "../implementor" { * @namespace SF * */ -export declare const setOwner: (path: string, params: SetOwnerParams) => Promise | E.Ok>; +export declare const setOwner: (path: string, params: SetOwnerParams) => Promise | EE.Ok>; export {}; diff --git a/docs/libs/v0/file/setOwner.mjs b/docs/libs/v0/dist/file/setOwner.mjs similarity index 64% rename from docs/libs/v0/file/setOwner.mjs rename to docs/libs/v0/dist/file/setOwner.mjs index 823cd69..270b8da 100644 --- a/docs/libs/v0/file/setOwner.mjs +++ b/docs/libs/v0/dist/file/setOwner.mjs @@ -1,4 +1,4 @@ -import { E } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; /** @@ -8,13 +8,13 @@ const setOwner = implementFunction("setOwner", { NODE: async (path, { userId, groupId }) => { const fs = await nodeFileSystem.value; return fs.chown(path, userId, groupId) - .then(E.ok) - .catch((value) => E.left("file-system-set-owner", value)); + .then(EE.ok) + .catch((value) => EE.left("file-system-set-owner", value)); }, DENO: (path, { userId, groupId }) => Deno .chown(path, userId, groupId) - .then(E.ok) - .catch((value) => E.left("file-system-set-owner", value)), + .then(EE.ok) + .catch((value) => EE.left("file-system-set-owner", value)), }); export { setOwner }; diff --git a/docs/libs/v0/dist/file/setTime.cjs b/docs/libs/v0/dist/file/setTime.cjs new file mode 100644 index 0000000..d426170 --- /dev/null +++ b/docs/libs/v0/dist/file/setTime.cjs @@ -0,0 +1,43 @@ +'use strict'; + +var EE = require('@duplojs/utils/either'); +var DD = require('@duplojs/utils/date'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); +var DD__namespace = /*#__PURE__*/_interopNamespaceDefault(DD); + +/** + * {@include file/setTime/index.md} + */ +const setTime = implementor.implementFunction("setTime", { + NODE: async (path, { accessTime, modifiedTime }) => { + const fs = await implementor.nodeFileSystem.value; + return fs.utimes(path, DD__namespace.toTimestamp(accessTime), DD__namespace.toTimestamp(modifiedTime)) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-set-time", value)); + }, + DENO: (path, { accessTime, modifiedTime }) => Deno + .utime(path, DD__namespace.toTimestamp(accessTime), DD__namespace.toTimestamp(modifiedTime)) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-set-time", value)), +}); + +exports.setTime = setTime; diff --git a/docs/libs/v0/file/setTime.d.ts b/docs/libs/v0/dist/file/setTime.d.ts similarity index 79% rename from docs/libs/v0/file/setTime.d.ts rename to docs/libs/v0/dist/file/setTime.d.ts index d24946b..3d6403c 100644 --- a/docs/libs/v0/file/setTime.d.ts +++ b/docs/libs/v0/dist/file/setTime.d.ts @@ -1,12 +1,13 @@ -import { D, E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; +import * as DD from "@duplojs/utils/date"; import type { FileSystemLeft } from "./types"; interface SetTimeParams { - accessTime: D.TheDate; - modifiedTime: D.TheDate; + accessTime: DD.TheDate; + modifiedTime: DD.TheDate; } declare module "../implementor" { interface ServerUtilsFunction { - setTime(path: string, params: SetTimeParams): Promise | E.Ok>; + setTime(path: string, params: SetTimeParams): Promise | EE.Ok>; } } /** @@ -34,5 +35,5 @@ declare module "../implementor" { * @namespace SF * */ -export declare const setTime: (path: string, params: SetTimeParams) => Promise | E.Ok>; +export declare const setTime: (path: string, params: SetTimeParams) => Promise | EE.Ok>; export {}; diff --git a/docs/libs/v0/dist/file/setTime.mjs b/docs/libs/v0/dist/file/setTime.mjs new file mode 100644 index 0000000..7dd2c04 --- /dev/null +++ b/docs/libs/v0/dist/file/setTime.mjs @@ -0,0 +1,21 @@ +import * as EE from '@duplojs/utils/either'; +import * as DD from '@duplojs/utils/date'; +import { implementFunction, nodeFileSystem } from '../implementor.mjs'; + +/** + * {@include file/setTime/index.md} + */ +const setTime = implementFunction("setTime", { + NODE: async (path, { accessTime, modifiedTime }) => { + const fs = await nodeFileSystem.value; + return fs.utimes(path, DD.toTimestamp(accessTime), DD.toTimestamp(modifiedTime)) + .then(EE.ok) + .catch((value) => EE.left("file-system-set-time", value)); + }, + DENO: (path, { accessTime, modifiedTime }) => Deno + .utime(path, DD.toTimestamp(accessTime), DD.toTimestamp(modifiedTime)) + .then(EE.ok) + .catch((value) => EE.left("file-system-set-time", value)), +}); + +export { setTime }; diff --git a/docs/libs/v0/dist/file/stat.cjs b/docs/libs/v0/dist/file/stat.cjs new file mode 100644 index 0000000..aeb1cf2 --- /dev/null +++ b/docs/libs/v0/dist/file/stat.cjs @@ -0,0 +1,110 @@ +'use strict'; + +var utils = require('@duplojs/utils'); +var EE = require('@duplojs/utils/either'); +var DD = require('@duplojs/utils/date'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); +var DD__namespace = /*#__PURE__*/_interopNamespaceDefault(DD); + +function createStatInfoWithFsSource(source) { + return { + isFile: source.isFile(), + isDirectory: source.isDirectory(), + isSymlink: source.isSymbolicLink(), + sizeBytes: source.size, + modifiedAt: DD__namespace.isSafeTimestamp(source.mtime.getTime()) ? DD__namespace.createOrThrow(source.mtime) : null, + accessedAt: DD__namespace.isSafeTimestamp(source.atime.getTime()) ? DD__namespace.createOrThrow(source.atime) : null, + createdAt: DD__namespace.isSafeTimestamp(source.birthtime.getTime()) ? DD__namespace.createOrThrow(source.birthtime) : null, + changedAt: DD__namespace.isSafeTimestamp(source.ctime.getTime()) ? DD__namespace.createOrThrow(source.ctime) : null, + deviceId: source.dev, + inode: source.ino, + permissionsMode: source.mode, + hardLinkCount: source.nlink, + ownerUserId: source.uid, + ownerGroupId: source.gid, + specialDeviceId: source.rdev, + ioBlockSize: source.blksize, + allocatedBlockCount: source.blocks, + isBlockDevice: source.isBlockDevice(), + isCharacterDevice: source.isCharacterDevice(), + isFifo: source.isFIFO(), + isSocket: source.isSocket(), + }; +} +function createStatInfoWithDeno(source) { + return { + isFile: source.isFile, + isDirectory: source.isDirectory, + isSymlink: source.isSymlink, + sizeBytes: source.size, + modifiedAt: source.mtime + && DD__namespace.isSafeTimestamp(source.mtime.getTime()) + ? DD__namespace.createOrThrow(source.mtime) + : null, + accessedAt: source.atime + && DD__namespace.isSafeTimestamp(source.atime.getTime()) + ? DD__namespace.createOrThrow(source.atime) + : null, + createdAt: source.birthtime + && DD__namespace.isSafeTimestamp(source.birthtime.getTime()) + ? DD__namespace.createOrThrow(source.birthtime) + : null, + changedAt: source.ctime + && DD__namespace.isSafeTimestamp(source.ctime.getTime()) + ? DD__namespace.createOrThrow(source.ctime) + : null, + deviceId: source.dev, + inode: source.ino, + permissionsMode: source.mode, + hardLinkCount: source.nlink, + ownerUserId: source.uid, + ownerGroupId: source.gid, + specialDeviceId: source.rdev, + ioBlockSize: source.blksize, + allocatedBlockCount: source.blocks, + isBlockDevice: source.isBlockDevice, + isCharacterDevice: source.isCharDevice, + isFifo: source.isFifo, + isSocket: source.isSocket, + }; +} +/** + * {@include file/stat/index.md} + */ +const stat = implementor.implementFunction("stat", { + NODE: async (path) => { + const fs = await implementor.nodeFileSystem.value; + return fs.stat(path) + .then(utils.innerPipe(createStatInfoWithFsSource, EE__namespace.success)) + .catch((value) => EE__namespace.left("file-system-stat", value)); + }, + DENO: (path) => Deno + .stat(path) + .then(utils.innerPipe(createStatInfoWithDeno, EE__namespace.success)) + .catch((value) => EE__namespace.left("file-system-stat", value)), + BUN: (path) => Bun.file(path) + .stat() + .then(utils.innerPipe(createStatInfoWithFsSource, EE__namespace.success)) + .catch((value) => EE__namespace.left("file-system-stat", value)), +}); + +exports.stat = stat; diff --git a/docs/libs/v0/file/stat.d.ts b/docs/libs/v0/dist/file/stat.d.ts similarity index 80% rename from docs/libs/v0/file/stat.d.ts rename to docs/libs/v0/dist/file/stat.d.ts index d2d6ac5..2ae7fa8 100644 --- a/docs/libs/v0/file/stat.d.ts +++ b/docs/libs/v0/dist/file/stat.d.ts @@ -1,4 +1,5 @@ -import { D, E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; +import * as DD from "@duplojs/utils/date"; import type { FileSystemLeft } from "./types"; export interface StatInfo { /** Type of entry */ @@ -8,10 +9,10 @@ export interface StatInfo { /** Size in bytes */ sizeBytes: number; /** Timestamps */ - modifiedAt: D.TheDate | null; - accessedAt: D.TheDate | null; - createdAt: D.TheDate | null; - changedAt: D.TheDate | null; + modifiedAt: DD.TheDate | null; + accessedAt: DD.TheDate | null; + createdAt: DD.TheDate | null; + changedAt: DD.TheDate | null; /** Unix/FS identifiers */ deviceId: number; inode: number | null; @@ -33,7 +34,7 @@ export interface StatInfo { } declare module "../implementor" { interface ServerUtilsFunction { - stat(path: GenericPath): Promise | E.Success>; + stat(path: GenericPath): Promise | EE.Success>; } } /** @@ -52,4 +53,4 @@ declare module "../implementor" { * @namespace SF * */ -export declare const stat: (path: GenericPath) => Promise | E.Success>; +export declare const stat: (path: GenericPath) => Promise | EE.Success>; diff --git a/docs/libs/v0/file/stat.mjs b/docs/libs/v0/dist/file/stat.mjs similarity index 59% rename from docs/libs/v0/file/stat.mjs rename to docs/libs/v0/dist/file/stat.mjs index 94f3123..2d09c4f 100644 --- a/docs/libs/v0/file/stat.mjs +++ b/docs/libs/v0/dist/file/stat.mjs @@ -1,4 +1,6 @@ -import { innerPipe, E, D } from '@duplojs/utils'; +import { innerPipe } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; +import * as DD from '@duplojs/utils/date'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; function createStatInfoWithFsSource(source) { @@ -7,10 +9,10 @@ function createStatInfoWithFsSource(source) { isDirectory: source.isDirectory(), isSymlink: source.isSymbolicLink(), sizeBytes: source.size, - modifiedAt: D.isSafeTimestamp(source.mtime.getTime()) ? D.createOrThrow(source.mtime) : null, - accessedAt: D.isSafeTimestamp(source.atime.getTime()) ? D.createOrThrow(source.atime) : null, - createdAt: D.isSafeTimestamp(source.birthtime.getTime()) ? D.createOrThrow(source.birthtime) : null, - changedAt: D.isSafeTimestamp(source.ctime.getTime()) ? D.createOrThrow(source.ctime) : null, + modifiedAt: DD.isSafeTimestamp(source.mtime.getTime()) ? DD.createOrThrow(source.mtime) : null, + accessedAt: DD.isSafeTimestamp(source.atime.getTime()) ? DD.createOrThrow(source.atime) : null, + createdAt: DD.isSafeTimestamp(source.birthtime.getTime()) ? DD.createOrThrow(source.birthtime) : null, + changedAt: DD.isSafeTimestamp(source.ctime.getTime()) ? DD.createOrThrow(source.ctime) : null, deviceId: source.dev, inode: source.ino, permissionsMode: source.mode, @@ -33,20 +35,20 @@ function createStatInfoWithDeno(source) { isSymlink: source.isSymlink, sizeBytes: source.size, modifiedAt: source.mtime - && D.isSafeTimestamp(source.mtime.getTime()) - ? D.createOrThrow(source.mtime) + && DD.isSafeTimestamp(source.mtime.getTime()) + ? DD.createOrThrow(source.mtime) : null, accessedAt: source.atime - && D.isSafeTimestamp(source.atime.getTime()) - ? D.createOrThrow(source.atime) + && DD.isSafeTimestamp(source.atime.getTime()) + ? DD.createOrThrow(source.atime) : null, createdAt: source.birthtime - && D.isSafeTimestamp(source.birthtime.getTime()) - ? D.createOrThrow(source.birthtime) + && DD.isSafeTimestamp(source.birthtime.getTime()) + ? DD.createOrThrow(source.birthtime) : null, changedAt: source.ctime - && D.isSafeTimestamp(source.ctime.getTime()) - ? D.createOrThrow(source.ctime) + && DD.isSafeTimestamp(source.ctime.getTime()) + ? DD.createOrThrow(source.ctime) : null, deviceId: source.dev, inode: source.ino, @@ -70,17 +72,17 @@ const stat = implementFunction("stat", { NODE: async (path) => { const fs = await nodeFileSystem.value; return fs.stat(path) - .then(innerPipe(createStatInfoWithFsSource, E.success)) - .catch((value) => E.left("file-system-stat", value)); + .then(innerPipe(createStatInfoWithFsSource, EE.success)) + .catch((value) => EE.left("file-system-stat", value)); }, DENO: (path) => Deno .stat(path) - .then(innerPipe(createStatInfoWithDeno, E.success)) - .catch((value) => E.left("file-system-stat", value)), + .then(innerPipe(createStatInfoWithDeno, EE.success)) + .catch((value) => EE.left("file-system-stat", value)), BUN: (path) => Bun.file(path) .stat() - .then(innerPipe(createStatInfoWithFsSource, E.success)) - .catch((value) => E.left("file-system-stat", value)), + .then(innerPipe(createStatInfoWithFsSource, EE.success)) + .catch((value) => EE.left("file-system-stat", value)), }); export { stat }; diff --git a/docs/libs/v0/dist/file/symlink.cjs b/docs/libs/v0/dist/file/symlink.cjs new file mode 100644 index 0000000..f4afe9a --- /dev/null +++ b/docs/libs/v0/dist/file/symlink.cjs @@ -0,0 +1,41 @@ +'use strict'; + +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/symlink/index.md} + */ +const symlink = implementor.implementFunction("symlink", { + NODE: async (oldPath, newPath, params) => { + const fs = await implementor.nodeFileSystem.value; + return fs.symlink(oldPath, newPath, params?.type) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-symlink", value)); + }, + DENO: (oldPath, newPath, params) => Deno + .symlink(oldPath, newPath, params) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-symlink", value)), +}); + +exports.symlink = symlink; diff --git a/docs/libs/v0/file/symlink.d.ts b/docs/libs/v0/dist/file/symlink.d.ts similarity index 90% rename from docs/libs/v0/file/symlink.d.ts rename to docs/libs/v0/dist/file/symlink.d.ts index 81d4d19..a6c296a 100644 --- a/docs/libs/v0/file/symlink.d.ts +++ b/docs/libs/v0/dist/file/symlink.d.ts @@ -1,4 +1,4 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; export interface SymlinkParams { /** @@ -10,7 +10,7 @@ export interface SymlinkParams { } declare module "../implementor" { interface ServerUtilsFunction { - symlink(oldPath: string, newPath: string, params?: SymlinkParams): Promise | E.Ok>; + symlink(oldPath: string, newPath: string, params?: SymlinkParams): Promise | EE.Ok>; } } /** @@ -31,4 +31,4 @@ declare module "../implementor" { * @namespace SF * */ -export declare const symlink: (oldPath: string, newPath: string, params?: SymlinkParams) => Promise | E.Ok>; +export declare const symlink: (oldPath: string, newPath: string, params?: SymlinkParams) => Promise | EE.Ok>; diff --git a/docs/libs/v0/file/symlink.mjs b/docs/libs/v0/dist/file/symlink.mjs similarity index 65% rename from docs/libs/v0/file/symlink.mjs rename to docs/libs/v0/dist/file/symlink.mjs index 0b74263..8699574 100644 --- a/docs/libs/v0/file/symlink.mjs +++ b/docs/libs/v0/dist/file/symlink.mjs @@ -1,4 +1,4 @@ -import { E } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; /** @@ -8,13 +8,13 @@ const symlink = implementFunction("symlink", { NODE: async (oldPath, newPath, params) => { const fs = await nodeFileSystem.value; return fs.symlink(oldPath, newPath, params?.type) - .then(E.ok) - .catch((value) => E.left("file-system-symlink", value)); + .then(EE.ok) + .catch((value) => EE.left("file-system-symlink", value)); }, DENO: (oldPath, newPath, params) => Deno .symlink(oldPath, newPath, params) - .then(E.ok) - .catch((value) => E.left("file-system-symlink", value)), + .then(EE.ok) + .catch((value) => EE.left("file-system-symlink", value)), }); export { symlink }; diff --git a/docs/libs/v0/dist/file/truncate.cjs b/docs/libs/v0/dist/file/truncate.cjs new file mode 100644 index 0000000..959605e --- /dev/null +++ b/docs/libs/v0/dist/file/truncate.cjs @@ -0,0 +1,42 @@ +'use strict'; + +var utils = require('@duplojs/utils'); +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/truncate/index.md} + */ +const truncate = implementor.implementFunction("truncate", { + NODE: async (path, size) => { + const fs = await implementor.nodeFileSystem.value; + return fs.truncate(path, size) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-truncate", value)); + }, + DENO: (path, size) => utils.pipe(path, utils.when(utils.instanceOf(URL), ({ pathname }) => decodeURIComponent(pathname)), (stringPath) => Deno + .truncate(stringPath, size) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-truncate", value))), +}); + +exports.truncate = truncate; diff --git a/docs/libs/v0/file/truncate.d.ts b/docs/libs/v0/dist/file/truncate.d.ts similarity index 85% rename from docs/libs/v0/file/truncate.d.ts rename to docs/libs/v0/dist/file/truncate.d.ts index 84e6b40..665155b 100644 --- a/docs/libs/v0/file/truncate.d.ts +++ b/docs/libs/v0/dist/file/truncate.d.ts @@ -1,8 +1,8 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; declare module "../implementor" { interface ServerUtilsFunction { - truncate(path: GenericPath, size?: number): Promise | E.Ok>; + truncate(path: GenericPath, size?: number): Promise | EE.Ok>; } } /** @@ -21,4 +21,4 @@ declare module "../implementor" { * @namespace SF * */ -export declare const truncate: (path: GenericPath, size?: number) => Promise | E.Ok>; +export declare const truncate: (path: GenericPath, size?: number) => Promise | EE.Ok>; diff --git a/docs/libs/v0/file/truncate.mjs b/docs/libs/v0/dist/file/truncate.mjs similarity index 62% rename from docs/libs/v0/file/truncate.mjs rename to docs/libs/v0/dist/file/truncate.mjs index c217f7a..c009b43 100644 --- a/docs/libs/v0/file/truncate.mjs +++ b/docs/libs/v0/dist/file/truncate.mjs @@ -1,4 +1,5 @@ -import { pipe, when, instanceOf, E } from '@duplojs/utils'; +import { pipe, when, instanceOf } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; /** @@ -8,13 +9,13 @@ const truncate = implementFunction("truncate", { NODE: async (path, size) => { const fs = await nodeFileSystem.value; return fs.truncate(path, size) - .then(E.ok) - .catch((value) => E.left("file-system-truncate", value)); + .then(EE.ok) + .catch((value) => EE.left("file-system-truncate", value)); }, DENO: (path, size) => pipe(path, when(instanceOf(URL), ({ pathname }) => decodeURIComponent(pathname)), (stringPath) => Deno .truncate(stringPath, size) - .then(E.ok) - .catch((value) => E.left("file-system-truncate", value))), + .then(EE.ok) + .catch((value) => EE.left("file-system-truncate", value))), }); export { truncate }; diff --git a/docs/libs/v0/dist/file/types/fileSystemLeft.d.ts b/docs/libs/v0/dist/file/types/fileSystemLeft.d.ts new file mode 100644 index 0000000..d875e98 --- /dev/null +++ b/docs/libs/v0/dist/file/types/fileSystemLeft.d.ts @@ -0,0 +1,2 @@ +import type * as EE from "@duplojs/utils/either"; +export type FileSystemLeft = EE.Left<`file-system-${GenericName}`, unknown>; diff --git a/docs/libs/v0/file/types/index.d.ts b/docs/libs/v0/dist/file/types/index.d.ts similarity index 100% rename from docs/libs/v0/file/types/index.d.ts rename to docs/libs/v0/dist/file/types/index.d.ts diff --git a/docs/libs/v0/file/unknownInterface.cjs b/docs/libs/v0/dist/file/unknownInterface.cjs similarity index 100% rename from docs/libs/v0/file/unknownInterface.cjs rename to docs/libs/v0/dist/file/unknownInterface.cjs diff --git a/docs/libs/v0/file/unknownInterface.d.ts b/docs/libs/v0/dist/file/unknownInterface.d.ts similarity index 88% rename from docs/libs/v0/file/unknownInterface.d.ts rename to docs/libs/v0/dist/file/unknownInterface.d.ts index 4443e09..d3a9ec7 100644 --- a/docs/libs/v0/file/unknownInterface.d.ts +++ b/docs/libs/v0/dist/file/unknownInterface.d.ts @@ -1,4 +1,5 @@ -import { type E, type Kind } from "@duplojs/utils"; +import { type Kind } from "@duplojs/utils"; +import type * as EE from "@duplojs/utils/either"; import { type StatInfo } from "./stat"; import type { FileSystemLeft } from "./types"; declare const unknownInterfaceKind: import("@duplojs/utils").KindHandler>; @@ -6,8 +7,8 @@ export interface UnknownInterface extends Kind | E.Success>; - exist(): Promise | E.Ok>; + stat(): Promise | EE.Success>; + exist(): Promise | EE.Ok>; } /** * Create an interface for an unknown path type. diff --git a/docs/libs/v0/file/unknownInterface.mjs b/docs/libs/v0/dist/file/unknownInterface.mjs similarity index 100% rename from docs/libs/v0/file/unknownInterface.mjs rename to docs/libs/v0/dist/file/unknownInterface.mjs diff --git a/docs/libs/v0/dist/file/walkDirectory.cjs b/docs/libs/v0/dist/file/walkDirectory.cjs new file mode 100644 index 0000000..668fd72 --- /dev/null +++ b/docs/libs/v0/dist/file/walkDirectory.cjs @@ -0,0 +1,48 @@ +'use strict'; + +var utils = require('@duplojs/utils'); +var GG = require('@duplojs/utils/generator'); +var EE = require('@duplojs/utils/either'); +var PP = require('@duplojs/utils/pattern'); +var implementor = require('../implementor.cjs'); +var fileInterface = require('./fileInterface.cjs'); +var folderInterface = require('./folderInterface.cjs'); +var unknownInterface = require('./unknownInterface.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var GG__namespace = /*#__PURE__*/_interopNamespaceDefault(GG); +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); +var PP__namespace = /*#__PURE__*/_interopNamespaceDefault(PP); + +/** + * {@include file/walkDirectory/index.md} + */ +const walkDirectory = implementor.implementFunction("walkDirectory", { + NODE: async (path, params) => { + const fs = await implementor.nodeFileSystem.value; + return fs.readdir(path, { + recursive: params?.recursive ?? false, + withFileTypes: true, + }) + .then(utils.innerPipe(GG__namespace.map(utils.innerPipe(PP__namespace.when((dirent) => dirent.isFile(), ({ parentPath, name }) => fileInterface.createFileInterface(`${parentPath}/${name}`)), PP__namespace.when((dirent) => dirent.isDirectory(), ({ parentPath, name }) => folderInterface.createFolderInterface(`${parentPath}/${name}`)), PP__namespace.otherwise(({ parentPath, name }) => unknownInterface.createUnknownInterface(`${parentPath}/${name}`)))), EE__namespace.success)) + .catch((value) => EE__namespace.left("file-system-walk-directory", value)); + }, +}); + +exports.walkDirectory = walkDirectory; diff --git a/docs/libs/v0/file/walkDirectory.d.ts b/docs/libs/v0/dist/file/walkDirectory.d.ts similarity index 80% rename from docs/libs/v0/file/walkDirectory.d.ts rename to docs/libs/v0/dist/file/walkDirectory.d.ts index 79a052f..6f7bdcc 100644 --- a/docs/libs/v0/file/walkDirectory.d.ts +++ b/docs/libs/v0/dist/file/walkDirectory.d.ts @@ -1,4 +1,4 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import { type FileInterface } from "./fileInterface"; import { type FolderInterface } from "./folderInterface"; import { type UnknownInterface } from "./unknownInterface"; @@ -8,7 +8,7 @@ interface WalkDirectoryParams { } declare module "../implementor" { interface ServerUtilsFunction { - walkDirectory(path: GenericPath, params?: WalkDirectoryParams): Promise | E.Success>>; + walkDirectory(path: GenericPath, params?: WalkDirectoryParams): Promise | EE.Success>>; } } /** @@ -27,5 +27,5 @@ declare module "../implementor" { * @namespace SF * */ -export declare const walkDirectory: (path: GenericPath, params?: WalkDirectoryParams) => Promise | E.Success>>; +export declare const walkDirectory: (path: GenericPath, params?: WalkDirectoryParams) => Promise | EE.Success>>; export {}; diff --git a/docs/libs/v0/dist/file/walkDirectory.mjs b/docs/libs/v0/dist/file/walkDirectory.mjs new file mode 100644 index 0000000..b5046fa --- /dev/null +++ b/docs/libs/v0/dist/file/walkDirectory.mjs @@ -0,0 +1,25 @@ +import { innerPipe } from '@duplojs/utils'; +import * as GG from '@duplojs/utils/generator'; +import * as EE from '@duplojs/utils/either'; +import * as PP from '@duplojs/utils/pattern'; +import { implementFunction, nodeFileSystem } from '../implementor.mjs'; +import { createFileInterface } from './fileInterface.mjs'; +import { createFolderInterface } from './folderInterface.mjs'; +import { createUnknownInterface } from './unknownInterface.mjs'; + +/** + * {@include file/walkDirectory/index.md} + */ +const walkDirectory = implementFunction("walkDirectory", { + NODE: async (path, params) => { + const fs = await nodeFileSystem.value; + return fs.readdir(path, { + recursive: params?.recursive ?? false, + withFileTypes: true, + }) + .then(innerPipe(GG.map(innerPipe(PP.when((dirent) => dirent.isFile(), ({ parentPath, name }) => createFileInterface(`${parentPath}/${name}`)), PP.when((dirent) => dirent.isDirectory(), ({ parentPath, name }) => createFolderInterface(`${parentPath}/${name}`)), PP.otherwise(({ parentPath, name }) => createUnknownInterface(`${parentPath}/${name}`)))), EE.success)) + .catch((value) => EE.left("file-system-walk-directory", value)); + }, +}); + +export { walkDirectory }; diff --git a/docs/libs/v0/dist/file/writeFile.cjs b/docs/libs/v0/dist/file/writeFile.cjs new file mode 100644 index 0000000..07cd0cb --- /dev/null +++ b/docs/libs/v0/dist/file/writeFile.cjs @@ -0,0 +1,46 @@ +'use strict'; + +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/writeFile/index.md} + */ +const writeFile = implementor.implementFunction("writeFile", { + NODE: async (path, data) => { + const fs = await implementor.nodeFileSystem.value; + return fs.writeFile(path, data) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-write-file", value)); + }, + DENO: (path, data) => Deno + .writeFile(path, data) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-write-file", value)), + BUN: (path, data) => Bun + .file(path) + .write(data) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-write-file", value)), +}); + +exports.writeFile = writeFile; diff --git a/docs/libs/v0/file/writeFile.d.ts b/docs/libs/v0/dist/file/writeFile.d.ts similarity index 84% rename from docs/libs/v0/file/writeFile.d.ts rename to docs/libs/v0/dist/file/writeFile.d.ts index b9d7600..f470937 100644 --- a/docs/libs/v0/file/writeFile.d.ts +++ b/docs/libs/v0/dist/file/writeFile.d.ts @@ -1,8 +1,8 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; declare module "../implementor" { interface ServerUtilsFunction { - writeFile(path: string, data: Uint8Array): Promise | E.Ok>; + writeFile(path: string, data: Uint8Array): Promise | EE.Ok>; } } /** @@ -22,4 +22,4 @@ declare module "../implementor" { * @namespace SF * */ -export declare const writeFile: (path: string, data: Uint8Array) => Promise | E.Ok>; +export declare const writeFile: (path: string, data: Uint8Array) => Promise | EE.Ok>; diff --git a/docs/libs/v0/file/writeFile.mjs b/docs/libs/v0/dist/file/writeFile.mjs similarity index 58% rename from docs/libs/v0/file/writeFile.mjs rename to docs/libs/v0/dist/file/writeFile.mjs index 3ffccca..d4d2580 100644 --- a/docs/libs/v0/file/writeFile.mjs +++ b/docs/libs/v0/dist/file/writeFile.mjs @@ -1,4 +1,4 @@ -import { E } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; /** @@ -8,18 +8,18 @@ const writeFile = implementFunction("writeFile", { NODE: async (path, data) => { const fs = await nodeFileSystem.value; return fs.writeFile(path, data) - .then(E.ok) - .catch((value) => E.left("file-system-write-file", value)); + .then(EE.ok) + .catch((value) => EE.left("file-system-write-file", value)); }, DENO: (path, data) => Deno .writeFile(path, data) - .then(E.ok) - .catch((value) => E.left("file-system-write-file", value)), + .then(EE.ok) + .catch((value) => EE.left("file-system-write-file", value)), BUN: (path, data) => Bun .file(path) .write(data) - .then(E.ok) - .catch((value) => E.left("file-system-write-file", value)), + .then(EE.ok) + .catch((value) => EE.left("file-system-write-file", value)), }); export { writeFile }; diff --git a/docs/libs/v0/dist/file/writeJsonFile.cjs b/docs/libs/v0/dist/file/writeJsonFile.cjs new file mode 100644 index 0000000..accd26a --- /dev/null +++ b/docs/libs/v0/dist/file/writeJsonFile.cjs @@ -0,0 +1,45 @@ +'use strict'; + +var utils = require('@duplojs/utils'); +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/writeJsonFile/index.md} + */ +const writeJsonFile = implementor.implementFunction("writeJsonFile", { + NODE: async (path, data, params) => { + const fs = await implementor.nodeFileSystem.value; + return utils.pipe(EE__namespace.safeCallback(() => JSON.stringify(data, null, params?.space)), EE__namespace.whenIsRight((value) => fs.writeFile(path, value, { encoding: "utf-8" }) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-write-json-file", value))), EE__namespace.whenIsLeft((value) => EE__namespace.left("file-system-write-json-file", value))); + }, + DENO: (path, data, params) => utils.asyncPipe(EE__namespace.safeCallback(() => JSON.stringify(data, null, params?.space)), EE__namespace.whenIsRight((value) => Deno.writeTextFile(path, value) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-write-json-file", value))), EE__namespace.whenIsLeft((value) => EE__namespace.left("file-system-write-json-file", value))), + BUN: (path, data, params) => utils.asyncPipe(EE__namespace.safeCallback(() => JSON.stringify(data, null, params?.space)), EE__namespace.whenIsRight((value) => Bun.file(path) + .write(value) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-write-json-file", value))), EE__namespace.whenIsLeft((value) => EE__namespace.left("file-system-write-json-file", value))), +}); + +exports.writeJsonFile = writeJsonFile; diff --git a/docs/libs/v0/file/writeJsonFile.d.ts b/docs/libs/v0/dist/file/writeJsonFile.d.ts similarity index 87% rename from docs/libs/v0/file/writeJsonFile.d.ts rename to docs/libs/v0/dist/file/writeJsonFile.d.ts index f64836f..e3d75c0 100644 --- a/docs/libs/v0/file/writeJsonFile.d.ts +++ b/docs/libs/v0/dist/file/writeJsonFile.d.ts @@ -1,11 +1,11 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; interface WriteJsonFile { space?: number; } declare module "../implementor" { interface ServerUtilsFunction { - writeJsonFile(path: string, data: unknown, params?: WriteJsonFile): Promise | E.Ok>; + writeJsonFile(path: string, data: unknown, params?: WriteJsonFile): Promise | EE.Ok>; } } /** @@ -26,5 +26,5 @@ declare module "../implementor" { * @namespace SF * */ -export declare const writeJsonFile: (path: string, data: unknown, params?: WriteJsonFile) => Promise | E.Ok>; +export declare const writeJsonFile: (path: string, data: unknown, params?: WriteJsonFile) => Promise | EE.Ok>; export {}; diff --git a/docs/libs/v0/dist/file/writeJsonFile.mjs b/docs/libs/v0/dist/file/writeJsonFile.mjs new file mode 100644 index 0000000..9411680 --- /dev/null +++ b/docs/libs/v0/dist/file/writeJsonFile.mjs @@ -0,0 +1,24 @@ +import { asyncPipe, pipe } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; +import { implementFunction, nodeFileSystem } from '../implementor.mjs'; + +/** + * {@include file/writeJsonFile/index.md} + */ +const writeJsonFile = implementFunction("writeJsonFile", { + NODE: async (path, data, params) => { + const fs = await nodeFileSystem.value; + return pipe(EE.safeCallback(() => JSON.stringify(data, null, params?.space)), EE.whenIsRight((value) => fs.writeFile(path, value, { encoding: "utf-8" }) + .then(EE.ok) + .catch((value) => EE.left("file-system-write-json-file", value))), EE.whenIsLeft((value) => EE.left("file-system-write-json-file", value))); + }, + DENO: (path, data, params) => asyncPipe(EE.safeCallback(() => JSON.stringify(data, null, params?.space)), EE.whenIsRight((value) => Deno.writeTextFile(path, value) + .then(EE.ok) + .catch((value) => EE.left("file-system-write-json-file", value))), EE.whenIsLeft((value) => EE.left("file-system-write-json-file", value))), + BUN: (path, data, params) => asyncPipe(EE.safeCallback(() => JSON.stringify(data, null, params?.space)), EE.whenIsRight((value) => Bun.file(path) + .write(value) + .then(EE.ok) + .catch((value) => EE.left("file-system-write-json-file", value))), EE.whenIsLeft((value) => EE.left("file-system-write-json-file", value))), +}); + +export { writeJsonFile }; diff --git a/docs/libs/v0/dist/file/writeTextFile.cjs b/docs/libs/v0/dist/file/writeTextFile.cjs new file mode 100644 index 0000000..d5663ac --- /dev/null +++ b/docs/libs/v0/dist/file/writeTextFile.cjs @@ -0,0 +1,46 @@ +'use strict'; + +var EE = require('@duplojs/utils/either'); +var implementor = require('../implementor.cjs'); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var EE__namespace = /*#__PURE__*/_interopNamespaceDefault(EE); + +/** + * {@include file/writeTextFile/index.md} + */ +const writeTextFile = implementor.implementFunction("writeTextFile", { + NODE: async (path, data) => { + const fs = await implementor.nodeFileSystem.value; + return fs.writeFile(path, data, { encoding: "utf-8" }) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-write-text-file", value)); + }, + DENO: (path, data) => Deno + .writeTextFile(path, data) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-write-text-file", value)), + BUN: (path, data) => Bun + .file(path) + .write(data) + .then(EE__namespace.ok) + .catch((value) => EE__namespace.left("file-system-write-text-file", value)), +}); + +exports.writeTextFile = writeTextFile; diff --git a/docs/libs/v0/file/writeTextFile.d.ts b/docs/libs/v0/dist/file/writeTextFile.d.ts similarity index 82% rename from docs/libs/v0/file/writeTextFile.d.ts rename to docs/libs/v0/dist/file/writeTextFile.d.ts index ab6b4c4..7f1a12f 100644 --- a/docs/libs/v0/file/writeTextFile.d.ts +++ b/docs/libs/v0/dist/file/writeTextFile.d.ts @@ -1,8 +1,8 @@ -import { E } from "@duplojs/utils"; +import * as EE from "@duplojs/utils/either"; import type { FileSystemLeft } from "./types"; declare module "../implementor" { interface ServerUtilsFunction { - writeTextFile(path: string, data: string): Promise | E.Ok>; + writeTextFile(path: string, data: string): Promise | EE.Ok>; } } /** @@ -21,4 +21,4 @@ declare module "../implementor" { * @namespace SF * */ -export declare const writeTextFile: (path: string, data: string) => Promise | E.Ok>; +export declare const writeTextFile: (path: string, data: string) => Promise | EE.Ok>; diff --git a/docs/libs/v0/file/writeTextFile.mjs b/docs/libs/v0/dist/file/writeTextFile.mjs similarity index 59% rename from docs/libs/v0/file/writeTextFile.mjs rename to docs/libs/v0/dist/file/writeTextFile.mjs index 88d6a6a..e0159de 100644 --- a/docs/libs/v0/file/writeTextFile.mjs +++ b/docs/libs/v0/dist/file/writeTextFile.mjs @@ -1,4 +1,4 @@ -import { E } from '@duplojs/utils'; +import * as EE from '@duplojs/utils/either'; import { implementFunction, nodeFileSystem } from '../implementor.mjs'; /** @@ -8,18 +8,18 @@ const writeTextFile = implementFunction("writeTextFile", { NODE: async (path, data) => { const fs = await nodeFileSystem.value; return fs.writeFile(path, data, { encoding: "utf-8" }) - .then(E.ok) - .catch((value) => E.left("file-system-write-text-file", value)); + .then(EE.ok) + .catch((value) => EE.left("file-system-write-text-file", value)); }, DENO: (path, data) => Deno .writeTextFile(path, data) - .then(E.ok) - .catch((value) => E.left("file-system-write-text-file", value)), + .then(EE.ok) + .catch((value) => EE.left("file-system-write-text-file", value)), BUN: (path, data) => Bun .file(path) .write(data) - .then(E.ok) - .catch((value) => E.left("file-system-write-text-file", value)), + .then(EE.ok) + .catch((value) => EE.left("file-system-write-text-file", value)), }); export { writeTextFile }; diff --git a/docs/libs/v0/implementor.cjs b/docs/libs/v0/dist/implementor.cjs similarity index 100% rename from docs/libs/v0/implementor.cjs rename to docs/libs/v0/dist/implementor.cjs diff --git a/docs/libs/v0/implementor.d.ts b/docs/libs/v0/dist/implementor.d.ts similarity index 100% rename from docs/libs/v0/implementor.d.ts rename to docs/libs/v0/dist/implementor.d.ts diff --git a/docs/libs/v0/implementor.mjs b/docs/libs/v0/dist/implementor.mjs similarity index 100% rename from docs/libs/v0/implementor.mjs rename to docs/libs/v0/dist/implementor.mjs diff --git a/docs/libs/v0/index.cjs b/docs/libs/v0/dist/index.cjs similarity index 100% rename from docs/libs/v0/index.cjs rename to docs/libs/v0/dist/index.cjs diff --git a/docs/libs/v0/index.d.ts b/docs/libs/v0/dist/index.d.ts similarity index 100% rename from docs/libs/v0/index.d.ts rename to docs/libs/v0/dist/index.d.ts diff --git a/docs/libs/v0/index.mjs b/docs/libs/v0/dist/index.mjs similarity index 100% rename from docs/libs/v0/index.mjs rename to docs/libs/v0/dist/index.mjs diff --git a/docs/libs/v0/kind.cjs b/docs/libs/v0/dist/kind.cjs similarity index 100% rename from docs/libs/v0/kind.cjs rename to docs/libs/v0/dist/kind.cjs diff --git a/docs/libs/v0/kind.d.ts b/docs/libs/v0/dist/kind.d.ts similarity index 100% rename from docs/libs/v0/kind.d.ts rename to docs/libs/v0/dist/kind.d.ts diff --git a/docs/libs/v0/kind.mjs b/docs/libs/v0/dist/kind.mjs similarity index 100% rename from docs/libs/v0/kind.mjs rename to docs/libs/v0/dist/kind.mjs diff --git a/docs/libs/v0/file/appendFile.cjs b/docs/libs/v0/file/appendFile.cjs deleted file mode 100644 index b404a29..0000000 --- a/docs/libs/v0/file/appendFile.cjs +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/appendFile/index.md} - */ -const appendFile = implementor.implementFunction("appendFile", { - NODE: async (path, data) => { - const fs = await implementor.nodeFileSystem.value; - return fs.appendFile(path, data) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-append-file", value)); - }, - DENO: (path, data) => Deno.writeFile(path, data, { append: true }) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-append-file", value)), -}); - -exports.appendFile = appendFile; diff --git a/docs/libs/v0/file/appendTextFile.cjs b/docs/libs/v0/file/appendTextFile.cjs deleted file mode 100644 index 66b6946..0000000 --- a/docs/libs/v0/file/appendTextFile.cjs +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/appendTextFile/index.md} - */ -const appendTextFile = implementor.implementFunction("appendTextFile", { - NODE: async (path, data) => { - const fs = await implementor.nodeFileSystem.value; - return fs.appendFile(path, data) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-append-text-file", value)); - }, - DENO: (path, data) => Deno.writeTextFile(path, data, { append: true }) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-append-text-file", value)), -}); - -exports.appendTextFile = appendTextFile; diff --git a/docs/libs/v0/file/copy.cjs b/docs/libs/v0/file/copy.cjs deleted file mode 100644 index 8ea6f9e..0000000 --- a/docs/libs/v0/file/copy.cjs +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/copy/index.md} - */ -const copy = implementor.implementFunction("copy", { - NODE: async (fromPath, toPath) => { - const fs = await implementor.nodeFileSystem.value; - return fs.cp(fromPath, toPath, { recursive: true }) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-copy", value)); - }, -}); - -exports.copy = copy; diff --git a/docs/libs/v0/file/ensureDirectory.cjs b/docs/libs/v0/file/ensureDirectory.cjs deleted file mode 100644 index cc22207..0000000 --- a/docs/libs/v0/file/ensureDirectory.cjs +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/ensureDirectory/index.md} - */ -const ensureDirectory = implementor.implementFunction("ensureDirectory", { - NODE: async (path) => { - const fs = await implementor.nodeFileSystem.value; - return fs.mkdir(path, { - recursive: true, - }) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-ensure-directory", value)); - }, - DENO: (path) => Deno.mkdir(path, { - recursive: true, - }) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-ensure-directory", value)), -}); - -exports.ensureDirectory = ensureDirectory; diff --git a/docs/libs/v0/file/ensureFile.cjs b/docs/libs/v0/file/ensureFile.cjs deleted file mode 100644 index a0da8b2..0000000 --- a/docs/libs/v0/file/ensureFile.cjs +++ /dev/null @@ -1,27 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/ensureFile/index.md} - */ -const ensureFile = implementor.implementFunction("ensureFile", { - NODE: async (path) => { - const fs = await implementor.nodeFileSystem.value; - return fs.open(path, "a") - .then((fh) => fh.close()) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-ensure-file", value)); - }, - DENO: (path) => Deno.open(path, { - write: true, - create: true, - append: true, - }) - .then((fh) => void fh.close()) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-ensure-file", value)), -}); - -exports.ensureFile = ensureFile; diff --git a/docs/libs/v0/file/exists.cjs b/docs/libs/v0/file/exists.cjs deleted file mode 100644 index f4be82c..0000000 --- a/docs/libs/v0/file/exists.cjs +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/exists/index.md} - */ -const exists = implementor.implementFunction("exists", { - NODE: async (path) => { - const fs = await implementor.nodeFileSystem.value; - return fs.access(path) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-exists", value)); - }, - DENO: (path) => Deno - .stat(path) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-exists", value)), - BUN: (path) => Bun.file(path) - .exists() - .then((value) => value - ? utils.E.ok() - : utils.E.left("file-system-exists", new Error("Path does not exist"))) - .catch((value) => utils.E.left("file-system-exists", value)), -}); - -exports.exists = exists; diff --git a/docs/libs/v0/file/link.cjs b/docs/libs/v0/file/link.cjs deleted file mode 100644 index 6d82c63..0000000 --- a/docs/libs/v0/file/link.cjs +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/link/index.md} - */ -const link = implementor.implementFunction("link", { - NODE: async (existingPath, newPath) => { - const fs = await implementor.nodeFileSystem.value; - return fs.link(existingPath, newPath) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-link", value)); - }, - DENO: (existingPath, newPath) => Deno - .link(existingPath, newPath) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-link", value)), -}); - -exports.link = link; diff --git a/docs/libs/v0/file/linkStat.cjs b/docs/libs/v0/file/linkStat.cjs deleted file mode 100644 index e9478b2..0000000 --- a/docs/libs/v0/file/linkStat.cjs +++ /dev/null @@ -1,84 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -function createStatInfoWithFsSource(source) { - return { - isFile: source.isFile(), - isDirectory: source.isDirectory(), - isSymlink: source.isSymbolicLink(), - sizeBytes: source.size, - modifiedAt: utils.D.isSafeTimestamp(source.mtime.getTime()) ? utils.D.createOrThrow(source.mtime) : null, - accessedAt: utils.D.isSafeTimestamp(source.atime.getTime()) ? utils.D.createOrThrow(source.atime) : null, - createdAt: utils.D.isSafeTimestamp(source.birthtime.getTime()) ? utils.D.createOrThrow(source.birthtime) : null, - changedAt: utils.D.isSafeTimestamp(source.ctime.getTime()) ? utils.D.createOrThrow(source.ctime) : null, - deviceId: source.dev, - inode: source.ino, - permissionsMode: source.mode, - hardLinkCount: source.nlink, - ownerUserId: source.uid, - ownerGroupId: source.gid, - specialDeviceId: source.rdev, - ioBlockSize: source.blksize, - allocatedBlockCount: source.blocks, - isBlockDevice: source.isBlockDevice(), - isCharacterDevice: source.isCharacterDevice(), - isFifo: source.isFIFO(), - isSocket: source.isSocket(), - }; -} -function createStatInfoWithDeno(source) { - return { - isFile: source.isFile, - isDirectory: source.isDirectory, - isSymlink: source.isSymlink, - sizeBytes: source.size, - modifiedAt: source.mtime - && utils.D.isSafeTimestamp(source.mtime.getTime()) - ? utils.D.createOrThrow(source.mtime) - : null, - accessedAt: source.atime - && utils.D.isSafeTimestamp(source.atime.getTime()) - ? utils.D.createOrThrow(source.atime) - : null, - createdAt: source.birthtime - && utils.D.isSafeTimestamp(source.birthtime.getTime()) - ? utils.D.createOrThrow(source.birthtime) - : null, - changedAt: source.ctime - && utils.D.isSafeTimestamp(source.ctime.getTime()) - ? utils.D.createOrThrow(source.ctime) - : null, - deviceId: source.dev, - inode: source.ino, - permissionsMode: source.mode, - hardLinkCount: source.nlink, - ownerUserId: source.uid, - ownerGroupId: source.gid, - specialDeviceId: source.rdev, - ioBlockSize: source.blksize, - allocatedBlockCount: source.blocks, - isBlockDevice: source.isBlockDevice, - isCharacterDevice: source.isCharDevice, - isFifo: source.isFifo, - isSocket: source.isSocket, - }; -} -/** - * {@include file/linkStat/index.md} - */ -const linkStat = implementor.implementFunction("linkStat", { - NODE: async (path) => { - const fs = await implementor.nodeFileSystem.value; - return fs.lstat(path) - .then(utils.innerPipe(createStatInfoWithFsSource, utils.E.success)) - .catch((value) => utils.E.left("file-system-link-stat", value)); - }, - DENO: (path) => Deno - .lstat(path) - .then(utils.innerPipe(createStatInfoWithDeno, utils.E.success)) - .catch((value) => utils.E.left("file-system-link-stat", value)), -}); - -exports.linkStat = linkStat; diff --git a/docs/libs/v0/file/makeDirectory.cjs b/docs/libs/v0/file/makeDirectory.cjs deleted file mode 100644 index af0bf06..0000000 --- a/docs/libs/v0/file/makeDirectory.cjs +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/makeDirectory/index.md} - */ -const makeDirectory = implementor.implementFunction("makeDirectory", { - NODE: async (path, params) => { - const fs = await implementor.nodeFileSystem.value; - return fs.mkdir(path, { - recursive: params?.recursive, - }) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-make-directory", value)); - }, - DENO: (path, params) => Deno.mkdir(path, { - recursive: params?.recursive, - }) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-make-directory", value)), -}); - -exports.makeDirectory = makeDirectory; diff --git a/docs/libs/v0/file/makeTemporaryDirectory.cjs b/docs/libs/v0/file/makeTemporaryDirectory.cjs deleted file mode 100644 index 2c77e3f..0000000 --- a/docs/libs/v0/file/makeTemporaryDirectory.cjs +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/makeTemporaryDirectory/index.md} - */ -const makeTemporaryDirectory = implementor.implementFunction("makeTemporaryDirectory", { - NODE: async (prefix) => { - const fs = await implementor.nodeFileSystem.value; - return fs.mkdtemp(prefix) - .then(utils.E.success) - .catch((value) => utils.E.left("file-system-make-temporary-directory", value)); - }, - DENO: (prefix) => Deno.makeTempDir({ prefix }) - .then(utils.E.success) - .catch((value) => utils.E.left("file-system-make-temporary-directory", value)), -}); - -exports.makeTemporaryDirectory = makeTemporaryDirectory; diff --git a/docs/libs/v0/file/makeTemporaryFile.cjs b/docs/libs/v0/file/makeTemporaryFile.cjs deleted file mode 100644 index 0490822..0000000 --- a/docs/libs/v0/file/makeTemporaryFile.cjs +++ /dev/null @@ -1,31 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/makeTemporaryFile/index.md} - */ -const makeTemporaryFile = implementor.implementFunction("makeTemporaryFile", { - NODE: async (prefix, suffix) => { - const fs = await implementor.nodeFileSystem.value; - const os = await implementor.nodeOs.value; - const crypto = await implementor.nodeCrypto.value; - const fileTemporaryPath = utils.Path.resolveRelative([ - os.tmpdir(), - `${prefix}${crypto.randomUUID()}${suffix ?? ""}`, - ]); - return fs.open(fileTemporaryPath, "wx") - .then((fh) => fh.close()) - .then(() => utils.E.success(fileTemporaryPath)) - .catch((value) => utils.E.left("file-system-make-temporary-file", value)); - }, - DENO: (prefix, suffix) => Deno.makeTempFile({ - prefix, - suffix, - }) - .then(utils.E.success) - .catch((value) => utils.E.left("file-system-make-temporary-file", value)), -}); - -exports.makeTemporaryFile = makeTemporaryFile; diff --git a/docs/libs/v0/file/move.cjs b/docs/libs/v0/file/move.cjs deleted file mode 100644 index b10cee0..0000000 --- a/docs/libs/v0/file/move.cjs +++ /dev/null @@ -1,21 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/move/index.md} - */ -const move = implementor.implementFunction("move", { - NODE: async (fromPath, toPath) => { - const fs = await implementor.nodeFileSystem.value; - return fs.rename(fromPath, toPath) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-move", value)); - }, - DENO: (fromPath, toPath) => Deno.rename(fromPath, toPath) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-move", value)), -}); - -exports.move = move; diff --git a/docs/libs/v0/file/readDirectory.cjs b/docs/libs/v0/file/readDirectory.cjs deleted file mode 100644 index 92e960e..0000000 --- a/docs/libs/v0/file/readDirectory.cjs +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/readDirectory/index.md} - */ -const readDirectory = implementor.implementFunction("readDirectory", { - NODE: async (path, params) => { - const fs = await implementor.nodeFileSystem.value; - return fs.readdir(path, { recursive: params?.recursive }) - .then(utils.E.success) - .catch((value) => utils.E.left("file-system-read-directory", value)); - }, -}); - -exports.readDirectory = readDirectory; diff --git a/docs/libs/v0/file/readFile.cjs b/docs/libs/v0/file/readFile.cjs deleted file mode 100644 index e42fb65..0000000 --- a/docs/libs/v0/file/readFile.cjs +++ /dev/null @@ -1,26 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/readFile/index.md} - */ -const readFile = implementor.implementFunction("readFile", { - NODE: async (path) => { - const fs = await implementor.nodeFileSystem.value; - return fs.readFile(path) - .then(utils.E.success) - .catch((value) => utils.E.left("file-system-read-file", value)); - }, - DENO: (path) => Deno - .readFile(path) - .then(utils.E.success) - .catch((value) => utils.E.left("file-system-read-file", value)), - BUN: (path) => Bun.file(path) - .bytes() - .then(utils.E.success) - .catch((value) => utils.E.left("file-system-read-file", value)), -}); - -exports.readFile = readFile; diff --git a/docs/libs/v0/file/readJsonFile.cjs b/docs/libs/v0/file/readJsonFile.cjs deleted file mode 100644 index 7bb2fb1..0000000 --- a/docs/libs/v0/file/readJsonFile.cjs +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/readJsonFile/index.md} - */ -const readJsonFile = implementor.implementFunction("readJsonFile", { - NODE: async (path) => { - const fs = await implementor.nodeFileSystem.value; - return fs.readFile(path, { encoding: "utf-8" }) - .then(JSON.parse) - .then(utils.E.success) - .catch((value) => utils.E.left("file-system-read-json-file", value)); - }, - DENO: (path) => Deno.readTextFile(path) - .then(JSON.parse) - .then(utils.E.success) - .catch((value) => utils.E.left("file-system-read-json-file", value)), - BUN: (path) => Bun.file(path) - .text() - .then(JSON.parse) - .then(utils.E.success) - .catch((value) => utils.E.left("file-system-read-json-file", value)), -}); - -exports.readJsonFile = readJsonFile; diff --git a/docs/libs/v0/file/readLink.cjs b/docs/libs/v0/file/readLink.cjs deleted file mode 100644 index c95b228..0000000 --- a/docs/libs/v0/file/readLink.cjs +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/readLink/index.md} - */ -const readLink = implementor.implementFunction("readLink", { - NODE: async (path) => { - const fs = await implementor.nodeFileSystem.value; - return fs.readlink(path, { encoding: "utf-8" }) - .then(utils.E.success) - .catch((value) => utils.E.left("file-system-read-link", value)); - }, - DENO: (path) => Deno - .readLink(path) - .then(utils.E.success) - .catch((value) => utils.E.left("file-system-read-link", value)), -}); - -exports.readLink = readLink; diff --git a/docs/libs/v0/file/readTextFile.cjs b/docs/libs/v0/file/readTextFile.cjs deleted file mode 100644 index 6a61476..0000000 --- a/docs/libs/v0/file/readTextFile.cjs +++ /dev/null @@ -1,26 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/readTextFile/index.md} - */ -const readTextFile = implementor.implementFunction("readTextFile", { - NODE: async (path) => { - const fs = await implementor.nodeFileSystem.value; - return fs.readFile(path, { encoding: "utf-8" }) - .then(utils.E.success) - .catch((value) => utils.E.left("file-system-read-text-file", value)); - }, - DENO: (path) => Deno - .readTextFile(path) - .then(utils.E.success) - .catch((value) => utils.E.left("file-system-read-text-file", value)), - BUN: (path) => Bun.file(path) - .text() - .then(utils.E.success) - .catch((value) => utils.E.left("file-system-read-text-file", value)), -}); - -exports.readTextFile = readTextFile; diff --git a/docs/libs/v0/file/realPath.cjs b/docs/libs/v0/file/realPath.cjs deleted file mode 100644 index fb69a0a..0000000 --- a/docs/libs/v0/file/realPath.cjs +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/realPath/index.md} - */ -const realPath = implementor.implementFunction("realPath", { - NODE: async (path) => { - const fs = await implementor.nodeFileSystem.value; - return fs.realpath(path) - .then(utils.E.success) - .catch((value) => utils.E.left("file-system-real-path", value)); - }, - DENO: (path) => Deno - .realPath(path) - .then(utils.E.success) - .catch((value) => utils.E.left("file-system-real-path", value)), -}); - -exports.realPath = realPath; diff --git a/docs/libs/v0/file/relocate.cjs b/docs/libs/v0/file/relocate.cjs deleted file mode 100644 index c38d70f..0000000 --- a/docs/libs/v0/file/relocate.cjs +++ /dev/null @@ -1,33 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/relocate/index.md} - */ -const relocate = implementor.implementFunction("relocate", { - NODE: async (fromPath, newParentPath) => { - const fs = await implementor.nodeFileSystem.value; - const baseName = utils.Path.getBaseName(fromPath); - if (!baseName) { - return utils.E.left("file-system-relocate", new Error(`Invalid base name ${fromPath}`)); - } - const newPath = utils.Path.resolveRelative([newParentPath, baseName]); - return fs.rename(fromPath, newPath) - .then(() => utils.E.success(newPath)) - .catch((value) => utils.E.left("file-system-relocate", value)); - }, - DENO: (fromPath, newParentPath) => { - const baseName = utils.Path.getBaseName(fromPath); - if (!baseName) { - return Promise.resolve(utils.E.left("file-system-relocate", new Error(`Invalid base name ${fromPath}`))); - } - const newPath = utils.Path.resolveRelative([newParentPath, baseName]); - return Deno.rename(fromPath, newPath) - .then(() => utils.E.success(newPath)) - .catch((value) => utils.E.left("file-system-relocate", value)); - }, -}); - -exports.relocate = relocate; diff --git a/docs/libs/v0/file/remove.cjs b/docs/libs/v0/file/remove.cjs deleted file mode 100644 index 293e29a..0000000 --- a/docs/libs/v0/file/remove.cjs +++ /dev/null @@ -1,26 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/remove/index.md} - */ -const remove = implementor.implementFunction("remove", { - NODE: async (path, params) => { - const fs = await implementor.nodeFileSystem.value; - return fs.rm(path, { - recursive: params?.recursive ?? false, - force: true, - }) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-remove", value)); - }, - DENO: (path, params) => Deno.remove(path, { - recursive: params?.recursive, - }) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-remove", value)), -}); - -exports.remove = remove; diff --git a/docs/libs/v0/file/rename.cjs b/docs/libs/v0/file/rename.cjs deleted file mode 100644 index 5960fb0..0000000 --- a/docs/libs/v0/file/rename.cjs +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/rename/index.md} - */ -const rename = implementor.implementFunction("rename", { - NODE: async (path, newName) => { - const fs = await implementor.nodeFileSystem.value; - const parentPath = utils.Path.getParentFolderPath(path); - if (!parentPath) { - return utils.E.left("file-system-rename", new Error(`Invalid parent path ${parentPath}.`)); - } - if (newName.includes("/")) { - return utils.E.left("file-system-rename", new Error(`Invalid new name ${newName}.`)); - } - const newPath = utils.Path.resolveRelative([parentPath, newName]); - return fs.rename(path, newPath) - .then(() => utils.E.success(newPath)) - .catch((value) => utils.E.left("file-system-rename", value)); - }, - DENO: (path, newName) => { - const parentPath = utils.Path.getParentFolderPath(path); - if (!parentPath) { - return Promise.resolve(utils.E.left("file-system-rename", new Error(`Invalid parent path ${parentPath}.`))); - } - if (newName.includes("/")) { - return Promise.resolve(utils.E.left("file-system-rename", new Error(`Invalid new name ${newName}.`))); - } - const newPath = utils.Path.resolveRelative([parentPath, newName]); - return Deno.rename(path, newPath) - .then(() => utils.E.success(newPath)) - .catch((value) => utils.E.left("file-system-rename", value)); - }, -}); - -exports.rename = rename; diff --git a/docs/libs/v0/file/setOwner.cjs b/docs/libs/v0/file/setOwner.cjs deleted file mode 100644 index dfc52b1..0000000 --- a/docs/libs/v0/file/setOwner.cjs +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/setOwner/index.md} - */ -const setOwner = implementor.implementFunction("setOwner", { - NODE: async (path, { userId, groupId }) => { - const fs = await implementor.nodeFileSystem.value; - return fs.chown(path, userId, groupId) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-set-owner", value)); - }, - DENO: (path, { userId, groupId }) => Deno - .chown(path, userId, groupId) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-set-owner", value)), -}); - -exports.setOwner = setOwner; diff --git a/docs/libs/v0/file/setTime.cjs b/docs/libs/v0/file/setTime.cjs deleted file mode 100644 index ff517e9..0000000 --- a/docs/libs/v0/file/setTime.cjs +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/setTime/index.md} - */ -const setTime = implementor.implementFunction("setTime", { - NODE: async (path, { accessTime, modifiedTime }) => { - const fs = await implementor.nodeFileSystem.value; - return fs.utimes(path, utils.D.toTimestamp(accessTime), utils.D.toTimestamp(modifiedTime)) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-set-time", value)); - }, - DENO: (path, { accessTime, modifiedTime }) => Deno - .utime(path, utils.D.toTimestamp(accessTime), utils.D.toTimestamp(modifiedTime)) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-set-time", value)), -}); - -exports.setTime = setTime; diff --git a/docs/libs/v0/file/setTime.mjs b/docs/libs/v0/file/setTime.mjs deleted file mode 100644 index 63d9063..0000000 --- a/docs/libs/v0/file/setTime.mjs +++ /dev/null @@ -1,20 +0,0 @@ -import { D, E } from '@duplojs/utils'; -import { implementFunction, nodeFileSystem } from '../implementor.mjs'; - -/** - * {@include file/setTime/index.md} - */ -const setTime = implementFunction("setTime", { - NODE: async (path, { accessTime, modifiedTime }) => { - const fs = await nodeFileSystem.value; - return fs.utimes(path, D.toTimestamp(accessTime), D.toTimestamp(modifiedTime)) - .then(E.ok) - .catch((value) => E.left("file-system-set-time", value)); - }, - DENO: (path, { accessTime, modifiedTime }) => Deno - .utime(path, D.toTimestamp(accessTime), D.toTimestamp(modifiedTime)) - .then(E.ok) - .catch((value) => E.left("file-system-set-time", value)), -}); - -export { setTime }; diff --git a/docs/libs/v0/file/stat.cjs b/docs/libs/v0/file/stat.cjs deleted file mode 100644 index 6b0fa6b..0000000 --- a/docs/libs/v0/file/stat.cjs +++ /dev/null @@ -1,88 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -function createStatInfoWithFsSource(source) { - return { - isFile: source.isFile(), - isDirectory: source.isDirectory(), - isSymlink: source.isSymbolicLink(), - sizeBytes: source.size, - modifiedAt: utils.D.isSafeTimestamp(source.mtime.getTime()) ? utils.D.createOrThrow(source.mtime) : null, - accessedAt: utils.D.isSafeTimestamp(source.atime.getTime()) ? utils.D.createOrThrow(source.atime) : null, - createdAt: utils.D.isSafeTimestamp(source.birthtime.getTime()) ? utils.D.createOrThrow(source.birthtime) : null, - changedAt: utils.D.isSafeTimestamp(source.ctime.getTime()) ? utils.D.createOrThrow(source.ctime) : null, - deviceId: source.dev, - inode: source.ino, - permissionsMode: source.mode, - hardLinkCount: source.nlink, - ownerUserId: source.uid, - ownerGroupId: source.gid, - specialDeviceId: source.rdev, - ioBlockSize: source.blksize, - allocatedBlockCount: source.blocks, - isBlockDevice: source.isBlockDevice(), - isCharacterDevice: source.isCharacterDevice(), - isFifo: source.isFIFO(), - isSocket: source.isSocket(), - }; -} -function createStatInfoWithDeno(source) { - return { - isFile: source.isFile, - isDirectory: source.isDirectory, - isSymlink: source.isSymlink, - sizeBytes: source.size, - modifiedAt: source.mtime - && utils.D.isSafeTimestamp(source.mtime.getTime()) - ? utils.D.createOrThrow(source.mtime) - : null, - accessedAt: source.atime - && utils.D.isSafeTimestamp(source.atime.getTime()) - ? utils.D.createOrThrow(source.atime) - : null, - createdAt: source.birthtime - && utils.D.isSafeTimestamp(source.birthtime.getTime()) - ? utils.D.createOrThrow(source.birthtime) - : null, - changedAt: source.ctime - && utils.D.isSafeTimestamp(source.ctime.getTime()) - ? utils.D.createOrThrow(source.ctime) - : null, - deviceId: source.dev, - inode: source.ino, - permissionsMode: source.mode, - hardLinkCount: source.nlink, - ownerUserId: source.uid, - ownerGroupId: source.gid, - specialDeviceId: source.rdev, - ioBlockSize: source.blksize, - allocatedBlockCount: source.blocks, - isBlockDevice: source.isBlockDevice, - isCharacterDevice: source.isCharDevice, - isFifo: source.isFifo, - isSocket: source.isSocket, - }; -} -/** - * {@include file/stat/index.md} - */ -const stat = implementor.implementFunction("stat", { - NODE: async (path) => { - const fs = await implementor.nodeFileSystem.value; - return fs.stat(path) - .then(utils.innerPipe(createStatInfoWithFsSource, utils.E.success)) - .catch((value) => utils.E.left("file-system-stat", value)); - }, - DENO: (path) => Deno - .stat(path) - .then(utils.innerPipe(createStatInfoWithDeno, utils.E.success)) - .catch((value) => utils.E.left("file-system-stat", value)), - BUN: (path) => Bun.file(path) - .stat() - .then(utils.innerPipe(createStatInfoWithFsSource, utils.E.success)) - .catch((value) => utils.E.left("file-system-stat", value)), -}); - -exports.stat = stat; diff --git a/docs/libs/v0/file/symlink.cjs b/docs/libs/v0/file/symlink.cjs deleted file mode 100644 index 86f94d5..0000000 --- a/docs/libs/v0/file/symlink.cjs +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/symlink/index.md} - */ -const symlink = implementor.implementFunction("symlink", { - NODE: async (oldPath, newPath, params) => { - const fs = await implementor.nodeFileSystem.value; - return fs.symlink(oldPath, newPath, params?.type) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-symlink", value)); - }, - DENO: (oldPath, newPath, params) => Deno - .symlink(oldPath, newPath, params) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-symlink", value)), -}); - -exports.symlink = symlink; diff --git a/docs/libs/v0/file/truncate.cjs b/docs/libs/v0/file/truncate.cjs deleted file mode 100644 index 48d9e7c..0000000 --- a/docs/libs/v0/file/truncate.cjs +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/truncate/index.md} - */ -const truncate = implementor.implementFunction("truncate", { - NODE: async (path, size) => { - const fs = await implementor.nodeFileSystem.value; - return fs.truncate(path, size) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-truncate", value)); - }, - DENO: (path, size) => utils.pipe(path, utils.when(utils.instanceOf(URL), ({ pathname }) => decodeURIComponent(pathname)), (stringPath) => Deno - .truncate(stringPath, size) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-truncate", value))), -}); - -exports.truncate = truncate; diff --git a/docs/libs/v0/file/types/fileSystemLeft.d.ts b/docs/libs/v0/file/types/fileSystemLeft.d.ts deleted file mode 100644 index 5ca2232..0000000 --- a/docs/libs/v0/file/types/fileSystemLeft.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -import type { E } from "@duplojs/utils"; -export type FileSystemLeft = E.Left<`file-system-${GenericName}`, unknown>; diff --git a/docs/libs/v0/file/walkDirectory.cjs b/docs/libs/v0/file/walkDirectory.cjs deleted file mode 100644 index 960110f..0000000 --- a/docs/libs/v0/file/walkDirectory.cjs +++ /dev/null @@ -1,24 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); -var fileInterface = require('./fileInterface.cjs'); -var folderInterface = require('./folderInterface.cjs'); -var unknownInterface = require('./unknownInterface.cjs'); - -/** - * {@include file/walkDirectory/index.md} - */ -const walkDirectory = implementor.implementFunction("walkDirectory", { - NODE: async (path, params) => { - const fs = await implementor.nodeFileSystem.value; - return fs.readdir(path, { - recursive: params?.recursive ?? false, - withFileTypes: true, - }) - .then(utils.innerPipe(utils.G.map(utils.innerPipe(utils.P.when((dirent) => dirent.isFile(), ({ parentPath, name }) => fileInterface.createFileInterface(`${parentPath}/${name}`)), utils.P.when((dirent) => dirent.isDirectory(), ({ parentPath, name }) => folderInterface.createFolderInterface(`${parentPath}/${name}`)), utils.P.otherwise(({ parentPath, name }) => unknownInterface.createUnknownInterface(`${parentPath}/${name}`)))), utils.E.success)) - .catch((value) => utils.E.left("file-system-walk-directory", value)); - }, -}); - -exports.walkDirectory = walkDirectory; diff --git a/docs/libs/v0/file/walkDirectory.mjs b/docs/libs/v0/file/walkDirectory.mjs deleted file mode 100644 index 8c293bc..0000000 --- a/docs/libs/v0/file/walkDirectory.mjs +++ /dev/null @@ -1,22 +0,0 @@ -import { innerPipe, G, P, E } from '@duplojs/utils'; -import { implementFunction, nodeFileSystem } from '../implementor.mjs'; -import { createFileInterface } from './fileInterface.mjs'; -import { createFolderInterface } from './folderInterface.mjs'; -import { createUnknownInterface } from './unknownInterface.mjs'; - -/** - * {@include file/walkDirectory/index.md} - */ -const walkDirectory = implementFunction("walkDirectory", { - NODE: async (path, params) => { - const fs = await nodeFileSystem.value; - return fs.readdir(path, { - recursive: params?.recursive ?? false, - withFileTypes: true, - }) - .then(innerPipe(G.map(innerPipe(P.when((dirent) => dirent.isFile(), ({ parentPath, name }) => createFileInterface(`${parentPath}/${name}`)), P.when((dirent) => dirent.isDirectory(), ({ parentPath, name }) => createFolderInterface(`${parentPath}/${name}`)), P.otherwise(({ parentPath, name }) => createUnknownInterface(`${parentPath}/${name}`)))), E.success)) - .catch((value) => E.left("file-system-walk-directory", value)); - }, -}); - -export { walkDirectory }; diff --git a/docs/libs/v0/file/writeFile.cjs b/docs/libs/v0/file/writeFile.cjs deleted file mode 100644 index 975ec27..0000000 --- a/docs/libs/v0/file/writeFile.cjs +++ /dev/null @@ -1,27 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/writeFile/index.md} - */ -const writeFile = implementor.implementFunction("writeFile", { - NODE: async (path, data) => { - const fs = await implementor.nodeFileSystem.value; - return fs.writeFile(path, data) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-write-file", value)); - }, - DENO: (path, data) => Deno - .writeFile(path, data) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-write-file", value)), - BUN: (path, data) => Bun - .file(path) - .write(data) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-write-file", value)), -}); - -exports.writeFile = writeFile; diff --git a/docs/libs/v0/file/writeJsonFile.cjs b/docs/libs/v0/file/writeJsonFile.cjs deleted file mode 100644 index 017de44..0000000 --- a/docs/libs/v0/file/writeJsonFile.cjs +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/writeJsonFile/index.md} - */ -const writeJsonFile = implementor.implementFunction("writeJsonFile", { - NODE: async (path, data, params) => { - const fs = await implementor.nodeFileSystem.value; - return utils.pipe(utils.E.safeCallback(() => JSON.stringify(data, null, params?.space)), utils.E.whenIsRight((value) => fs.writeFile(path, value, { encoding: "utf-8" }) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-write-json-file", value))), utils.E.whenIsLeft((value) => utils.E.left("file-system-write-json-file", value))); - }, - DENO: (path, data, params) => utils.asyncPipe(utils.E.safeCallback(() => JSON.stringify(data, null, params?.space)), utils.E.whenIsRight((value) => Deno.writeTextFile(path, value) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-write-json-file", value))), utils.E.whenIsLeft((value) => utils.E.left("file-system-write-json-file", value))), - BUN: (path, data, params) => utils.asyncPipe(utils.E.safeCallback(() => JSON.stringify(data, null, params?.space)), utils.E.whenIsRight((value) => Bun.file(path) - .write(value) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-write-json-file", value))), utils.E.whenIsLeft((value) => utils.E.left("file-system-write-json-file", value))), -}); - -exports.writeJsonFile = writeJsonFile; diff --git a/docs/libs/v0/file/writeJsonFile.mjs b/docs/libs/v0/file/writeJsonFile.mjs deleted file mode 100644 index 8a186b3..0000000 --- a/docs/libs/v0/file/writeJsonFile.mjs +++ /dev/null @@ -1,23 +0,0 @@ -import { asyncPipe, E, pipe } from '@duplojs/utils'; -import { implementFunction, nodeFileSystem } from '../implementor.mjs'; - -/** - * {@include file/writeJsonFile/index.md} - */ -const writeJsonFile = implementFunction("writeJsonFile", { - NODE: async (path, data, params) => { - const fs = await nodeFileSystem.value; - return pipe(E.safeCallback(() => JSON.stringify(data, null, params?.space)), E.whenIsRight((value) => fs.writeFile(path, value, { encoding: "utf-8" }) - .then(E.ok) - .catch((value) => E.left("file-system-write-json-file", value))), E.whenIsLeft((value) => E.left("file-system-write-json-file", value))); - }, - DENO: (path, data, params) => asyncPipe(E.safeCallback(() => JSON.stringify(data, null, params?.space)), E.whenIsRight((value) => Deno.writeTextFile(path, value) - .then(E.ok) - .catch((value) => E.left("file-system-write-json-file", value))), E.whenIsLeft((value) => E.left("file-system-write-json-file", value))), - BUN: (path, data, params) => asyncPipe(E.safeCallback(() => JSON.stringify(data, null, params?.space)), E.whenIsRight((value) => Bun.file(path) - .write(value) - .then(E.ok) - .catch((value) => E.left("file-system-write-json-file", value))), E.whenIsLeft((value) => E.left("file-system-write-json-file", value))), -}); - -export { writeJsonFile }; diff --git a/docs/libs/v0/file/writeTextFile.cjs b/docs/libs/v0/file/writeTextFile.cjs deleted file mode 100644 index 581a3af..0000000 --- a/docs/libs/v0/file/writeTextFile.cjs +++ /dev/null @@ -1,27 +0,0 @@ -'use strict'; - -var utils = require('@duplojs/utils'); -var implementor = require('../implementor.cjs'); - -/** - * {@include file/writeTextFile/index.md} - */ -const writeTextFile = implementor.implementFunction("writeTextFile", { - NODE: async (path, data) => { - const fs = await implementor.nodeFileSystem.value; - return fs.writeFile(path, data, { encoding: "utf-8" }) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-write-text-file", value)); - }, - DENO: (path, data) => Deno - .writeTextFile(path, data) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-write-text-file", value)), - BUN: (path, data) => Bun - .file(path) - .write(data) - .then(utils.E.ok) - .catch((value) => utils.E.left("file-system-write-text-file", value)), -}); - -exports.writeTextFile = writeTextFile; diff --git a/docs/libs/v0/package.json b/docs/libs/v0/package.json new file mode 100644 index 0000000..43df381 --- /dev/null +++ b/docs/libs/v0/package.json @@ -0,0 +1,44 @@ +{ + "name": "v0", + "type": "module", + "exports": { + ".": { + "import": "./dist/index.mjs", + "require": "./dist/index.cjs", + "types": "./dist/index.d.ts" + }, + "./file": { + "import": "./dist/file/index.mjs", + "require": "./dist/file/index.cjs", + "types": "./dist/file/index.d.ts" + }, + "./common": { + "import": "./dist/common/index.mjs", + "require": "./dist/common/index.cjs", + "types": "./dist/common/index.d.ts" + }, + "./dataParser": { + "import": "./dist/dataParser/index.mjs", + "require": "./dist/dataParser/index.cjs", + "types": "./dist/dataParser/index.d.ts" + }, + "./dataParserCoerce": { + "import": "./dist/dataParser/parsers/coerce/index.mjs", + "require": "./dist/dataParser/parsers/coerce/index.cjs", + "types": "./dist/dataParser/parsers/coerce/index.d.ts" + }, + "./dataParserExtended": { + "import": "./dist/dataParser/extended/index.mjs", + "require": "./dist/dataParser/extended/index.cjs", + "types": "./dist/dataParser/extended/index.d.ts" + }, + "./command": { + "import": "./dist/command/index.mjs", + "require": "./dist/command/index.cjs", + "types": "./dist/command/index.d.ts" + } + }, + "peerDependencies": { + "@duplojs/utils": ">=1.6.5 <2.0.0" + } +} diff --git a/docs/package.json b/docs/package.json index 027a47e..eba0cba 100644 --- a/docs/package.json +++ b/docs/package.json @@ -4,13 +4,20 @@ "scripts": { "docs:dev": "vitepress dev", "docs:build": "vitepress build", - "docs:preview": "vitepress preview" + "docs:preview": "vitepress preview", + "test:types": "./.commands/test-types.sh" }, + "workspaces": [ + "libs/**" + ], "devDependencies": { "@shikijs/vitepress-twoslash": "3.21.0", + "@types/web": "^0.0.344", "@vue/tsconfig": "0.8.1", - "vitepress": "^2.0.0-alpha.15", + "vitepress": "^2.0.0-alpha.16", + "@server-utils/v0": "file:libs/v0", "vitepress-plugin-group-icons": "1.7.1", "vue": "3.5.27" } } + \ No newline at end of file diff --git a/integration/deno/deno.json b/integration/deno/deno.json index 4797342..14119a0 100644 --- a/integration/deno/deno.json +++ b/integration/deno/deno.json @@ -24,7 +24,7 @@ }, "imports": { "@duplojs/server-utils": "../../dist/index.mjs", - "@duplojs/utils": "npm:@duplojs/utils@1.6.3", + "@duplojs/utils": "npm:@duplojs/utils@1.7.0", "@std/assert": "jsr:@std/assert@^1.0.0", "@std/testing": "jsr:@std/testing@^1.0.0" }, diff --git a/integration/deno/deno.lock b/integration/deno/deno.lock index 00a33ac..6dfe7ad 100644 --- a/integration/deno/deno.lock +++ b/integration/deno/deno.lock @@ -9,7 +9,7 @@ "jsr:@std/internal@^1.0.12": "1.0.12", "jsr:@std/path@^1.1.4": "1.1.4", "jsr:@std/testing@1": "1.0.17", - "npm:@duplojs/utils@1.6.3": "1.6.3" + "npm:@duplojs/utils@1.7.0": "1.7.0" }, "jsr": { "@std/assert@1.0.17": { @@ -52,15 +52,15 @@ } }, "npm": { - "@duplojs/utils@1.6.3": { - "integrity": "sha512-83qJLc1D+l9cXVRjPSdq7H+/yTrwAidWYKBU+DoBX3iYppDodpk54D1M2dqoFQ16MKYco8CR0f5GxGWN2r5KWQ==" + "@duplojs/utils@1.7.0": { + "integrity": "sha512-LBb/ZpBh7OGJbGYKx6cvq6dmPXTt8EH6FOpPZUBgEcerb2P4boW6gMX/MkGnJ4maR921V3KGZNiIeBA+uK5mWw==" } }, "workspace": { "dependencies": [ "jsr:@std/assert@1", "jsr:@std/testing@1", - "npm:@duplojs/utils@1.6.3" + "npm:@duplojs/utils@1.7.0" ] } } diff --git a/integration/node/index.test.ts b/integration/node/index.test.ts index 4724e77..be40ed1 100644 --- a/integration/node/index.test.ts +++ b/integration/node/index.test.ts @@ -274,49 +274,69 @@ describe("node integration", () => { commandExecuteSpy, ); - try { - getProcessArgumentsSpy.mockReturnValue(["--help"]); - await SC.exec( - { - subject: [command], - }, - rootExecuteSpy, - ); + getProcessArgumentsSpy.mockReturnValue(["--help"]); + await SC.exec( + { + subject: command, + }, + rootExecuteSpy, + ); - expect(logSpy).toHaveBeenCalled(); - expect( - stripAnsiColor( - logSpy.mock.calls.map(([message]) => String(message)).join("\n"), - ), - ).toMatchSnapshot("help root"); - - logSpy.mockClear(); - await command.execute(["--help"]); - expect( - stripAnsiColor( - logSpy.mock.calls.map(([message]) => String(message)).join("\n"), - ), - ).toMatchSnapshot("help command"); - - logSpy.mockClear(); - await command.execute(["help-db", "--help"]); - expect( - stripAnsiColor( - logSpy.mock.calls.map(([message]) => String(message)).join("\n"), - ), - ).toMatchSnapshot("help sub-command"); - - await command.execute(["seed", "--force", "users"]); - expect(subCommandExecuteSpy).toHaveBeenCalledWith({ - options: { - force: true, - }, - subject: ["users"], - }); - } finally { - setEnvironment("NODE"); - TESTImplementation.clear(); - logSpy.mockRestore(); - } + expect(logSpy).toHaveBeenCalled(); + expect( + stripAnsiColor( + logSpy.mock.calls.map(([message]) => String(message)).join("\n"), + ), + ).toMatchSnapshot("help root"); + + logSpy.mockClear(); + getProcessArgumentsSpy.mockReturnValue(["db", "--help"]); + await SC.exec( + { + subject: command, + }, + rootExecuteSpy, + ); + expect( + stripAnsiColor( + logSpy.mock.calls.map(([message]) => String(message)).join("\n"), + ), + ).toMatchSnapshot("help command"); + + logSpy.mockClear(); + getProcessArgumentsSpy.mockReturnValue(["db", "help-db", "--help"]); + await SC.exec( + { + subject: command, + }, + rootExecuteSpy, + ); + expect( + stripAnsiColor( + logSpy.mock.calls.map(([message]) => String(message)).join("\n"), + ), + ).toMatchSnapshot("help sub-command"); + + getProcessArgumentsSpy.mockReturnValue(["db", "seed", "--force", "users"]); + await SC.exec( + { + subject: command, + }, + rootExecuteSpy, + ); + + expect(rootExecuteSpy).not.toHaveBeenCalled(); + expect(commandExecuteSpy).not.toHaveBeenCalled(); + expect(subHelpExecuteSpy).not.toHaveBeenCalled(); + expect(subCommandExecuteSpy).toHaveBeenCalledWith({ + options: { + force: true, + }, + subject: ["users"], + }); + + setEnvironment("NODE"); + TESTImplementation.clear(); + logSpy.mockRestore(); }); }); diff --git a/jsDoc/command/create/example.ts b/jsDoc/command/create/example.ts index ae01bab..8b046a5 100644 --- a/jsDoc/command/create/example.ts +++ b/jsDoc/command/create/example.ts @@ -1,5 +1,5 @@ import { SC } from "@scripts"; -import { DP } from "@duplojs/utils"; +import { C, DP } from "@duplojs/utils"; const ping = SC.create( "ping", @@ -8,13 +8,17 @@ const ping = SC.create( }, ); +const UserId = C.createNewType("user-id", DP.number(), C.Positive); + const greet = SC.create( "greet", { - options: [SC.createOption("name", DP.string(), { required: true })], + options: [SC.createOption("email", C.Email)], + subject: UserId, }, - ({ options: { name } }) => { - // name: string + ({ options: { email }, subject }) => { + // email: C.Email | undefined + // subject: C.GetNewType }, ); diff --git a/jsDoc/command/create/index.md b/jsDoc/command/create/index.md index 9def702..42ae004 100644 --- a/jsDoc/command/create/index.md +++ b/jsDoc/command/create/index.md @@ -1,13 +1,13 @@ Create a command node. -Use this builder to define a command name, its optional options/subject, and the execute handler called after parsing. +Use this builder to define a command name, optional options, an optional subject, and the execute handler called after parsing. ```ts -{@include command/create/example.ts[4,36]} +{@include command/create/example.ts[4,40]} ``` @remarks -`create` supports child commands by setting `subject` to an array of commands. +`subject` can be a parser-like contract for positional arguments, or an array of child commands for nested command trees. @see https://server-utils.duplojs.dev/en/v0/api/command/create @namespace SC diff --git a/jsDoc/command/createArrayOption/example.ts b/jsDoc/command/createArrayOption/example.ts index 904d614..c9caa37 100644 --- a/jsDoc/command/createArrayOption/example.ts +++ b/jsDoc/command/createArrayOption/example.ts @@ -1,11 +1,9 @@ import { SC } from "@scripts"; -import { DP } from "@duplojs/utils"; - -const tags = SC.createArrayOption("tags", DP.string()); +import { C, DP } from "@duplojs/utils"; const ids = SC.createArrayOption( "ids", - DP.string(), + DP.number(), { required: true, min: 1, @@ -18,14 +16,22 @@ const paths = SC.createArrayOption( { separator: ";" }, ); +const UserId = C.createNewType("user-id", DP.number(), C.Positive); +const userIds = SC.createArrayOption("userIds", UserId); + +const tags = SC.createArrayOption("tags", DP.string()); +const emails = SC.createArrayOption("emails", C.Email); + SC.create( "batch", { - options: [tags, ids, paths], + options: [tags, ids, paths, emails, userIds], }, - ({ options: { ids, tags, paths } }) => { - // ids: [string, ...string[]] + ({ options: { ids, tags, paths, emails, userIds } }) => { + // ids: [number, ...number[]] // tags: string[] | undefined // paths: string[] | undefined + // emails: C.Email[] | undefined + // userIds: C.GetNewType[] | undefined }, ); diff --git a/jsDoc/command/createArrayOption/index.md b/jsDoc/command/createArrayOption/index.md index 68b1e17..910d131 100644 --- a/jsDoc/command/createArrayOption/index.md +++ b/jsDoc/command/createArrayOption/index.md @@ -1,13 +1,13 @@ Create an option that parses an array of values. -This option parses a delimited string value into an array and validates each element with the provided DataParser schema. +This option parses a delimited string value into an array and validates each element with the provided DataParser or clean contract. ```ts -{@include command/createArrayOption/example.ts[4,31]} +{@include command/createArrayOption/example.ts[4,37]} ``` @remarks -The default separator is `,`. You can customize it with `separator`. +The default separator is `,`. You can customize it with `separator`, and primitive elements are coerced from CLI string input. @see https://server-utils.duplojs.dev/en/v0/api/command/createArrayOption @namespace SC diff --git a/jsDoc/command/createOption/example.ts b/jsDoc/command/createOption/example.ts index 5d296cd..4bc2145 100644 --- a/jsDoc/command/createOption/example.ts +++ b/jsDoc/command/createOption/example.ts @@ -1,7 +1,5 @@ import { SC } from "@scripts"; -import { DP } from "@duplojs/utils"; - -const port = SC.createOption("port", DP.string()); +import { C, DP } from "@duplojs/utils"; const name = SC.createOption( "name", @@ -17,14 +15,22 @@ const mode = SC.createOption( DP.literal(["dev", "prod"]), ); +const UserId = C.createNewType("user-id", DP.number(), C.Positive); +const userId = SC.createOption("userId", UserId); + +const port = SC.createOption("port", DP.number()); +const email = SC.createOption("email", C.Email); + SC.create( "serve", { - options: [port, name, mode], + options: [port, name, mode, email, userId], }, - ({ options: { port, name, mode } }) => { - // port: string | undefined + ({ options: { port, name, mode, email, userId } }) => { + // port: number | undefined // name: string // mode: "dev" | "prod" | undefined + // email: C.Email | undefined + // userId: C.GetNewType | undefined }, ); diff --git a/jsDoc/command/createOption/index.md b/jsDoc/command/createOption/index.md index c4a987d..1d59c10 100644 --- a/jsDoc/command/createOption/index.md +++ b/jsDoc/command/createOption/index.md @@ -1,13 +1,13 @@ Create an option with a single parsed value. -Use a DataParser schema to parse and validate the option value from `--name=value` or `--name value`. +Use a DataParser or a clean contract to parse and validate the option value from `--name=value` or `--name value`. ```ts -{@include command/createOption/example.ts[4,27]} +{@include command/createOption/example.ts[4,36]} ``` @remarks -Set `required: true` to throw when the option is missing. +Primitive parsers and clean primitive contracts are coerced from CLI string input automatically. @see https://server-utils.duplojs.dev/en/v0/api/command/createOption @namespace SC diff --git a/jsDoc/command/execOptions/example.ts b/jsDoc/command/execOptions/example.ts index 97d092c..03ce9d7 100644 --- a/jsDoc/command/execOptions/example.ts +++ b/jsDoc/command/execOptions/example.ts @@ -9,7 +9,7 @@ const portOption = SC.createOption( required: true, }, ); -const portResult = SC.execOptions(portOption); +const portResult = await SC.execOptions(portOption); // portResult.port: number const tagOption = SC.createArrayOption( @@ -22,5 +22,5 @@ const tagOption = SC.createArrayOption( ); const forceOption = SC.createBooleanOption("force"); -const options = SC.execOptions(tagOption, forceOption); +const options = await SC.execOptions(tagOption, forceOption); // options.tag: string[] | undefined diff --git a/jsDoc/command/execOptions/index.md b/jsDoc/command/execOptions/index.md index a2b1ced..7feef53 100644 --- a/jsDoc/command/execOptions/index.md +++ b/jsDoc/command/execOptions/index.md @@ -1,6 +1,6 @@ Execute command options from process arguments. -`execOptions` reads runtime arguments, executes each option parser, and returns an object keyed by option name. +`execOptions` reads runtime arguments, executes each option parser, and resolves to an object keyed by option name. It also adds an automatic `--help` / `-h` manual generated from the declared options. ```ts diff --git a/package-lock.json b/package-lock.json index 0e6a749..7d969a5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -38,18 +38,29 @@ "node": ">=22.15.1" }, "peerDependencies": { - "@duplojs/utils": ">=1.6.5 <2.0.0" + "@duplojs/utils": ">=1.7.0 <2.0.0" } }, "docs": { + "workspaces": [ + "libs/**" + ], "devDependencies": { + "@server-utils/v0": "file:libs/v0", "@shikijs/vitepress-twoslash": "3.21.0", + "@types/web": "^0.0.344", "@vue/tsconfig": "0.8.1", - "vitepress": "^2.0.0-alpha.15", + "vitepress": "^2.0.0-alpha.16", "vitepress-plugin-group-icons": "1.7.1", "vue": "3.5.27" } }, + "docs/libs/v0": { + "dev": true, + "peerDependencies": { + "@duplojs/utils": ">=1.6.5 <2.0.0" + } + }, "integration": { "dependencies": { "@duplojs/server-utils": "file:.." @@ -600,6 +611,13 @@ "dev": true, "license": "MIT" }, + "node_modules/@docsearch/sidepanel-js": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/@docsearch/sidepanel-js/-/sidepanel-js-4.6.2.tgz", + "integrity": "sha512-Pni85AP/GwRj7fFg8cBJp0U04tzbueBvWSd3gysgnOsVnQVSZwSYncfErUScLE1CAtR+qocPDFjmYR9AMRNJtQ==", + "dev": true, + "license": "MIT" + }, "node_modules/@duplojs/dev-tools": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/@duplojs/dev-tools/-/dev-tools-0.2.0.tgz", @@ -1086,9 +1104,9 @@ "link": true }, "node_modules/@duplojs/utils": { - "version": "1.6.5", - "resolved": "https://registry.npmjs.org/@duplojs/utils/-/utils-1.6.5.tgz", - "integrity": "sha512-IvjhYJ8Rw/ZWGEEETZtXapZGzm0+SDrMdwFCeHauGA/0UmPRheyctRMpC8ctD8CDYT1rnOuS8i6oBhMadgxcIQ==", + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/@duplojs/utils/-/utils-1.7.0.tgz", + "integrity": "sha512-LBb/ZpBh7OGJbGYKx6cvq6dmPXTt8EH6FOpPZUBgEcerb2P4boW6gMX/MkGnJ4maR921V3KGZNiIeBA+uK5mWw==", "license": "MIT", "peer": true, "workspaces": [ @@ -1844,9 +1862,9 @@ } }, "node_modules/@iconify-json/simple-icons": { - "version": "1.2.68", - "resolved": "https://registry.npmjs.org/@iconify-json/simple-icons/-/simple-icons-1.2.68.tgz", - "integrity": "sha512-bQPl1zuZlX6AnofreA1v7J+hoPncrFMppqGboe/SH54jZO37meiBUGBqNOxEpc0HKfZGxJaVVJwZd4gdMYu3hw==", + "version": "1.2.79", + "resolved": "https://registry.npmjs.org/@iconify-json/simple-icons/-/simple-icons-1.2.79.tgz", + "integrity": "sha512-aNyO7Fd1qej9oQfIyohYFRv0lhQLaZ+6UkK1c1qwax0MDPUOZOdq65MlU500kow97pD/W+b2u1And3e25eE24Q==", "dev": true, "license": "CC0-1.0", "dependencies": { @@ -2010,9 +2028,9 @@ } }, "node_modules/@rolldown/pluginutils": { - "version": "1.0.0-beta.53", - "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-beta.53.tgz", - "integrity": "sha512-vENRlFU4YbrwVqNDZ7fLvy+JR1CRkyr01jhSiDpE1u6py3OMzQfztQU2jxykW3ALNxO4kSlqIDeYyD0Y9RcQeQ==", + "version": "1.0.0-rc.13", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.13.tgz", + "integrity": "sha512-3ngTAv6F/Py35BsYbeeLeecvhMKdsKm4AoOETVhAA+Qc8nrA2I0kF7oa93mE9qnIurngOSpMnQ0x2nQY2FPviA==", "dev": true, "license": "MIT" }, @@ -2360,6 +2378,10 @@ "win32" ] }, + "node_modules/@server-utils/v0": { + "resolved": "docs/libs/v0", + "link": true + }, "node_modules/@shikijs/core": { "version": "3.21.0", "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-3.21.0.tgz", @@ -2417,14 +2439,38 @@ } }, "node_modules/@shikijs/transformers": { - "version": "3.21.0", - "resolved": "https://registry.npmjs.org/@shikijs/transformers/-/transformers-3.21.0.tgz", - "integrity": "sha512-CZwvCWWIiRRiFk9/JKzdEooakAP8mQDtBOQ1TKiCaS2E1bYtyBCOkUzS8akO34/7ufICQ29oeSfkb3tT5KtrhA==", + "version": "3.23.0", + "resolved": "https://registry.npmjs.org/@shikijs/transformers/-/transformers-3.23.0.tgz", + "integrity": "sha512-F9msZVxdF+krQNSdQ4V+Ja5QemeAoTQ2jxt7nJCwhDsdF1JWS3KxIQXA3lQbyKwS3J61oHRUSv4jYWv3CkaKTQ==", "dev": true, "license": "MIT", "dependencies": { - "@shikijs/core": "3.21.0", - "@shikijs/types": "3.21.0" + "@shikijs/core": "3.23.0", + "@shikijs/types": "3.23.0" + } + }, + "node_modules/@shikijs/transformers/node_modules/@shikijs/core": { + "version": "3.23.0", + "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-3.23.0.tgz", + "integrity": "sha512-NSWQz0riNb67xthdm5br6lAkvpDJRTgB36fxlo37ZzM2yq0PQFFzbd8psqC2XMPgCzo1fW6cVi18+ArJ44wqgA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "3.23.0", + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.4", + "hast-util-to-html": "^9.0.5" + } + }, + "node_modules/@shikijs/transformers/node_modules/@shikijs/types": { + "version": "3.23.0", + "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-3.23.0.tgz", + "integrity": "sha512-3JZ5HXOZfYjsYSk0yPwBrkupyYSLpAE26Qc0HLghhZNGTZg/SKxXIIgoxOpmmeQP0RRSDJTk1/vPfw9tbw+jSQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.4" } }, "node_modules/@shikijs/twoslash": { @@ -2668,6 +2714,13 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/web": { + "version": "0.0.344", + "resolved": "https://registry.npmjs.org/@types/web/-/web-0.0.344.tgz", + "integrity": "sha512-5CqToBLlIpnOfqd7KDOTC5aHWvc5XykMruv1h+FGl2MHSvZIxHjxt0WKNJspoGVHf95n8e88jMBATPFBhKRyLQ==", + "dev": true, + "license": "Apache-2.0" + }, "node_modules/@types/web-bluetooth": { "version": "0.0.21", "resolved": "https://registry.npmjs.org/@types/web-bluetooth/-/web-bluetooth-0.0.21.tgz", @@ -2837,19 +2890,19 @@ "license": "ISC" }, "node_modules/@vitejs/plugin-vue": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-6.0.3.tgz", - "integrity": "sha512-TlGPkLFLVOY3T7fZrwdvKpjprR3s4fxRln0ORDo1VQ7HHyxJwTlrjKU3kpVWTlaAjIEuCTokmjkZnr8Tpc925w==", + "version": "6.0.6", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-6.0.6.tgz", + "integrity": "sha512-u9HHgfrq3AjXlysn0eINFnWQOJQLO9WN6VprZ8FXl7A2bYisv3Hui9Ij+7QZ41F/WYWarHjwBbXtD7dKg3uxbg==", "dev": true, "license": "MIT", "dependencies": { - "@rolldown/pluginutils": "1.0.0-beta.53" + "@rolldown/pluginutils": "1.0.0-rc.13" }, "engines": { "node": "^20.19.0 || >=22.12.0" }, "peerDependencies": { - "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0", + "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0", "vue": "^3.2.25" } }, @@ -3214,15 +3267,15 @@ } }, "node_modules/@vueuse/core": { - "version": "14.1.0", - "resolved": "https://registry.npmjs.org/@vueuse/core/-/core-14.1.0.tgz", - "integrity": "sha512-rgBinKs07hAYyPF834mDTigH7BtPqvZ3Pryuzt1SD/lg5wEcWqvwzXXYGEDb2/cP0Sj5zSvHl3WkmMELr5kfWw==", + "version": "14.2.1", + "resolved": "https://registry.npmjs.org/@vueuse/core/-/core-14.2.1.tgz", + "integrity": "sha512-3vwDzV+GDUNpdegRY6kzpLm4Igptq+GA0QkJ3W61Iv27YWwW/ufSlOfgQIpN6FZRMG0mkaz4gglJRtq5SeJyIQ==", "dev": true, "license": "MIT", "dependencies": { "@types/web-bluetooth": "^0.0.21", - "@vueuse/metadata": "14.1.0", - "@vueuse/shared": "14.1.0" + "@vueuse/metadata": "14.2.1", + "@vueuse/shared": "14.2.1" }, "funding": { "url": "https://github.com/sponsors/antfu" @@ -3232,14 +3285,14 @@ } }, "node_modules/@vueuse/integrations": { - "version": "14.1.0", - "resolved": "https://registry.npmjs.org/@vueuse/integrations/-/integrations-14.1.0.tgz", - "integrity": "sha512-eNQPdisnO9SvdydTIXnTE7c29yOsJBD/xkwEyQLdhDC/LKbqrFpXHb3uS//7NcIrQO3fWVuvMGp8dbK6mNEMCA==", + "version": "14.2.1", + "resolved": "https://registry.npmjs.org/@vueuse/integrations/-/integrations-14.2.1.tgz", + "integrity": "sha512-2LIUpBi/67PoXJGqSDQUF0pgQWpNHh7beiA+KG2AbybcNm+pTGWT6oPGlBgUoDWmYwfeQqM/uzOHqcILpKL7nA==", "dev": true, "license": "MIT", "dependencies": { - "@vueuse/core": "14.1.0", - "@vueuse/shared": "14.1.0" + "@vueuse/core": "14.2.1", + "@vueuse/shared": "14.2.1" }, "funding": { "url": "https://github.com/sponsors/antfu" @@ -3249,7 +3302,7 @@ "axios": "^1", "change-case": "^5", "drauu": "^0.4", - "focus-trap": "^7", + "focus-trap": "^7 || ^8", "fuse.js": "^7", "idb-keyval": "^6", "jwt-decode": "^4", @@ -3299,9 +3352,9 @@ } }, "node_modules/@vueuse/metadata": { - "version": "14.1.0", - "resolved": "https://registry.npmjs.org/@vueuse/metadata/-/metadata-14.1.0.tgz", - "integrity": "sha512-7hK4g015rWn2PhKcZ99NyT+ZD9sbwm7SGvp7k+k+rKGWnLjS/oQozoIZzWfCewSUeBmnJkIb+CNr7Zc/EyRnnA==", + "version": "14.2.1", + "resolved": "https://registry.npmjs.org/@vueuse/metadata/-/metadata-14.2.1.tgz", + "integrity": "sha512-1ButlVtj5Sb/HDtIy1HFr1VqCP4G6Ypqt5MAo0lCgjokrk2mvQKsK2uuy0vqu/Ks+sHfuHo0B9Y9jn9xKdjZsw==", "dev": true, "license": "MIT", "funding": { @@ -3309,9 +3362,9 @@ } }, "node_modules/@vueuse/shared": { - "version": "14.1.0", - "resolved": "https://registry.npmjs.org/@vueuse/shared/-/shared-14.1.0.tgz", - "integrity": "sha512-EcKxtYvn6gx1F8z9J5/rsg3+lTQnvOruQd8fUecW99DCK04BkWD7z5KQ/wTAx+DazyoEE9dJt/zV8OIEQbM6kw==", + "version": "14.2.1", + "resolved": "https://registry.npmjs.org/@vueuse/shared/-/shared-14.2.1.tgz", + "integrity": "sha512-shTJncjV9JTI4oVNyF1FQonetYAiTBd+Qj7cY89SWbXSkx7gyhrgtEdF2ZAVWS1S3SHlaROO6F2IesJxQEkZBw==", "dev": true, "license": "MIT", "funding": { @@ -4817,9 +4870,9 @@ } }, "node_modules/focus-trap": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/focus-trap/-/focus-trap-7.8.0.tgz", - "integrity": "sha512-/yNdlIkpWbM0ptxno3ONTuf+2g318kh2ez3KSeZN5dZ8YC6AAmgeWz+GasYYiBJPFaYcSAPeu4GfhUaChzIJXA==", + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/focus-trap/-/focus-trap-8.1.0.tgz", + "integrity": "sha512-T65crff26CKV2CZ3csg5y05r+560srp0b8EbAif35euW58hzklVf/Gb4Q+/HCtB8e9III3QFEyk5BWV5XJuOyw==", "dev": true, "license": "MIT", "dependencies": { @@ -8638,9 +8691,9 @@ } }, "node_modules/vite": { - "version": "7.3.0", - "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.0.tgz", - "integrity": "sha512-dZwN5L1VlUBewiP6H9s2+B3e3Jg96D0vzN+Ry73sOefebhYr9f94wwkMNN/9ouoU8pV1BqA1d1zGk8928cx0rg==", + "version": "7.3.2", + "resolved": "https://registry.npmjs.org/vite/-/vite-7.3.2.tgz", + "integrity": "sha512-Bby3NOsna2jsjfLVOHKes8sGwgl4TT0E6vvpYgnAYDIF/tie7MRaFthmKuHx1NSXjiTueXH3do80FMQgvEktRg==", "dev": true, "license": "MIT", "dependencies": { @@ -8756,30 +8809,31 @@ } }, "node_modules/vitepress": { - "version": "2.0.0-alpha.15", - "resolved": "https://registry.npmjs.org/vitepress/-/vitepress-2.0.0-alpha.15.tgz", - "integrity": "sha512-jhjSYd10Z6RZiKOa7jy0xMVf5NB5oSc/lS3bD/QoUc6V8PrvQR5JhC9104NEt6+oTGY/ftieVWxY9v7YI+1IjA==", + "version": "2.0.0-alpha.17", + "resolved": "https://registry.npmjs.org/vitepress/-/vitepress-2.0.0-alpha.17.tgz", + "integrity": "sha512-Z3VPUpwk/bHYqt1uMVOOK1/4xFiWQov1GNc2FvMdz6kvje4JRXEOngVI9C+bi5jeedMSHiA4dwKkff1NCvbZ9Q==", "dev": true, "license": "MIT", "dependencies": { - "@docsearch/css": "^4.3.2", - "@docsearch/js": "^4.3.2", - "@iconify-json/simple-icons": "^1.2.59", - "@shikijs/core": "^3.15.0", - "@shikijs/transformers": "^3.15.0", - "@shikijs/types": "^3.15.0", + "@docsearch/css": "^4.5.3", + "@docsearch/js": "^4.5.3", + "@docsearch/sidepanel-js": "^4.5.3", + "@iconify-json/simple-icons": "^1.2.69", + "@shikijs/core": "^3.22.0", + "@shikijs/transformers": "^3.22.0", + "@shikijs/types": "^3.22.0", "@types/markdown-it": "^14.1.2", - "@vitejs/plugin-vue": "^6.0.1", + "@vitejs/plugin-vue": "^6.0.4", "@vue/devtools-api": "^8.0.5", - "@vue/shared": "^3.5.24", - "@vueuse/core": "^14.0.0", - "@vueuse/integrations": "^14.0.0", - "focus-trap": "^7.6.6", + "@vue/shared": "^3.5.27", + "@vueuse/core": "^14.2.0", + "@vueuse/integrations": "^14.2.0", + "focus-trap": "^8.0.0", "mark.js": "8.11.1", "minisearch": "^7.2.0", - "shiki": "^3.15.0", - "vite": "^7.2.2", - "vue": "^3.5.24" + "shiki": "^3.22.0", + "vite": "^7.3.1", + "vue": "^3.5.27" }, "bin": { "vitepress": "bin/vitepress.js" @@ -8821,6 +8875,90 @@ } } }, + "node_modules/vitepress/node_modules/@shikijs/core": { + "version": "3.23.0", + "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-3.23.0.tgz", + "integrity": "sha512-NSWQz0riNb67xthdm5br6lAkvpDJRTgB36fxlo37ZzM2yq0PQFFzbd8psqC2XMPgCzo1fW6cVi18+ArJ44wqgA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "3.23.0", + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.4", + "hast-util-to-html": "^9.0.5" + } + }, + "node_modules/vitepress/node_modules/@shikijs/engine-javascript": { + "version": "3.23.0", + "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-3.23.0.tgz", + "integrity": "sha512-aHt9eiGFobmWR5uqJUViySI1bHMqrAgamWE1TYSUoftkAeCCAiGawPMwM+VCadylQtF4V3VNOZ5LmfItH5f3yA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "3.23.0", + "@shikijs/vscode-textmate": "^10.0.2", + "oniguruma-to-es": "^4.3.4" + } + }, + "node_modules/vitepress/node_modules/@shikijs/engine-oniguruma": { + "version": "3.23.0", + "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-3.23.0.tgz", + "integrity": "sha512-1nWINwKXxKKLqPibT5f4pAFLej9oZzQTsby8942OTlsJzOBZ0MWKiwzMsd+jhzu8YPCHAswGnnN1YtQfirL35g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "3.23.0", + "@shikijs/vscode-textmate": "^10.0.2" + } + }, + "node_modules/vitepress/node_modules/@shikijs/langs": { + "version": "3.23.0", + "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-3.23.0.tgz", + "integrity": "sha512-2Ep4W3Re5aB1/62RSYQInK9mM3HsLeB91cHqznAJMuylqjzNVAVCMnNWRHFtcNHXsoNRayP9z1qj4Sq3nMqYXg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "3.23.0" + } + }, + "node_modules/vitepress/node_modules/@shikijs/themes": { + "version": "3.23.0", + "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-3.23.0.tgz", + "integrity": "sha512-5qySYa1ZgAT18HR/ypENL9cUSGOeI2x+4IvYJu4JgVJdizn6kG4ia5Q1jDEOi7gTbN4RbuYtmHh0W3eccOrjMA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/types": "3.23.0" + } + }, + "node_modules/vitepress/node_modules/@shikijs/types": { + "version": "3.23.0", + "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-3.23.0.tgz", + "integrity": "sha512-3JZ5HXOZfYjsYSk0yPwBrkupyYSLpAE26Qc0HLghhZNGTZg/SKxXIIgoxOpmmeQP0RRSDJTk1/vPfw9tbw+jSQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.4" + } + }, + "node_modules/vitepress/node_modules/shiki": { + "version": "3.23.0", + "resolved": "https://registry.npmjs.org/shiki/-/shiki-3.23.0.tgz", + "integrity": "sha512-55Dj73uq9ZXL5zyeRPzHQsK7Nbyt6Y10k5s7OjuFZGMhpp4r/rsLBH0o/0fstIzX1Lep9VxefWljK/SKCzygIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@shikijs/core": "3.23.0", + "@shikijs/engine-javascript": "3.23.0", + "@shikijs/engine-oniguruma": "3.23.0", + "@shikijs/langs": "3.23.0", + "@shikijs/themes": "3.23.0", + "@shikijs/types": "3.23.0", + "@shikijs/vscode-textmate": "^10.0.2", + "@types/hast": "^3.0.4" + } + }, "node_modules/vitest": { "version": "3.2.4", "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.4.tgz", diff --git a/package.json b/package.json index 3f325a3..abaf1e4 100644 --- a/package.json +++ b/package.json @@ -13,15 +13,14 @@ }, "scripts": { "build": "rollup --config", - "test:tu": "vitest --coverage", - "test:tu:bench": "vitest bench", - "test:tu:watch": "vitest --coverage --watch", - "test:tu:update": "vitest --coverage --update", + "test:tu": "./.commands/test-tu.sh", + "test:tu:watch": "./.commands/test-tu.sh --watch", + "test:tu:update": "./.commands/test-tu.sh --update", "test:integration:bun": "bun test integration/bun", "test:integration:deno": "deno test -P -c integration/deno/deno.json integration/deno", - "test:types": "tsc -p tsconfig.test.json", - "test:lint": "eslint --quiet", - "test:lint:fix": "eslint --fix --quiet", + "test:types": "./.commands/test-types.sh", + "test:lint": "./.commands/test-lint.sh", + "test:lint:fix": "./.commands/test-lint.sh --fix", "docs:dev": "npm -w docs run docs:dev", "docs:build": "npm -w docs run docs:build", "docs:preview": "npm -w docs run docs:preview", @@ -92,7 +91,7 @@ "@duplojs/dev-tools": "0.2.0" }, "peerDependencies": { - "@duplojs/utils": ">=1.6.5 <2.0.0" + "@duplojs/utils": ">=1.7.0 <2.0.0" }, "workspaces": [ "integration", diff --git a/scripts/command/create.ts b/scripts/command/create.ts deleted file mode 100644 index 86c19c8..0000000 --- a/scripts/command/create.ts +++ /dev/null @@ -1,258 +0,0 @@ -import { type SimplifyTopLevel, type Kind, type AnyFunction, type RemoveKind, unwrap, type MaybePromise } from "@duplojs/utils"; -import * as AA from "@duplojs/utils/array"; -import * as OO from "@duplojs/utils/object"; -import * as DDP from "@duplojs/utils/dataParser"; -import * as EE from "@duplojs/utils/either"; -import { createBooleanOption, type Option } from "./options"; -import { createDuplojsServerUtilsKind } from "@scripts/kind"; -import type { EligibleDataParser } from "./types"; -import { exitProcess } from "@scripts/common/exitProcess"; -import { addIssue, addDataParserError, createError, interpretCommandError, popErrorPath, setErrorPath, SymbolCommandError, type CommandError } from "./error"; -import { logCommandHelp } from "./help"; - -export type Subject = ( - | EligibleDataParser - | DDP.DataParserArray< - SimplifyTopLevel< - & Omit - & { - readonly element: EligibleDataParser; - } - > - > - | DDP.AdvancedContract< - DDP.DataParserTuple< - SimplifyTopLevel< - & Omit - & { - readonly shape: readonly [ - EligibleDataParser, - ...EligibleDataParser[], - ]; - readonly rest: EligibleDataParser | undefined; - } - > - > - > -); - -function printError(commandError: CommandError, error?: CommandError): SymbolCommandError { - if (!error) { - // eslint-disable-next-line no-console - console.error(interpretCommandError(commandError)); - exitProcess(1); - } - - return SymbolCommandError; -} - -const commandKind = createDuplojsServerUtilsKind("command"); - -const helpOption = createBooleanOption("help", { aliases: ["h"] }); - -export interface Command extends Kind< - typeof commandKind.definition -> { - readonly name: string; - readonly description: string | null; - readonly subject: Subject | null | readonly Command[]; - readonly options: readonly Option[]; - execute(args: readonly string[], error?: CommandError): Promise; -} - -export interface CreateCommandParams< - GenericOptions extends readonly Option[] = [], - GenericSubject extends Subject = Subject, -> { - description?: string; - options?: GenericOptions; - subject?: GenericSubject | readonly Command[]; -} - -export interface CreateCommandExecuteParams< - GenericOptions extends readonly Option[], - GenericSubject extends Subject, -> { - options: { - [GenericOptionName in GenericOptions[number]["name"]]: Exclude< - ReturnType< - Extract< - GenericOptions[number], - { name: GenericOptionName } - >["execute"] - >, - SymbolCommandError - >["result"] - }; - subject: DDP.Output; -} - -/** - * {@include command/create/index.md} - */ -export function create( - name: string, - execute: () => void, -): Command; - -export function create< - GenericOptions extends readonly Option[], - GenericSubject extends Subject, ->( - name: string, - params: CreateCommandParams< - GenericOptions, - GenericSubject - >, - execute: ( - params: CreateCommandExecuteParams, - ) => MaybePromise, -): Command; - -export function create( - ...args: [string, AnyFunction] | [string, CreateCommandParams, AnyFunction] -): Command { - const [name, params, execute] = args.length === 2 - ? [args[0], {}, args[1]] - : args; - - const self: Command = commandKind.setTo( - { - name, - description: params.description ?? null, - options: params.options ?? [], - subject: params.subject ?? null, - execute: async(args, error?) => { - const commandError = error ?? createError(self.name); - const pathIndex = commandError.currentCommandPath.length; - - if (self.subject instanceof Array) { - for (const command of self.subject) { - if (args[0] === command.name) { - let result: Awaited> | undefined = undefined; - - setErrorPath(commandError, command.name, pathIndex); - try { - result = await command.execute(AA.shift(args), commandError); - } finally { - popErrorPath(commandError); - } - - if (result === SymbolCommandError) { - return printError(commandError, error); - } - - return result; - } - } - } - - const help = helpOption.execute(args, commandError); - - if (help === SymbolCommandError) { - return printError(commandError, error); - } else if (help.result) { - logCommandHelp(self); - return void exitProcess(0); - } - - const commandOptions = AA.reduce( - self.options, - AA.reduceFrom<{ - options: Record; - restArgs: readonly string[]; - }>({ - options: {}, - restArgs: args, - }), - ({ element: option, lastValue, next, exit }) => { - const optionResult = option.execute(lastValue.restArgs, commandError); - - if (optionResult === SymbolCommandError) { - return exit(SymbolCommandError); - } - - return next({ - options: OO.override( - lastValue.options, - { - [option.name]: optionResult.result, - }, - ), - restArgs: optionResult.argumentRest, - }); - }, - ); - - if (commandOptions === SymbolCommandError) { - return printError(commandError, error); - } - - if (self.subject === null) { - await execute({ options: commandOptions.options }); - } else if ( - DDP.identifier(self.subject, DDP.arrayKind) - || DDP.identifier(self.subject, DDP.tupleKind) - ) { - const subjectResult = self.subject.parse(commandOptions.restArgs); - - if (EE.isLeft(subjectResult)) { - addDataParserError( - commandError, - unwrap(subjectResult), - { - type: "subject", - }, - ); - - return printError(commandError, error); - } - - await execute({ - options: commandOptions.options, - subject: unwrap(subjectResult), - }); - } else if (DDP.identifier(self.subject, DDP.dataParserKind)) { - if (commandOptions.restArgs.length > 1) { - addIssue( - commandError, - { - type: "command", - expected: "exactly one subject argument", - received: commandOptions.restArgs, - message: `Expected exactly one subject argument, received ${commandOptions.restArgs.length}.`, - }, - ); - - return printError(commandError, error); - } - - const subjectResult = self.subject.parse(commandOptions.restArgs); - - if (EE.isLeft(subjectResult)) { - addDataParserError( - commandError, - unwrap(subjectResult), - { - type: "subject", - }, - ); - - return printError(commandError, error); - } - - await execute({ - options: commandOptions.options, - subject: unwrap(subjectResult), - }); - } else { - await execute({}); - } - - return void exitProcess(0); - }, - } satisfies RemoveKind, - ); - - return self; -} diff --git a/scripts/command/create/index.ts b/scripts/command/create/index.ts new file mode 100644 index 0000000..2f2519f --- /dev/null +++ b/scripts/command/create/index.ts @@ -0,0 +1,249 @@ +import { type Kind, type AnyFunction, type RemoveKind, unwrap, type MaybePromise, type AnyTuple, justExec, type IsEqual } from "@duplojs/utils"; +import * as AA from "@duplojs/utils/array"; +import * as GG from "@duplojs/utils/generator"; +import * as OO from "@duplojs/utils/object"; +import * as EE from "@duplojs/utils/either"; +import type * as DDP from "@duplojs/utils/dataParser"; +import { createDuplojsServerUtilsKind } from "@scripts/kind"; +import { exitProcess } from "@scripts/common/exitProcess"; +import type { Option } from "../options"; +import { addIssue, addIssueDataParser, SymbolCommandError, type CommandError } from "../error"; +import { logCommandHelp, helpOption } from "../help"; +import { isMultiSubject, subjectToDataParser, type ComputeSubject, type Subject } from "./subject"; + +export type { Subject } from "./subject"; + +const commandKind = createDuplojsServerUtilsKind("command"); + +export function isCommand(input: unknown): input is Command | AnyTuple { + return input instanceof Array + ? input.every(commandKind.has) + : commandKind.has(input); +} + +export type CommandChildren = { + type: "subCommand"; + subCommands: readonly Command[]; +} | { + type: "subject"; + subject: Subject; + dataParser: DDP.DataParser; +}; + +export interface Command extends Kind< + typeof commandKind.definition +> { + readonly name: string; + readonly description: string | null; + readonly children: CommandChildren | null; + readonly options: readonly Option[]; + execute(args: readonly string[], error: CommandError): Promise; +} + +export interface CreateCommandParams< + GenericOptions extends readonly Option[] = readonly [], + GenericSubject extends Subject | Command | AnyTuple | undefined = undefined, +> { + description?: string; + options?: GenericOptions; + subject?: GenericSubject; +} + +export type CreateCommandExecuteParams< + GenericOptions extends readonly Option[] = readonly [], + GenericSubject extends Subject | Command | AnyTuple | undefined = undefined, +> = ( + & ( + IsEqual extends true + ? {} + : { + options: { + [GenericOption in GenericOptions[number] as GenericOption["name"]]: Exclude< + Awaited>, + SymbolCommandError + >["result"] + }; + } + ) + & ( + [GenericSubject] extends [Subject] + ? { + subject: ComputeSubject; + } + : {} + ) +); + +/** + * {@include command/create/index.md} + */ +export function create( + name: string, + execute: () => void, +): Command; + +export function create< + GenericOptions extends readonly Option[] = readonly [], + GenericSubject extends Subject | Command | AnyTuple | undefined = undefined, +>( + name: string, + params: CreateCommandParams< + GenericOptions, + GenericSubject + >, + execute: ( + params: CreateCommandExecuteParams, + ) => MaybePromise, +): Command; + +export function create( + ...args: [string, AnyFunction] | [string, CreateCommandParams, AnyFunction] +): Command { + const [name, params, execute] = args.length === 2 + ? [args[0], {}, args[1]] + : args; + + const self: Command = commandKind.setTo( + { + name, + description: params.description ?? null, + options: params.options ?? [], + children: justExec((): CommandChildren | null => { + if (isCommand(params.subject)) { + return { + type: "subCommand", + subCommands: AA.coalescing(params.subject), + }; + } else if (params.subject) { + return { + type: "subject", + subject: params.subject, + dataParser: subjectToDataParser(params.subject), + }; + } + + return null; + }), + execute: async(args, error) => { + if (self.children?.type === "subCommand") { + for (const command of self.children.subCommands) { + if (args[0] === command.name) { + error.currentCommandPath[ + error.currentCommandPath.length + ] = command.name; + return command.execute(AA.shift(args), error); + } + } + } + + const help = await helpOption.execute(args, error); + + if (help === SymbolCommandError) { + return SymbolCommandError; + } else if (help.result) { + logCommandHelp(self); + return void exitProcess(0); + } + + const commandOptions = await GG.asyncReduce( + self.options, + GG.reduceFrom<{ + options: Record; + restArgs: readonly string[]; + }>({ + options: {}, + restArgs: args, + }), + async({ element: option, lastValue, next, exit }) => { + const optionResult = await option.execute(lastValue.restArgs, error); + + if (optionResult === SymbolCommandError) { + return exit(SymbolCommandError); + } + + return next({ + options: OO.override( + lastValue.options, + { + [option.name]: optionResult.result, + }, + ), + restArgs: optionResult.argumentRest, + }); + }, + ); + + if (commandOptions === SymbolCommandError) { + return SymbolCommandError; + } + + if (self.children?.type === "subject") { + const hasMultiSubject = isMultiSubject(self.children.subject); + + if ( + !hasMultiSubject + && commandOptions.restArgs.length > 1 + ) { + addIssue( + error, + { + type: "command", + expected: "exactly one subject argument", + received: commandOptions.restArgs, + message: `Expected exactly one subject argument, received ${commandOptions.restArgs.length}.`, + }, + ); + + return SymbolCommandError; + } + + const subjectInput = hasMultiSubject + ? commandOptions.restArgs + : commandOptions.restArgs[0]; + + const subjectResult = self.children.dataParser.isAsynchronous() + ? await self.children.dataParser.asyncParse(subjectInput) + : self.children.dataParser.parse(subjectInput); + + if (EE.isLeft(subjectResult)) { + addIssueDataParser( + error, + unwrap(subjectResult), + { + type: "subject", + }, + ); + + return SymbolCommandError; + } + + await execute({ + options: commandOptions.options, + subject: unwrap(subjectResult), + }); + } else { + if (commandOptions.restArgs.length > 0) { + addIssue( + error, + { + type: "command", + expected: "existing child command", + received: commandOptions.restArgs[0], + message: `Unknown child command "${commandOptions.restArgs[0]}".`, + }, + ); + return SymbolCommandError; + } + + await execute({ options: commandOptions.options }); + } + + return void exitProcess(0); + }, + } satisfies RemoveKind, + ); + + return self; +} diff --git a/scripts/command/create/subject.ts b/scripts/command/create/subject.ts new file mode 100644 index 0000000..1cf05ad --- /dev/null +++ b/scripts/command/create/subject.ts @@ -0,0 +1,132 @@ +import { hasSomeKinds, type AnyTuple, type SimplifyTopLevel, type ExpectType } from "@duplojs/utils"; +import * as DDP from "@duplojs/utils/dataParser"; +import * as AA from "@duplojs/utils/array"; +import * as CC from "@duplojs/utils/clean"; +import * as SDP from "@scripts/dataParser"; +import type { ComputeEligibleCleanType, EligibleCleanType, EligibleDataParser } from "../types"; + +export type Subject = ( + | EligibleDataParser + | DDP.DataParserArray< + SimplifyTopLevel< + & Omit + & { + readonly element: EligibleDataParser; + } + > + > + | DDP.AdvancedContract< + DDP.DataParserTuple< + SimplifyTopLevel< + & Omit + & { + readonly shape: readonly [ + EligibleDataParser, + ...EligibleDataParser[], + ]; + readonly rest: EligibleDataParser | undefined; + } + > + > + > + | EligibleCleanType + | AnyTuple +); + +export type ComputeSubject< + GenericSubject extends Subject, +> = [GenericSubject] extends [DDP.DataParser] + ? DDP.Output + : [GenericSubject] extends [EligibleCleanType] + ? ComputeEligibleCleanType + : [GenericSubject] extends [AnyTuple] + ? { + [GenericKey in keyof GenericSubject]: + GenericSubject[GenericKey] extends EligibleCleanType | EligibleDataParser + ? ComputeSubject + : never + } + : never; + +export function subjectToDataParser( + contract: Subject, +): DDP.DataParser { + if ( + hasSomeKinds(contract, [ + DDP.numberKind, + DDP.bigIntKind, + DDP.dateKind, + DDP.timeKind, + DDP.nilKind, + SDP.fileKind, + ]) + ) { + const clone = contract.clone(); + + (clone.definition.coerce as any) = true; + + return clone; + } else if (DDP.identifier(contract, DDP.arrayKind)) { + return DDP.array( + subjectToDataParser(contract.definition.element), + contract.definition, + ); + } else if (DDP.identifier(contract, DDP.tupleKind)) { + return DDP.tuple( + AA.mapTuple( + contract.definition.shape, + (part) => subjectToDataParser(part), + ), + { + ...contract.definition, + rest: contract.definition.rest + ? subjectToDataParser(contract.definition.rest) + : undefined, + }, + ); + } else if (contract instanceof Array) { + return DDP.tuple( + AA.mapTuple( + contract as never, + subjectToDataParser, + ), + ); + } else if ( + hasSomeKinds( + contract, + [ + DDP.unionKind, + DDP.pipeKind, + DDP.optionalKind, + DDP.literalKind, + DDP.transformKind, + DDP.templateLiteralKind, + DDP.stringKind, + ], + ) + ) { + return contract; + } else { + type _check = ExpectType< + typeof contract, + EligibleCleanType, + "strict" + >; + return CC.toMapDataParser( + contract as never, + { coerce: true }, + ); + } +} + +export function isMultiSubject(subject: Subject): boolean { + return subject instanceof Array + || hasSomeKinds( + subject, + [ + DDP.tupleKind, + DDP.arrayKind, + CC.entityPropertyArrayKind, + ], + ); +} diff --git a/scripts/command/error.ts b/scripts/command/error.ts index c7a56f9..22aeb16 100644 --- a/scripts/command/error.ts +++ b/scripts/command/error.ts @@ -31,7 +31,7 @@ export function createError( export function addIssue( error: CommandError, issue: Omit, -): typeof SymbolCommandError { +): SymbolCommandError { error.issues.push( { ...issue, @@ -42,25 +42,7 @@ export function addIssue( return SymbolCommandError; } -export function setErrorPath( - error: CommandError, - value: string, - index: number, -): CommandError { - error.currentCommandPath[index] = value; - - return error; -} - -export function popErrorPath( - error: CommandError, -): CommandError { - error.currentCommandPath.pop(); - - return error; -} - -export function addDataParserError( +export function addIssueDataParser( error: CommandError, parseError: DDP.DataParserError, params: { diff --git a/scripts/command/exec.ts b/scripts/command/exec.ts index 1d604a5..c9a255f 100644 --- a/scripts/command/exec.ts +++ b/scripts/command/exec.ts @@ -1,7 +1,8 @@ -import type { AnyFunction, MaybePromise } from "@duplojs/utils"; -import { type CreateCommandExecuteParams, type CreateCommandParams, type Subject, create } from "./create"; +import type { AnyFunction, MaybePromise, AnyTuple } from "@duplojs/utils"; +import { type Command, type Subject, type CreateCommandExecuteParams, type CreateCommandParams, create } from "./create"; import type { Option } from "./options"; -import { getProcessArguments } from "@scripts/common"; +import { exitProcess, getProcessArguments } from "@scripts/common"; +import { createError, interpretCommandError, SymbolCommandError } from "./error"; /** * {@include command/exec/index.md} @@ -12,7 +13,7 @@ export function exec( export function exec< GenericOptions extends readonly Option[], - GenericSubject extends Subject, + GenericSubject extends Subject | Command | AnyTuple | undefined, >( params: CreateCommandParams< GenericOptions, @@ -30,11 +31,20 @@ export async function exec( ? [{}, args[0]] : args; - await create( + const error = createError("root"); + + const result = await create( "root", params, execute, ).execute( getProcessArguments(), + error, ); + + if (result === SymbolCommandError) { + // eslint-disable-next-line no-console + console.error(interpretCommandError(error)); + return void exitProcess(1); + } } diff --git a/scripts/command/execOptions.ts b/scripts/command/execOptions.ts index 319b85c..e8bf20e 100644 --- a/scripts/command/execOptions.ts +++ b/scripts/command/execOptions.ts @@ -1,15 +1,13 @@ -import type { SimplifyTopLevel } from "@duplojs/utils"; -import * as AA from "@duplojs/utils/array"; +import type { AnyTuple, SimplifyTopLevel } from "@duplojs/utils"; +import * as GG from "@duplojs/utils/generator"; import * as OO from "@duplojs/utils/object"; import { createError, interpretExecOptionError, SymbolCommandError } from "./error"; -import { logExecOptionHelp } from "./help"; -import { createBooleanOption, type Option } from "./options"; +import { logExecOptionHelp, helpOption } from "./help"; +import type { Option } from "./options"; import { exitProcess, getProcessArguments } from "@scripts/common"; -const helpOption = createBooleanOption("help", { aliases: ["h"] }); - type ComputeResult< - GenericOptions extends [Option, ...Option[]], + GenericOptions extends AnyTuple