minisign: replace libsodium dependency with node:crypto

We have this dependency anyway (since we're running on Node). This drops
the problematic libsodium dependency so that the Action works on targets
which libsodium doesn't support.

Resolves: #56
This commit is contained in:
Matthew Lugg
2025-11-28 16:01:44 +00:00
parent c09d84c4b1
commit 1796bca884
127 changed files with 21 additions and 12268 deletions
+2 -2
View File
@@ -25,9 +25,9 @@ async function downloadFromMirror(mirror, tarball_filename) {
const tarball_data = await fs.readFile(tarball_path);
const key = minisign.parseKey(MINISIGN_KEY);
const key = await minisign.parseKey(MINISIGN_KEY);
const signature = minisign.parseSignature(signature_data);
if (!minisign.verifySignature(key, signature, tarball_data)) {
if (!await minisign.verifySignature(key, signature, tarball_data)) {
throw new Error(`signature verification failed for '${mirror}/${tarball_filename}'`);
}
+17 -13
View File
@@ -1,20 +1,20 @@
const sodium = require('sodium-native');
const crypto = require('node:crypto');
// Parse a minisign key represented as a base64 string.
// Throws exceptions on invalid keys.
function parseKey(key_str) {
async function parseKey(key_str) {
const key_info = Buffer.from(key_str, 'base64');
const id = key_info.subarray(2, 10);
const key = key_info.subarray(10);
if (key.byteLength !== sodium.crypto_sign_PUBLICKEYBYTES) {
if (key.byteLength !== 32) {
throw new Error('invalid public key given');
}
return {
id: id,
key: key
key: await crypto.subtle.importKey('raw', key, 'Ed25519', false, ['verify']),
};
}
@@ -77,25 +77,29 @@ function parseSignature(sig_buf) {
// Given a parsed key, parsed signature file, and raw file content, verifies the signature,
// including the global signature (hence validating the trusted comment). Does not throw.
// Returns 'true' if the signature is valid for this file, 'false' otherwise.
function verifySignature(pubkey, signature, file_content) {
async function verifySignature(pubkey, signature, file_content) {
if (!signature.key_id.equals(pubkey.id)) {
return false;
return false; // wrong key
}
let signed_content;
if (signature.algorithm.equals(Buffer.from('ED'))) {
signed_content = Buffer.alloc(sodium.crypto_generichash_BYTES_MAX);
sodium.crypto_generichash(signed_content, file_content);
} else {
const hash = crypto.createHash('BLAKE2b512');
hash.update(file_content);
signed_content = hash.digest();
} else if (signature.algorithm.equals(Buffer.from('Ed'))) {
signed_content = file_content;
} else {
return false; // unsupported algorithm
}
if (!sodium.crypto_sign_verify_detached(signature.signature, signed_content, pubkey.key)) {
return false;
if (!await crypto.subtle.verify('Ed25519', pubkey.key, signature.signature, signed_content)) {
return false; // signature verification failure
}
const global_signed_content = Buffer.concat([signature.signature, signature.trusted_comment]);
if (!sodium.crypto_sign_verify_detached(signature.global_signature, global_signed_content, pubkey.key)) {
return false;
if (!await crypto.subtle.verify('Ed25519', pubkey.key, signature.global_signature, global_signed_content)) {
return false; // signature verification failure
}
return true;
-90
View File
@@ -678,74 +678,6 @@
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"license": "MIT"
},
"node_modules/bare-addon-resolve": {
"version": "1.9.4",
"resolved": "https://registry.npmjs.org/bare-addon-resolve/-/bare-addon-resolve-1.9.4.tgz",
"integrity": "sha512-unn6Vy/Yke6F99vg/7tcrvM2KUvIhTNniaSqDbam4AWkd4NhvDVSrQiRYVlNzUV2P7SPobkCK7JFVxrJk9btCg==",
"license": "Apache-2.0",
"dependencies": {
"bare-module-resolve": "^1.10.0",
"bare-semver": "^1.0.0"
},
"peerDependencies": {
"bare-url": "*"
},
"peerDependenciesMeta": {
"bare-url": {
"optional": true
}
}
},
"node_modules/bare-module-resolve": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/bare-module-resolve/-/bare-module-resolve-1.11.1.tgz",
"integrity": "sha512-DCxeT9i8sTs3vUMA3w321OX/oXtNEu5EjObQOnTmCdNp5RXHBAvAaBDHvAi9ta0q/948QPz+co6SsGi6aQMYRg==",
"license": "Apache-2.0",
"dependencies": {
"bare-semver": "^1.0.0"
},
"peerDependencies": {
"bare-url": "*"
},
"peerDependenciesMeta": {
"bare-url": {
"optional": true
}
}
},
"node_modules/bare-os": {
"version": "3.6.1",
"resolved": "https://registry.npmjs.org/bare-os/-/bare-os-3.6.1.tgz",
"integrity": "sha512-uaIjxokhFidJP+bmmvKSgiMzj2sV5GPHaZVAIktcxcpCyBFFWO+YlikVAdhmUo2vYFvFhOXIAlldqV29L8126g==",
"license": "Apache-2.0",
"engines": {
"bare": ">=1.14.0"
}
},
"node_modules/bare-path": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.0.0.tgz",
"integrity": "sha512-tyfW2cQcB5NN8Saijrhqn0Zh7AnFNsnczRcuWODH0eYAXBsJ5gVxAUuNr7tsHSC6IZ77cA0SitzT+s47kot8Mw==",
"license": "Apache-2.0",
"dependencies": {
"bare-os": "^3.0.1"
}
},
"node_modules/bare-semver": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/bare-semver/-/bare-semver-1.0.1.tgz",
"integrity": "sha512-UtggzHLiTrmFOC/ogQ+Hy7VfoKoIwrP1UFcYtTxoCUdLtsIErT8+SWtOC2DH/snT9h+xDrcBEPcwKei1mzemgg==",
"license": "Apache-2.0"
},
"node_modules/bare-url": {
"version": "2.1.6",
"resolved": "https://registry.npmjs.org/bare-url/-/bare-url-2.1.6.tgz",
"integrity": "sha512-FgjDeR+/yDH34By4I0qB5NxAoWv7dOTYcOXwn73kr+c93HyC2lU6tnjifqUe33LKMJcDyCYPQjEAqgOQiXkE2Q==",
"license": "Apache-2.0",
"dependencies": {
"bare-path": "^3.0.0"
}
},
"node_modules/before-after-hook": {
"version": "2.2.3",
"resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.2.3.tgz",
@@ -1136,19 +1068,6 @@
"wrappy": "1"
}
},
"node_modules/require-addon": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/require-addon/-/require-addon-1.1.0.tgz",
"integrity": "sha512-KbXAD5q2+v1GJnkzd8zzbOxchTkStSyJZ9QwoCq3QwEXAaIlG3wDYRZGzVD357jmwaGY7hr5VaoEAL0BkF0Kvg==",
"license": "Apache-2.0",
"dependencies": {
"bare-addon-resolve": "^1.3.0",
"bare-url": "^2.1.0"
},
"engines": {
"bare": ">=1.10.0"
}
},
"node_modules/safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
@@ -1184,15 +1103,6 @@
"semver": "bin/semver.js"
}
},
"node_modules/sodium-native": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/sodium-native/-/sodium-native-4.3.3.tgz",
"integrity": "sha512-OnxSlN3uyY8D0EsLHpmm2HOFmKddQVvEMmsakCrXUzSd8kjjbzL413t4ZNF3n0UxSwNgwTyUvkmZHTfuCeiYSw==",
"license": "MIT",
"dependencies": {
"require-addon": "^1.1.0"
}
},
"node_modules/strnum": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/strnum/-/strnum-2.1.1.tgz",
-201
View File
@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-164
View File
@@ -1,164 +0,0 @@
# bare-addon-resolve
Low-level addon resolution algorithm for Bare. The algorithm is implemented as a generator function that yields either package manifests to be read or resolution candidates to be tested by the caller. As a convenience, the main export is a synchronous and asynchronous iterable that relies on package manifests being read by a callback. For asynchronous iteration, the callback may return promises which will be awaited before being passed to the generator.
```
npm i bare-addon-resolve
```
## Usage
For synchronous resolution:
```js
const resolve = require('bare-addon-resolve')
function readPackage(url) {
// Read and parse `url` if it exists, otherwise `null`
}
for (const resolution of resolve(
'./addon',
new URL('file:///directory/'),
readPackage
)) {
console.log(resolution)
}
```
For asynchronous resolution:
```js
const resolve = require('bare-addon-resolve')
async function readPackage(url) {
// Read and parse `url` if it exists, otherwise `null`
}
for await (const resolution of resolve(
'./addon',
new URL('file:///directory/'),
readPackage
)) {
console.log(resolution)
}
```
## API
#### `const resolver = resolve(specifier, parentURL[, options][, readPackage])`
Resolve `specifier` relative to `parentURL`, which must be a WHATWG `URL` instance. `readPackage` is called with a `URL` instance for every package manifest to be read and must either return the parsed JSON package manifest, if it exists, or `null`. If `readPackage` returns a promise, synchronous iteration is not supported.
Options include:
```js
options = {
// A list of builtin addon specifiers. If matched, the protocol of the
// resolved URL will be `builtinProtocol`.
builtins: [],
// The protocol to use for resolved builtin addon specifiers.
builtinProtocol: 'builtin:',
// Whether or not addons linked ahead-of-time should be resolved.
linked: true,
// The protocol to use for addons linked ahead-of-time.
linkedProtocol: 'linked:',
// The supported import conditions. "default" is always recognized.
conditions: [],
// An array reference which will contain the matched conditions when yielding
// resolutions.
matchedConditions: [],
// The `<platform>-<arch>` combinations to look for when resolving dynamic
// addons. If empty, only builtin specifiers can be resolved. In Bare,
// pass `[Bare.Addon.host]`.
hosts: [],
// The file extensions to look for when resolving dynamic addons.
extensions: [],
// A map of preresolved imports with keys being serialized directory URLs and
// values being "imports" maps.
resolutions
}
```
#### `for (const resolution of resolver)`
Synchronously iterate the addon resolution candidates. The resolved addon is the first candidate that exists as a file on the file system.
#### `for await (const resolution of resolver)`
Asynchronously iterate the addon resolution candidates. If `readPackage` returns promises, these will be awaited. The same comments as `for (const resolution of resolver)` apply.
### Algorithm
The following generator functions implement the resolution algorithm. The yielded values have the following shape:
**Package manifest**
```js
next.value = {
package: URL
}
```
If the package manifest identified by `next.value.package` exists, `generator.next()` must be passed the parsed JSON value of the manifest. If it does not exist, pass `null` instead.
**Resolution candidate**
```js
next.value = {
resolution: URL
}
```
If the addon identified by `next.value.resolution` exists, `generator.next()` may be passed `true` to signal that the resolution for the current set of conditions has been identified. If it does not exist, pass `false` instead.
To drive the generator functions, a loop like the following can be used:
```js
const generator = resolve.addon(specifier, parentURL)
let next = generator.next()
while (next.done !== true) {
const value = next.value
if (value.package) {
// Read and parse `value.package` if it exists, otherwise `null`
let info
next = generator.next(info)
} else {
const resolution = value.resolution
// `true` if `resolution` was the correct candidate, otherwise `false`
let resolved
next = generator.next(resolved)
}
}
```
Options are the same as `resolve()` for all functions.
> [!WARNING]
> These functions are currently subject to change between minor releases. If using them directly, make sure to specify a tilde range (`~1.2.3`) when declaring the module dependency.
#### `const generator = resolve.addon(specifier, parentURL[, options])`
#### `const generator = resolve.url(url, parentURL[, options])`
#### `const generator = resolve.package(packageSpecifier, packageVersion, parentURL[, options])`
#### `const generator = resolve.packageSelf(packageName, packageSubpath, packageVersion, parentURL[, options])`
#### `const generator = resolve.preresolved(directoryURL, resolutions[, options])`
#### `const generator = resolve.file(filename, parentURL[, options])`
#### `const generator = resolve.directory(dirname, version, parentURL[, options])`
#### `const generator = resolve.linked(name, version[, options])`
## License
Apache-2.0
-106
View File
@@ -1,106 +0,0 @@
import URL from 'bare-url'
import {
constants,
type Builtins,
type Conditions,
type ResolutionsMap
} from 'bare-module-resolve'
type JSON = string | number | boolean | JSON[] | { [key: string]: JSON }
interface ResolveOptions {
builtinProtocol?: string
builtins?: Builtins
conditions?: Conditions
extensions?: string[]
host?: string
hosts?: string[]
linked?: boolean
linkedProtocol?: string
matchedConditions?: string[]
resolutions?: ResolutionsMap
}
declare function resolve(
specifier: string,
parentURL: URL,
readPackage?: (url: URL) => JSON | null
): Iterable<URL>
declare function resolve(
specifier: string,
parentURL: URL,
readPackage: (url: URL) => Promise<JSON | null>
): AsyncIterable<URL>
declare function resolve(
specifier: string,
parentURL: URL,
opts: ResolveOptions,
readPackage?: (url: URL) => JSON | null
): Iterable<URL>
declare function resolve(
specifier: string,
parentURL: URL,
opts: ResolveOptions,
readPackage: (url: URL) => Promise<JSON | null>
): AsyncIterable<URL>
declare namespace resolve {
export { constants, type ResolveOptions }
export type Resolver = Generator<
{ resolution: URL } | { package: URL },
number,
void | boolean | JSON | null
>
export function addon(
specifier: string,
parentURL: URL,
opts?: ResolveOptions
): Resolver
export function url(
specifier: string,
parentURL: URL,
opts?: ResolveOptions
): Resolver
export function package(
packageSpecifier: string,
packageVersion: string,
parentURL: URL,
opts?: ResolveOptions
): Resolver
export function packageSelf(
packageName: string,
packageSubpath: string,
packageVersion: string,
parentURL: URL,
opts?: ResolveOptions
): Resolver
export function file(
filename: string,
parentURL: URL,
opts?: ResolveOptions
): Resolver
export function directory(
dirname: string,
version: string,
parentURL: URL,
opts?: ResolveOptions
): Resolver
export function linked(
name: string,
version?: string,
opts?: ResolveOptions
): Resolver
}
export = resolve
-505
View File
@@ -1,505 +0,0 @@
const resolve = require('bare-module-resolve')
const { Version } = require('bare-semver')
const errors = require('./lib/errors')
module.exports = exports = function resolve(
specifier,
parentURL,
opts,
readPackage
) {
if (typeof opts === 'function') {
readPackage = opts
opts = {}
} else if (typeof readPackage !== 'function') {
readPackage = defaultReadPackage
}
return {
*[Symbol.iterator]() {
const generator = exports.addon(specifier, parentURL, opts)
let next = generator.next()
while (next.done !== true) {
const value = next.value
if (value.package) {
next = generator.next(readPackage(value.package))
} else {
next = generator.next(yield value.resolution)
}
}
return next.value
},
async *[Symbol.asyncIterator]() {
const generator = exports.addon(specifier, parentURL, opts)
let next = generator.next()
while (next.done !== true) {
const value = next.value
if (value.package) {
next = generator.next(await readPackage(value.package))
} else {
next = generator.next(yield value.resolution)
}
}
return next.value
}
}
}
function defaultReadPackage() {
return null
}
const { UNRESOLVED, YIELDED, RESOLVED } = resolve.constants
exports.constants = {
UNRESOLVED,
YIELDED,
RESOLVED
}
exports.addon = function* (specifier, parentURL, opts = {}) {
const { resolutions = null } = opts
if (exports.startsWithWindowsDriveLetter(specifier)) {
specifier = '/' + specifier
}
let status
if (resolutions) {
status = yield* resolve.preresolved(specifier, resolutions, parentURL, opts)
if (status) return status
}
status = yield* exports.url(specifier, parentURL, opts)
if (status) return status
let version = null
const i = specifier.lastIndexOf('@')
if (i > 0) {
version = specifier.substring(i + 1)
try {
Version.parse(version)
specifier = specifier.substring(0, i)
} catch {
version = null
}
}
if (
specifier === '.' ||
specifier === '..' ||
specifier[0] === '/' ||
specifier[0] === '\\' ||
specifier.startsWith('./') ||
specifier.startsWith('.\\') ||
specifier.startsWith('../') ||
specifier.startsWith('..\\')
) {
return yield* exports.directory(specifier, version, parentURL, opts)
}
return yield* exports.package(specifier, version, parentURL, opts)
}
exports.url = function* (url, parentURL, opts = {}) {
let resolution
try {
resolution = new URL(url)
} catch {
return UNRESOLVED
}
const resolved = yield { resolution }
return resolved ? RESOLVED : YIELDED
}
exports.package = function* (
packageSpecifier,
packageVersion,
parentURL,
opts = {}
) {
if (packageSpecifier === '') {
throw errors.INVALID_ADDON_SPECIFIER(
`Addon specifier '${packageSpecifier}' is not a valid package name`
)
}
let packageName
if (packageSpecifier[0] !== '@') {
packageName = packageSpecifier.split('/', 1).join()
} else {
if (!packageSpecifier.includes('/')) {
throw errors.INVALID_ADDON_SPECIFIER(
`Addon specifier '${packageSpecifier}' is not a valid package name`
)
}
packageName = packageSpecifier.split('/', 2).join('/')
}
if (
packageName[0] === '.' ||
packageName.includes('\\') ||
packageName.includes('%')
) {
throw errors.INVALID_ADDON_SPECIFIER(
`Addon specifier '${packageSpecifier}' is not a valid package name`
)
}
const packageSubpath = '.' + packageSpecifier.substring(packageName.length)
const status = yield* exports.packageSelf(
packageName,
packageSubpath,
packageVersion,
parentURL,
opts
)
if (status) return status
parentURL = new URL(parentURL.href)
do {
const packageURL = new URL('node_modules/' + packageName + '/', parentURL)
parentURL.pathname = parentURL.pathname.substring(
0,
parentURL.pathname.lastIndexOf('/')
)
const info = yield { package: new URL('package.json', packageURL) }
if (info) {
return yield* exports.directory(
packageSubpath,
packageVersion,
packageURL,
opts
)
}
} while (parentURL.pathname !== '' && parentURL.pathname !== '/')
return UNRESOLVED
}
exports.packageSelf = function* (
packageName,
packageSubpath,
packageVersion,
parentURL,
opts = {}
) {
for (const packageURL of resolve.lookupPackageScope(parentURL, opts)) {
const info = yield { package: packageURL }
if (info) {
if (info.name === packageName) {
return yield* exports.directory(
packageSubpath,
packageVersion,
packageURL,
opts
)
}
break
}
}
return UNRESOLVED
}
exports.lookupPrebuildsScope = function* lookupPrebuildsScope(url, opts = {}) {
const { resolutions = null } = opts
if (resolutions) {
for (const { resolution } of resolve.preresolved(
'#prebuilds',
resolutions,
url,
opts
)) {
if (resolution) return yield resolution
}
}
const scopeURL = new URL(url.href)
do {
yield new URL('prebuilds/', scopeURL)
scopeURL.pathname = scopeURL.pathname.substring(
0,
scopeURL.pathname.lastIndexOf('/')
)
if (
scopeURL.pathname.length === 3 &&
exports.isWindowsDriveLetter(scopeURL.pathname.substring(1))
) {
break
}
} while (scopeURL.pathname !== '' && scopeURL.pathname !== '/')
}
exports.file = function* (filename, parentURL, opts = {}) {
if (parentURL.protocol === 'file:' && /%2f|%5c/i.test(filename)) {
throw errors.INVALID_ADDON_SPECIFIER(
`Addon specifier '${filename}' is invalid`
)
}
const { extensions = [] } = opts
let status = UNRESOLVED
for (const ext of extensions) {
if (yield { resolution: new URL(filename + ext, parentURL) }) {
return RESOLVED
}
status = YIELDED
}
return status
}
exports.directory = function* (dirname, version, parentURL, opts = {}) {
const {
resolutions = null,
host = null, // Shorthand for single host resolution
hosts = host !== null ? [host] : [],
builtins = [],
matchedConditions = []
} = opts
let directoryURL
if (
dirname[dirname.length - 1] === '/' ||
dirname[dirname.length - 1] === '\\'
) {
directoryURL = new URL(dirname, parentURL)
} else {
directoryURL = new URL(dirname + '/', parentURL)
}
// Internal preresolution path, do not depend on this! It will be removed without
// warning.
if (resolutions) {
const status = yield* resolve.preresolved(
'bare:addon',
resolutions,
directoryURL,
opts
)
if (status) return status
}
const unversioned = version === null
let name = null
const info = yield { package: new URL('package.json', directoryURL) }
if (info) {
if (typeof info.name === 'string' && info.name !== '') {
if (info.name.includes('__')) {
throw errors.INVALID_PACKAGE_NAME(
`Package name '${info.name}' is invalid`
)
}
name = info.name.replace(/\//g, '__').replace(/^@/, '')
} else {
return UNRESOLVED
}
if (typeof info.version === 'string' && info.version !== '') {
if (version !== null && info.version !== version) return UNRESOLVED
version = info.version
}
} else {
return UNRESOLVED
}
let status
status = yield* resolve.builtinTarget(name, version, builtins, opts)
if (status) return status
for (const prebuildsURL of exports.lookupPrebuildsScope(directoryURL, opts)) {
status = UNRESOLVED
for (const host of hosts) {
const conditions = host.split('-')
matchedConditions.push(...conditions)
if (version !== null) {
status |= yield* exports.file(
host + '/' + name + '@' + version,
prebuildsURL,
opts
)
}
if (unversioned) {
status |= yield* exports.file(host + '/' + name, prebuildsURL, opts)
}
for (const _ of conditions) matchedConditions.pop()
}
if (status === RESOLVED) return status
}
return yield* exports.linked(name, version, opts)
}
exports.linked = function* (name, version = null, opts = {}) {
const {
linked = true,
host = null, // Shorthand for single host resolution
hosts = host !== null ? [host] : [],
matchedConditions = []
} = opts
if (linked === false || hosts.length === 0) return UNRESOLVED
let status = UNRESOLVED
for (const host of hosts) {
const [platform = null] = host.split('-', 1)
if (platform === null) continue
matchedConditions.push(platform)
status |= yield* platformArtefact(name, version, platform, opts)
matchedConditions.pop()
}
return status
}
function* platformArtefact(name, version = null, platform, opts = {}) {
const { linkedProtocol = 'linked:' } = opts
if (platform === 'darwin' || platform === 'ios') {
if (version !== null) {
if (
yield {
resolution: new URL(
`${linkedProtocol}${name}.${version}.framework/${name}.${version}`
)
}
) {
return RESOLVED
}
if (platform === 'darwin') {
if (
yield {
resolution: new URL(`${linkedProtocol}lib${name}.${version}.dylib`)
}
) {
return RESOLVED
}
}
}
if (
yield {
resolution: new URL(`${linkedProtocol}${name}.framework/${name}`)
}
) {
return RESOLVED
}
if (platform === 'darwin') {
if (
yield {
resolution: new URL(`${linkedProtocol}lib${name}.dylib`)
}
) {
return RESOLVED
}
}
return YIELDED
}
if (platform === 'linux' || platform === 'android') {
if (version !== null) {
if (
yield {
resolution: new URL(`${linkedProtocol}lib${name}.${version}.so`)
}
) {
return RESOLVED
}
}
if (
yield {
resolution: new URL(`${linkedProtocol}lib${name}.so`)
}
) {
return RESOLVED
}
return YIELDED
}
if (platform === 'win32') {
if (version !== null) {
if (
yield {
resolution: new URL(`${linkedProtocol}${name}-${version}.dll`)
}
) {
return RESOLVED
}
}
if (
yield {
resolution: new URL(`${linkedProtocol}${name}.dll`)
}
) {
return RESOLVED
}
}
return UNRESOLVED
}
exports.isWindowsDriveLetter = resolve.isWindowsDriveLetter
exports.startsWithWindowsDriveLetter = resolve.startsWithWindowsDriveLetter
-8
View File
@@ -1,8 +0,0 @@
declare class AddonResolveError extends Error {
readonly code: string
static INVALID_ADDON_SPECIFIER(msg: string): AddonResolveError
static INVALID_PACKAGE_NAME(msg: string): AddonResolveError
}
export = AddonResolveError
-30
View File
@@ -1,30 +0,0 @@
module.exports = class AddonResolveError extends Error {
constructor(msg, code, fn = AddonResolveError) {
super(`${code}: ${msg}`)
this.code = code
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn)
}
}
get name() {
return 'AddonResolveError'
}
static INVALID_ADDON_SPECIFIER(msg) {
return new AddonResolveError(
msg,
'INVALID_ADDON_SPECIFIER',
AddonResolveError.INVALID_ADDON_SPECIFIER
)
}
static INVALID_PACKAGE_NAME(msg) {
return new AddonResolveError(
msg,
'INVALID_PACKAGE_NAME',
AddonResolveError.INVALID_PACKAGE_NAME
)
}
}
-52
View File
@@ -1,52 +0,0 @@
{
"name": "bare-addon-resolve",
"version": "1.9.4",
"description": "Low-level addon resolution algorithm for Bare",
"exports": {
"./package": "./package.json",
".": {
"types": "./index.d.ts",
"default": "./index.js"
},
"./errors": {
"types": "./lib/errors.d.ts",
"default": "./lib/errors.js"
}
},
"files": [
"index.js",
"index.d.ts",
"lib"
],
"scripts": {
"test": "prettier . --check && bare test.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/holepunchto/bare-addon-resolve.git"
},
"author": "Holepunch",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/holepunchto/bare-addon-resolve/issues"
},
"homepage": "https://github.com/holepunchto/bare-addon-resolve#readme",
"dependencies": {
"bare-module-resolve": "^1.10.0",
"bare-semver": "^1.0.0"
},
"devDependencies": {
"bare-url": "^2.1.3",
"brittle": "^3.2.1",
"prettier": "^3.3.3",
"prettier-config-standard": "^7.0.0"
},
"peerDependencies": {
"bare-url": "*"
},
"peerDependenciesMeta": {
"bare-url": {
"optional": true
}
}
}
-201
View File
@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-358
View File
@@ -1,358 +0,0 @@
# bare-module-resolve
Low-level module resolution algorithm for Bare. The algorithm is implemented as a generator function that yields either package manifests to be read or resolution candidates to be tested by the caller. As a convenience, the main export is a synchronous and asynchronous iterable that relies on package manifests being read by a callback. For asynchronous iteration, the callback may return promises which will be awaited before being passed to the generator.
```
npm i bare-module-resolve
```
## Usage
For synchronous resolution:
```js
const resolve = require('bare-module-resolve')
function readPackage(url) {
// Read and parse `url` if it exists, otherwise `null`
}
for (const resolution of resolve(
'./file.js',
new URL('file:///directory/'),
readPackage
)) {
console.log(resolution)
}
```
For asynchronous resolution:
```js
const resolve = require('bare-module-resolve')
async function readPackage(url) {
// Read and parse `url` if it exists, otherwise `null`
}
for await (const resolution of resolve(
'./file.js',
new URL('file:///directory/'),
readPackage
)) {
console.log(resolution)
}
```
## API
#### `const resolver = resolve(specifier, parentURL[, options][, readPackage])`
Resolve `specifier` relative to `parentURL`, which must be a WHATWG `URL` instance. `readPackage` is called with a `URL` instance for every package manifest to be read and must either return the parsed JSON package manifest, if it exists, or `null`. If `readPackage` returns a promise, synchronous iteration is not supported.
Options include:
```js
options = {
// A default "imports" map to apply to all specifiers. Follows the same
// syntax and rules as the "imports" property defined in `package.json`.
imports,
// A list of builtin module specifiers. If matched, the protocol of the
// resolved URL will be `builtinProtocol`.
builtins: [],
// The protocol to use for resolved builtin module specifiers.
builtinProtocol: 'builtin:',
// A list of module specifiers whose resolution should be deferred. If matched,
// the protocol of the resolved URL will be `deferredProtocol`.
defer: [],
// The protocol to use for resolved deferred module specifiers.
deferredProtocol: 'deferred:',
// The supported import conditions. "default" is always recognized.
conditions: [],
// An array reference which will contain the matched conditions when yielding
// resolutions.
matchedConditions: [],
// The supported engine versions.
engines: {},
// The file extensions to look for. Must be provided to support extensionless
// specifier resolution and directory support, such as resolving './foo' to
// './foo.js' or './foo/index.js'.
extensions: [],
// A map of preresolved imports with keys being serialized parent URLs and
// values being "imports" maps.
resolutions
}
```
#### `for (const resolution of resolver)`
Synchronously iterate the module resolution candidates. The resolved module is the first candidate that exists, either as a file on a file system, a resource at a URL, or something else entirely.
#### `for await (const resolution of resolver)`
Asynchronously iterate the module resolution candidates. If `readPackage` returns promises, these will be awaited. The same comments as `for (const resolution of resolver)` apply.
### Algorithm
The following generator functions implement the resolution algorithm, which has been adapted from the Node.js resolution algorithms for CommonJS and ES modules. Unlike Node.js, Bare uses the same resolution algorithm for both module formats. The yielded values have the following shape:
**Package manifest**
```js
next.value = {
package: URL
}
```
If the package manifest identified by `next.value.package` exists, `generator.next()` must be passed the parsed JSON value of the manifest. If it does not exist, pass `null` instead.
**Resolution candidate**
```js
next.value = {
resolution: URL
}
```
If the module identified by `next.value.resolution` exists, `generator.next()` may be passed `true` to signal that the resolution for the current set of conditions has been identified. If it does not exist, pass `false` instead.
To drive the generator functions, a loop like the following can be used:
```js
const generator = resolve.module(specifier, parentURL)
let next = generator.next()
while (next.done !== true) {
const value = next.value
if (value.package) {
// Read and parse `value.package` if it exists, otherwise `null`
let info
next = generator.next(info)
} else {
const resolution = value.resolution
// `true` if `resolution` was the correct candidate, otherwise `false`
let resolved
next = generator.next(resolved)
}
}
```
Options are the same as `resolve()` for all functions.
> [!WARNING]
> These functions are currently subject to change between minor releases. If using them directly, make sure to specify a tilde range (`~1.2.3`) when declaring the module dependency.
#### `const generator = resolve.module(specifier, parentURL[, options])`
1. If `specifier` [starts with a Windows drive letter](https://url.spec.whatwg.org/#start-with-a-windows-drive-letter):
1. Prepend `/` to `specifier`.
2. If `options.resolutions` is set:
1. If `preresolved(specifier, options.resolutions, parentURL, options)` yields, return.
3. If `url(specifier, parentURL, options)` yields, return.
4. If `packageImports(specifier, parentURL, options)` yields, return.
5. If `specifier` equals `.` or `..`, or if `specifier` starts with `/`, `\`, `./`, `.\`, `../`, or `..\`:
1. If `options.imports` is set:
1. If `packageImportsExports(specifier, options.imports, parentURL, true, options)` yields, return.
2. If `deferred(specifier, options)` yields, return.
3. If `file(specifier, parentURL, false, options)` resolves, return.
4. Return `directory(specifier, parentURL, options)`.
6. Return `package(specifier, parentURL, options)`.
#### `const generator = resolve.url(url, parentURL[, options])`
1. If `url` is not a valid URL, return.
2. If `options.imports` is set:
1. If `packageImportsExports(url.href, options.imports, parentURL, true, options)` yields, return.
3. If `url.protocol` equals `options.deferredProtocol`:
1. Let `specifier` be `url.pathname`.
2. Return `module(specifier, parentURL, options)`.
4. If `url.protocol` equals `node:`:
1. Let `specifier` be `url.pathname`.
2. If `specifier` equals `.` or `..`, or if `specifier` starts with `/`, `\`, `./`, `.\`, `../`, or `..\`, throw.
3. Return `package(specifier, parentURL, options)`.
5. Yield `url`.
#### `const generator = resolve.preresolved(specifier, resolutions, parentURL[, options])`
1. Let `imports` be `resolutions[parentURL]`.
2. If `imports` is a non-`null` object:
1. Return `packageImportsExports(specifier, imports, parentURL, true, options)`.
#### `const generator = resolve.deferred(specifier[, options])`
1. If `options.defer` includes `specifier`:
1. Yield `options.deferredProtocol` concatenated with `specifier` and return.
#### `const generator = resolve.package(packageSpecifier, parentURL[, options])`
1. If `packageSpecifier` is the empty string, throw.
2. If `packageSpecifier` does not start with `@`:
1. Set `packageName` to the substring of `packageSpecifier` until the first `/` or the end of the string.
3. Let `packageName` be `undefined`.
4. Otherwise:
1. If `packageSpecifier` does not include `/`, throw.
2. Set `packageName` to the substring of `packageSpecifier` until the second `/` or the end of the string.
5. If `packageName` starts with `.` or includes `\` or `%`, throw.
6. If `builtinTarget(packageSpecifier, null, options.builtins, options)` yields, return.
7. If `deferred(packageSpecifier, options)` yields, return.
8. Let `packageSubpath` be `.` concatenated with the substring of `packageSpecifier` from the position at the length of `packageName`.
9. If `packageSelf(packageName, packageSubpath, parentURL, options)` yields, return.
10. Repeat:
1. Let `packageURL` be the resolution of `node_modules/` concatenated with `packageName` and `/` relative to `parentURL`.
2. Set `parentURL` to the substring of `parentURL` until the last `/`.
3. Let `info` be the result of yielding the resolution of `package.json` relative to `packageURL`.
4. If `info` is not `null`:
1. If `info.engines` is set:
1. Call `validateEngines(packageURL, info.engines, options)`.
2. If `info.exports` is set:
1. Return `packageExports(packageURL, packageSubpath, info.exports, options)`.
3. If `packageSubpath` is `.`:
1. If `info.main` is a non-empty string:
1. Set `packageSubpath` to `info.main`.
2. Otherwise:
1. Return `file('index', packageURL, true, options)`.
4. If `file(packageSubpath, packageURL, false, options)` resolves, return.
5. Return `directory(packageSubpath, packageURL, options)`.
5. If `parentURL` is the file system root, return.
#### `const generator = resolve.packageSelf(packageName, packageSubpath, parentURL[, options])`
1. For each value `packageURL` of `lookupPackageScope(parentURL, options)`:
1. Let `info` be the result of yielding `packageURL`.
2. If `info` is not `null`:
1. If `info.name` does not equal `packageName`, return.
2. If `info.exports` is set:
1. Return `packageExports(packageURL, packageSubpath, info.exports, options)`.
3. If `packageSubpath` is `.`:
1. If `info.main` is a non-empty string:
1. Set `packageSubpath` to `info.main`.
2. Otherwise:
1. Return `file('index', packageURL, true, options)`.
4. If `file(packageSubpath, packageURL, false, options)` resolves, return.
5. Return `directory(packageSubpath, packageURL, options)`.
#### `const generator = resolve.packageExports(packageURL, subpath, exports[, options])`
1. If `subpath` is `.`:
1. Let `mainExport` be `undefined`.
2. If `exports` is a string or an array:
1. Set `mainExport` to `exports`.
3. If `exports` is a non-`null` object:
1. If some keys of `exports` start with `.`:
1. If `.` is a key of `exports`:
1. Set `mainExport` to `exports['.']`.
2. Otherwise:
1. Set `mainExport` to `exports`.
4. If `mainExport` is not `undefined`:
1. If `packageTarget(packageURL, mainExport, null, false, options)` yields, return.
2. Otherwise, if `exports` is a non-`null` object:
1. If every key of `exports` starts with `.`:
1. If `packageImportsExports(subpath, exports, packageURL, false, options)` yields, return.
3. Throw.
#### `const generator = resolve.packageImports(specifier, parentURL[, options])`
1. If `specifier` is `#` or starts with `#/`, throw.
2. For each value `packageURL` of `lookupPackageScope(parentURL, opions)`:
1. Let `info` be the result of yielding `packageURL`.
2. If `info` is not `null`:
1. If `info.imports` is set:
1. If `packageImportsExports(specifier, info.imports, packageURL, true, options)` yields, return.
2. If specifier starts with `#`, throw.
3. Return.
3. If `options.imports` is set:
1. If `packageImportsExports(url.href, options.imports, parentURL, true, options)` yields, return.
#### `const generator = resolve.packageImportsExports(matchKey, matchObject, packageURL, isImports[, options])`
1. If `matchKey` is a key of `matchObject` and `matchKey` does not include `*`:
1. Let `target` be `matchObject[matchKey]`.
2. Return `packageTarget(packageURL, target, null, isImports, options)`.
2. Let `expansionKeys` be the keys of `matchObject` that include `*` sorted by `patternKeyCompare`.
3. For each value `expansionKey` of `expansionKeys`:
1. Let `patternBase` be the substring of `expansionKey` until the first `*`.
2. If `matchKey` starts with but isn't equal to `patternBase`:
1. Let `patternTrailer` be the substring of `expansionKey` from the position at the index after the first `*`.
2. If `patternTrailer` is the empty string, or if `matchKey` ends with `patternTrailer` and the length of `matchKey` is greater than or equal to the length of `expansionKey`:
1. Let `target` be `matchObject[expansionKey]`.
2. Let `patternMatch` be the substring of `matchKey` from the position at the length of `patternBase` until the length of `matchKey` minus the length of `patternTrailer`.
3. Return `packageTarget(packageURL, target, patternMatch, isImports, options)`.
#### `const generator = resolve.packageTarget(packageURL, target, patternMatch, isImports[, options])`
1. If `target` is a string:
1. If `target` does not start with `./` and `isImports` is `false`, throw.
2. If `patternMatch` is not `null`:
1. Replace every instance of `*` in `target` with `patternMatch`.
3. If `url(target, packageURL, options)` yields, return.
4. If `target` equals `.` or `..`, or if `target` starts with `/`, `./`, or `../`:
1. Yield the resolution of `target` relative to `packageURL` and return.
5. Return `package(target, packageURL, options)`.
2. If `target` is an array:
1. For each value `targetValue` of `target`:
1. If `packageTarget(packageURL, targetValue, patternMatch, isImports, options)` yields, return.
3. If `target` is a non-`null` object:
1. For each key `condition` of `target`:
1. If `condition` equals `default` or if `options.conditions` includes `condition`:
1. Let `targetValue` be `target[condition]`.
2. Return `packageTarget(packageURL, targetValue, patternMatch, isImports, options)`.
#### `const generator = resolve.builtinTarget(packageSpecifier, packageVersion, target[, options])`
1. If `target` is a string:
1. If `target` does not start with `@`:
1. Let `targetName` be the substring of `target` until the first `@` or the end of the string.
2. Let `targetVersion` be the substring of `target` from the character following the first `@` and to the end of string, or `null` if no such substring exists.
2. Otherwise:
1. Let `targetName` be the substring of `target` until the second `@` or the end of the string.
2. Let `targetVersion` be the substring of `target` from the character following the second `@` and to the end of string, or `null` if no such substring exists.
3. If `packageSpecifier` equals `targetName`:
1. If `packageVersion` is `null` and `targetVersion` is `null`:
1. Yield `options.builtinProtocol` concatenated with `packageSpecifier` and return.
2. Let `version` be `null`.
3. If `packageVersion` is `null`, let `version` be `targetVersion`.
4. Otherwise, if `targetVersion` is either `null` or equals `packageVersion`, let `version` be `packageVersion`
5. If `version` is not `null`:
1. Yield `options.builtinProtocol` concatenated with `packageSpecifier`, `@`, and `version` and return.
2. If `target` is an array:
1. For each value `targetValue` of `target`:
1. If `builtinTarget(packageSpecifier, packageVersion, targetValue, options)` yields, return.
3. If `target` is a non-`null` object:
1. For each key `condition` of `target`:
1. If `condition` equals `default` or if `options.conditions` includes `condition`:
1. Let `targetValue` be `target[condition]`.
2. Return `builtinTarget(packageSpecifier, packageVersion, targetValue, options)`.
#### `const generator = resolve.file(filename, parentURL, isIndex[, options])`
1. If `filename` equals `.` or `..`, or if `filename` ends with `/` or `\`, return.
2. If `parentURL` is a `file:` URL and `filename` includes encoded `/` or `\`, throw.
3. If `isIndex` is `false`:
1. Yield the resolution of `filename` relative to `parentURL`.
4. For each value `ext` of `options.extensions`:
1. Yield the resolution of `filename` concatenated with `ext` relative to `parentURL`.
#### `const generator = resolve.directory(dirname, parentURL[, options])`
1. Let `directoryURL` be `undefined`.
2. If `dirname` ends with `/` or `\`:
1. Set `directoryURL` to the resolution of `dirname` relative to `parentURL`.
3. Otherwise:
1. Set `directoryURL` to the resolution of `dirname` concatenated with `/` relative to `parentURL`.
4. Let `info` be the result of yielding the resolution of `package.json` relative to `directoryURL`.
5. If `info` is not `null`:
1. If `info.exports` is set:
1. Return `packageExports(directoryURL, '.', info.exports, options)`.
2. If `info.main` is a non-empty string:
1. If `file(info.main, directoryURL, false, options)` resolves, return.
2. Return `directory(info.main, directoryURL, options)`.
6. Return `file('index', directoryURL, true, options)`.
## License
Apache-2.0
-167
View File
@@ -1,167 +0,0 @@
import URL from 'bare-url'
type ConditionalSpecifier =
| string
| ConditionalSpecifier[]
| { [condition: string]: ConditionalSpecifier }
type ImportsMap = { [specifier: string]: ConditionalSpecifier }
type ExportsMap = ImportsMap
type ResolutionsMap = { [href: string]: ImportsMap }
type Builtins = ConditionalSpecifier[]
type Conditions = string[] | Conditions[]
type Engines = { [name: string]: string }
type JSON = string | number | boolean | JSON[] | { [key: string]: JSON }
interface ResolveOptions {
builtinProtocol?: string
builtins?: Builtins
conditions?: Conditions
defer?: string[]
deferredProtocol?: string
engines?: Engines
extensions?: string[]
imports?: ImportsMap
matchedConditions?: string[]
resolutions?: ResolutionsMap
}
declare function resolve(
specifier: string,
parentURL: URL,
readPackage?: (url: URL) => JSON | null
): Iterable<URL>
declare function resolve(
specifier: string,
parentURL: URL,
readPackage: (url: URL) => Promise<JSON | null>
): AsyncIterable<URL>
declare function resolve(
specifier: string,
parentURL: URL,
opts: ResolveOptions,
readPackage?: (url: URL) => JSON | null
): Iterable<URL>
declare function resolve(
specifier: string,
parentURL: URL,
opts: ResolveOptions,
readPackage: (url: URL) => Promise<JSON | null>
): AsyncIterable<URL>
declare namespace resolve {
export {
type ConditionalSpecifier,
type ImportsMap,
type ExportsMap,
type ResolutionsMap,
type Builtins,
type Conditions,
type Engines,
type ResolveOptions
}
export const constants: {
UNRESOLVED: number
YIELDED: number
RESOLVED: number
}
export type Resolver = Generator<
{ package: URL } | { resolution: URL },
number,
void | boolean | JSON | null
>
export function module(
specifier: string,
parentURL: URL,
opts?: ResolveOptions
): Resolver
export function url(
url: string,
parentURL: URL,
opts?: ResolveOptions
): Resolver
export function preresolved(
specifier: string,
resolutions: ResolutionsMap,
parentURL: URL,
opts?: ResolveOptions
): Resolver
export function package(
packageSpecifier: string,
parentURL: URL,
opts?: ResolveOptions
): Resolver
export function packageSelf(
packageName: string,
packageSubpath: string,
parentURL: URL,
opts?: ResolveOptions
): Resolver
export function packageExports(
packageURL: URL,
subpath: string,
packageExports: ExportsMap,
opts?: ResolveOptions
): Resolver
export function packageImports(
specifier: string,
parentURL: URL,
opts?: ResolveOptions
): Resolver
export function packageImportsExports(
matchKey: string,
matchObject: ImportsMap | ExportsMap,
packageURL: URL,
isImports: boolean,
opts?: ResolveOptions
): Resolver
export function packageTarget(
packageURL: URL,
target: ConditionalSpecifier,
patternMatch: string,
isImports: boolean,
opts?: ResolveOptions
): Resolver
export function builtinTarget(
packageSpecifier: string,
packageVersion: string,
target: ConditionalSpecifier,
opts?: ResolveOptions
): Resolver
export function file(
filename: string,
parentURL: URL,
isIndex: boolean,
opts?: ResolveOptions
): Resolver
export function directory(
dirname: string,
parentURL: URL,
opts?: ResolveOptions
): Resolver
}
export = resolve
-908
View File
@@ -1,908 +0,0 @@
const { satisfies } = require('bare-semver')
const errors = require('./lib/errors')
module.exports = exports = function resolve(
specifier,
parentURL,
opts,
readPackage
) {
if (typeof opts === 'function') {
readPackage = opts
opts = {}
} else if (typeof readPackage !== 'function') {
readPackage = defaultReadPackage
}
return {
*[Symbol.iterator]() {
const generator = exports.module(specifier, parentURL, opts)
let next = generator.next()
while (next.done !== true) {
const value = next.value
if (value.package) {
next = generator.next(readPackage(value.package))
} else {
next = generator.next(yield value.resolution)
}
}
return next.value
},
async *[Symbol.asyncIterator]() {
const generator = exports.module(specifier, parentURL, opts)
let next = generator.next()
while (next.done !== true) {
const value = next.value
if (value.package) {
next = generator.next(await readPackage(value.package))
} else {
next = generator.next(yield value.resolution)
}
}
return next.value
}
}
}
function defaultReadPackage() {
return null
}
// No resolution candidate was yielded
const UNRESOLVED = 0x0
// At least 1 resolution candidate was yielded
const YIELDED = 0x1
// At least 1 resolution candidate was yielded and resolved
const RESOLVED = YIELDED | 0x2
exports.constants = {
UNRESOLVED,
YIELDED,
RESOLVED
}
exports.module = function* (specifier, parentURL, opts = {}) {
const { resolutions = null, imports = null } = opts
if (exports.startsWithWindowsDriveLetter(specifier)) {
specifier = '/' + specifier
}
let status
if (resolutions) {
status = yield* exports.preresolved(specifier, resolutions, parentURL, opts)
if (status) return status
}
status = yield* exports.url(specifier, parentURL, opts)
if (status) return status
status = yield* exports.packageImports(specifier, parentURL, opts)
if (status) return status
if (
specifier === '.' ||
specifier === '..' ||
specifier[0] === '/' ||
specifier[0] === '\\' ||
specifier.startsWith('./') ||
specifier.startsWith('.\\') ||
specifier.startsWith('../') ||
specifier.startsWith('..\\')
) {
if (imports) {
status = yield* exports.packageImportsExports(
specifier,
imports,
parentURL,
true,
opts
)
if (status) return status
}
status = yield* exports.deferred(specifier, opts)
if (status) return status
status = yield* exports.file(specifier, parentURL, false, opts)
if (status === RESOLVED) return status
return yield* exports.directory(specifier, parentURL, opts)
}
return yield* exports.package(specifier, parentURL, opts)
}
exports.url = function* (url, parentURL, opts = {}) {
const { imports = null, deferredProtocol = 'deferred:' } = opts
let resolution
try {
resolution = new URL(url)
} catch {
return UNRESOLVED
}
if (imports) {
const status = yield* exports.packageImportsExports(
resolution.href,
imports,
parentURL,
true,
opts
)
if (status) return status
}
if (resolution.protocol === deferredProtocol) {
const specifier = resolution.pathname
return yield* exports.module(specifier, parentURL, opts)
}
if (resolution.protocol === 'node:') {
const specifier = resolution.pathname
if (
specifier === '.' ||
specifier === '..' ||
specifier[0] === '/' ||
specifier.startsWith('./') ||
specifier.startsWith('../')
) {
throw errors.INVALID_MODULE_SPECIFIER(
`Module specifier '${url}' is not a valid package name`
)
}
return yield* exports.package(specifier, parentURL, opts)
}
const resolved = yield { resolution }
return resolved ? RESOLVED : YIELDED
}
exports.preresolved = function* (specifier, resolutions, parentURL, opts = {}) {
const imports = resolutions[parentURL.href]
if (typeof imports === 'object' && imports !== null) {
return yield* exports.packageImportsExports(
specifier,
imports,
parentURL,
true,
opts
)
}
return UNRESOLVED
}
exports.deferred = function* (specifier, opts = {}) {
const { deferredProtocol = 'deferred:', defer = [] } = opts
if (defer.includes(specifier)) {
const resolved = yield { resolution: new URL(deferredProtocol + specifier) }
return resolved ? RESOLVED : YIELDED
}
return UNRESOLVED
}
exports.package = function* (packageSpecifier, parentURL, opts = {}) {
const { builtins = [] } = opts
if (packageSpecifier === '') {
throw errors.INVALID_MODULE_SPECIFIER(
`Module specifier '${packageSpecifier}' is not a valid package name`
)
}
let packageName
if (packageSpecifier[0] !== '@') {
packageName = packageSpecifier.split('/', 1).join()
} else {
if (!packageSpecifier.includes('/')) {
throw errors.INVALID_MODULE_SPECIFIER(
`Module specifier '${packageSpecifier}' is not a valid package name`
)
}
packageName = packageSpecifier.split('/', 2).join('/')
}
if (
packageName[0] === '.' ||
packageName.includes('\\') ||
packageName.includes('%')
) {
throw errors.INVALID_MODULE_SPECIFIER(
`Module specifier '${packageSpecifier}' is not a valid package name`
)
}
let status
status = yield* exports.builtinTarget(packageSpecifier, null, builtins, opts)
if (status) return status
status = yield* exports.deferred(packageSpecifier, opts)
if (status) return status
let packageSubpath = '.' + packageSpecifier.substring(packageName.length)
status = yield* exports.packageSelf(
packageName,
packageSubpath,
parentURL,
opts
)
if (status) return status
parentURL = new URL(parentURL.href)
do {
const packageURL = new URL('node_modules/' + packageName + '/', parentURL)
parentURL.pathname = parentURL.pathname.substring(
0,
parentURL.pathname.lastIndexOf('/')
)
const info = yield { package: new URL('package.json', packageURL) }
if (info) {
if (info.engines) exports.validateEngines(packageURL, info.engines, opts)
if (info.exports) {
return yield* exports.packageExports(
packageURL,
packageSubpath,
info.exports,
opts
)
}
if (packageSubpath === '.') {
if (typeof info.main === 'string' && info.main !== '') {
packageSubpath = info.main
} else {
return yield* exports.file('index', packageURL, true, opts)
}
}
status = yield* exports.file(packageSubpath, packageURL, false, opts)
if (status === RESOLVED) return status
return yield* exports.directory(packageSubpath, packageURL, opts)
}
} while (parentURL.pathname !== '' && parentURL.pathname !== '/')
return UNRESOLVED
}
exports.packageSelf = function* (
packageName,
packageSubpath,
parentURL,
opts = {}
) {
for (const packageURL of exports.lookupPackageScope(parentURL, opts)) {
const info = yield { package: packageURL }
if (info) {
if (info.name !== packageName) return false
if (info.exports) {
return yield* exports.packageExports(
packageURL,
packageSubpath,
info.exports,
opts
)
}
if (packageSubpath === '.') {
if (typeof info.main === 'string' && info.main !== '') {
packageSubpath = info.main
} else {
return yield* exports.file('index', packageURL, true, opts)
}
}
const status = yield* exports.file(
packageSubpath,
packageURL,
false,
opts
)
if (status === RESOLVED) return status
return yield* exports.directory(packageSubpath, packageURL, opts)
}
}
return UNRESOLVED
}
exports.packageExports = function* (
packageURL,
subpath,
packageExports,
opts = {}
) {
if (subpath === '.') {
let mainExport
if (typeof packageExports === 'string' || Array.isArray(packageExports)) {
mainExport = packageExports
} else if (typeof packageExports === 'object' && packageExports !== null) {
const keys = Object.keys(packageExports)
if (keys.some((key) => key.startsWith('.'))) {
if ('.' in packageExports) mainExport = packageExports['.']
} else {
mainExport = packageExports
}
}
if (mainExport) {
const status = yield* exports.packageTarget(
packageURL,
mainExport,
null,
false,
opts
)
if (status) return status
}
} else if (typeof packageExports === 'object' && packageExports !== null) {
const keys = Object.keys(packageExports)
if (keys.every((key) => key.startsWith('.'))) {
const status = yield* exports.packageImportsExports(
subpath,
packageExports,
packageURL,
false,
opts
)
if (status) return status
}
}
packageURL = new URL('package.json', packageURL)
throw errors.PACKAGE_PATH_NOT_EXPORTED(
`Package subpath '${subpath}' is not defined by "exports" in '${packageURL}'`
)
}
exports.packageImports = function* (specifier, parentURL, opts = {}) {
const { imports = null } = opts
if (specifier === '#' || specifier.startsWith('#/')) {
throw errors.INVALID_MODULE_SPECIFIER(
`Module specifier '${specifier}' is not a valid internal imports specifier`
)
}
for (const packageURL of exports.lookupPackageScope(parentURL, opts)) {
const info = yield { package: packageURL }
if (info) {
if (info.imports) {
const status = yield* exports.packageImportsExports(
specifier,
info.imports,
packageURL,
true,
opts
)
if (status) return status
}
if (specifier.startsWith('#')) {
throw errors.PACKAGE_IMPORT_NOT_DEFINED(
`Package import specifier '${specifier}' is not defined by "imports" in '${packageURL}'`
)
}
break
}
}
if (imports) {
const status = yield* exports.packageImportsExports(
specifier,
imports,
parentURL,
true,
opts
)
if (status) return status
}
return UNRESOLVED
}
exports.packageImportsExports = function* (
matchKey,
matchObject,
packageURL,
isImports,
opts = {}
) {
if (matchKey in matchObject && !matchKey.includes('*')) {
const target = matchObject[matchKey]
return yield* exports.packageTarget(
packageURL,
target,
null,
isImports,
opts
)
}
const expansionKeys = Object.keys(matchObject)
.filter((key) => key.includes('*'))
.sort(exports.patternKeyCompare)
for (const expansionKey of expansionKeys) {
const patternIndex = expansionKey.indexOf('*')
const patternBase = expansionKey.substring(0, patternIndex)
if (matchKey.startsWith(patternBase) && matchKey !== patternBase) {
const patternTrailer = expansionKey.substring(patternIndex + 1)
if (
patternTrailer === '' ||
(matchKey.endsWith(patternTrailer) &&
matchKey.length >= expansionKey.length)
) {
const target = matchObject[expansionKey]
const patternMatch = matchKey.substring(
patternBase.length,
matchKey.length - patternTrailer.length
)
return yield* exports.packageTarget(
packageURL,
target,
patternMatch,
isImports,
opts
)
}
}
}
return UNRESOLVED
}
exports.validateEngines = function validateEngines(
packageURL,
packageEngines,
opts = {}
) {
const { engines = {} } = opts
for (const [engine, range] of Object.entries(packageEngines)) {
if (engine in engines) {
const version = engines[engine]
if (!satisfies(version, range)) {
packageURL = new URL('package.json', packageURL)
throw errors.UNSUPPORTED_ENGINE(
`Package not compatible with engine '${engine}' ${version}, requires range '${range}' defined by "engines" in '${packageURL}'`
)
}
}
}
}
exports.patternKeyCompare = function patternKeyCompare(keyA, keyB) {
const patternIndexA = keyA.indexOf('*')
const patternIndexB = keyB.indexOf('*')
const baseLengthA = patternIndexA === -1 ? keyA.length : patternIndexA + 1
const baseLengthB = patternIndexB === -1 ? keyB.length : patternIndexB + 1
if (baseLengthA > baseLengthB) return -1
if (baseLengthB > baseLengthA) return 1
if (patternIndexA === -1) return 1
if (patternIndexB === -1) return -1
if (keyA.length > keyB.length) return -1
if (keyB.length > keyA.length) return 1
return 0
}
exports.packageTarget = function* (
packageURL,
target,
patternMatch,
isImports,
opts = {}
) {
const { conditions = [], matchedConditions = [] } = opts
if (typeof target === 'string') {
if (!target.startsWith('./') && !isImports) {
packageURL = new URL('package.json', packageURL)
throw errors.INVALID_PACKAGE_TARGET(
`Invalid target '${target}' defined by "exports" in '${packageURL}'`
)
}
if (patternMatch !== null) {
target = target.replaceAll('*', patternMatch)
}
const status = yield* exports.url(target, packageURL, opts)
if (status) return status
if (
target === '.' ||
target === '..' ||
target[0] === '/' ||
target.startsWith('./') ||
target.startsWith('../')
) {
const resolved = yield { resolution: new URL(target, packageURL) }
return resolved ? RESOLVED : YIELDED
}
return yield* exports.package(target, packageURL, opts)
}
if (Array.isArray(target)) {
for (const targetValue of target) {
const status = yield* exports.packageTarget(
packageURL,
targetValue,
patternMatch,
isImports,
opts
)
if (status) return status
}
} else if (typeof target === 'object' && target !== null) {
let status = UNRESOLVED
for (const [condition, targetValue, subset] of exports.conditionMatches(
target,
conditions,
opts
)) {
matchedConditions.push(condition)
status |= yield* exports.packageTarget(
packageURL,
targetValue,
patternMatch,
isImports,
{ ...opts, conditions: subset }
)
matchedConditions.pop()
}
if (status) return status
}
return UNRESOLVED
}
exports.builtinTarget = function* (
packageSpecifier,
packageVersion,
target,
opts = {}
) {
const {
builtinProtocol = 'builtin:',
conditions = [],
matchedConditions = []
} = opts
if (typeof target === 'string') {
const targetParts = target.split('@')
let targetName
let targetVersion
if (target[0] !== '@') {
targetName = targetParts[0]
targetVersion = targetParts[1] || null
} else {
targetName = targetParts.slice(0, 2).join('@')
targetVersion = targetParts[2] || null
}
if (packageSpecifier === targetName) {
if (packageVersion === null && targetVersion === null) {
const resolved = yield {
resolution: new URL(builtinProtocol + packageSpecifier)
}
return resolved ? RESOLVED : YIELDED
}
let version = null
if (packageVersion === null) {
version = targetVersion
} else if (targetVersion === null || packageVersion === targetVersion) {
version = packageVersion
}
if (version !== null) {
const resolved = yield {
resolution: new URL(
builtinProtocol + packageSpecifier + '@' + version
)
}
return resolved ? RESOLVED : YIELDED
}
}
} else if (Array.isArray(target)) {
for (const targetValue of target) {
const status = yield* exports.builtinTarget(
packageSpecifier,
packageVersion,
targetValue,
opts
)
if (status) return status
}
} else if (typeof target === 'object' && target !== null) {
let status = UNRESOLVED
for (const [condition, targetValue, subset] of exports.conditionMatches(
target,
conditions,
opts
)) {
matchedConditions.push(condition)
status |= yield* exports.builtinTarget(
packageSpecifier,
packageVersion,
targetValue,
{ ...opts, conditions: subset }
)
matchedConditions.pop()
}
if (status) return status
}
return UNRESOLVED
}
exports.conditionMatches = function* conditionMatches(
target,
conditions,
opts = {}
) {
if (conditions.every((condition) => typeof condition === 'string')) {
const keys = Object.keys(target)
for (const condition of keys) {
if (condition === 'default' || conditions.includes(condition)) {
yield [condition, target[condition], conditions]
return true
}
}
return false
}
let yielded = false
for (const subset of conditions) {
if (yield* conditionMatches(target, subset, opts)) {
yielded = true
}
}
return yielded
}
exports.lookupPackageScope = function* lookupPackageScope(url, opts = {}) {
const { resolutions = null } = opts
if (resolutions) {
for (const { resolution } of exports.preresolved(
'#package',
resolutions,
url,
opts
)) {
if (resolution) return yield resolution
}
// Internal preresolution path, do not depend on this! It will be removed without
// warning.
for (const { resolution } of exports.preresolved(
'bare:package',
resolutions,
url,
opts
)) {
if (resolution) return yield resolution
}
}
const scopeURL = new URL(url.href)
do {
if (scopeURL.pathname.endsWith('/node_modules')) break
yield new URL('package.json', scopeURL)
scopeURL.pathname = scopeURL.pathname.substring(
0,
scopeURL.pathname.lastIndexOf('/')
)
if (
scopeURL.pathname.length === 3 &&
exports.isWindowsDriveLetter(scopeURL.pathname.substring(1))
) {
break
}
} while (scopeURL.pathname !== '' && scopeURL.pathname !== '/')
}
exports.file = function* (filename, parentURL, isIndex, opts = {}) {
if (
filename === '.' ||
filename === '..' ||
filename[filename.length - 1] === '/' ||
filename[filename.length - 1] === '\\'
) {
return UNRESOLVED
}
if (parentURL.protocol === 'file:' && /%2f|%5c/i.test(filename)) {
throw errors.INVALID_MODULE_SPECIFIER(
`Module specifier '${filename}' is invalid`
)
}
const { extensions = [] } = opts
let status = UNRESOLVED
if (!isIndex) {
if (yield { resolution: new URL(filename, parentURL) }) {
return RESOLVED
}
status = YIELDED
}
for (const ext of extensions) {
if (yield { resolution: new URL(filename + ext, parentURL) }) {
return RESOLVED
}
status = YIELDED
}
return status
}
exports.directory = function* (dirname, parentURL, opts = {}) {
let directoryURL
if (
dirname[dirname.length - 1] === '/' ||
dirname[dirname.length - 1] === '\\'
) {
directoryURL = new URL(dirname, parentURL)
} else {
directoryURL = new URL(dirname + '/', parentURL)
}
const info = yield { package: new URL('package.json', directoryURL) }
if (info) {
if (info.exports) {
return yield* exports.packageExports(
directoryURL,
'.',
info.exports,
opts
)
}
if (typeof info.main === 'string' && info.main !== '') {
const status = yield* exports.file(info.main, directoryURL, false, opts)
if (status === RESOLVED) return status
return yield* exports.directory(info.main, directoryURL, opts)
}
}
return yield* exports.file('index', directoryURL, true, opts)
}
// https://infra.spec.whatwg.org/#ascii-upper-alpha
function isASCIIUpperAlpha(c) {
return c >= 0x41 && c <= 0x5a
}
// https://infra.spec.whatwg.org/#ascii-lower-alpha
function isASCIILowerAlpha(c) {
return c >= 0x61 && c <= 0x7a
}
// https://infra.spec.whatwg.org/#ascii-alpha
function isASCIIAlpha(c) {
return isASCIIUpperAlpha(c) || isASCIILowerAlpha(c)
}
// https://url.spec.whatwg.org/#windows-drive-letter
exports.isWindowsDriveLetter = function isWindowsDriveLetter(input) {
return (
input.length >= 2 &&
isASCIIAlpha(input.charCodeAt(0)) &&
(input.charCodeAt(1) === 0x3a || input.charCodeAt(1) === 0x7c)
)
}
// https://url.spec.whatwg.org/#start-with-a-windows-drive-letter
exports.startsWithWindowsDriveLetter = function startsWithWindowsDriveLetter(
input
) {
return (
input.length >= 2 &&
exports.isWindowsDriveLetter(input) &&
(input.length === 2 ||
input.charCodeAt(2) === 0x2f ||
input.charCodeAt(2) === 0x5c ||
input.charCodeAt(2) === 0x3f ||
input.charCodeAt(2) === 0x23)
)
}
-11
View File
@@ -1,11 +0,0 @@
declare class ModuleResolveError extends Error {
readonly code: string
static INVALID_MODULE_SPECIFIER(msg: string): ModuleResolveError
static INVALID_PACKAGE_TARGET(msg: string): ModuleResolveError
static PACKAGE_PATH_NOT_EXPORTED(msg: string): ModuleResolveError
static PACKAGE_IMPORT_NOT_DEFINED(msg: string): ModuleResolveError
static UNSUPPORTED_ENGINE(msg: string): ModuleResolveError
}
export = ModuleResolveError
-54
View File
@@ -1,54 +0,0 @@
module.exports = class ModuleResolveError extends Error {
constructor(msg, code, fn = ModuleResolveError) {
super(`${code}: ${msg}`)
this.code = code
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn)
}
}
get name() {
return 'ModuleResolveError'
}
static INVALID_MODULE_SPECIFIER(msg) {
return new ModuleResolveError(
msg,
'INVALID_MODULE_SPECIFIER',
ModuleResolveError.INVALID_MODULE_SPECIFIER
)
}
static INVALID_PACKAGE_TARGET(msg) {
return new ModuleResolveError(
msg,
'INVALID_PACKAGE_TARGET',
ModuleResolveError.INVALID_PACKAGE_TARGET
)
}
static PACKAGE_PATH_NOT_EXPORTED(msg) {
return new ModuleResolveError(
msg,
'PACKAGE_PATH_NOT_EXPORTED',
ModuleResolveError.PACKAGE_PATH_NOT_EXPORTED
)
}
static PACKAGE_IMPORT_NOT_DEFINED(msg) {
return new ModuleResolveError(
msg,
'PACKAGE_IMPORT_NOT_DEFINED',
ModuleResolveError.PACKAGE_IMPORT_NOT_DEFINED
)
}
static UNSUPPORTED_ENGINE(msg) {
return new ModuleResolveError(
msg,
'UNSUPPORTED_ENGINE',
ModuleResolveError.UNSUPPORTED_ENGINE
)
}
}
-51
View File
@@ -1,51 +0,0 @@
{
"name": "bare-module-resolve",
"version": "1.11.1",
"description": "Low-level module resolution algorithm for Bare",
"exports": {
"./package": "./package.json",
".": {
"types": "./index.d.ts",
"default": "./index.js"
},
"./errors": {
"types": "./lib/errors.d.ts",
"default": "./lib/errors.js"
}
},
"files": [
"index.js",
"index.d.ts",
"lib"
],
"scripts": {
"test": "prettier . --check && bare test.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/holepunchto/bare-module-resolve.git"
},
"author": "Holepunch",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/holepunchto/bare-module-resolve/issues"
},
"homepage": "https://github.com/holepunchto/bare-module-resolve#readme",
"dependencies": {
"bare-semver": "^1.0.0"
},
"devDependencies": {
"bare-url": "^2.1.3",
"brittle": "^3.2.1",
"prettier": "^3.3.3",
"prettier-config-standard": "^7.0.0"
},
"peerDependencies": {
"bare-url": "*"
},
"peerDependenciesMeta": {
"bare-url": {
"optional": true
}
}
}
-13
View File
@@ -1,13 +0,0 @@
cmake_minimum_required(VERSION 3.25)
find_package(cmake-bare REQUIRED PATHS node_modules/cmake-bare)
project(bare_os C)
add_bare_module(bare_os)
target_sources(
${bare_os}
PRIVATE
binding.c
)
-201
View File
@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-11
View File
@@ -1,11 +0,0 @@
# bare-os
Operating system utilities for Javascript.
```
npm i bare-os
```
## License
Apache-2.0
-1119
View File
File diff suppressed because it is too large Load Diff
-1
View File
@@ -1 +0,0 @@
module.exports = require.addon()
-109
View File
@@ -1,109 +0,0 @@
export const constants: {
signals: Record<string, number>
errnos: Record<string, number>
}
export const EOL: '\r\n' | '\n'
export function platform(): 'android' | 'darwin' | 'ios' | 'linux' | 'win32'
export function arch(): 'arm' | 'arm64' | 'ia32' | 'x64'
export function type(): string
export function version(): string
export function release(): string
export function machine(): string
export function execPath(): string
export function pid(): number
export function ppid(): number
export function cwd(): string
export function chdir(dir: string): string
export function tmpdir(): string
export function homedir(): string
export function hostname(): string
export function kill(pid: number, signal?: string | number): void
export function endianness(): 'LE' | 'BE'
export function availableParallelism(): number
export interface CpuUsage {
user: number
system: number
}
export function cpuUsage(previous?: CpuUsage): CpuUsage
export function threadCpuUsage(previous?: CpuUsage): CpuUsage
export function resourceUsage(): {
userCPUTime: number
systemCPUTime: number
maxRSS: number
sharedMemorySize: number
unsharedDataSize: number
unsharedStackSize: number
minorPageFault: number
majorPageFault: number
swappedOut: number
fsRead: number
fsWrite: number
ipcSent: number
ipcReceived: number
signalsCount: number
voluntaryContextSwitches: number
involuntaryContextSwitches: number
}
export function memoryUsage(): {
rss: number
heapTotal: number
heapUsed: number
external: number
}
export function freemem(): number
export function totalmem(): number
export function uptime(): number
export function loadavg(): ArrayLike<number>
export function cpus(): {
model: string
speed: number
times: {
user: number
nice: number
sys: number
idle: number
irq: number
}
}[]
export function getProcessTitle(): string
export function setProcessTitle(title: unknown): void
export function getEnvKeys(): string[]
export function getEnv(name: string): string | undefined
export function hasEnv(name: string): boolean
export function setEnv(name: string, value: string): void
export function unsetEnv(name: string): void
-99
View File
@@ -1,99 +0,0 @@
const binding = require('./binding')
const errors = require('./lib/errors')
const constants = require('./lib/constants')
exports.constants = constants
exports.EOL = binding.platform === 'win32' ? '\r\n' : '\n'
exports.platform = function platform() {
return binding.platform
}
exports.arch = function arch() {
return binding.arch
}
exports.type = binding.type
exports.version = binding.version
exports.release = binding.release
exports.machine = binding.machine
exports.execPath = binding.execPath
exports.pid = binding.pid
exports.ppid = binding.ppid
exports.cwd = binding.cwd
exports.chdir = binding.chdir
exports.tmpdir = binding.tmpdir
exports.homedir = binding.homedir
exports.hostname = binding.hostname
exports.userInfo = binding.userInfo
exports.kill = function kill(pid, signal = constants.signals.SIGTERM) {
if (typeof signal === 'string') {
if (signal in constants.signals === false) {
throw errors.UNKNOWN_SIGNAL('Unknown signal: ' + signal)
}
signal = constants.signals[signal]
}
binding.kill(pid, signal)
}
exports.endianness = function endianness() {
return binding.isLittleEndian ? 'LE' : 'BE'
}
exports.availableParallelism = binding.availableParallelism
exports.cpuUsage = function cpuUsage(previous) {
const current = binding.cpuUsage()
if (previous) {
return {
user: current.user - previous.user,
system: current.system - previous.system
}
}
return current
}
exports.threadCpuUsage = function threadCpuUsage(previous) {
const current = binding.threadCpuUsage()
if (previous) {
return {
user: current.user - previous.user,
system: current.system - previous.system
}
}
return current
}
exports.resourceUsage = binding.resourceUsage
exports.memoryUsage = binding.memoryUsage
exports.freemem = binding.freemem
exports.totalmem = binding.totalmem
exports.uptime = binding.uptime
exports.loadavg = binding.loadavg
exports.cpus = binding.cpus
exports.getProcessTitle = binding.getProcessTitle
exports.setProcessTitle = function setProcessTitle(title) {
if (typeof title !== 'string') title = title.toString()
if (title.length >= 256) {
throw errors.TITLE_OVERFLOW('Process title is too long')
}
binding.setProcessTitle(title)
}
exports.getEnvKeys = binding.getEnvKeys
exports.getEnv = binding.getEnv
exports.hasEnv = binding.hasEnv
exports.setEnv = binding.setEnv
exports.unsetEnv = binding.unsetEnv
-6
View File
@@ -1,6 +0,0 @@
const binding = require('../binding')
module.exports = {
signals: binding.signals,
errnos: binding.errnos
}
-22
View File
@@ -1,22 +0,0 @@
module.exports = class OSError extends Error {
constructor(msg, code, fn = OSError) {
super(`${code}: ${msg}`)
this.code = code
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn)
}
}
get name() {
return 'OSError'
}
static UNKNOWN_SIGNAL(msg) {
return new OSError(msg, 'UNKNOWN_SIGNAL', OSError.UNKNOWN_SIGNAL)
}
static TITLE_OVERFLOW(msg) {
return new OSError(msg, 'TITLE_OVERFLOW', OSError.TITLE_OVERFLOW)
}
}
-46
View File
@@ -1,46 +0,0 @@
{
"name": "bare-os",
"version": "3.6.1",
"description": "Operating system utilities for Javascript",
"exports": {
".": {
"types": "./index.d.ts",
"default": "./index.js"
},
"./package": "./package.json",
"./constants": "./lib/constants.js",
"./errors": "./lib/errors.js"
},
"files": [
"index.js",
"index.d.ts",
"binding.c",
"binding.js",
"CMakeLists.txt",
"lib",
"prebuilds"
],
"addon": true,
"scripts": {
"test": "prettier . --check && bare test.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/holepunchto/bare-os.git"
},
"author": "Holepunch",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/holepunchto/bare-os/issues"
},
"homepage": "https://github.com/holepunchto/bare-os#readme",
"engines": {
"bare": ">=1.14.0"
},
"devDependencies": {
"brittle": "^3.1.1",
"cmake-bare": "^1.1.6",
"prettier": "^3.4.2",
"prettier-config-standard": "^7.0.0"
}
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
-201
View File
@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-28
View File
@@ -1,28 +0,0 @@
Copyright 2023 Holepunch Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
---
Copyright Joyent, Inc. and other Node contributors.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the
following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
-19
View File
@@ -1,19 +0,0 @@
# bare-path
Path manipulation library for JavaScript.
```
npm i bare-path
```
## Usage
``` js
const path = require('bare-path')
path.join('foo', 'bar') // foo/bar on posix, foo\bar on windows
```
## License
Apache-2.0
-11
View File
@@ -1,11 +0,0 @@
/* global Bare */
// This export SHOULD NOT be shortened in any way as having the full
// `module.exports = require(...)` statement is crucial for synthesizing
// ESM exports.
if (Bare.platform === 'win32') {
module.exports = require('./lib/win32')
} else {
module.exports = require('./lib/posix')
}
-11
View File
@@ -1,11 +0,0 @@
module.exports = {
CHAR_UPPERCASE_A: 0x41,
CHAR_LOWERCASE_A: 0x61,
CHAR_UPPERCASE_Z: 0x5a,
CHAR_LOWERCASE_Z: 0x7a,
CHAR_DOT: 0x2e,
CHAR_FORWARD_SLASH: 0x2f,
CHAR_BACKWARD_SLASH: 0x5c,
CHAR_COLON: 0x3a,
CHAR_QUESTION_MARK: 0x3f
}
-242
View File
@@ -1,242 +0,0 @@
const os = require('bare-os')
const { normalizeString } = require('./shared')
const {
CHAR_DOT,
CHAR_FORWARD_SLASH
} = require('./constants')
function isPosixPathSeparator (code) {
return code === CHAR_FORWARD_SLASH
}
exports.win32 = require('./win32')
exports.posix = exports
exports.sep = '/'
exports.delimiter = ':'
exports.resolve = function resolve (...args) {
let resolvedPath = ''
let resolvedAbsolute = false
for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
const path = i >= 0 ? args[i] : os.cwd()
if (path.length === 0) {
continue
}
resolvedPath = `${path}/${resolvedPath}`
resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
}
resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator)
if (resolvedAbsolute) {
return `/${resolvedPath}`
}
return resolvedPath.length > 0 ? resolvedPath : '.'
}
exports.normalize = function normalize (path) {
if (path.length === 0) return '.'
const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH
const trailingSeparator = path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH
path = normalizeString(path, !isAbsolute, '/', isPosixPathSeparator)
if (path.length === 0) {
if (isAbsolute) return '/'
return trailingSeparator ? './' : '.'
}
if (trailingSeparator) path += '/'
return isAbsolute ? `/${path}` : path
}
exports.isAbsolute = function isAbsolute (path) {
return path.length > 0 && path.charCodeAt(0) === CHAR_FORWARD_SLASH
}
exports.join = function join (...args) {
if (args.length === 0) return '.'
let joined
for (let i = 0; i < args.length; ++i) {
const arg = args[i]
if (arg.length > 0) {
if (joined === undefined) joined = arg
else joined += `/${arg}`
}
}
if (joined === undefined) return '.'
return exports.normalize(joined)
}
exports.relative = function relative (from, to) {
if (from === to) return ''
from = exports.resolve(from)
to = exports.resolve(to)
if (from === to) return ''
const fromStart = 1
const fromEnd = from.length
const fromLen = fromEnd - fromStart
const toStart = 1
const toLen = to.length - toStart
const length = (fromLen < toLen ? fromLen : toLen)
let lastCommonSep = -1
let i = 0
for (; i < length; i++) {
const fromCode = from.charCodeAt(fromStart + i)
if (fromCode !== to.charCodeAt(toStart + i)) {
break
} else if (fromCode === CHAR_FORWARD_SLASH) {
lastCommonSep = i
}
}
if (i === length) {
if (toLen > length) {
if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) {
return to.substring(toStart + i + 1)
}
if (i === 0) {
return to.substring(toStart + i)
}
} else if (fromLen > length) {
if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) {
lastCommonSep = i
} else if (i === 0) {
lastCommonSep = 0
}
}
}
let out = ''
for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
if (i === fromEnd || from.charCodeAt(i) === CHAR_FORWARD_SLASH) {
out += out.length === 0 ? '..' : '/..'
}
}
return `${out}${to.substring(toStart + lastCommonSep)}`
}
exports.toNamespacedPath = function toNamespacedPath (path) {
return path
}
exports.dirname = function dirname (path) {
if (path.length === 0) return '.'
const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH
let end = -1
let matchedSlash = true
for (let i = path.length - 1; i >= 1; --i) {
if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
if (!matchedSlash) {
end = i
break
}
} else {
matchedSlash = false
}
}
if (end === -1) return hasRoot ? '/' : '.'
if (hasRoot && end === 1) return '//'
return path.substring(0, end)
}
exports.basename = function basename (path, suffix) {
let start = 0
let end = -1
let matchedSlash = true
if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
if (suffix === path) { return '' }
let extIdx = suffix.length - 1
let firstNonSlashEnd = -1
for (let i = path.length - 1; i >= 0; --i) {
const code = path.charCodeAt(i)
if (code === CHAR_FORWARD_SLASH) {
if (!matchedSlash) {
start = i + 1
break
}
} else {
if (firstNonSlashEnd === -1) {
matchedSlash = false
firstNonSlashEnd = i + 1
}
if (extIdx >= 0) {
if (code === suffix.charCodeAt(extIdx)) {
if (--extIdx === -1) {
end = i
}
} else {
extIdx = -1
end = firstNonSlashEnd
}
}
}
}
if (start === end) end = firstNonSlashEnd
else if (end === -1) end = path.length
return path.substring(start, end)
}
for (let i = path.length - 1; i >= 0; --i) {
if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) {
if (!matchedSlash) {
start = i + 1
break
}
} else if (end === -1) {
matchedSlash = false
end = i + 1
}
}
if (end === -1) return ''
return path.substring(start, end)
}
exports.extname = function extname (path) {
let startDot = -1
let startPart = 0
let end = -1
let matchedSlash = true
let preDotState = 0
for (let i = path.length - 1; i >= 0; --i) {
const code = path.charCodeAt(i)
if (code === CHAR_FORWARD_SLASH) {
if (!matchedSlash) {
startPart = i + 1
break
}
continue
}
if (end === -1) {
matchedSlash = false
end = i + 1
}
if (code === CHAR_DOT) {
if (startDot === -1) startDot = i
else if (preDotState !== 1) preDotState = 1
} else if (startDot !== -1) {
preDotState = -1
}
}
if (startDot === -1 || end === -1 || preDotState === 0 || (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)) {
return ''
}
return path.substring(startDot, end)
}
-67
View File
@@ -1,67 +0,0 @@
const {
CHAR_DOT,
CHAR_FORWARD_SLASH
} = require('./constants')
exports.normalizeString = function normalizeString (path, allowAboveRoot, separator, isPathSeparator) {
let res = ''
let lastSegmentLength = 0
let lastSlash = -1
let dots = 0
let code = 0
for (let i = 0; i <= path.length; ++i) {
if (i < path.length) {
code = path.charCodeAt(i)
} else if (isPathSeparator(code)) {
break
} else {
code = CHAR_FORWARD_SLASH
}
if (isPathSeparator(code)) {
if (lastSlash === i - 1 || dots === 1) ;
else if (dots === 2) {
if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== CHAR_DOT || res.charCodeAt(res.length - 2) !== CHAR_DOT) {
if (res.length > 2) {
const lastSlashIndex = res.lastIndexOf(separator)
if (lastSlashIndex === -1) {
res = ''
lastSegmentLength = 0
} else {
res = res.substring(0, lastSlashIndex)
lastSegmentLength =
res.length - 1 - res.lastIndexOf(separator)
}
lastSlash = i
dots = 0
continue
} else if (res.length !== 0) {
res = ''
lastSegmentLength = 0
lastSlash = i
dots = 0
continue
}
}
if (allowAboveRoot) {
res += res.length > 0 ? `${separator}..` : '..'
lastSegmentLength = 2
}
} else {
if (res.length > 0) {
res += `${separator}${path.substring(lastSlash + 1, i)}`
} else {
res = path.substring(lastSlash + 1, i)
}
lastSegmentLength = i - lastSlash - 1
}
lastSlash = i
dots = 0
} else if (code === CHAR_DOT && dots !== -1) {
++dots
} else {
dots = -1
}
}
return res
}
-513
View File
@@ -1,513 +0,0 @@
const os = require('bare-os')
const { normalizeString } = require('./shared')
const {
CHAR_UPPERCASE_A,
CHAR_LOWERCASE_A,
CHAR_UPPERCASE_Z,
CHAR_LOWERCASE_Z,
CHAR_DOT,
CHAR_FORWARD_SLASH,
CHAR_BACKWARD_SLASH,
CHAR_COLON,
CHAR_QUESTION_MARK
} = require('./constants')
function isWindowsPathSeparator (code) {
return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH
}
function isWindowsDeviceRoot (code) {
return (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) ||
(code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z)
}
exports.posix = require('./posix')
exports.win32 = exports
exports.sep = '\\'
exports.delimiter = ';'
exports.resolve = function resolve (...args) {
let resolvedDevice = ''
let resolvedTail = ''
let resolvedAbsolute = false
for (let i = args.length - 1; i >= -1; i--) {
let path
if (i >= 0) {
path = args[i]
if (path.length === 0) continue
} else if (resolvedDevice.length === 0) {
path = os.cwd()
} else {
path = os.getEnv(`=${resolvedDevice}`) || os.cwd()
if (path === undefined || (path.substring(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() && path.charCodeAt(2) === CHAR_BACKWARD_SLASH)) {
path = `${resolvedDevice}\\`
}
}
const len = path.length
let rootEnd = 0
let device = ''
let isAbsolute = false
const code = path.charCodeAt(0)
if (len === 1) {
if (isWindowsPathSeparator(code)) {
rootEnd = 1
isAbsolute = true
}
} else if (isWindowsPathSeparator(code)) {
isAbsolute = true
if (isWindowsPathSeparator(path.charCodeAt(1))) {
let j = 2
let last = j
while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
j++
}
if (j < len && j !== last) {
const firstPart = path.substring(last, j)
last = j
while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
j++
}
if (j < len && j !== last) {
last = j
while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
j++
}
if (j === len || j !== last) {
device = `\\\\${firstPart}\\${path.substring(last, j)}`
rootEnd = j
}
}
}
} else {
rootEnd = 1
}
} else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
device = path.substring(0, 2)
rootEnd = 2
if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
isAbsolute = true
rootEnd = 3
}
}
if (device.length > 0) {
if (resolvedDevice.length > 0) {
if (device.toLowerCase() !== resolvedDevice.toLowerCase()) { continue }
} else {
resolvedDevice = device
}
}
if (resolvedAbsolute) {
if (resolvedDevice.length > 0) { break }
} else {
resolvedTail = `${path.substring(rootEnd)}\\${resolvedTail}`
resolvedAbsolute = isAbsolute
if (isAbsolute && resolvedDevice.length > 0) {
break
}
}
}
resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isWindowsPathSeparator)
return resolvedAbsolute ? `${resolvedDevice}\\${resolvedTail}` : `${resolvedDevice}${resolvedTail}` || '.'
}
exports.normalize = function normalize (path) {
const len = path.length
if (len === 0) return '.'
let rootEnd = 0
let device
let isAbsolute = false
const code = path.charCodeAt(0)
if (len === 1) {
return code === CHAR_FORWARD_SLASH ? '\\' : path
}
if (isWindowsPathSeparator(code)) {
isAbsolute = true
if (isWindowsPathSeparator(path.charCodeAt(1))) {
let j = 2
let last = j
while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
j++
}
if (j < len && j !== last) {
const firstPart = path.substring(last, j)
last = j
while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
j++
}
if (j < len && j !== last) {
last = j
while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
j++
}
if (j === len) {
return `\\\\${firstPart}\\${path.substring(last)}\\`
}
if (j !== last) {
device = `\\\\${firstPart}\\${path.substring(last, j)}`
rootEnd = j
}
}
}
} else {
rootEnd = 1
}
} else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
device = path.substring(0, 2)
rootEnd = 2
if (len > 2 && isWindowsPathSeparator(path.charCodeAt(2))) {
isAbsolute = true
rootEnd = 3
}
}
let tail = rootEnd < len ? normalizeString(path.substring(rootEnd), !isAbsolute, '\\', isWindowsPathSeparator) : ''
if (tail.length === 0 && !isAbsolute) {
tail = '.'
}
if (tail.length > 0 && isWindowsPathSeparator(path.charCodeAt(len - 1))) {
tail += '\\'
}
if (device === undefined) {
return isAbsolute ? `\\${tail}` : tail
}
return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`
}
exports.isAbsolute = function isAbsolute (path) {
const len = path.length
if (len === 0) return false
const code = path.charCodeAt(0)
return isWindowsPathSeparator(code) || (len > 2 && isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON && isWindowsPathSeparator(path.charCodeAt(2)))
}
exports.join = function join (...args) {
if (args.length === 0) return '.'
let joined
let firstPart
for (let i = 0; i < args.length; ++i) {
const arg = args[i]
if (arg.length > 0) {
if (joined === undefined) joined = firstPart = arg
else joined += `\\${arg}`
}
}
if (joined === undefined) return '.'
let needsReplace = true
let slashCount = 0
if (isWindowsPathSeparator(firstPart.charCodeAt(0))) {
++slashCount
const firstLen = firstPart.length
if (firstLen > 1 && isWindowsPathSeparator(firstPart.charCodeAt(1))) {
++slashCount
if (firstLen > 2) {
if (isWindowsPathSeparator(firstPart.charCodeAt(2))) {
++slashCount
} else {
needsReplace = false
}
}
}
}
if (needsReplace) {
while (slashCount < joined.length && isWindowsPathSeparator(joined.charCodeAt(slashCount))) {
slashCount++
}
if (slashCount >= 2) {
joined = `\\${joined.substring(slashCount)}`
}
}
return exports.normalize(joined)
}
exports.relative = function relative (from, to) {
if (from === to) return ''
const fromOrig = exports.resolve(from)
const toOrig = exports.resolve(to)
if (fromOrig === toOrig) return ''
from = fromOrig.toLowerCase()
to = toOrig.toLowerCase()
if (from === to) return ''
let fromStart = 0
while (fromStart < from.length && from.charCodeAt(fromStart) === CHAR_BACKWARD_SLASH) {
fromStart++
}
let fromEnd = from.length
while (fromEnd - 1 > fromStart && from.charCodeAt(fromEnd - 1) === CHAR_BACKWARD_SLASH) {
fromEnd--
}
const fromLen = fromEnd - fromStart
let toStart = 0
while (toStart < to.length && to.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
toStart++
}
let toEnd = to.length
while (toEnd - 1 > toStart && to.charCodeAt(toEnd - 1) === CHAR_BACKWARD_SLASH) {
toEnd--
}
const toLen = toEnd - toStart
const length = fromLen < toLen ? fromLen : toLen
let lastCommonSep = -1
let i = 0
for (; i < length; i++) {
const fromCode = from.charCodeAt(fromStart + i)
if (fromCode !== to.charCodeAt(toStart + i)) {
break
} else if (fromCode === CHAR_BACKWARD_SLASH) {
lastCommonSep = i
}
}
if (i !== length) {
if (lastCommonSep === -1) return toOrig
} else {
if (toLen > length) {
if (to.charCodeAt(toStart + i) === CHAR_BACKWARD_SLASH) {
return toOrig.substring(toStart + i + 1)
}
if (i === 2) {
return toOrig.substring(toStart + i)
}
}
if (fromLen > length) {
if (from.charCodeAt(fromStart + i) === CHAR_BACKWARD_SLASH) {
lastCommonSep = i
} else if (i === 2) {
lastCommonSep = 3
}
}
if (lastCommonSep === -1) lastCommonSep = 0
}
let out = ''
for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
if (i === fromEnd || from.charCodeAt(i) === CHAR_BACKWARD_SLASH) {
out += out.length === 0 ? '..' : '\\..'
}
}
toStart += lastCommonSep
if (out.length > 0) {
return `${out}${toOrig.substring(toStart, toEnd)}`
}
if (toOrig.charCodeAt(toStart) === CHAR_BACKWARD_SLASH) {
++toStart
}
return toOrig.substring(toStart, toEnd)
}
exports.toNamespacedPath = function toNamespacedPath (path) {
if (path.length === 0) return path
const resolvedPath = exports.resolve(path)
if (resolvedPath.length <= 2) return path
if (resolvedPath.charCodeAt(0) === CHAR_BACKWARD_SLASH) {
if (resolvedPath.charCodeAt(1) === CHAR_BACKWARD_SLASH) {
const code = resolvedPath.charCodeAt(2)
if (code !== CHAR_QUESTION_MARK && code !== CHAR_DOT) {
return `\\\\?\\UNC\\${resolvedPath.substring(2)}`
}
}
} else if (
isWindowsDeviceRoot(resolvedPath.charCodeAt(0)) &&
resolvedPath.charCodeAt(1) === CHAR_COLON &&
resolvedPath.charCodeAt(2) === CHAR_BACKWARD_SLASH
) {
return `\\\\?\\${resolvedPath}`
}
return path
}
exports.dirname = function dirname (path) {
const len = path.length
if (len === 0) return '.'
let rootEnd = -1
let offset = 0
const code = path.charCodeAt(0)
if (len === 1) {
return isWindowsPathSeparator(code) ? path : '.'
}
if (isWindowsPathSeparator(code)) {
rootEnd = offset = 1
if (isWindowsPathSeparator(path.charCodeAt(1))) {
let j = 2
let last = j
while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
j++
}
if (j < len && j !== last) {
last = j
while (j < len && isWindowsPathSeparator(path.charCodeAt(j))) {
j++
}
if (j < len && j !== last) {
last = j
while (j < len && !isWindowsPathSeparator(path.charCodeAt(j))) {
j++
}
if (j === len) {
return path
}
if (j !== last) {
rootEnd = offset = j + 1
}
}
}
}
} else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) {
rootEnd = len > 2 && isWindowsPathSeparator(path.charCodeAt(2)) ? 3 : 2
offset = rootEnd
}
let end = -1
let matchedSlash = true
for (let i = len - 1; i >= offset; --i) {
if (isWindowsPathSeparator(path.charCodeAt(i))) {
if (!matchedSlash) {
end = i
break
}
} else {
matchedSlash = false
}
}
if (end === -1) {
if (rootEnd === -1) return '.'
end = rootEnd
}
return path.substring(0, end)
}
exports.basename = function basename (path, suffix) {
let start = 0
let end = -1
let matchedSlash = true
if (path.length >= 2 && isWindowsDeviceRoot(path.charCodeAt(0)) && path.charCodeAt(1) === CHAR_COLON) {
start = 2
}
if (suffix !== undefined && suffix.length > 0 && suffix.length <= path.length) {
if (suffix === path) return ''
let extIdx = suffix.length - 1
let firstNonSlashEnd = -1
for (let i = path.length - 1; i >= start; --i) {
const code = path.charCodeAt(i)
if (isWindowsPathSeparator(code)) {
if (!matchedSlash) {
start = i + 1
break
}
} else {
if (firstNonSlashEnd === -1) {
matchedSlash = false
firstNonSlashEnd = i + 1
}
if (extIdx >= 0) {
if (code === suffix.charCodeAt(extIdx)) {
if (--extIdx === -1) {
end = i
}
} else {
extIdx = -1
end = firstNonSlashEnd
}
}
}
}
if (start === end) end = firstNonSlashEnd
else if (end === -1) end = path.length
return path.substring(start, end)
}
for (let i = path.length - 1; i >= start; --i) {
if (isWindowsPathSeparator(path.charCodeAt(i))) {
if (!matchedSlash) {
start = i + 1
break
}
} else if (end === -1) {
matchedSlash = false
end = i + 1
}
}
if (end === -1) return ''
return path.substring(start, end)
}
exports.extname = function extname (path) {
let start = 0
let startDot = -1
let startPart = 0
let end = -1
let matchedSlash = true
let preDotState = 0
if (path.length >= 2 && path.charCodeAt(1) === CHAR_COLON && isWindowsDeviceRoot(path.charCodeAt(0))) {
start = startPart = 2
}
for (let i = path.length - 1; i >= start; --i) {
const code = path.charCodeAt(i)
if (isWindowsPathSeparator(code)) {
if (!matchedSlash) {
startPart = i + 1
break
}
continue
}
if (end === -1) {
matchedSlash = false
end = i + 1
}
if (code === CHAR_DOT) {
if (startDot === -1) startDot = i
else if (preDotState !== 1) preDotState = 1
} else if (startDot !== -1) {
preDotState = -1
}
}
if (startDot === -1 || end === -1 || preDotState === 0 || (preDotState === 1 && startDot === end - 1 && startDot === startPart + 1)) {
return ''
}
return path.substring(startDot, end)
}
-36
View File
@@ -1,36 +0,0 @@
{
"name": "bare-path",
"version": "3.0.0",
"description": "Path manipulation library for JavaScript",
"exports": {
".": "./index.js",
"./package": "./package.json",
"./posix": "./lib/posix.js",
"./win32": "./lib/win32.js"
},
"files": [
"index.js",
"lib",
"NOTICE"
],
"scripts": {
"test": "standard && bare test.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/holepunchto/bare-path.git"
},
"author": "Holepunch",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/holepunchto/bare-path/issues"
},
"homepage": "https://github.com/holepunchto/bare-path#readme",
"dependencies": {
"bare-os": "^3.0.1"
},
"devDependencies": {
"brittle": "^3.3.2",
"standard": "^17.0.0"
}
}
-201
View File
@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-19
View File
@@ -1,19 +0,0 @@
# bare-semver
Minimal semantic versioning library for Bare.
```
npm i bare-semver
```
## Usage
```js
const { Version } = require('bare-semver')
Version.parse('1.2.3')
```
## License
Apache-2.0
-13
View File
@@ -1,13 +0,0 @@
exports.constants = require('./lib/constants')
exports.errors = require('./lib/errors')
const Version = exports.Version = require('./lib/version')
const Range = exports.Range = require('./lib/range')
exports.Comparator = require('./lib/comparator')
exports.satisfies = function satisfies (version, range) {
if (typeof version === 'string') version = Version.parse(version)
if (typeof range === 'string') range = Range.parse(range)
return range.test(version)
}
-32
View File
@@ -1,32 +0,0 @@
const constants = require('./constants')
const symbols = {
[constants.EQ]: '=',
[constants.LT]: '<',
[constants.LTE]: '<=',
[constants.GT]: '>',
[constants.GTE]: '>='
}
module.exports = class Comparator {
constructor (operator, version) {
this.operator = operator
this.version = version
}
test (version) {
const result = version.compare(this.version)
switch (this.operator) {
case constants.LT: return result < 0
case constants.LTE: return result <= 0
case constants.GT: return result > 0
case constants.GTE: return result >= 0
default: return result === 0
}
}
toString () {
return symbols[this.operator] + this.version
}
}
-7
View File
@@ -1,7 +0,0 @@
module.exports = {
EQ: 1,
LT: 2,
LTE: 3,
GT: 4,
GTE: 5
}
-22
View File
@@ -1,22 +0,0 @@
module.exports = class SemVerError extends Error {
constructor (msg, code, fn = SemVerError) {
super(`${code}: ${msg}`)
this.code = code
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn)
}
}
get name () {
return 'SemVerError'
}
static INVALID_VERSION (msg, fn = SemVerError.INVALID_VERSION) {
return new SemVerError(msg, 'INVALID_VERSION', fn)
}
static INVALID_RANGE (msg, fn = SemVerError.INVALID_RANGE) {
return new SemVerError(msg, 'INVALID_RANGE', fn)
}
}
-117
View File
@@ -1,117 +0,0 @@
const constants = require('./constants')
const errors = require('./errors')
const Version = require('./version')
const Comparator = require('./comparator')
const Range = module.exports = exports = class Range {
constructor (comparators = []) {
this.comparators = comparators
}
test (version) {
for (const set of this.comparators) {
let matches = true
for (const comparator of set) {
if (comparator.test(version)) continue
matches = false
break
}
if (matches) return true
}
return false
}
toString () {
let result = ''
let first = true
for (const set of this.comparators) {
if (first) first = false
else result += ' || '
result += set.join(' ')
}
return result
}
}
exports.parse = function parse (input, state = { position: 0, partial: false }) {
let i = state.position
let c
const unexpected = (expected) => {
let msg
if (i >= input.length) {
msg = `Unexpected end of input in '${input}'`
} else {
msg = `Unexpected token '${input[i]}' in '${input}' at position ${i}`
}
if (expected) msg += `, ${expected}`
throw errors.INVALID_VERSION(msg, unexpected)
}
const comparators = []
while (i < input.length) {
const set = []
while (i < input.length) {
c = input[i]
let operator = constants.EQ
if (c === '<') {
operator = constants.LT
c = input[++i]
if (c === '=') {
operator = constants.LTE
c = input[++i]
}
} else if (c === '>') {
operator = constants.GT
c = input[++i]
if (c === '=') {
operator = constants.GTE
c = input[++i]
}
} else if (c === '=') {
c = input[++i]
}
const state = { position: i, partial: true }
set.push(new Comparator(operator, Version.parse(input, state)))
c = input[i = state.position]
while (c === ' ') c = input[++i]
if (c === '|' && input[i + 1] === '|') {
c = input[i += 2]
while (c === ' ') c = input[++i]
break
}
if (c && c !== '<' && c !== '>') unexpected('expected \'||\', \'<\', or \'>\'')
}
if (set.length) comparators.push(set)
}
if (i < input.length && state.partial === false) unexpected('expected end of input')
state.position = i
return new Range(comparators)
}
-190
View File
@@ -1,190 +0,0 @@
const errors = require('./errors')
const Version = module.exports = exports = class Version {
constructor (major, minor, patch, opts = {}) {
const {
prerelease = [],
build = []
} = opts
this.major = major
this.minor = minor
this.patch = patch
this.prerelease = prerelease
this.build = build
}
compare (version) {
return exports.compare(this, version)
}
toString () {
let result = `${this.major}.${this.minor}.${this.patch}`
if (this.prerelease.length) {
result += '-' + this.prerelease.join('.')
}
if (this.build.length) {
result += '+' + this.build.join('.')
}
return result
}
}
exports.parse = function parse (input, state = { position: 0, partial: false }) {
let i = state.position
let c
const unexpected = (expected) => {
let msg
if (i >= input.length) {
msg = `Unexpected end of input in '${input}'`
} else {
msg = `Unexpected token '${input[i]}' in '${input}' at position ${i}`
}
if (expected) msg += `, ${expected}`
throw errors.INVALID_VERSION(msg, unexpected)
}
const components = []
while (components.length < 3) {
c = input[i]
if (components.length > 0) {
if (c === '.') c = input[++i]
else unexpected('expected \'.\'')
}
if (c === '0') {
components.push(0)
i++
} else if (c >= '1' && c <= '9') {
let j = 0
do c = input[i + ++j]
while (c >= '0' && c <= '9')
components.push(parseInt(input.substring(i, i + j)))
i += j
} else unexpected('expected /[0-9]/')
}
const prerelease = []
if (input[i] === '-') {
i++
while (true) {
c = input[i]
let tag = ''
let j = 0
while (c >= '0' && c <= '9') c = input[i + ++j]
let isNumeric = false
if (j) {
tag += input.substring(i, i + j)
c = input[i += j]
isNumeric = tag[0] !== '0' || tag.length === 1
}
j = 0
while ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c === '-') c = input[i + ++j]
if (j) {
tag += input.substring(i, i + j)
c = input[i += j]
} else if (!isNumeric) unexpected('expected /[a-zA-Z-]/')
prerelease.push(tag)
if (c === '.') c = input[++i]
else break
}
}
const build = []
if (input[i] === '+') {
i++
while (true) {
c = input[i]
let tag = ''
let j = 0
while ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c === '-') c = input[i + ++j]
if (j) {
tag += input.substring(i, i + j)
c = input[i += j]
} else unexpected('expected /[0-9a-zA-Z-]/')
build.push(tag)
if (c === '.') c = input[++i]
else break
}
}
if (i < input.length && state.partial === false) unexpected('expected end of input')
state.position = i
return new Version(...components, { prerelease, build })
}
const integer = /^[0-9]+$/
exports.compare = function compare (a, b) {
if (a.major > b.major) return 1
if (a.major < b.major) return -1
if (a.minor > b.minor) return 1
if (a.minor < b.minor) return -1
if (a.patch > b.patch) return 1
if (a.patch < b.patch) return -1
if (a.prerelease.length === 0) return b.prerelease.length === 0 ? 0 : 1
if (b.prerelease.length === 0) return -1
let i = 0
do {
let x = a.prerelease[i]
let y = b.prerelease[i]
if (x === undefined) return y === undefined ? 0 : -1
if (y === undefined) return 1
if (x === y) continue
const xInt = integer.test(x)
const yInt = integer.test(y)
if (xInt && yInt) {
x = +x
y = +y
} else {
if (xInt) return -1
if (yInt) return 1
}
return x > y ? 1 : -1
} while (++i)
}
-35
View File
@@ -1,35 +0,0 @@
{
"name": "bare-semver",
"version": "1.0.1",
"description": "Minimal semantic versioning library for Bare",
"exports": {
".": "./index.js",
"./package": "./package.json",
"./constants": "./lib/constants.js",
"./errors": "./lib/errors.js",
"./version": "./lib/version.js",
"./range": "./lib/range.js",
"./comparator": "./lib/comparator.js"
},
"files": [
"index.js",
"lib"
],
"scripts": {
"test": "standard && bare test.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/holepunchto/bare-semver.git"
},
"author": "Holepunch",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/holepunchto/bare-semver/issues"
},
"homepage": "https://github.com/holepunchto/bare-semver#readme",
"devDependencies": {
"brittle": "^3.2.1",
"standard": "^17.0.0"
}
}
-25
View File
@@ -1,25 +0,0 @@
cmake_minimum_required(VERSION 3.25)
find_package(cmake-bare REQUIRED PATHS node_modules/cmake-bare)
find_package(cmake-fetch REQUIRED PATHS node_modules/cmake-fetch)
project(bare_url C)
fetch_package("github:holepunchto/libutf#9c5d642")
fetch_package("github:holepunchto/liburl#03f1488")
add_bare_module(bare_url)
target_sources(
${bare_url}
PRIVATE
binding.c
)
target_link_libraries(
${bare_url}
PRIVATE
$<TARGET_OBJECTS:url>
PUBLIC
url
)
-201
View File
@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-19
View File
@@ -1,19 +0,0 @@
# bare-url
WHATWG URL implementation for JavaScript.
```
npm i bare-url
```
## Usage
```js
const url = require('bare-url')
const p = url.fileURLToPath('file:///foo') // --> /foo
```
## License
Apache-2.0
-188
View File
@@ -1,188 +0,0 @@
#include <assert.h>
#include <bare.h>
#include <js.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <url.h>
#include <utf.h>
#include <utf/string.h>
static js_type_tag_t bare_url__tag = {0x6f1fd92f476698b0, 0x93b59c349143ee50};
static js_value_t *
bare_url_parse (js_env_t *env, js_callback_info_t *info) {
int err;
size_t argc = 4;
js_value_t *argv[4];
err = js_get_callback_info(env, info, &argc, argv, NULL, NULL);
assert(err == 0);
assert(argc == 4);
bool should_throw;
err = js_get_value_bool(env, argv[3], &should_throw);
assert(err == 0);
bool has_base;
err = js_is_string(env, argv[1], &has_base);
assert(err == 0);
url_t base;
url_init(&base);
if (has_base) {
size_t len;
err = js_get_value_string_utf8(env, argv[1], NULL, 0, &len);
assert(err == 0);
utf8_t *input = malloc(len);
err = js_get_value_string_utf8(env, argv[1], input, len, NULL);
assert(err == 0);
err = url_parse(&base, input, len, NULL);
free(input);
if (err < 0) {
url_destroy(&base);
if (should_throw) js_throw_error(env, NULL, "Invalid base URL");
return NULL;
}
}
size_t len;
err = js_get_value_string_utf8(env, argv[0], NULL, 0, &len);
assert(err == 0);
utf8_t *input = malloc(len);
err = js_get_value_string_utf8(env, argv[0], input, len, NULL);
assert(err == 0);
js_value_t *handle;
url_t url;
url_init(&url);
err = url_parse(&url, input, len, has_base ? &base : NULL);
free(input);
if (err < 0) {
url_destroy(&base);
url_destroy(&url);
if (should_throw) js_throw_error(env, NULL, "Invalid URL");
return NULL;
}
js_value_t *href;
err = js_create_string_utf8(env, url.href.data, url.href.len, &href);
assert(err == 0);
uint32_t *components;
err = js_get_typedarray_info(env, argv[2], NULL, (void **) &components, NULL, NULL, NULL);
assert(err == 0);
memcpy(components, &url.components, sizeof(url.components));
url_destroy(&base);
url_destroy(&url);
return href;
}
static js_value_t *
bare_url_can_parse (js_env_t *env, js_callback_info_t *info) {
int err;
size_t argc = 2;
js_value_t *argv[2];
err = js_get_callback_info(env, info, &argc, argv, NULL, NULL);
assert(err == 0);
assert(argc == 2);
bool has_base;
err = js_is_string(env, argv[1], &has_base);
assert(err == 0);
url_t base;
url_init(&base);
if (has_base) {
size_t len;
err = js_get_value_string_utf8(env, argv[1], NULL, 0, &len);
assert(err == 0);
utf8_t *input = malloc(len);
err = js_get_value_string_utf8(env, argv[1], input, len, NULL);
assert(err == 0);
err = url_parse(&base, input, len, NULL);
free(input);
if (err < 0) {
url_destroy(&base);
js_value_t *result;
err = js_get_boolean(env, false, &result);
assert(err == 0);
return result;
}
}
size_t len;
err = js_get_value_string_utf8(env, argv[0], NULL, 0, &len);
assert(err == 0);
utf8_t *input = malloc(len);
err = js_get_value_string_utf8(env, argv[0], input, len, NULL);
assert(err == 0);
url_t url;
url_init(&url);
err = url_parse(&url, input, len, has_base ? &base : NULL);
free(input);
url_destroy(&base);
url_destroy(&url);
js_value_t *result;
err = js_get_boolean(env, err == 0, &result);
assert(err == 0);
return result;
}
static js_value_t *
bare_url_exports (js_env_t *env, js_value_t *exports) {
int err;
#define V(name, fn) \
{ \
js_value_t *val; \
err = js_create_function(env, name, -1, fn, NULL, &val); \
assert(err == 0); \
err = js_set_named_property(env, exports, name, val); \
assert(err == 0); \
}
V("parse", bare_url_parse)
V("canParse", bare_url_can_parse)
#undef V
return exports;
}
BARE_MODULE(bare_url, bare_url_exports)
-1
View File
@@ -1 +0,0 @@
module.exports = require.addon()
-9
View File
@@ -1,9 +0,0 @@
import * as url from '.'
type URLConstructor = typeof url.URL
declare global {
type URL = url.URL
const URL: URLConstructor
}
-1
View File
@@ -1 +0,0 @@
global.URL = require('.')
-37
View File
@@ -1,37 +0,0 @@
import URLError from './lib/errors'
interface URL {
href: string
protocol: string
username: string
password: string
host: string
hostname: string
port: string
pathname: string
search: string
hash: string
toString(): string
toJSON(): string
}
declare class URL {
constructor(input: string, base?: string | URL)
}
declare namespace URL {
export function isURL(value: unknown): value is URL
export function parse(input: string, base?: string | URL): URL | null
export function canParse(input: string, base?: string | URL): boolean
export function fileURLToPath(url: URL | string): string
export function pathToFileURL(pathname: string): URL
export { URL, type URLError, URLError as errors }
}
export = URL
-374
View File
@@ -1,374 +0,0 @@
const path = require('bare-path')
const binding = require('./binding')
const errors = require('./lib/errors')
const kind = Symbol.for('bare.url.kind')
const isWindows = Bare.platform === 'win32'
module.exports = exports = class URL {
static get [kind]() {
return 0 // Compatibility version
}
constructor(input, base, opts = {}) {
if (arguments.length === 0) throw errors.INVALID_URL()
input = `${input}`
if (base !== undefined) base = `${base}`
this._components = new Uint32Array(8)
this._parse(input, base, opts.throw !== false)
}
get [kind]() {
return URL[kind]
}
// https://url.spec.whatwg.org/#dom-url-href
get href() {
return this._href
}
set href(value) {
this._update(value)
}
// https://url.spec.whatwg.org/#dom-url-protocol
get protocol() {
return this._slice(0, this._components[0]) + ':'
}
set protocol(value) {
this._update(
this._replace(value.replace(/:+$/, ''), 0, this._components[0])
)
}
// https://url.spec.whatwg.org/#dom-url-username
get username() {
return this._slice(this._components[0] + 3 /* :// */, this._components[1])
}
set username(value) {
if (cannotHaveCredentialsOrPort(this)) {
return
}
if (this.username === '') value += '@'
this._update(
this._replace(
value,
this._components[0] + 3 /* :// */,
this._components[1]
)
)
}
// https://url.spec.whatwg.org/#dom-url-password
get password() {
return this._href.slice(
this._components[1] + 1 /* : */,
this._components[2] - 1 /* @ */
)
}
set password(value) {
if (cannotHaveCredentialsOrPort(this)) {
return
}
let start = this._components[1] + 1 /* : */
let end = this._components[2] - 1 /* @ */
if (this.password === '') {
value = ':' + value
start--
}
if (this.username === '') {
value += '@'
end++
}
this._update(this._replace(value, start, end))
}
// https://url.spec.whatwg.org/#dom-url-host
get host() {
return this._slice(this._components[2], this._components[5])
}
set host(value) {
if (hasOpaquePath(this)) {
return
}
this._update(
this._replace(
value,
this._components[2],
this._components[value.includes(':') ? 5 : 3]
)
)
}
// https://url.spec.whatwg.org/#dom-url-hostname
get hostname() {
return this._slice(this._components[2], this._components[3])
}
set hostname(value) {
if (hasOpaquePath(this)) {
return
}
this._update(this._replace(value, this._components[2], this._components[3]))
}
// https://url.spec.whatwg.org/#dom-url-port
get port() {
return this._slice(this._components[3] + 1 /* : */, this._components[5])
}
set port(value) {
if (cannotHaveCredentialsOrPort(this)) {
return
}
let start = this._components[3] + 1 /* : */
if (this.port === '') {
value = ':' + value
start--
}
this._update(this._replace(value, start, this._components[5]))
}
// https://url.spec.whatwg.org/#dom-url-pathname
get pathname() {
return this._slice(this._components[5], this._components[6] - 1 /* ? */)
}
set pathname(value) {
if (hasOpaquePath(this)) {
return
}
if (value[0] !== '/' && value[0] !== '\\') {
value = '/' + value
}
this._update(
this._replace(value, this._components[5], this._components[6] - 1 /* ? */)
)
}
// https://url.spec.whatwg.org/#dom-url-search
get search() {
return this._slice(
this._components[6] - 1 /* ? */,
this._components[7] - 1 /* # */
)
}
set search(value) {
if (value && value[0] !== '?') value = '?' + value
this._update(
this._replace(
value,
this._components[6] - 1 /* ? */,
this._components[7] - 1 /* # */
)
)
}
// https://url.spec.whatwg.org/#dom-url-hash
get hash() {
return this._slice(this._components[7] - 1 /* # */)
}
set hash(value) {
if (value && value[0] !== '#') value = '#' + value
this._update(this._replace(value, this._components[7] - 1 /* # */))
}
toString() {
return this._href
}
toJSON() {
return this._href
}
[Symbol.for('bare.inspect')]() {
return {
__proto__: { constructor: URL },
href: this.href,
protocol: this.protocol,
username: this.username,
password: this.password,
host: this.host,
hostname: this.hostname,
port: this.port,
pathname: this.pathname,
search: this.search,
hash: this.hash
}
}
_slice(start, end = this._href.length) {
return this._href.slice(start, end)
}
_replace(replacement, start, end = this._href.length) {
return this._slice(0, start) + replacement + this._slice(end)
}
_parse(href, base, shouldThrow) {
try {
this._href = binding.parse(
String(href),
base ? String(base) : null,
this._components,
shouldThrow
)
} catch (err) {
if (err instanceof TypeError) throw err
throw errors.INVALID_URL()
}
}
_update(href) {
try {
this._parse(href, null, true)
} catch (err) {
if (err instanceof TypeError) throw err
}
}
}
// https://url.spec.whatwg.org/#url-opaque-path
function hasOpaquePath(url) {
return url.pathname[0] !== '/'
}
// https://url.spec.whatwg.org/#cannot-have-a-username-password-port
function cannotHaveCredentialsOrPort(url) {
return url.hostname === '' || url.protocol === 'file:'
}
const URL = exports
exports.URL = URL // For Node.js compatibility
exports.errors = errors
exports.isURL = function isURL(value) {
if (value instanceof URL) return true
return (
typeof value === 'object' && value !== null && value[kind] === URL[kind]
)
}
exports.parse = function parse(input, base) {
const url = new URL(input, base, { throw: false })
return url.href ? url : null
}
exports.canParse = function canParse(input, base) {
return binding.canParse(String(input), base ? String(base) : null)
}
exports.fileURLToPath = function fileURLToPath(url) {
if (typeof url === 'string') {
url = new URL(url)
}
if (url.protocol !== 'file:') {
throw errors.INVALID_URL_SCHEME('The URL must use the file: protocol')
}
if (isWindows) {
if (/%2f|%5c/i.test(url.pathname)) {
throw errors.INVALID_FILE_URL_PATH(
'The file: URL path must not include encoded \\ or / characters'
)
}
} else {
if (url.hostname) {
throw errors.INVALID_FILE_URL_HOST(
"The file: URL host must be 'localhost' or empty"
)
}
if (/%2f/i.test(url.pathname)) {
throw errors.INVALID_FILE_URL_PATH(
'The file: URL path must not include encoded / characters'
)
}
}
const pathname = path.normalize(decodeURIComponent(url.pathname))
if (isWindows) {
if (url.hostname) return '\\\\' + url.hostname + pathname
const letter = pathname.charCodeAt(1) | 0x20
if (
letter < 0x61 /* a */ ||
letter > 0x7a /* z */ ||
pathname.charCodeAt(2) !== 0x3a /* : */
) {
throw errors.INVALID_FILE_URL_PATH('The file: URL path must be absolute')
}
return pathname.slice(1)
}
return pathname
}
exports.pathToFileURL = function pathToFileURL(pathname) {
let resolved = path.resolve(pathname)
if (pathname[pathname.length - 1] === '/') {
resolved += '/'
} else if (isWindows && pathname[pathname.length - 1] === '\\') {
resolved += '\\'
}
resolved = resolved
.replaceAll('%', '%25') // Must be first
.replaceAll('#', '%23')
.replaceAll('?', '%3f')
.replaceAll('\n', '%0a')
.replaceAll('\r', '%0d')
.replaceAll('\t', '%09')
if (!isWindows) {
resolved = resolved.replaceAll('\\', '%5c')
}
return new URL('file:' + resolved)
}
-8
View File
@@ -1,8 +0,0 @@
declare class URLError extends Error {
static INVALID_URL(msg?: string): URLError
static INVALID_URL_SCHEME(msg?: string): URLError
static INVALID_FILE_URL_HOST(msg?: string): URLError
static INVALID_FILE_URL_PATH(msg?: string): URLError
}
export = URLError
-38
View File
@@ -1,38 +0,0 @@
module.exports = class URLError extends Error {
constructor(msg, code, fn = URLError) {
super(`${code}: ${msg}`)
this.code = code
if (Error.captureStackTrace) {
Error.captureStackTrace(this, fn)
}
}
get name() {
return 'URLError'
}
static INVALID_URL(msg = 'Invalid URL') {
return new URLError(msg, 'INVALID_URL', URLError.INVALID_URL)
}
static INVALID_URL_SCHEME(msg = 'Invalid URL') {
return new URLError(msg, 'INVALID_URL_SCHEME', URLError.INVALID_URL_SCHEME)
}
static INVALID_FILE_URL_HOST(msg = 'Invalid file: URL host') {
return new URLError(
msg,
'INVALID_FILE_URL_HOST',
URLError.INVALID_FILE_URL_HOST
)
}
static INVALID_FILE_URL_PATH(msg = 'Invalid file: URL path') {
return new URLError(
msg,
'INVALID_FILE_URL_PATH',
URLError.INVALID_FILE_URL_PATH
)
}
}
-51
View File
@@ -1,51 +0,0 @@
{
"name": "bare-url",
"version": "2.1.6",
"description": "WHATWG URL implementation for JavaScript",
"exports": {
"./package": "./package.json",
".": {
"types": "./index.d.ts",
"default": "./index.js"
},
"./global": {
"types": "./global.d.ts",
"default": "./global.js"
}
},
"files": [
"index.js",
"index.d.ts",
"global.js",
"global.d.ts",
"binding.c",
"binding.js",
"CMakeLists.txt",
"lib",
"prebuilds"
],
"addon": true,
"scripts": {
"test": "prettier . --check && bare test.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/holepunchto/bare-url.git"
},
"author": "Holepunch",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/holepunchto/bare-url/issues"
},
"homepage": "https://github.com/holepunchto/bare-url",
"dependencies": {
"bare-path": "^3.0.0"
},
"devDependencies": {
"brittle": "^3.3.2",
"cmake-bare": "^1.1.6",
"cmake-fetch": "^1.0.0",
"prettier": "^3.3.3",
"prettier-config-standard": "^7.0.0"
}
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
-201
View File
@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-19
View File
@@ -1,19 +0,0 @@
# require-addon
Import native addons across JavaScript runtimes.
```
npm i require-addon
```
## Usage
```js
require.addon = require('require-addon')
const bindings = require.addon('.', __filename)
```
## License
Apache-2.0
-9
View File
@@ -1,9 +0,0 @@
const runtime = require('./lib/runtime')
if (runtime === 'bare') {
module.exports = require('./lib/runtime/bare')
} else if (runtime === 'node') {
module.exports = require('./lib/runtime/node')
} else {
module.exports = require('./lib/runtime/default')
}
-6
View File
@@ -1,6 +0,0 @@
module.exports =
typeof Bare !== 'undefined'
? 'bare'
: typeof process !== 'undefined'
? 'node'
: 'unknown'
-1
View File
@@ -1 +0,0 @@
module.exports = require.addon.bind(require)
-9
View File
@@ -1,9 +0,0 @@
if (typeof require.addon === 'function') {
module.exports = require.addon.bind(require)
} else {
module.exports = function addon(specifier, parentURL) {
throw new Error(
`Cannot find addon '${specifier}' imported from '${parentURL}'`
)
}
}
-42
View File
@@ -1,42 +0,0 @@
if (typeof require.addon === 'function') {
module.exports = require.addon.bind(require)
} else {
const url = require('url')
const resolve = require('bare-addon-resolve')
const host = process.platform + '-' + process.arch
const conditions = ['node', process.platform, process.arch]
const extensions = ['.node']
module.exports = function addon(specifier, parentURL) {
if (typeof parentURL === 'string') parentURL = url.pathToFileURL(parentURL)
for (const resolution of resolve(
specifier,
parentURL,
{ host, conditions, extensions },
readPackage
)) {
switch (resolution.protocol) {
case 'file:':
try {
return require(url.fileURLToPath(resolution))
} catch {
continue
}
}
}
throw new Error(
`Cannot find addon '${specifier}' imported from '${parentURL.href}'`
)
function readPackage(packageURL) {
try {
return require(url.fileURLToPath(packageURL))
} catch (err) {
return null
}
}
}
}
-59
View File
@@ -1,59 +0,0 @@
{
"name": "require-addon",
"version": "1.1.0",
"description": "Import native addons across JavaScript runtimes",
"exports": {
".": "./index.js",
"./package": "./package.json"
},
"imports": {
"fs": {
"bare": "bare-fs",
"default": "fs"
},
"path": {
"bare": "bare-path",
"default": "path"
},
"url": {
"bare": "bare-url",
"default": "url"
}
},
"files": [
"index.js",
"lib"
],
"scripts": {
"test": "npm run lint && npm run test:bare && npm run test:node",
"test:bare": "bare test.js",
"test:node": "node test.js",
"lint": "prettier . --check"
},
"repository": {
"type": "git",
"url": "git+https://github.com/holepunchto/require-addon.git"
},
"author": "Holepunch",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/holepunchto/require-addon/issues"
},
"homepage": "https://github.com/holepunchto/require-addon#readme",
"engines": {
"bare": ">=1.10.0"
},
"dependencies": {
"bare-addon-resolve": "^1.3.0",
"bare-url": "^2.1.0"
},
"devDependencies": {
"bare-bundle": "^1.8.1",
"bare-bundle-evaluate": "^1.1.0",
"bare-fs": "^4.0.0",
"bare-path": "^3.0.0",
"brittle": "^3.7.0",
"prettier": "^3.4.1",
"prettier-config-standard": "^7.0.0"
}
}
-249
View File
@@ -1,249 +0,0 @@
cmake_minimum_required(VERSION 3.25)
find_package(cmake-bare REQUIRED PATHS node_modules/cmake-bare)
find_package(cmake-fetch REQUIRED PATHS node_modules/cmake-fetch)
find_package(cmake-napi REQUIRED PATHS node_modules/cmake-napi)
set(CMAKE_POSITION_INDEPENDENT_CODE ON)
project(sodium_native C ASM)
fetch_package("github:jedisct1/libsodium#stable" SOURCE_DIR sodium)
bare_target(target)
if(target MATCHES "win32")
add_compile_options(/MT$<$<CONFIG:Debug>:d>)
endif()
file(COPY_FILE "${sodium}/builds/msvc/version.h" "${sodium}/src/libsodium/include/sodium/version.h")
file(GLOB_RECURSE sodium_headers CONFIGURE_DEPENDS "${sodium}/src/libsodium/**/*.h")
file(GLOB_RECURSE sodium_sources CONFIGURE_DEPENDS "${sodium}/src/libsodium/**/*.c")
file(GLOB_RECURSE sodium_asm_sources CONFIGURE_DEPENDS "${sodium}/src/libsodium/**/*.S")
add_library(sodium OBJECT)
target_sources(
sodium
INTERFACE
${sodium_headers}
PRIVATE
${sodium_sources}
)
target_include_directories(
sodium
INTERFACE
"${sodium}/src/libsodium/include"
PRIVATE
"${sodium}/src/libsodium/include/sodium"
)
if(NOT target MATCHES "win32")
target_compile_options(
sodium
PRIVATE
-fvisibility=hidden
-fno-strict-aliasing
-fwrapv
-flax-vector-conversions
)
endif()
target_compile_definitions(
sodium
PUBLIC
SODIUM_STATIC=1
PRIVATE
_GNU_SOURCE=1
CONFIGURED=1
DEV_MODE=1
HAVE_ATOMIC_OPS=1
HAVE_C11_MEMORY_FENCES=1
HAVE_CET_H=1
HAVE_GCC_MEMORY_FENCES=1
HAVE_INLINE_ASM=1
HAVE_INTTYPES_H=1
HAVE_STDINT_H=1
HAVE_TI_MODE=1
)
if(target MATCHES "darwin|ios")
target_compile_definitions(
sodium
PRIVATE
ASM_HIDE_SYMBOL=.private_extern
TLS=_Thread_local
HAVE_ARC4RANDOM=1
HAVE_ARC4RANDOM_BUF=1
HAVE_CATCHABLE_ABRT=1
HAVE_CATCHABLE_SEGV=1
HAVE_CLOCK_GETTIME=1
HAVE_GETPID=1
HAVE_MADVISE=1
HAVE_MEMSET_S=1
HAVE_MLOCK=1
HAVE_MMAP=1
HAVE_MPROTECT=1
HAVE_NANOSLEEP=1
HAVE_POSIX_MEMALIGN=1
HAVE_PTHREAD=1
HAVE_PTHREAD_PRIO_INHERIT=1
HAVE_RAISE=1
HAVE_SYSCONF=1
HAVE_SYS_MMAN_H=1
HAVE_SYS_PARAM_H=1
HAVE_WEAK_SYMBOLS=1
)
if(NOT target MATCHES "ios")
target_compile_definitions(
sodium
PRIVATE
HAVE_GETENTROPY=1
HAVE_SYS_RANDOM_H=1
)
endif()
endif()
if(target MATCHES "linux")
target_compile_definitions(
sodium
PRIVATE
ASM_HIDE_SYMBOL=.hidden
TLS=_Thread_local
HAVE_CATCHABLE_ABRT=1
HAVE_CATCHABLE_SEGV=1
HAVE_CLOCK_GETTIME=1
HAVE_GETPID=1
HAVE_MADVISE=1
HAVE_MLOCK=1
HAVE_MMAP=1
HAVE_MPROTECT=1
HAVE_NANOSLEEP=1
HAVE_POSIX_MEMALIGN=1
HAVE_PTHREAD_PRIO_INHERIT=1
HAVE_PTHREAD=1
HAVE_RAISE=1
HAVE_SYSCONF=1
HAVE_SYS_AUXV_H=1
HAVE_SYS_MMAN_H=1
HAVE_SYS_PARAM_H=1
HAVE_SYS_RANDOM_H=1
HAVE_WEAK_SYMBOLS=1
)
endif()
if(target MATCHES "win32")
target_compile_definitions(
sodium
PRIVATE
_CRT_SECURE_NO_WARNINGS=1
HAVE_RAISE=1
)
endif()
if(target MATCHES "x64")
target_compile_definitions(
sodium
PRIVATE
HAVE_CPUID=1
HAVE_RDRAND=1
HAVE_EMMINTRIN_H=1 # SSE2
HAVE_PMMINTRIN_H=1 # SSE3
HAVE_TMMINTRIN_H=1 # SSSE3
HAVE_SMMINTRIN_H=1 # SSE4.1
HAVE_WMMINTRIN_H=1 # AES
HAVE_AVXINTRIN_H=1 # AVX
HAVE_AVX2INTRIN_H=1 # AVX2
HAVE_AVX512FINTRIN_H # AVX512F
)
if(NOT target MATCHES "win32")
target_compile_definitions(
sodium
PRIVATE
HAVE_AMD64_ASM=1
HAVE_AVX_ASM=1
)
target_sources(
sodium
PRIVATE
${sodium_asm_sources}
)
endif()
endif()
if(target MATCHES "arm64")
target_compile_definitions(
sodium
PRIVATE
HAVE_ARMCRYPTO=1
)
endif()
if(CMAKE_C_BYTE_ORDER MATCHES "BIG_ENDIAN")
target_compile_definitions(
sodium
PRIVATE
NATIVE_BIG_ENDIAN=1
)
else()
target_compile_definitions(
sodium
PRIVATE
NATIVE_LITTLE_ENDIAN=1
)
endif()
if(target MATCHES "linux|android")
target_link_options(
sodium
PUBLIC
-Wl,-z,noexecstack
)
endif()
add_bare_module(sodium_native_bare)
target_sources(
${sodium_native_bare}
PRIVATE
binding.c
macros.h
extensions/tweak/tweak.c
extensions/tweak/tweak.h
extensions/pbkdf2/pbkdf2.c
extensions/pbkdf2/pbkdf2.h
)
target_link_libraries(
${sodium_native_bare}
PRIVATE
$<TARGET_OBJECTS:sodium>
PUBLIC
sodium
)
add_napi_module(sodium_native_node)
target_sources(
${sodium_native_node}
PRIVATE
binding.c
macros.h
extensions/tweak/tweak.c
extensions/tweak/tweak.h
extensions/pbkdf2/pbkdf2.c
extensions/pbkdf2/pbkdf2.h
)
target_link_libraries(
${sodium_native_node}
PRIVATE
$<TARGET_OBJECTS:sodium>
PUBLIC
sodium
)
-21
View File
@@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2016 Mathias Buus and Emil Bay
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-51
View File
@@ -1,51 +0,0 @@
# sodium-native
Low level bindings for [libsodium](https://github.com/jedisct1/libsodium).
```
npm install sodium-native
```
The goal of this project is to be thin, stable, unopionated wrapper around libsodium.
All methods exposed are more or less a direct translation of the libsodium c-api.
This means that most data types are buffers and you have to manage allocating return values and passing them in as arguments instead of receiving them as return values.
This makes this API harder to use than other libsodium wrappers out there, but also means that you'll be able to get a lot of perf / memory improvements as you can do stuff like inline encryption / decryption, reuse buffers etc.
This also makes this library useful as a foundation for more high level crypto abstractions that you want to make.
## Usage
``` js
var sodium = require('sodium-native')
var nonce = Buffer.alloc(sodium.crypto_secretbox_NONCEBYTES)
var key = sodium.sodium_malloc(sodium.crypto_secretbox_KEYBYTES) // secure buffer
var message = Buffer.from('Hello, World!')
var ciphertext = Buffer.alloc(message.length + sodium.crypto_secretbox_MACBYTES)
sodium.randombytes_buf(nonce) // insert random data into nonce
sodium.randombytes_buf(key) // insert random data into key
// encrypted message is stored in ciphertext.
sodium.crypto_secretbox_easy(ciphertext, message, nonce, key)
console.log('Encrypted message:', ciphertext)
var plainText = Buffer.alloc(ciphertext.length - sodium.crypto_secretbox_MACBYTES)
if (!sodium.crypto_secretbox_open_easy(plainText, ciphertext, nonce, key)) {
console.log('Decryption failed!')
} else {
console.log('Decrypted message:', plainText, '(' + plainText.toString() + ')')
}
```
## Documentation
Complete documentation may be found on the [sodium-friends website](https://sodium-friends.github.io/docs/docs/getstarted)
## License
MIT
-3470
View File
File diff suppressed because it is too large Load Diff
-90
View File
@@ -1,90 +0,0 @@
/*-
* Copyright 2005,2007,2009 Colin Percival
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* Adapted from libsodium/crypto_pwhash/scryptsalsa208sha256/pbkdf-sha256.c
*/
#include <string.h>
#include <sodium.h>
#include "pbkdf2.h"
/**
* pbkdf2_sha512(passwd, passwdlen, salt, saltlen, c, buf, dkLen):
* Compute PBKDF2(passwd, salt, c, dkLen) using HMAC-SHA256 as the PRF, and
* write the output to buf. The value dkLen must be at most 32 * (2^32 - 1).
*/
int
sn__extension_pbkdf2_sha512(const unsigned char *passwd, size_t passwdlen,
const unsigned char *salt, size_t saltlen, uint64_t c,
unsigned char *buf, size_t dkLen)
{
crypto_auth_hmacsha512_state PShctx, hctx;
size_t i;
unsigned char ivec[4];
unsigned char U[64];
unsigned char T[64];
uint64_t j;
unsigned int k;
size_t clen;
if (dkLen > sn__extension_pbkdf2_sha512_BYTES_MAX) {
return -1;
}
crypto_auth_hmacsha512_init(&PShctx, passwd, passwdlen);
crypto_auth_hmacsha512_update(&PShctx, salt, saltlen);
for (i = 0; i * crypto_auth_hmacsha512_BYTES < dkLen; i++) {
SN_PBKDF2_STORE32_BE(ivec, (uint32_t)(i + 1));
memcpy(&hctx, &PShctx, sizeof(crypto_auth_hmacsha512_state));
crypto_auth_hmacsha512_update(&hctx, ivec, 4);
crypto_auth_hmacsha512_final(&hctx, U);
memcpy(T, U, crypto_auth_hmacsha512_BYTES);
/* LCOV_EXCL_START */
for (j = 2; j <= c; j++) {
crypto_auth_hmacsha512_init(&hctx, passwd, passwdlen);
crypto_auth_hmacsha512_update(&hctx, U, crypto_auth_hmacsha512_BYTES);
crypto_auth_hmacsha512_final(&hctx, U);
for (k = 0; k < crypto_auth_hmacsha512_BYTES; k++) {
T[k] ^= U[k];
}
}
/* LCOV_EXCL_STOP */
clen = dkLen - i * crypto_auth_hmacsha512_BYTES;
if (clen > crypto_auth_hmacsha512_BYTES) {
clen = crypto_auth_hmacsha512_BYTES;
}
memcpy(&buf[i * crypto_auth_hmacsha512_BYTES], T, clen);
}
sodium_memzero((void *) &PShctx, sizeof PShctx);
return 0;
}
-54
View File
@@ -1,54 +0,0 @@
/*-
* Copyright 2005,2007,2009 Colin Percival
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
*/
/*
* Adapted from libsodium/crypto_pwhash/scryptsalsa208sha256/pbkdf-sha256.c
*/
#include <sodium.h>
#define SN_PBKDF2_STORE32_BE(buf, n32) \
buf[0] = n32 >> 24 & 0xff; \
buf[1] = n32 >> 16 & 0xff; \
buf[2] = n32 >> 8 & 0xff; \
buf[3] = n32 >> 0 & 0xff;
#define sn__extension_pbkdf2_sha512_SALTBYTES 16U
#define sn__extension_pbkdf2_sha512_HASHBYTES crypto_hash_sha512_BYTES
#define sn__extension_pbkdf2_sha512_ITERATIONS_MIN 1U
#define sn__extension_pbkdf2_sha512_BYTES_MAX 0x3fffffffc0ULL
/**
* extension_pbkdf2_sha512(passwd, passwdlen, salt, saltlen, c, buf, dkLen):
* Compute PBKDF2(passwd, salt, c, dkLen) using HMAC-SHA256 as the PRF, and
* write the output to buf. The value dkLen must be at most 32 * (2^32 - 1).
*/
int sn__extension_pbkdf2_sha512(const unsigned char *, size_t, const unsigned char *, size_t,
uint64_t, unsigned char *, size_t);
-206
View File
@@ -1,206 +0,0 @@
#include "tweak.h"
/*
*EXPERIMENTAL API*
This module is an experimental implementation of a key tweaking protocol
over ed25519 keys. The signature algorithm has been reimplemented from
libsodium, but the nonce generation algorithm is *non-standard*.
Use at your own risk
*/
static void _extension_tweak_nonce (unsigned char *nonce, const unsigned char *n,
const unsigned char *m, unsigned long long mlen)
{
// dom2(x, y) with x = 0 (not prehashed) and y = "crypto_tweak_ed25519"
static const unsigned char TWEAK_PREFIX[32 + 2 + 20] = {
'S', 'i', 'g', 'E', 'd', '2', '5', '5', '1', '9', ' ',
'n', 'o', ' ', 'E', 'd', '2', '5', '5', '1', '9', ' ',
'c', 'o', 'l', 'l', 'i', 's', 'i', 'o', 'n', 's', 0,
20, 'c', 'r', 'y', 'p', 't', 'o', '_', 't', 'w', 'e',
'a', 'k', '_', 'e', 'd', '2', '5', '5', '1', '9'
};
crypto_hash_sha512_state hs;
crypto_hash_sha512_init(&hs);
crypto_hash_sha512_update(&hs, TWEAK_PREFIX, sizeof TWEAK_PREFIX);
crypto_hash_sha512_update(&hs, n, 32);
crypto_hash_sha512_update(&hs, m, mlen);
crypto_hash_sha512_final(&hs, nonce);
}
static inline void
_crypto_sign_ed25519_clamp(unsigned char k[32])
{
k[0] &= 248;
k[31] &= 127;
k[31] |= 64;
}
static void _extension_tweak_ed25519(unsigned char *q, unsigned char *n,
const unsigned char *ns, unsigned long long nslen)
{
sodium_memzero(q, sizeof q);
crypto_hash(n, ns, nslen);
n[31] &= 127; // clear highest bit
crypto_scalarmult_ed25519_base_noclamp(q, n);
// hash tweak until we get a valid tweaked q
while (crypto_core_ed25519_is_valid_point(q) != 1) {
crypto_hash(n, n, 32);
n[31] &= 127; // clear highest bit
crypto_scalarmult_ed25519_base_noclamp(q, n);
}
}
void sn__extension_tweak_ed25519_base(unsigned char *pk, unsigned char *scalar,
const unsigned char *ns, unsigned long long nslen)
{
unsigned char n64[64];
_extension_tweak_ed25519(pk, n64, ns, nslen);
SN_TWEAK_COPY_32(scalar, n64)
}
int sn__extension_tweak_ed25519_sign_detached(unsigned char *sig, unsigned long long *siglen_p,
const unsigned char *m, unsigned long long mlen,
const unsigned char *n, unsigned char *pk)
{
crypto_hash_sha512_state hs;
unsigned char nonce[64];
unsigned char R[32];
unsigned char hram[64];
unsigned char _pk[32];
// check if pk was passed
if (pk == NULL) {
pk = _pk;
// derive pk from scalar
if (crypto_scalarmult_ed25519_base_noclamp(pk, n) != 0) {
return -1;
}
}
_extension_tweak_nonce(nonce, n, m, mlen);
crypto_core_ed25519_scalar_reduce(nonce, nonce);
// R = G ^ nonce : curve point from nonce
if (crypto_scalarmult_ed25519_base_noclamp(R, nonce) != 0) {
return -1;
}
// generate challenge as h(ram) = hash(R, pk, message)
crypto_hash_sha512_init(&hs);
crypto_hash_sha512_update(&hs, R, 32);
crypto_hash_sha512_update(&hs, pk, 32);
crypto_hash_sha512_update(&hs, m, mlen);
crypto_hash_sha512_final(&hs, hram);
crypto_core_ed25519_scalar_reduce(hram, hram);
// sig = nonce + n * h(ram)
crypto_core_ed25519_scalar_mul(sig, hram, n);
crypto_core_ed25519_scalar_add(sig + 32, nonce, sig);
SN_TWEAK_COPY_32(sig, R)
if (siglen_p != NULL) {
*siglen_p = 64U;
}
return 0;
}
// tweak a secret key
void sn__extension_tweak_ed25519_sk_to_scalar(unsigned char *n, const unsigned char *sk)
{
unsigned char n64[64];
// get sk scalar from seed, cf. crypto_sign_keypair_seed
crypto_hash(n64, sk, 32);
_crypto_sign_ed25519_clamp(n64);
SN_TWEAK_COPY_32(n, n64)
}
// tweak a secret key
void sn__extension_tweak_ed25519_scalar(unsigned char *scalar_out,
const unsigned char *scalar,
const unsigned char *ns,
unsigned long long nslen)
{
unsigned char n[64];
unsigned char q[32];
_extension_tweak_ed25519(q, n, ns, nslen);
crypto_core_ed25519_scalar_add(scalar_out, scalar, n);
}
// tweak a public key
int sn__extension_tweak_ed25519_pk(unsigned char *tpk,
const unsigned char *pk,
const unsigned char *ns,
unsigned long long nslen)
{
unsigned char n[64];
unsigned char q[32];
_extension_tweak_ed25519(q, n, ns, nslen);
return crypto_core_ed25519_add(tpk, q, pk);
}
void sn__extension_tweak_ed25519_keypair(unsigned char *pk, unsigned char *scalar_out,
unsigned char *scalar, const unsigned char *ns,
unsigned long long nslen)
{
unsigned char n64[64];
crypto_hash(n64, ns, nslen);
n64[31] &= 127; // clear highest bit
sn__extension_tweak_ed25519_scalar_add(scalar_out, scalar, n64);
crypto_scalarmult_ed25519_base_noclamp(pk, scalar_out);
// hash tweak until we get a valid tweaked point
while (crypto_core_ed25519_is_valid_point(pk) != 1) {
crypto_hash(n64, n64, 32);
n64[31] &= 127; // clear highest bit
sn__extension_tweak_ed25519_scalar_add(scalar_out, scalar, n64);
crypto_scalarmult_ed25519_base_noclamp(pk, scalar_out);
}
}
// add tweak to scalar
void sn__extension_tweak_ed25519_scalar_add(unsigned char *scalar_out,
const unsigned char *scalar,
const unsigned char *n)
{
crypto_core_ed25519_scalar_add(scalar_out, scalar, n);
}
// add tweak point to public key
int sn__extension_tweak_ed25519_pk_add(unsigned char *tpk,
const unsigned char *pk,
const unsigned char *q)
{
return crypto_core_ed25519_add(tpk, pk, q);
}
int sn__extension_tweak_ed25519_keypair_add(unsigned char *pk, unsigned char *scalar_out,
unsigned char *scalar, const unsigned char *tweak)
{
sn__extension_tweak_ed25519_scalar_add(scalar_out, scalar, tweak);
return crypto_scalarmult_ed25519_base_noclamp(pk, scalar_out);
}
-54
View File
@@ -1,54 +0,0 @@
#include <sodium.h>
// copy 32 bytes using int64_t pointers
#define SN_TWEAK_COPY_32(a, b) \
{ \
long long *dst = (long long *) a; \
long long *src = (long long *) b; \
dst[0] = src[0]; \
dst[1] = src[1]; \
dst[2] = src[2]; \
dst[3] = src[3]; \
}
#define sn__extension_tweak_ed25519_BYTES crypto_sign_ed25519_PUBLICKEYBYTES
#define sn__extension_tweak_ed25519_SCALARBYTES crypto_scalarmult_ed25519_SCALARBYTES
int sn__extension_tweak_ed25519_sign_detached(unsigned char *sig, unsigned long long *siglen_p,
const unsigned char *m, unsigned long long mlen,
const unsigned char *n, unsigned char *pk);
void sn__extension_tweak_ed25519_base(unsigned char *pk, unsigned char *scalar,
const unsigned char *ns, unsigned long long nslen);
void sn__extension_tweak_ed25519_sk_to_scalar(unsigned char *scalar, const unsigned char *sk);
// tweak a secret key
void sn__extension_tweak_ed25519_scalar(unsigned char *scalar_out,
const unsigned char *scalar,
const unsigned char *ns,
unsigned long long nslen);
// tweak a public key
int sn__extension_tweak_ed25519_pk(unsigned char *tpk,
const unsigned char *pk,
const unsigned char *ns,
unsigned long long nslen);
void sn__extension_tweak_ed25519_keypair(unsigned char *pk, unsigned char *scalar_out,
unsigned char *scalar, const unsigned char *ns,
unsigned long long nslen);
// add tweak scalar to private key
void sn__extension_tweak_ed25519_scalar_add(unsigned char *scalar_out,
const unsigned char *scalar,
const unsigned char *n);
// add tweak point to public key
int sn__extension_tweak_ed25519_pk_add(unsigned char *tpk,
const unsigned char *pk,
const unsigned char *q);
int sn__extension_tweak_ed25519_keypair_add(unsigned char *pk, unsigned char *scalar_out,
unsigned char *scalar, const unsigned char *tweak);
-3
View File
@@ -1,3 +0,0 @@
require.addon = require('require-addon')
module.exports = require.addon('.', __filename)

Some files were not shown because too many files have changed in this diff Show More