@@ -45,19 +45,84 @@ yarn add @flex-development/pkg-types@flex-development/pkg-types
4545
4646## Use
4747
48- ** TODO** : Update documentation.
48+ ``` typescript
49+ import type { PackageJson } from ' @flex-development/pkg-types'
50+ import fs from ' node:fs'
51+ import path from ' node:path'
52+
53+ /**
54+ * Enables or disables [`type`][1] in `package.json`.
55+ *
56+ * [1]: https://nodejs.org/api/packages.html#type
57+ *
58+ * @example
59+ * toggle()
60+ * @example
61+ * toggle('off')
62+ * @example
63+ * toggle('on')
64+ *
65+ * @param {'off' | 'on'} [command] - Toggle command
66+ * @return {void} Nothing when complete
67+ */
68+ function toggle(command ? : ' off' | ' on' ): void {
69+ // see: https://yarnpkg.com/advanced/lifecycle-scripts#environment-variables
70+ const { npm_package_json = ' package.json' } = process .env
71+
72+ /**
73+ * Absolute path to `package.json`.
74+ *
75+ * @const {string} pkgfile
76+ */
77+ const pkgfile: string = path .resolve (npm_package_json )
78+
79+ /**
80+ * `package.json` data.
81+ *
82+ * @var {PackageJson} pkg
83+ */
84+ let pkg: PackageJson = JSON .parse (fs .readFileSync (pkgfile , ' utf8' ))
85+
86+ // toggle package type
87+ pkg = Object .keys (pkg ).reduce <PackageJson >((acc , key ) => {
88+ const [, type, prefix = ' ' ] = / ^ ((#? )type)$ / .exec (key ) ?? []
89+
90+ if (type ) {
91+ key = command
92+ ? ` ${command === ' off' ? ' #' : ' ' }type `
93+ : prefix
94+ ? type .replace (new RegExp (' ^' + prefix ), ' ' )
95+ : ' #' + type
96+
97+ acc [key ] = pkg [type ]!
98+ } else {
99+ acc [key ] = pkg [key ]!
100+ }
101+
102+ return acc
103+ }, {})
104+
105+ // rewrite package.json
106+ return void fs .writeFileSync (pkgfile , JSON .stringify (pkg , null , 2 ) + ' \n ' )
107+ }
108+
109+ export default toggle
110+ ```
111+
112+ Need this functionality? See [ ` toggle-pkg-type ` ] [ 2 ] :blush :
49113
50114## API
51115
52116** TODO** : Update documentation.
53117
54118## Related
55119
56- - [ ` tsconfig-types ` ] [ 2 ] - TypeScript definitions for ` tsconfig.json `
120+ - [ ` tsconfig-types ` ] [ 3 ] & mdash ; TypeScript definitions for ` tsconfig.json `
57121
58122## Contribute
59123
60124See [ ` CONTRIBUTING.md ` ] ( CONTRIBUTING.md ) .
61125
62126[ 1 ] : https://typescriptlang.org/
63- [ 2 ] : https://github.com/flex-development/tsconfig-types
127+ [ 2 ] : https://github.com/flex-development/toggle-pkg-type
128+ [ 3 ] : https://github.com/flex-development/tsconfig-types
0 commit comments