Upload folder using huggingface_hub (part 9)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .nvm/versions/node/v20.20.2/include/node/v8-version.h +20 -0
- .nvm/versions/node/v20.20.2/include/node/v8-wasm.h +201 -0
- .nvm/versions/node/v20.20.2/include/node/v8-weak-callback-info.h +80 -0
- .nvm/versions/node/v20.20.2/include/node/v8.h +88 -0
- .nvm/versions/node/v20.20.2/include/node/v8config.h +943 -0
- .nvm/versions/node/v20.20.2/include/node/zconf.h +558 -0
- .nvm/versions/node/v20.20.2/include/node/zlib.h +1967 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/README.md +365 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/dist/index.js +637 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/dist/lib.js +393 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/dist/path-utils.js +108 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/dist/path-validation.js +75 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/dist/roots-utils.js +71 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/.bin/node-which +52 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/LICENSE +21 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/README.md +448 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/conninfo.cjs +22 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/conninfo.d.cts +11 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/conninfo.d.mts +11 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/conninfo.mjs +20 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/constants-BLSFu_RU.mjs +5 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/constants-BXAKTxRC.cjs +11 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/early-hints.cjs +35 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/early-hints.d.cts +16 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/early-hints.d.mts +16 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/early-hints.mjs +33 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/index.cjs +1340 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/index.d.cts +101 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/index.d.mts +101 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/index.mjs +1335 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/serve-static.cjs +152 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/serve-static.d.cts +19 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/serve-static.d.mts +19 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/serve-static.mjs +151 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/utils/response.cjs +8 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/utils/response.d.cts +4 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/utils/response.d.mts +4 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/utils/response.mjs +7 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/utils/stream.cjs +65 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/utils/stream.d.cts +6 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/utils/stream.d.mts +6 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/utils/stream.mjs +64 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/package.json +128 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@modelcontextprotocol/sdk/LICENSE +21 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@modelcontextprotocol/sdk/README.md +172 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.d.ts +231 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.d.ts.map +1 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.js +320 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.js.map +1 -0
- .nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth.d.ts +473 -0
.nvm/versions/node/v20.20.2/include/node/v8-version.h
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2015 the V8 project authors. All rights reserved.
|
| 2 |
+
// Use of this source code is governed by a BSD-style license that can be
|
| 3 |
+
// found in the LICENSE file.
|
| 4 |
+
|
| 5 |
+
#ifndef V8_INCLUDE_VERSION_H_ // V8_VERSION_H_ conflicts with src/version.h
|
| 6 |
+
#define V8_INCLUDE_VERSION_H_
|
| 7 |
+
|
| 8 |
+
// These macros define the version number for the current version.
|
| 9 |
+
// NOTE these macros are used by some of the tool scripts and the build
|
| 10 |
+
// system so their names cannot be changed without changing the scripts.
|
| 11 |
+
#define V8_MAJOR_VERSION 11
|
| 12 |
+
#define V8_MINOR_VERSION 3
|
| 13 |
+
#define V8_BUILD_NUMBER 244
|
| 14 |
+
#define V8_PATCH_LEVEL 8
|
| 15 |
+
|
| 16 |
+
// Use 1 for candidates and 0 otherwise.
|
| 17 |
+
// (Boolean macro values are not supported by all preprocessors.)
|
| 18 |
+
#define V8_IS_C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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2021 the V8 project authors. All rights reserved.
|
| 2 |
+
// Use of this source code is governed by a BSD-style license that can be
|
| 3 |
+
// found in the LICENSE file.
|
| 4 |
+
|
| 5 |
+
#ifndef INCLUDE_V8_WASM_H_
|
| 6 |
+
#define INCLUDE_V8_WASM_H_
|
| 7 |
+
|
| 8 |
+
#include <functional>
|
| 9 |
+
#include <memory>
|
| 10 |
+
#include <string>
|
| 11 |
+
|
| 12 |
+
#include "v8-local-handle.h" // NOLINT(build/include_directory)
|
| 13 |
+
#include "v8-memory-span.h" // NOLINT(build/include_directory)
|
| 14 |
+
#include "v8-object.h" // NOLINT(build/include_directory)
|
| 15 |
+
#include "v8config.h" // NOLINT(build/include_directory)
|
| 16 |
+
|
| 17 |
+
namespace v8 {
|
| 18 |
+
|
| 19 |
+
class ArrayBuffer;
|
| 20 |
+
class Promise;
|
| 21 |
+
|
| 22 |
+
namespace internal {
|
| 23 |
+
namespace wasm {
|
| 24 |
+
class NativeModule;
|
| 25 |
+
class StreamingDecoder;
|
| 26 |
+
} // namespace wasm
|
| 27 |
+
} // namespace internal
|
| 28 |
+
|
| 29 |
+
/**
|
| 30 |
+
* An owned byte buffer with associated size.
|
| 31 |
+
*/
|
| 32 |
+
struct OwnedBuffer {
|
| 33 |
+
std::unique_ptr<const uint8_t[]> buffer;
|
| 34 |
+
size_t size = 0;
|
| 35 |
+
OwnedBuffer(std::unique_ptr<const uint8_t[]> buffer, size_t size)
|
| 36 |
+
: buffer(std::move(buffer)), size(size) {}
|
| 37 |
+
OwnedBuffer() = default;
|
| 38 |
+
};
|
| 39 |
+
|
| 40 |
+
// Wrapper around a compiled WebAssembly module, which is potentially shared by
|
| 41 |
+
// different WasmModuleObjects.
|
| 42 |
+
class V8_EXPORT CompiledWasmModule {
|
| 43 |
+
public:
|
| 44 |
+
/**
|
| 45 |
+
* Serialize the compiled module. The serialized data does not include the
|
| 46 |
+
* wire bytes.
|
| 47 |
+
*/
|
| 48 |
+
OwnedBuffer Serialize();
|
| 49 |
+
|
| 50 |
+
/**
|
| 51 |
+
* Get the (wasm-encoded) wire bytes that were used to compile this module.
|
| 52 |
+
*/
|
| 53 |
+
MemorySpan<const uint8_t> GetWireBytesRef();
|
| 54 |
+
|
| 55 |
+
const std::string& source_url() const { return source_url_; }
|
| 56 |
+
|
| 57 |
+
private:
|
| 58 |
+
friend class WasmModuleObject;
|
| 59 |
+
friend class WasmStreaming;
|
| 60 |
+
|
| 61 |
+
explicit CompiledWasmModule(std::shared_ptr<internal::wasm::NativeModule>,
|
| 62 |
+
const char* source_url, size_t url_length);
|
| 63 |
+
|
| 64 |
+
const std::shared_ptr<internal::wasm::NativeModule> native_module_;
|
| 65 |
+
const std::string source_url_;
|
| 66 |
+
};
|
| 67 |
+
|
| 68 |
+
// An instance of WebAssembly.Memory.
|
| 69 |
+
class V8_EXPORT WasmMemoryObject : public Object {
|
| 70 |
+
public:
|
| 71 |
+
WasmMemoryObject() = delete;
|
| 72 |
+
|
| 73 |
+
/**
|
| 74 |
+
* Returns underlying ArrayBuffer.
|
| 75 |
+
*/
|
| 76 |
+
Local<ArrayBuffer> Buffer();
|
| 77 |
+
|
| 78 |
+
V8_INLINE static WasmMemoryObject* Cast(Value* value) {
|
| 79 |
+
#ifdef V8_ENABLE_CHECKS
|
| 80 |
+
CheckCast(value);
|
| 81 |
+
#endif
|
| 82 |
+
return static_cast<WasmMemoryObject*>(value);
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
private:
|
| 86 |
+
static void CheckCast(Value* object);
|
| 87 |
+
};
|
| 88 |
+
|
| 89 |
+
// An instance of WebAssembly.Module.
|
| 90 |
+
class V8_EXPORT WasmModuleObject : public Object {
|
| 91 |
+
public:
|
| 92 |
+
WasmModuleObject() = delete;
|
| 93 |
+
|
| 94 |
+
/**
|
| 95 |
+
* Efficiently re-create a WasmModuleObject, without recompiling, from
|
| 96 |
+
* a CompiledWasmModule.
|
| 97 |
+
*/
|
| 98 |
+
static MaybeLocal<WasmModuleObject> FromCompiledModule(
|
| 99 |
+
Isolate* isolate, const CompiledWasmModule&);
|
| 100 |
+
|
| 101 |
+
/**
|
| 102 |
+
* Get the compiled module for this module object. The compiled module can be
|
| 103 |
+
* shared by several module objects.
|
| 104 |
+
*/
|
| 105 |
+
CompiledWasmModule GetCompiledModule();
|
| 106 |
+
|
| 107 |
+
/**
|
| 108 |
+
* Compile a Wasm module from the provided uncompiled bytes.
|
| 109 |
+
*/
|
| 110 |
+
static MaybeLocal<WasmModuleObject> Compile(
|
| 111 |
+
Isolate* isolate, MemorySpan<const uint8_t> wire_bytes);
|
| 112 |
+
|
| 113 |
+
V8_INLINE static WasmModuleObject* Cast(Value* value) {
|
| 114 |
+
#ifdef V8_ENABLE_CHECKS
|
| 115 |
+
CheckCast(value);
|
| 116 |
+
#endif
|
| 117 |
+
return static_cast<WasmModuleObject*>(value);
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
private:
|
| 121 |
+
static void CheckCast(Value* obj);
|
| 122 |
+
};
|
| 123 |
+
|
| 124 |
+
/**
|
| 125 |
+
* The V8 interface for WebAssembly streaming compilation. When streaming
|
| 126 |
+
* compilation is initiated, V8 passes a {WasmStreaming} object to the embedder
|
| 127 |
+
* such that the embedder can pass the input bytes for streaming compilation to
|
| 128 |
+
* V8.
|
| 129 |
+
*/
|
| 130 |
+
class V8_EXPORT WasmStreaming final {
|
| 131 |
+
public:
|
| 132 |
+
class WasmStreamingImpl;
|
| 133 |
+
|
| 134 |
+
explicit WasmStreaming(std::unique_ptr<WasmStreamingImpl> impl);
|
| 135 |
+
|
| 136 |
+
~WasmStreaming();
|
| 137 |
+
|
| 138 |
+
/**
|
| 139 |
+
* Pass a new chunk of bytes to WebAssembly streaming compilation.
|
| 140 |
+
* The buffer passed into {OnBytesReceived} is owned by the caller.
|
| 141 |
+
*/
|
| 142 |
+
void OnBytesReceived(const uint8_t* bytes, size_t size);
|
| 143 |
+
|
| 144 |
+
/**
|
| 145 |
+
* {Finish} should be called after all received bytes where passed to
|
| 146 |
+
* {OnBytesReceived} to tell V8 that there will be no more bytes. {Finish}
|
| 147 |
+
* must not be called after {Abort} has been called already.
|
| 148 |
+
* If {can_use_compiled_module} is true and {SetCompiledModuleBytes} was
|
| 149 |
+
* previously called, the compiled module bytes can be used.
|
| 150 |
+
* If {can_use_compiled_module} is false, the compiled module bytes previously
|
| 151 |
+
* set by {SetCompiledModuleBytes} should not be used.
|
| 152 |
+
*/
|
| 153 |
+
void Finish(bool can_use_compiled_module = true);
|
| 154 |
+
|
| 155 |
+
/**
|
| 156 |
+
* Abort streaming compilation. If {exception} has a value, then the promise
|
| 157 |
+
* associated with streaming compilation is rejected with that value. If
|
| 158 |
+
* {exception} does not have value, the promise does not get rejected.
|
| 159 |
+
* {Abort} must not be called repeatedly, or after {Finish}.
|
| 160 |
+
*/
|
| 161 |
+
void Abort(MaybeLocal<Value> exception);
|
| 162 |
+
|
| 163 |
+
/**
|
| 164 |
+
* Passes previously compiled module bytes. This must be called before
|
| 165 |
+
* {OnBytesReceived}, {Finish}, or {Abort}. Returns true if the module bytes
|
| 166 |
+
* can be used, false otherwise. The buffer passed via {bytes} and {size}
|
| 167 |
+
* is owned by the caller. If {SetCompiledModuleBytes} returns true, the
|
| 168 |
+
* buffer must remain valid until either {Finish} or {Abort} completes.
|
| 169 |
+
* The compiled module bytes should not be used until {Finish(true)} is
|
| 170 |
+
* called, because they can be invalidated later by {Finish(false)}.
|
| 171 |
+
*/
|
| 172 |
+
bool SetCompiledModuleBytes(const uint8_t* bytes, size_t size);
|
| 173 |
+
|
| 174 |
+
/**
|
| 175 |
+
* Sets a callback which is called whenever a significant number of new
|
| 176 |
+
* functions are ready for serialization.
|
| 177 |
+
*/
|
| 178 |
+
void SetMoreFunctionsCanBeSerializedCallback(
|
| 179 |
+
std::function<void(CompiledWasmModule)>);
|
| 180 |
+
|
| 181 |
+
/*
|
| 182 |
+
* Sets the UTF-8 encoded source URL for the {Script} object. This must be
|
| 183 |
+
* called before {Finish}.
|
| 184 |
+
*/
|
| 185 |
+
void SetUrl(const char* url, size_t length);
|
| 186 |
+
|
| 187 |
+
/**
|
| 188 |
+
* Unpacks a {WasmStreaming} object wrapped in a {Managed} for the embedder.
|
| 189 |
+
* Since the embedder is on the other side of the API, it cannot unpack the
|
| 190 |
+
* {Managed} itself.
|
| 191 |
+
*/
|
| 192 |
+
static std::shared_ptr<WasmStreaming> Unpack(Isolate* isolate,
|
| 193 |
+
Local<Value> value);
|
| 194 |
+
|
| 195 |
+
private:
|
| 196 |
+
std::unique_ptr<WasmStreamingImpl> impl_;
|
| 197 |
+
};
|
| 198 |
+
|
| 199 |
+
} // namespace v8
|
| 200 |
+
|
| 201 |
+
#endif // INCLUDE_V8_WASM_H_
|
.nvm/versions/node/v20.20.2/include/node/v8-weak-callback-info.h
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2021 the V8 project authors. All rights reserved.
|
| 2 |
+
// Use of this source code is governed by a BSD-style license that can be
|
| 3 |
+
// found in the LICENSE file.
|
| 4 |
+
|
| 5 |
+
#ifndef INCLUDE_V8_WEAK_CALLBACK_INFO_H_
|
| 6 |
+
#define INCLUDE_V8_WEAK_CALLBACK_INFO_H_
|
| 7 |
+
|
| 8 |
+
#include "v8config.h" // NOLINT(build/include_directory)
|
| 9 |
+
|
| 10 |
+
namespace v8 {
|
| 11 |
+
|
| 12 |
+
class Isolate;
|
| 13 |
+
|
| 14 |
+
namespace api_internal {
|
| 15 |
+
V8_EXPORT void InternalFieldOutOfBounds(int index);
|
| 16 |
+
} // namespace api_internal
|
| 17 |
+
|
| 18 |
+
static const int kInternalFieldsInWeakCallback = 2;
|
| 19 |
+
static const int kEmbedderFieldsInWeakCallback = 2;
|
| 20 |
+
|
| 21 |
+
template <typename T>
|
| 22 |
+
class WeakCallbackInfo {
|
| 23 |
+
public:
|
| 24 |
+
using Callback = void (*)(const WeakCallbackInfo<T>& data);
|
| 25 |
+
|
| 26 |
+
WeakCallbackInfo(Isolate* isolate, T* parameter,
|
| 27 |
+
void* embedder_fields[kEmbedderFieldsInWeakCallback],
|
| 28 |
+
Callback* callback)
|
| 29 |
+
: isolate_(isolate), parameter_(parameter), callback_(callback) {
|
| 30 |
+
for (int i = 0; i < kEmbedderFieldsInWeakCallback; ++i) {
|
| 31 |
+
embedder_fields_[i] = embedder_fields[i];
|
| 32 |
+
}
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
V8_INLINE Isolate* GetIsolate() const { return isolate_; }
|
| 36 |
+
V8_INLINE T* GetParameter() const { return parameter_; }
|
| 37 |
+
V8_INLINE void* GetInternalField(int index) const;
|
| 38 |
+
|
| 39 |
+
// When first called, the embedder MUST Reset() the Global which triggered the
|
| 40 |
+
// callback. The Global itself is unusable for anything else. No v8 other api
|
| 41 |
+
// calls may be called in the first callback. Should additional work be
|
| 42 |
+
// required, the embedder must set a second pass callback, which will be
|
| 43 |
+
// called after all the initial callbacks are processed.
|
| 44 |
+
// Calling SetSecondPassCallback on the second pass will immediately crash.
|
| 45 |
+
void SetSecondPassCallback(Callback callback) const { *callback_ = callback; }
|
| 46 |
+
|
| 47 |
+
private:
|
| 48 |
+
Isolate* isolate_;
|
| 49 |
+
T* parameter_;
|
| 50 |
+
Callback* callback_;
|
| 51 |
+
void* embedder_fields_[kEmbedderFieldsInWeakCallback];
|
| 52 |
+
};
|
| 53 |
+
|
| 54 |
+
/**
|
| 55 |
+
* Weakness type for weak handles.
|
| 56 |
+
*/
|
| 57 |
+
enum class WeakCallbackType {
|
| 58 |
+
/**
|
| 59 |
+
* Passes a user-defined void* parameter back to the callback.
|
| 60 |
+
*/
|
| 61 |
+
kParameter,
|
| 62 |
+
/**
|
| 63 |
+
* Passes the first two internal fields of the object back to the callback.
|
| 64 |
+
*/
|
| 65 |
+
kInternalFields,
|
| 66 |
+
};
|
| 67 |
+
|
| 68 |
+
template <class T>
|
| 69 |
+
void* WeakCallbackInfo<T>::GetInternalField(int index) const {
|
| 70 |
+
#ifdef V8_ENABLE_CHECKS
|
| 71 |
+
if (index < 0 || index >= kEmbedderFieldsInWeakCallback) {
|
| 72 |
+
api_internal::InternalFieldOutOfBounds(index);
|
| 73 |
+
}
|
| 74 |
+
#endif
|
| 75 |
+
return embedder_fields_[index];
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
} // namespace v8
|
| 79 |
+
|
| 80 |
+
#endif // INCLUDE_V8_WEAK_CALLBACK_INFO_H_
|
.nvm/versions/node/v20.20.2/include/node/v8.h
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2012 the V8 project authors. All rights reserved.
|
| 2 |
+
// Use of this source code is governed by a BSD-style license that can be
|
| 3 |
+
// found in the LICENSE file.
|
| 4 |
+
|
| 5 |
+
/** \mainpage V8 API Reference Guide
|
| 6 |
+
*
|
| 7 |
+
* V8 is Google's open source JavaScript engine.
|
| 8 |
+
*
|
| 9 |
+
* This set of documents provides reference material generated from the
|
| 10 |
+
* V8 header files in the include/ subdirectory.
|
| 11 |
+
*
|
| 12 |
+
* For other documentation see https://v8.dev/.
|
| 13 |
+
*/
|
| 14 |
+
|
| 15 |
+
#ifndef INCLUDE_V8_H_
|
| 16 |
+
#define INCLUDE_V8_H_
|
| 17 |
+
|
| 18 |
+
#include <stddef.h>
|
| 19 |
+
#include <stdint.h>
|
| 20 |
+
|
| 21 |
+
#include <memory>
|
| 22 |
+
|
| 23 |
+
#include "cppgc/common.h"
|
| 24 |
+
#include "v8-array-buffer.h" // NOLINT(build/include_directory)
|
| 25 |
+
#include "v8-container.h" // NOLINT(build/include_directory)
|
| 26 |
+
#include "v8-context.h" // NOLINT(build/include_directory)
|
| 27 |
+
#include "v8-data.h" // NOLINT(build/include_directory)
|
| 28 |
+
#include "v8-date.h" // NOLINT(build/include_directory)
|
| 29 |
+
#include "v8-debug.h" // NOLINT(build/include_directory)
|
| 30 |
+
#include "v8-exception.h" // NOLINT(build/include_directory)
|
| 31 |
+
#include "v8-extension.h" // NOLINT(build/include_directory)
|
| 32 |
+
#include "v8-external.h" // NOLINT(build/include_directory)
|
| 33 |
+
#include "v8-function.h" // NOLINT(build/include_directory)
|
| 34 |
+
#include "v8-initialization.h" // NOLINT(build/include_directory)
|
| 35 |
+
#include "v8-internal.h" // NOLINT(build/include_directory)
|
| 36 |
+
#include "v8-isolate.h" // NOLINT(build/include_directory)
|
| 37 |
+
#include "v8-json.h" // NOLINT(build/include_directory)
|
| 38 |
+
#include "v8-local-handle.h" // NOLINT(build/include_directory)
|
| 39 |
+
#include "v8-locker.h" // NOLINT(build/include_directory)
|
| 40 |
+
#include "v8-maybe.h" // NOLINT(build/include_directory)
|
| 41 |
+
#include "v8-memory-span.h" // NOLINT(build/include_directory)
|
| 42 |
+
#include "v8-message.h" // NOLINT(build/include_directory)
|
| 43 |
+
#include "v8-microtask-queue.h" // NOLINT(build/include_directory)
|
| 44 |
+
#include "v8-microtask.h" // NOLINT(build/include_directory)
|
| 45 |
+
#include "v8-object.h" // NOLINT(build/include_directory)
|
| 46 |
+
#include "v8-persistent-handle.h" // NOLINT(build/include_directory)
|
| 47 |
+
#include "v8-primitive-object.h" // NOLINT(build/include_directory)
|
| 48 |
+
#include "v8-primitive.h" // NOLINT(build/include_directory)
|
| 49 |
+
#include "v8-promise.h" // NOLINT(build/include_directory)
|
| 50 |
+
#include "v8-proxy.h" // NOLINT(build/include_directory)
|
| 51 |
+
#include "v8-regexp.h" // NOLINT(build/include_directory)
|
| 52 |
+
#include "v8-script.h" // NOLINT(build/include_directory)
|
| 53 |
+
#include "v8-snapshot.h" // NOLINT(build/include_directory)
|
| 54 |
+
#include "v8-statistics.h" // NOLINT(build/include_directory)
|
| 55 |
+
#include "v8-template.h" // NOLINT(build/include_directory)
|
| 56 |
+
#include "v8-traced-handle.h" // NOLINT(build/include_directory)
|
| 57 |
+
#include "v8-typed-array.h" // NOLINT(build/include_directory)
|
| 58 |
+
#include "v8-unwinder.h" // NOLINT(build/include_directory)
|
| 59 |
+
#include "v8-value-serializer.h" // NOLINT(build/include_directory)
|
| 60 |
+
#include "v8-value.h" // NOLINT(build/include_directory)
|
| 61 |
+
#include "v8-version.h" // NOLINT(build/include_directory)
|
| 62 |
+
#include "v8-wasm.h" // NOLINT(build/include_directory)
|
| 63 |
+
#include "v8config.h" // NOLINT(build/include_directory)
|
| 64 |
+
|
| 65 |
+
// We reserve the V8_* prefix for macros defined in V8 public API and
|
| 66 |
+
// assume there are no name conflicts with the embedder's code.
|
| 67 |
+
|
| 68 |
+
/**
|
| 69 |
+
* The v8 JavaScript engine.
|
| 70 |
+
*/
|
| 71 |
+
namespace v8 {
|
| 72 |
+
|
| 73 |
+
class Platform;
|
| 74 |
+
|
| 75 |
+
/**
|
| 76 |
+
* \example shell.cc
|
| 77 |
+
* A simple shell that takes a list of expressions on the
|
| 78 |
+
* command-line and executes them.
|
| 79 |
+
*/
|
| 80 |
+
|
| 81 |
+
/**
|
| 82 |
+
* \example process.cc
|
| 83 |
+
*/
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
} // namespace v8
|
| 87 |
+
|
| 88 |
+
#endif // INCLUDE_V8_H_
|
.nvm/versions/node/v20.20.2/include/node/v8config.h
ADDED
|
@@ -0,0 +1,943 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Copyright 2013 the V8 project authors. All rights reserved.
|
| 2 |
+
// Use of this source code is governed by a BSD-style license that can be
|
| 3 |
+
// found in the LICENSE file.
|
| 4 |
+
|
| 5 |
+
#ifndef V8CONFIG_H_
|
| 6 |
+
#define V8CONFIG_H_
|
| 7 |
+
|
| 8 |
+
#ifdef V8_GN_HEADER
|
| 9 |
+
#if __cplusplus >= 201703L && !__has_include("v8-gn.h")
|
| 10 |
+
#error Missing v8-gn.h. The configuration for v8 is missing from the include \
|
| 11 |
+
path. Add it with -I<path> to the command line
|
| 12 |
+
#endif
|
| 13 |
+
#include "v8-gn.h" // NOLINT(build/include_directory)
|
| 14 |
+
#endif
|
| 15 |
+
|
| 16 |
+
// clang-format off
|
| 17 |
+
|
| 18 |
+
// Platform headers for feature detection below.
|
| 19 |
+
#if defined(__ANDROID__)
|
| 20 |
+
# include <sys/cdefs.h>
|
| 21 |
+
#elif defined(__APPLE__)
|
| 22 |
+
# include <TargetConditionals.h>
|
| 23 |
+
#elif defined(__linux__)
|
| 24 |
+
# include <features.h>
|
| 25 |
+
#endif
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
// This macro allows to test for the version of the GNU C library (or
|
| 29 |
+
// a compatible C library that masquerades as glibc). It evaluates to
|
| 30 |
+
// 0 if libc is not GNU libc or compatible.
|
| 31 |
+
// Use like:
|
| 32 |
+
// #if V8_GLIBC_PREREQ(2, 3)
|
| 33 |
+
// ...
|
| 34 |
+
// #endif
|
| 35 |
+
#if defined(__GLIBC__) && defined(__GLIBC_MINOR__)
|
| 36 |
+
# define V8_GLIBC_PREREQ(major, minor) \
|
| 37 |
+
((__GLIBC__ * 100 + __GLIBC_MINOR__) >= ((major) * 100 + (minor)))
|
| 38 |
+
#else
|
| 39 |
+
# define V8_GLIBC_PREREQ(major, minor) 0
|
| 40 |
+
#endif
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
// This macro allows to test for the version of the GNU C++ compiler.
|
| 44 |
+
// Note that this also applies to compilers that masquerade as GCC,
|
| 45 |
+
// for example clang and the Intel C++ compiler for Linux.
|
| 46 |
+
// Use like:
|
| 47 |
+
// #if V8_GNUC_PREREQ(4, 3, 1)
|
| 48 |
+
// ...
|
| 49 |
+
// #endif
|
| 50 |
+
#if defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__)
|
| 51 |
+
# define V8_GNUC_PREREQ(major, minor, patchlevel) \
|
| 52 |
+
((__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) >= \
|
| 53 |
+
((major) * 10000 + (minor) * 100 + (patchlevel)))
|
| 54 |
+
#elif defined(__GNUC__) && defined(__GNUC_MINOR__)
|
| 55 |
+
# define V8_GNUC_PREREQ(major, minor, patchlevel) \
|
| 56 |
+
((__GNUC__ * 10000 + __GNUC_MINOR__ * 100) >= \
|
| 57 |
+
((major) * 10000 + (minor) * 100 + (patchlevel)))
|
| 58 |
+
#else
|
| 59 |
+
# define V8_GNUC_PREREQ(major, minor, patchlevel) 0
|
| 60 |
+
#endif
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
// -----------------------------------------------------------------------------
|
| 65 |
+
// Operating system detection (host)
|
| 66 |
+
//
|
| 67 |
+
// V8_OS_ANDROID - Android
|
| 68 |
+
// V8_OS_BSD - BSDish (macOS, Net/Free/Open/DragonFlyBSD)
|
| 69 |
+
// V8_OS_CYGWIN - Cygwin
|
| 70 |
+
// V8_OS_DRAGONFLYBSD - DragonFlyBSD
|
| 71 |
+
// V8_OS_FREEBSD - FreeBSD
|
| 72 |
+
// V8_OS_FUCHSIA - Fuchsia
|
| 73 |
+
// V8_OS_LINUX - Linux (Android, ChromeOS, Linux, ...)
|
| 74 |
+
// V8_OS_DARWIN - Darwin (macOS, iOS)
|
| 75 |
+
// V8_OS_MACOS - macOS
|
| 76 |
+
// V8_OS_IOS - iOS
|
| 77 |
+
// V8_OS_NETBSD - NetBSD
|
| 78 |
+
// V8_OS_OPENBSD - OpenBSD
|
| 79 |
+
// V8_OS_POSIX - POSIX compatible (mostly everything except Windows)
|
| 80 |
+
// V8_OS_QNX - QNX Neutrino
|
| 81 |
+
// V8_OS_SOLARIS - Sun Solaris and OpenSolaris
|
| 82 |
+
// V8_OS_STARBOARD - Starboard (platform abstraction for Cobalt)
|
| 83 |
+
// V8_OS_AIX - AIX
|
| 84 |
+
// V8_OS_WIN - Microsoft Windows
|
| 85 |
+
|
| 86 |
+
#if defined(__ANDROID__)
|
| 87 |
+
# define V8_OS_ANDROID 1
|
| 88 |
+
# define V8_OS_LINUX 1
|
| 89 |
+
# define V8_OS_POSIX 1
|
| 90 |
+
# define V8_OS_STRING "android"
|
| 91 |
+
|
| 92 |
+
#elif defined(__APPLE__)
|
| 93 |
+
# define V8_OS_POSIX 1
|
| 94 |
+
# define V8_OS_BSD 1
|
| 95 |
+
# define V8_OS_DARWIN 1
|
| 96 |
+
# if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
|
| 97 |
+
# define V8_OS_IOS 1
|
| 98 |
+
# define V8_OS_STRING "ios"
|
| 99 |
+
# else
|
| 100 |
+
# define V8_OS_MACOS 1
|
| 101 |
+
# define V8_OS_STRING "macos"
|
| 102 |
+
# endif // defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
|
| 103 |
+
|
| 104 |
+
#elif defined(__CYGWIN__)
|
| 105 |
+
# define V8_OS_CYGWIN 1
|
| 106 |
+
# define V8_OS_POSIX 1
|
| 107 |
+
# define V8_OS_STRING "cygwin"
|
| 108 |
+
|
| 109 |
+
#elif defined(__linux__)
|
| 110 |
+
# define V8_OS_LINUX 1
|
| 111 |
+
# define V8_OS_POSIX 1
|
| 112 |
+
# define V8_OS_STRING "linux"
|
| 113 |
+
|
| 114 |
+
#elif defined(__sun)
|
| 115 |
+
# define V8_OS_POSIX 1
|
| 116 |
+
# define V8_OS_SOLARIS 1
|
| 117 |
+
# define V8_OS_STRING "sun"
|
| 118 |
+
|
| 119 |
+
#elif defined(STARBOARD)
|
| 120 |
+
# define V8_OS_STARBOARD 1
|
| 121 |
+
# define V8_OS_STRING "starboard"
|
| 122 |
+
|
| 123 |
+
#elif defined(_AIX)
|
| 124 |
+
# define V8_OS_POSIX 1
|
| 125 |
+
# define V8_OS_AIX 1
|
| 126 |
+
# define V8_OS_STRING "aix"
|
| 127 |
+
|
| 128 |
+
#elif defined(__FreeBSD__)
|
| 129 |
+
# define V8_OS_BSD 1
|
| 130 |
+
# define V8_OS_FREEBSD 1
|
| 131 |
+
# define V8_OS_POSIX 1
|
| 132 |
+
# define V8_OS_STRING "freebsd"
|
| 133 |
+
|
| 134 |
+
#elif defined(__Fuchsia__)
|
| 135 |
+
# define V8_OS_FUCHSIA 1
|
| 136 |
+
# define V8_OS_POSIX 1
|
| 137 |
+
# define V8_OS_STRING "fuchsia"
|
| 138 |
+
|
| 139 |
+
#elif defined(__DragonFly__)
|
| 140 |
+
# define V8_OS_BSD 1
|
| 141 |
+
# define V8_OS_DRAGONFLYBSD 1
|
| 142 |
+
# define V8_OS_POSIX 1
|
| 143 |
+
# define V8_OS_STRING "dragonflybsd"
|
| 144 |
+
|
| 145 |
+
#elif defined(__NetBSD__)
|
| 146 |
+
# define V8_OS_BSD 1
|
| 147 |
+
# define V8_OS_NETBSD 1
|
| 148 |
+
# define V8_OS_POSIX 1
|
| 149 |
+
# define V8_OS_STRING "netbsd"
|
| 150 |
+
|
| 151 |
+
#elif defined(__OpenBSD__)
|
| 152 |
+
# define V8_OS_BSD 1
|
| 153 |
+
# define V8_OS_OPENBSD 1
|
| 154 |
+
# define V8_OS_POSIX 1
|
| 155 |
+
# define V8_OS_STRING "openbsd"
|
| 156 |
+
|
| 157 |
+
#elif defined(__QNXNTO__)
|
| 158 |
+
# define V8_OS_POSIX 1
|
| 159 |
+
# define V8_OS_QNX 1
|
| 160 |
+
# define V8_OS_STRING "qnx"
|
| 161 |
+
|
| 162 |
+
#elif defined(_WIN32)
|
| 163 |
+
# define V8_OS_WIN 1
|
| 164 |
+
# define V8_OS_STRING "windows"
|
| 165 |
+
#endif
|
| 166 |
+
|
| 167 |
+
// -----------------------------------------------------------------------------
|
| 168 |
+
// Operating system detection (target)
|
| 169 |
+
//
|
| 170 |
+
// V8_TARGET_OS_ANDROID
|
| 171 |
+
// V8_TARGET_OS_FUCHSIA
|
| 172 |
+
// V8_TARGET_OS_IOS
|
| 173 |
+
// V8_TARGET_OS_LINUX
|
| 174 |
+
// V8_TARGET_OS_MACOS
|
| 175 |
+
// V8_TARGET_OS_WIN
|
| 176 |
+
// V8_TARGET_OS_CHROMEOS
|
| 177 |
+
//
|
| 178 |
+
// If not set explicitly, these fall back to corresponding V8_OS_ values.
|
| 179 |
+
|
| 180 |
+
#ifdef V8_HAVE_TARGET_OS
|
| 181 |
+
|
| 182 |
+
// The target OS is provided, just check that at least one known value is set.
|
| 183 |
+
# if !defined(V8_TARGET_OS_ANDROID) \
|
| 184 |
+
&& !defined(V8_TARGET_OS_FUCHSIA) \
|
| 185 |
+
&& !defined(V8_TARGET_OS_IOS) \
|
| 186 |
+
&& !defined(V8_TARGET_OS_LINUX) \
|
| 187 |
+
&& !defined(V8_TARGET_OS_MACOS) \
|
| 188 |
+
&& !defined(V8_TARGET_OS_WIN) \
|
| 189 |
+
&& !defined(V8_TARGET_OS_CHROMEOS)
|
| 190 |
+
# error No known target OS defined.
|
| 191 |
+
# endif
|
| 192 |
+
|
| 193 |
+
#else // V8_HAVE_TARGET_OS
|
| 194 |
+
|
| 195 |
+
# if defined(V8_TARGET_OS_ANDROID) \
|
| 196 |
+
|| defined(V8_TARGET_OS_FUCHSIA) \
|
| 197 |
+
|| defined(V8_TARGET_OS_IOS) \
|
| 198 |
+
|| defined(V8_TARGET_OS_LINUX) \
|
| 199 |
+
|| defined(V8_TARGET_OS_MACOS) \
|
| 200 |
+
|| defined(V8_TARGET_OS_WIN) \
|
| 201 |
+
|| defined(V8_TARGET_OS_CHROMEOS)
|
| 202 |
+
# error A target OS is defined but V8_HAVE_TARGET_OS is unset.
|
| 203 |
+
# endif
|
| 204 |
+
|
| 205 |
+
// Fall back to the detected host OS.
|
| 206 |
+
#ifdef V8_OS_ANDROID
|
| 207 |
+
# define V8_TARGET_OS_ANDROID
|
| 208 |
+
#endif
|
| 209 |
+
|
| 210 |
+
#ifdef V8_OS_FUCHSIA
|
| 211 |
+
# define V8_TARGET_OS_FUCHSIA
|
| 212 |
+
#endif
|
| 213 |
+
|
| 214 |
+
#ifdef V8_OS_IOS
|
| 215 |
+
# define V8_TARGET_OS_IOS
|
| 216 |
+
#endif
|
| 217 |
+
|
| 218 |
+
#ifdef V8_OS_LINUX
|
| 219 |
+
# define V8_TARGET_OS_LINUX
|
| 220 |
+
#endif
|
| 221 |
+
|
| 222 |
+
#ifdef V8_OS_MACOS
|
| 223 |
+
# define V8_TARGET_OS_MACOS
|
| 224 |
+
#endif
|
| 225 |
+
|
| 226 |
+
#ifdef V8_OS_WIN
|
| 227 |
+
# define V8_TARGET_OS_WIN
|
| 228 |
+
#endif
|
| 229 |
+
|
| 230 |
+
#endif // V8_HAVE_TARGET_OS
|
| 231 |
+
|
| 232 |
+
#if defined(V8_TARGET_OS_ANDROID)
|
| 233 |
+
# define V8_TARGET_OS_STRING "android"
|
| 234 |
+
#elif defined(V8_TARGET_OS_FUCHSIA)
|
| 235 |
+
# define V8_TARGET_OS_STRING "fuchsia"
|
| 236 |
+
#elif defined(V8_TARGET_OS_IOS)
|
| 237 |
+
# define V8_TARGET_OS_STRING "ios"
|
| 238 |
+
#elif defined(V8_TARGET_OS_LINUX)
|
| 239 |
+
# define V8_TARGET_OS_STRING "linux"
|
| 240 |
+
#elif defined(V8_TARGET_OS_MACOS)
|
| 241 |
+
# define V8_TARGET_OS_STRING "macos"
|
| 242 |
+
#elif defined(V8_TARGET_OS_WINDOWS)
|
| 243 |
+
# define V8_TARGET_OS_STRING "windows"
|
| 244 |
+
#else
|
| 245 |
+
# define V8_TARGET_OS_STRING "unknown"
|
| 246 |
+
#endif
|
| 247 |
+
|
| 248 |
+
// -----------------------------------------------------------------------------
|
| 249 |
+
// C library detection
|
| 250 |
+
//
|
| 251 |
+
// V8_LIBC_MSVCRT - MSVC libc
|
| 252 |
+
// V8_LIBC_BIONIC - Bionic libc
|
| 253 |
+
// V8_LIBC_BSD - BSD libc derivate
|
| 254 |
+
// V8_LIBC_GLIBC - GNU C library
|
| 255 |
+
// V8_LIBC_UCLIBC - uClibc
|
| 256 |
+
//
|
| 257 |
+
// Note that testing for libc must be done using #if not #ifdef. For example,
|
| 258 |
+
// to test for the GNU C library, use:
|
| 259 |
+
// #if V8_LIBC_GLIBC
|
| 260 |
+
// ...
|
| 261 |
+
// #endif
|
| 262 |
+
|
| 263 |
+
#if defined (_MSC_VER)
|
| 264 |
+
# define V8_LIBC_MSVCRT 1
|
| 265 |
+
#elif defined(__BIONIC__)
|
| 266 |
+
# define V8_LIBC_BIONIC 1
|
| 267 |
+
# define V8_LIBC_BSD 1
|
| 268 |
+
#elif defined(__UCLIBC__)
|
| 269 |
+
// Must test for UCLIBC before GLIBC, as UCLIBC pretends to be GLIBC.
|
| 270 |
+
# define V8_LIBC_UCLIBC 1
|
| 271 |
+
#elif defined(__GLIBC__) || defined(__GNU_LIBRARY__)
|
| 272 |
+
# define V8_LIBC_GLIBC 1
|
| 273 |
+
#else
|
| 274 |
+
# define V8_LIBC_BSD V8_OS_BSD
|
| 275 |
+
#endif
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
// -----------------------------------------------------------------------------
|
| 279 |
+
// Compiler detection
|
| 280 |
+
//
|
| 281 |
+
// V8_CC_GNU - GCC, or clang in gcc mode
|
| 282 |
+
// V8_CC_INTEL - Intel C++
|
| 283 |
+
// V8_CC_MINGW - Minimalist GNU for Windows
|
| 284 |
+
// V8_CC_MINGW32 - Minimalist GNU for Windows (mingw32)
|
| 285 |
+
// V8_CC_MINGW64 - Minimalist GNU for Windows (mingw-w64)
|
| 286 |
+
// V8_CC_MSVC - Microsoft Visual C/C++, or clang in cl.exe mode
|
| 287 |
+
//
|
| 288 |
+
// C++11 feature detection
|
| 289 |
+
//
|
| 290 |
+
// Compiler-specific feature detection
|
| 291 |
+
//
|
| 292 |
+
// V8_HAS_ATTRIBUTE_ALWAYS_INLINE - __attribute__((always_inline))
|
| 293 |
+
// supported
|
| 294 |
+
// V8_HAS_ATTRIBUTE_CONSTINIT - __attribute__((require_constant_
|
| 295 |
+
// initialization))
|
| 296 |
+
// supported
|
| 297 |
+
// V8_HAS_ATTRIBUTE_NONNULL - __attribute__((nonnull)) supported
|
| 298 |
+
// V8_HAS_ATTRIBUTE_NOINLINE - __attribute__((noinline)) supported
|
| 299 |
+
// V8_HAS_ATTRIBUTE_UNUSED - __attribute__((unused)) supported
|
| 300 |
+
// V8_HAS_ATTRIBUTE_VISIBILITY - __attribute__((visibility)) supported
|
| 301 |
+
// V8_HAS_ATTRIBUTE_WARN_UNUSED_RESULT - __attribute__((warn_unused_result))
|
| 302 |
+
// supported
|
| 303 |
+
// V8_HAS_CPP_ATTRIBUTE_NODISCARD - [[nodiscard]] supported
|
| 304 |
+
// V8_HAS_CPP_ATTRIBUTE_NO_UNIQUE_ADDRESS
|
| 305 |
+
// - [[no_unique_address]] supported
|
| 306 |
+
// V8_HAS_BUILTIN_BSWAP16 - __builtin_bswap16() supported
|
| 307 |
+
// V8_HAS_BUILTIN_BSWAP32 - __builtin_bswap32() supported
|
| 308 |
+
// V8_HAS_BUILTIN_BSWAP64 - __builtin_bswap64() supported
|
| 309 |
+
// V8_HAS_BUILTIN_CLZ - __builtin_clz() supported
|
| 310 |
+
// V8_HAS_BUILTIN_CTZ - __builtin_ctz() supported
|
| 311 |
+
// V8_HAS_BUILTIN_EXPECT - __builtin_expect() supported
|
| 312 |
+
// V8_HAS_BUILTIN_FRAME_ADDRESS - __builtin_frame_address() supported
|
| 313 |
+
// V8_HAS_BUILTIN_POPCOUNT - __builtin_popcount() supported
|
| 314 |
+
// V8_HAS_BUILTIN_ADD_OVERFLOW - __builtin_add_overflow() supported
|
| 315 |
+
// V8_HAS_BUILTIN_SUB_OVERFLOW - __builtin_sub_overflow() supported
|
| 316 |
+
// V8_HAS_BUILTIN_MUL_OVERFLOW - __builtin_mul_overflow() supported
|
| 317 |
+
// V8_HAS_BUILTIN_SADD_OVERFLOW - __builtin_sadd_overflow() supported
|
| 318 |
+
// V8_HAS_BUILTIN_SSUB_OVERFLOW - __builtin_ssub_overflow() supported
|
| 319 |
+
// V8_HAS_BUILTIN_UADD_OVERFLOW - __builtin_uadd_overflow() supported
|
| 320 |
+
// V8_HAS_BUILTIN_SMUL_OVERFLOW - __builtin_smul_overflow() supported
|
| 321 |
+
// V8_HAS_COMPUTED_GOTO - computed goto/labels as values
|
| 322 |
+
// supported
|
| 323 |
+
// V8_HAS_DECLSPEC_NOINLINE - __declspec(noinline) supported
|
| 324 |
+
// V8_HAS_DECLSPEC_SELECTANY - __declspec(selectany) supported
|
| 325 |
+
// V8_HAS___FORCEINLINE - __forceinline supported
|
| 326 |
+
//
|
| 327 |
+
// Note that testing for compilers and/or features must be done using #if
|
| 328 |
+
// not #ifdef. For example, to test for Intel C++ Compiler, use:
|
| 329 |
+
// #if V8_CC_INTEL
|
| 330 |
+
// ...
|
| 331 |
+
// #endif
|
| 332 |
+
|
| 333 |
+
#if defined(__has_cpp_attribute)
|
| 334 |
+
#define V8_HAS_CPP_ATTRIBUTE(FEATURE) __has_cpp_attribute(FEATURE)
|
| 335 |
+
#else
|
| 336 |
+
#define V8_HAS_CPP_ATTRIBUTE(FEATURE) 0
|
| 337 |
+
#endif
|
| 338 |
+
|
| 339 |
+
#if defined(__clang__)
|
| 340 |
+
|
| 341 |
+
#if defined(__GNUC__) // Clang in gcc mode.
|
| 342 |
+
# define V8_CC_GNU 1
|
| 343 |
+
#endif
|
| 344 |
+
|
| 345 |
+
# define V8_HAS_ATTRIBUTE_ALWAYS_INLINE (__has_attribute(always_inline))
|
| 346 |
+
# define V8_HAS_ATTRIBUTE_CONSTINIT \
|
| 347 |
+
(__has_attribute(require_constant_initialization))
|
| 348 |
+
# define V8_HAS_ATTRIBUTE_CONST (__has_attribute(const))
|
| 349 |
+
# define V8_HAS_ATTRIBUTE_NONNULL (__has_attribute(nonnull))
|
| 350 |
+
# define V8_HAS_ATTRIBUTE_NOINLINE (__has_attribute(noinline))
|
| 351 |
+
# define V8_HAS_ATTRIBUTE_UNUSED (__has_attribute(unused))
|
| 352 |
+
// Support for the "preserve_most" attribute is limited:
|
| 353 |
+
// - 32-bit platforms do not implement it,
|
| 354 |
+
// - component builds fail because _dl_runtime_resolve clobbers registers,
|
| 355 |
+
// - we see crashes on arm64 on Windows (https://crbug.com/1409934), which can
|
| 356 |
+
// hopefully be fixed in the future.
|
| 357 |
+
// Additionally, the initial implementation in clang <= 16 overwrote the return
|
| 358 |
+
// register(s) in the epilogue of a preserve_most function, so we only use
|
| 359 |
+
// preserve_most in clang >= 17 (see https://reviews.llvm.org/D143425).
|
| 360 |
+
#if (defined(_M_X64) || defined(__x86_64__) /* x64 (everywhere) */ \
|
| 361 |
+
|| ((defined(__AARCH64EL__) || defined(_M_ARM64)) /* arm64, but ... */ \
|
| 362 |
+
&& !defined(_WIN32))) /* not on windows */ \
|
| 363 |
+
&& !defined(COMPONENT_BUILD) /* no component build */\
|
| 364 |
+
&& __clang_major__ >= 17 /* clang >= 17 */
|
| 365 |
+
# define V8_HAS_ATTRIBUTE_PRESERVE_MOST (__has_attribute(preserve_most))
|
| 366 |
+
#endif
|
| 367 |
+
# define V8_HAS_ATTRIBUTE_VISIBILITY (__has_attribute(visibility))
|
| 368 |
+
# define V8_HAS_ATTRIBUTE_WARN_UNUSED_RESULT \
|
| 369 |
+
(__has_attribute(warn_unused_result))
|
| 370 |
+
|
| 371 |
+
# define V8_HAS_CPP_ATTRIBUTE_NODISCARD (V8_HAS_CPP_ATTRIBUTE(nodiscard))
|
| 372 |
+
# define V8_HAS_CPP_ATTRIBUTE_NO_UNIQUE_ADDRESS \
|
| 373 |
+
(V8_HAS_CPP_ATTRIBUTE(no_unique_address))
|
| 374 |
+
|
| 375 |
+
# define V8_HAS_BUILTIN_ASSUME (__has_builtin(__builtin_assume))
|
| 376 |
+
# define V8_HAS_BUILTIN_ASSUME_ALIGNED (__has_builtin(__builtin_assume_aligned))
|
| 377 |
+
# define V8_HAS_BUILTIN_BSWAP16 (__has_builtin(__builtin_bswap16))
|
| 378 |
+
# define V8_HAS_BUILTIN_BSWAP32 (__has_builtin(__builtin_bswap32))
|
| 379 |
+
# define V8_HAS_BUILTIN_BSWAP64 (__has_builtin(__builtin_bswap64))
|
| 380 |
+
# define V8_HAS_BUILTIN_CLZ (__has_builtin(__builtin_clz))
|
| 381 |
+
# define V8_HAS_BUILTIN_CTZ (__has_builtin(__builtin_ctz))
|
| 382 |
+
# define V8_HAS_BUILTIN_EXPECT (__has_builtin(__builtin_expect))
|
| 383 |
+
# define V8_HAS_BUILTIN_FRAME_ADDRESS (__has_builtin(__builtin_frame_address))
|
| 384 |
+
# define V8_HAS_BUILTIN_POPCOUNT (__has_builtin(__builtin_popcount))
|
| 385 |
+
# define V8_HAS_BUILTIN_ADD_OVERFLOW (__has_builtin(__builtin_add_overflow))
|
| 386 |
+
# define V8_HAS_BUILTIN_SUB_OVERFLOW (__has_builtin(__builtin_sub_overflow))
|
| 387 |
+
# define V8_HAS_BUILTIN_MUL_OVERFLOW (__has_builtin(__builtin_mul_overflow))
|
| 388 |
+
# define V8_HAS_BUILTIN_SADD_OVERFLOW (__has_builtin(__builtin_sadd_overflow))
|
| 389 |
+
# define V8_HAS_BUILTIN_SSUB_OVERFLOW (__has_builtin(__builtin_ssub_overflow))
|
| 390 |
+
# define V8_HAS_BUILTIN_UADD_OVERFLOW (__has_builtin(__builtin_uadd_overflow))
|
| 391 |
+
# define V8_HAS_BUILTIN_SMUL_OVERFLOW (__has_builtin(__builtin_smul_overflow))
|
| 392 |
+
# define V8_HAS_BUILTIN_UNREACHABLE (__has_builtin(__builtin_unreachable))
|
| 393 |
+
|
| 394 |
+
// Clang has no __has_feature for computed gotos.
|
| 395 |
+
// GCC doc: https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html
|
| 396 |
+
# define V8_HAS_COMPUTED_GOTO 1
|
| 397 |
+
|
| 398 |
+
#elif defined(__GNUC__)
|
| 399 |
+
|
| 400 |
+
# define V8_CC_GNU 1
|
| 401 |
+
# if defined(__INTEL_COMPILER) // Intel C++ also masquerades as GCC 3.2.0
|
| 402 |
+
# define V8_CC_INTEL 1
|
| 403 |
+
# endif
|
| 404 |
+
# if defined(__MINGW32__)
|
| 405 |
+
# define V8_CC_MINGW32 1
|
| 406 |
+
# endif
|
| 407 |
+
# if defined(__MINGW64__)
|
| 408 |
+
# define V8_CC_MINGW64 1
|
| 409 |
+
# endif
|
| 410 |
+
# define V8_CC_MINGW (V8_CC_MINGW32 || V8_CC_MINGW64)
|
| 411 |
+
|
| 412 |
+
// always_inline is available in gcc 4.0 but not very reliable until 4.4.
|
| 413 |
+
// Works around "sorry, unimplemented: inlining failed" build errors with
|
| 414 |
+
// older compilers.
|
| 415 |
+
# define V8_HAS_ATTRIBUTE_ALWAYS_INLINE 1
|
| 416 |
+
# define V8_HAS_ATTRIBUTE_NOINLINE 1
|
| 417 |
+
# define V8_HAS_ATTRIBUTE_UNUSED 1
|
| 418 |
+
# define V8_HAS_ATTRIBUTE_VISIBILITY 1
|
| 419 |
+
# define V8_HAS_ATTRIBUTE_WARN_UNUSED_RESULT (!V8_CC_INTEL)
|
| 420 |
+
|
| 421 |
+
// [[nodiscard]] does not work together with with
|
| 422 |
+
// __attribute__((visibility(""))) on GCC 7.4 which is why there is no define
|
| 423 |
+
// for V8_HAS_CPP_ATTRIBUTE_NODISCARD. See https://crbug.com/v8/11707.
|
| 424 |
+
|
| 425 |
+
# define V8_HAS_BUILTIN_ASSUME_ALIGNED 1
|
| 426 |
+
# define V8_HAS_BUILTIN_CLZ 1
|
| 427 |
+
# define V8_HAS_BUILTIN_CTZ 1
|
| 428 |
+
# define V8_HAS_BUILTIN_EXPECT 1
|
| 429 |
+
# define V8_HAS_BUILTIN_FRAME_ADDRESS 1
|
| 430 |
+
# define V8_HAS_BUILTIN_POPCOUNT 1
|
| 431 |
+
# define V8_HAS_BUILTIN_UNREACHABLE 1
|
| 432 |
+
|
| 433 |
+
// GCC doc: https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html
|
| 434 |
+
#define V8_HAS_COMPUTED_GOTO 1
|
| 435 |
+
|
| 436 |
+
#endif
|
| 437 |
+
|
| 438 |
+
#if defined(_MSC_VER)
|
| 439 |
+
# define V8_CC_MSVC 1
|
| 440 |
+
|
| 441 |
+
# define V8_HAS_DECLSPEC_NOINLINE 1
|
| 442 |
+
# define V8_HAS_DECLSPEC_SELECTANY 1
|
| 443 |
+
|
| 444 |
+
# define V8_HAS___FORCEINLINE 1
|
| 445 |
+
|
| 446 |
+
#endif
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
// -----------------------------------------------------------------------------
|
| 450 |
+
// Helper macros
|
| 451 |
+
|
| 452 |
+
// A macro used to make better inlining. Don't bother for debug builds.
|
| 453 |
+
// Use like:
|
| 454 |
+
// V8_INLINE int GetZero() { return 0; }
|
| 455 |
+
#if !defined(DEBUG) && V8_HAS_ATTRIBUTE_ALWAYS_INLINE
|
| 456 |
+
# define V8_INLINE inline __attribute__((always_inline))
|
| 457 |
+
#elif !defined(DEBUG) && V8_HAS___FORCEINLINE
|
| 458 |
+
# define V8_INLINE __forceinline
|
| 459 |
+
#else
|
| 460 |
+
# define V8_INLINE inline
|
| 461 |
+
#endif
|
| 462 |
+
|
| 463 |
+
#ifdef DEBUG
|
| 464 |
+
// In debug mode, check assumptions instead of actually adding annotations.
|
| 465 |
+
# define V8_ASSUME(condition) DCHECK(condition)
|
| 466 |
+
#elif V8_HAS_BUILTIN_ASSUME
|
| 467 |
+
# define V8_ASSUME(condition) __builtin_assume(condition)
|
| 468 |
+
#elif V8_HAS_BUILTIN_UNREACHABLE
|
| 469 |
+
# define V8_ASSUME(condition) \
|
| 470 |
+
do { if (!(condition)) __builtin_unreachable(); } while (false)
|
| 471 |
+
#else
|
| 472 |
+
# define V8_ASSUME(condition)
|
| 473 |
+
#endif
|
| 474 |
+
|
| 475 |
+
#if V8_HAS_BUILTIN_ASSUME_ALIGNED
|
| 476 |
+
# define V8_ASSUME_ALIGNED(ptr, alignment) \
|
| 477 |
+
__builtin_assume_aligned((ptr), (alignment))
|
| 478 |
+
#else
|
| 479 |
+
# define V8_ASSUME_ALIGNED(ptr, alignment) (ptr)
|
| 480 |
+
#endif
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
// A macro to mark functions whose values don't change (e.g. across calls)
|
| 484 |
+
// and thereby compiler is free to hoist and fold multiple calls together.
|
| 485 |
+
// Use like:
|
| 486 |
+
// V8_CONST int foo() { ... }
|
| 487 |
+
#if V8_HAS_ATTRIBUTE_CONST
|
| 488 |
+
# define V8_CONST __attribute__((const))
|
| 489 |
+
#else
|
| 490 |
+
# define V8_CONST
|
| 491 |
+
#endif
|
| 492 |
+
|
| 493 |
+
// A macro to mark a declaration as requiring constant initialization.
|
| 494 |
+
// Use like:
|
| 495 |
+
// int* foo V8_CONSTINIT;
|
| 496 |
+
#if V8_HAS_ATTRIBUTE_CONSTINIT
|
| 497 |
+
# define V8_CONSTINIT __attribute__((require_constant_initialization))
|
| 498 |
+
#else
|
| 499 |
+
# define V8_CONSTINIT
|
| 500 |
+
#endif
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
// A macro to mark specific arguments as non-null.
|
| 504 |
+
// Use like:
|
| 505 |
+
// int add(int* x, int y, int* z) V8_NONNULL(1, 3) { return *x + y + *z; }
|
| 506 |
+
#if V8_HAS_ATTRIBUTE_NONNULL
|
| 507 |
+
# define V8_NONNULL(...) __attribute__((nonnull(__VA_ARGS__)))
|
| 508 |
+
#else
|
| 509 |
+
# define V8_NONNULL(...) /* NOT SUPPORTED */
|
| 510 |
+
#endif
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
// A macro used to tell the compiler to never inline a particular function.
|
| 514 |
+
// Use like:
|
| 515 |
+
// V8_NOINLINE int GetMinusOne() { return -1; }
|
| 516 |
+
#if V8_HAS_ATTRIBUTE_NOINLINE
|
| 517 |
+
# define V8_NOINLINE __attribute__((noinline))
|
| 518 |
+
#elif V8_HAS_DECLSPEC_NOINLINE
|
| 519 |
+
# define V8_NOINLINE __declspec(noinline)
|
| 520 |
+
#else
|
| 521 |
+
# define V8_NOINLINE /* NOT SUPPORTED */
|
| 522 |
+
#endif
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
// A macro used to change the calling conventions to preserve all registers (no
|
| 526 |
+
// caller-saved registers). Use this for cold functions called from hot
|
| 527 |
+
// functions.
|
| 528 |
+
// Note: The attribute is considered experimental, so apply with care. Also,
|
| 529 |
+
// "preserve_most" is currently not handling the return value correctly, so only
|
| 530 |
+
// use it for functions returning void (see https://reviews.llvm.org/D141020).
|
| 531 |
+
// Use like:
|
| 532 |
+
// V8_NOINLINE V8_PRESERVE_MOST void UnlikelyMethod();
|
| 533 |
+
#if V8_HAS_ATTRIBUTE_PRESERVE_MOST
|
| 534 |
+
# define V8_PRESERVE_MOST __attribute__((preserve_most))
|
| 535 |
+
#else
|
| 536 |
+
# define V8_PRESERVE_MOST /* NOT SUPPORTED */
|
| 537 |
+
#endif
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
// A macro (V8_DEPRECATED) to mark classes or functions as deprecated.
|
| 541 |
+
#if defined(V8_DEPRECATION_WARNINGS)
|
| 542 |
+
# define V8_DEPRECATED(message) [[deprecated(message)]]
|
| 543 |
+
#else
|
| 544 |
+
# define V8_DEPRECATED(message)
|
| 545 |
+
#endif
|
| 546 |
+
|
| 547 |
+
|
| 548 |
+
// A macro (V8_DEPRECATE_SOON) to make it easier to see what will be deprecated.
|
| 549 |
+
#if defined(V8_IMMINENT_DEPRECATION_WARNINGS)
|
| 550 |
+
# define V8_DEPRECATE_SOON(message) [[deprecated(message)]]
|
| 551 |
+
#else
|
| 552 |
+
# define V8_DEPRECATE_SOON(message)
|
| 553 |
+
#endif
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
#if defined(V8_IMMINENT_DEPRECATION_WARNINGS) || \
|
| 557 |
+
defined(V8_DEPRECATION_WARNINGS)
|
| 558 |
+
#if defined(V8_CC_MSVC)
|
| 559 |
+
# define START_ALLOW_USE_DEPRECATED() \
|
| 560 |
+
__pragma(warning(push)) \
|
| 561 |
+
__pragma(warning(disable : 4996))
|
| 562 |
+
# define END_ALLOW_USE_DEPRECATED() __pragma(warning(pop))
|
| 563 |
+
#else // !defined(V8_CC_MSVC)
|
| 564 |
+
# define START_ALLOW_USE_DEPRECATED() \
|
| 565 |
+
_Pragma("GCC diagnostic push") \
|
| 566 |
+
_Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
|
| 567 |
+
#define END_ALLOW_USE_DEPRECATED() _Pragma("GCC diagnostic pop")
|
| 568 |
+
#endif // !defined(V8_CC_MSVC)
|
| 569 |
+
#else // !(defined(V8_IMMINENT_DEPRECATION_WARNINGS) ||
|
| 570 |
+
// defined(V8_DEPRECATION_WARNINGS))
|
| 571 |
+
#define START_ALLOW_USE_DEPRECATED()
|
| 572 |
+
#define END_ALLOW_USE_DEPRECATED()
|
| 573 |
+
#endif // !(defined(V8_IMMINENT_DEPRECATION_WARNINGS) ||
|
| 574 |
+
// defined(V8_DEPRECATION_WARNINGS))
|
| 575 |
+
#define ALLOW_COPY_AND_MOVE_WITH_DEPRECATED_FIELDS(ClassName) \
|
| 576 |
+
START_ALLOW_USE_DEPRECATED() \
|
| 577 |
+
ClassName(const ClassName&) = default; \
|
| 578 |
+
ClassName(ClassName&&) = default; \
|
| 579 |
+
ClassName& operator=(const ClassName&) = default; \
|
| 580 |
+
ClassName& operator=(ClassName&&) = default; \
|
| 581 |
+
END_ALLOW_USE_DEPRECATED()
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
#if defined(__GNUC__) && !defined(__clang__) && (__GNUC__ < 6)
|
| 585 |
+
# define V8_ENUM_DEPRECATED(message)
|
| 586 |
+
# define V8_ENUM_DEPRECATE_SOON(message)
|
| 587 |
+
#else
|
| 588 |
+
# define V8_ENUM_DEPRECATED(message) V8_DEPRECATED(message)
|
| 589 |
+
# define V8_ENUM_DEPRECATE_SOON(message) V8_DEPRECATE_SOON(message)
|
| 590 |
+
#endif
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
// A macro to provide the compiler with branch prediction information.
|
| 594 |
+
#if V8_HAS_BUILTIN_EXPECT
|
| 595 |
+
# define V8_UNLIKELY(condition) (__builtin_expect(!!(condition), 0))
|
| 596 |
+
# define V8_LIKELY(condition) (__builtin_expect(!!(condition), 1))
|
| 597 |
+
#else
|
| 598 |
+
# define V8_UNLIKELY(condition) (condition)
|
| 599 |
+
# define V8_LIKELY(condition) (condition)
|
| 600 |
+
#endif
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
// Annotate a function indicating the caller must examine the return value.
|
| 604 |
+
// Use like:
|
| 605 |
+
// int foo() V8_WARN_UNUSED_RESULT;
|
| 606 |
+
#if V8_HAS_ATTRIBUTE_WARN_UNUSED_RESULT
|
| 607 |
+
#define V8_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
|
| 608 |
+
#else
|
| 609 |
+
#define V8_WARN_UNUSED_RESULT /* NOT SUPPORTED */
|
| 610 |
+
#endif
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
// Annotate a class or constructor indicating the caller must assign the
|
| 614 |
+
// constructed instances.
|
| 615 |
+
// Apply to the whole class like:
|
| 616 |
+
// class V8_NODISCARD Foo() { ... };
|
| 617 |
+
// or apply to just one constructor like:
|
| 618 |
+
// V8_NODISCARD Foo() { ... };
|
| 619 |
+
// [[nodiscard]] comes in C++17 but supported in clang with -std >= c++11.
|
| 620 |
+
#if V8_HAS_CPP_ATTRIBUTE_NODISCARD
|
| 621 |
+
#define V8_NODISCARD [[nodiscard]]
|
| 622 |
+
#else
|
| 623 |
+
#define V8_NODISCARD /* NOT SUPPORTED */
|
| 624 |
+
#endif
|
| 625 |
+
|
| 626 |
+
// The no_unique_address attribute allows tail padding in a non-static data
|
| 627 |
+
// member to overlap other members of the enclosing class (and in the special
|
| 628 |
+
// case when the type is empty, permits it to fully overlap other members). The
|
| 629 |
+
// field is laid out as if a base class were encountered at the corresponding
|
| 630 |
+
// point within the class (except that it does not share a vptr with the
|
| 631 |
+
// enclosing object).
|
| 632 |
+
//
|
| 633 |
+
// Apply to a data member like:
|
| 634 |
+
//
|
| 635 |
+
// class Foo {
|
| 636 |
+
// V8_NO_UNIQUE_ADDRESS Bar bar_;
|
| 637 |
+
// };
|
| 638 |
+
//
|
| 639 |
+
// [[no_unique_address]] comes in C++20 but supported in clang with
|
| 640 |
+
// -std >= c++11.
|
| 641 |
+
#if V8_HAS_CPP_ATTRIBUTE_NO_UNIQUE_ADDRESS
|
| 642 |
+
#define V8_NO_UNIQUE_ADDRESS [[no_unique_address]]
|
| 643 |
+
#else
|
| 644 |
+
#define V8_NO_UNIQUE_ADDRESS /* NOT SUPPORTED */
|
| 645 |
+
#endif
|
| 646 |
+
|
| 647 |
+
// Marks a type as being eligible for the "trivial" ABI despite having a
|
| 648 |
+
// non-trivial destructor or copy/move constructor. Such types can be relocated
|
| 649 |
+
// after construction by simply copying their memory, which makes them eligible
|
| 650 |
+
// to be passed in registers. The canonical example is std::unique_ptr.
|
| 651 |
+
//
|
| 652 |
+
// Use with caution; this has some subtle effects on constructor/destructor
|
| 653 |
+
// ordering and will be very incorrect if the type relies on its address
|
| 654 |
+
// remaining constant. When used as a function argument (by value), the value
|
| 655 |
+
// may be constructed in the caller's stack frame, passed in a register, and
|
| 656 |
+
// then used and destructed in the callee's stack frame. A similar thing can
|
| 657 |
+
// occur when values are returned.
|
| 658 |
+
//
|
| 659 |
+
// TRIVIAL_ABI is not needed for types which have a trivial destructor and
|
| 660 |
+
// copy/move constructors, since those are automatically trivial by the ABI
|
| 661 |
+
// spec.
|
| 662 |
+
//
|
| 663 |
+
// It is also not likely to be effective on types too large to be passed in one
|
| 664 |
+
// or two registers on typical target ABIs.
|
| 665 |
+
//
|
| 666 |
+
// See also:
|
| 667 |
+
// https://clang.llvm.org/docs/AttributeReference.html#trivial-abi
|
| 668 |
+
// https://libcxx.llvm.org/docs/DesignDocs/UniquePtrTrivialAbi.html
|
| 669 |
+
#if defined(__clang__) && defined(__has_attribute)
|
| 670 |
+
#if __has_attribute(trivial_abi)
|
| 671 |
+
#define V8_TRIVIAL_ABI [[clang::trivial_abi]]
|
| 672 |
+
#endif // __has_attribute(trivial_abi)
|
| 673 |
+
#endif // defined(__clang__) && defined(__has_attribute)
|
| 674 |
+
#if !defined(V8_TRIVIAL_ABI)
|
| 675 |
+
#define V8_TRIVIAL_ABI
|
| 676 |
+
#endif //!defined(V8_TRIVIAL_ABI)
|
| 677 |
+
|
| 678 |
+
// Helper macro to define no_sanitize attributes only with clang.
|
| 679 |
+
#if defined(__clang__) && defined(__has_attribute)
|
| 680 |
+
#if __has_attribute(no_sanitize)
|
| 681 |
+
#define V8_CLANG_NO_SANITIZE(what) __attribute__((no_sanitize(what)))
|
| 682 |
+
#endif
|
| 683 |
+
#endif
|
| 684 |
+
#if !defined(V8_CLANG_NO_SANITIZE)
|
| 685 |
+
#define V8_CLANG_NO_SANITIZE(what)
|
| 686 |
+
#endif
|
| 687 |
+
|
| 688 |
+
#if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED)
|
| 689 |
+
#error Inconsistent build configuration: To build the V8 shared library \
|
| 690 |
+
set BUILDING_V8_SHARED, to include its headers for linking against the \
|
| 691 |
+
V8 shared library set USING_V8_SHARED.
|
| 692 |
+
#endif
|
| 693 |
+
|
| 694 |
+
#ifdef V8_OS_WIN
|
| 695 |
+
|
| 696 |
+
// Setup for Windows DLL export/import. When building the V8 DLL the
|
| 697 |
+
// BUILDING_V8_SHARED needs to be defined. When building a program which uses
|
| 698 |
+
// the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
|
| 699 |
+
// static library or building a program which uses the V8 static library neither
|
| 700 |
+
// BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
|
| 701 |
+
#ifdef BUILDING_V8_SHARED
|
| 702 |
+
# define V8_EXPORT __declspec(dllexport)
|
| 703 |
+
#elif USING_V8_SHARED
|
| 704 |
+
# define V8_EXPORT __declspec(dllimport)
|
| 705 |
+
#else
|
| 706 |
+
# define V8_EXPORT
|
| 707 |
+
#endif // BUILDING_V8_SHARED
|
| 708 |
+
|
| 709 |
+
#else // V8_OS_WIN
|
| 710 |
+
|
| 711 |
+
// Setup for Linux shared library export.
|
| 712 |
+
#if V8_HAS_ATTRIBUTE_VISIBILITY
|
| 713 |
+
# ifdef BUILDING_V8_SHARED
|
| 714 |
+
# define V8_EXPORT __attribute__ ((visibility("default")))
|
| 715 |
+
# else
|
| 716 |
+
# define V8_EXPORT
|
| 717 |
+
# endif
|
| 718 |
+
#else
|
| 719 |
+
# define V8_EXPORT
|
| 720 |
+
#endif
|
| 721 |
+
|
| 722 |
+
#endif // V8_OS_WIN
|
| 723 |
+
|
| 724 |
+
// clang-format on
|
| 725 |
+
|
| 726 |
+
// Processor architecture detection. For more info on what's defined, see:
|
| 727 |
+
// http://msdn.microsoft.com/en-us/library/b0084kay.aspx
|
| 728 |
+
// http://www.agner.org/optimize/calling_conventions.pdf
|
| 729 |
+
// or with gcc, run: "echo | gcc -E -dM -"
|
| 730 |
+
// The V8_HOST_ARCH_* macros correspond to the architecture on which V8, as a
|
| 731 |
+
// virtual machine and compiler, runs. Don't confuse this with the architecture
|
| 732 |
+
// on which V8 is built.
|
| 733 |
+
#if defined(_M_X64) || defined(__x86_64__)
|
| 734 |
+
#define V8_HOST_ARCH_X64 1
|
| 735 |
+
#if defined(__x86_64__) && __SIZEOF_POINTER__ == 4 // Check for x32.
|
| 736 |
+
#define V8_HOST_ARCH_32_BIT 1
|
| 737 |
+
#else
|
| 738 |
+
#define V8_HOST_ARCH_64_BIT 1
|
| 739 |
+
#endif
|
| 740 |
+
#elif defined(_M_IX86) || defined(__i386__)
|
| 741 |
+
#define V8_HOST_ARCH_IA32 1
|
| 742 |
+
#define V8_HOST_ARCH_32_BIT 1
|
| 743 |
+
#elif defined(__AARCH64EL__) || defined(_M_ARM64)
|
| 744 |
+
#define V8_HOST_ARCH_ARM64 1
|
| 745 |
+
#define V8_HOST_ARCH_64_BIT 1
|
| 746 |
+
#elif defined(__ARMEL__)
|
| 747 |
+
#define V8_HOST_ARCH_ARM 1
|
| 748 |
+
#define V8_HOST_ARCH_32_BIT 1
|
| 749 |
+
#elif defined(__mips64)
|
| 750 |
+
#define V8_HOST_ARCH_MIPS64 1
|
| 751 |
+
#define V8_HOST_ARCH_64_BIT 1
|
| 752 |
+
#elif defined(__loongarch64)
|
| 753 |
+
#define V8_HOST_ARCH_LOONG64 1
|
| 754 |
+
#define V8_HOST_ARCH_64_BIT 1
|
| 755 |
+
#elif defined(__PPC64__) || defined(_ARCH_PPC64)
|
| 756 |
+
#define V8_HOST_ARCH_PPC64 1
|
| 757 |
+
#define V8_HOST_ARCH_64_BIT 1
|
| 758 |
+
#elif defined(__PPC__) || defined(_ARCH_PPC)
|
| 759 |
+
#define V8_HOST_ARCH_PPC 1
|
| 760 |
+
#define V8_HOST_ARCH_32_BIT 1
|
| 761 |
+
#elif defined(__s390__) || defined(__s390x__)
|
| 762 |
+
#define V8_HOST_ARCH_S390 1
|
| 763 |
+
#if defined(__s390x__)
|
| 764 |
+
#define V8_HOST_ARCH_64_BIT 1
|
| 765 |
+
#else
|
| 766 |
+
#define V8_HOST_ARCH_32_BIT 1
|
| 767 |
+
#endif
|
| 768 |
+
#elif defined(__riscv) || defined(__riscv__)
|
| 769 |
+
#if __riscv_xlen == 64
|
| 770 |
+
#define V8_HOST_ARCH_RISCV64 1
|
| 771 |
+
#define V8_HOST_ARCH_64_BIT 1
|
| 772 |
+
#elif __riscv_xlen == 32
|
| 773 |
+
#define V8_HOST_ARCH_RISCV32 1
|
| 774 |
+
#define V8_HOST_ARCH_32_BIT 1
|
| 775 |
+
#else
|
| 776 |
+
#error "Cannot detect Riscv's bitwidth"
|
| 777 |
+
#endif
|
| 778 |
+
#else
|
| 779 |
+
#error "Host architecture was not detected as supported by v8"
|
| 780 |
+
#endif
|
| 781 |
+
|
| 782 |
+
// Target architecture detection. This corresponds to the architecture for which
|
| 783 |
+
// V8's JIT will generate code (the last stage of the canadian cross-compiler).
|
| 784 |
+
// The macros may be set externally. If not, detect in the same way as the host
|
| 785 |
+
// architecture, that is, target the native environment as presented by the
|
| 786 |
+
// compiler.
|
| 787 |
+
#if !V8_TARGET_ARCH_X64 && !V8_TARGET_ARCH_IA32 && !V8_TARGET_ARCH_ARM && \
|
| 788 |
+
!V8_TARGET_ARCH_ARM64 && !V8_TARGET_ARCH_MIPS64 && !V8_TARGET_ARCH_PPC && \
|
| 789 |
+
!V8_TARGET_ARCH_PPC64 && !V8_TARGET_ARCH_S390 && \
|
| 790 |
+
!V8_TARGET_ARCH_RISCV64 && !V8_TARGET_ARCH_LOONG64 && \
|
| 791 |
+
!V8_TARGET_ARCH_RISCV32
|
| 792 |
+
#if defined(_M_X64) || defined(__x86_64__)
|
| 793 |
+
#define V8_TARGET_ARCH_X64 1
|
| 794 |
+
#elif defined(_M_IX86) || defined(__i386__)
|
| 795 |
+
#define V8_TARGET_ARCH_IA32 1
|
| 796 |
+
#elif defined(__AARCH64EL__) || defined(_M_ARM64)
|
| 797 |
+
#define V8_TARGET_ARCH_ARM64 1
|
| 798 |
+
#elif defined(__ARMEL__)
|
| 799 |
+
#define V8_TARGET_ARCH_ARM 1
|
| 800 |
+
#elif defined(__mips64)
|
| 801 |
+
#define V8_TARGET_ARCH_MIPS64 1
|
| 802 |
+
#elif defined(__loongarch64)
|
| 803 |
+
#define V8_TARGET_ARCH_LOONG64 1
|
| 804 |
+
#elif defined(_ARCH_PPC64)
|
| 805 |
+
#define V8_TARGET_ARCH_PPC64 1
|
| 806 |
+
#elif defined(_ARCH_PPC)
|
| 807 |
+
#define V8_TARGET_ARCH_PPC 1
|
| 808 |
+
#elif defined(__s390__)
|
| 809 |
+
#define V8_TARGET_ARCH_S390 1
|
| 810 |
+
#if defined(__s390x__)
|
| 811 |
+
#define V8_TARGET_ARCH_S390X 1
|
| 812 |
+
#endif
|
| 813 |
+
#elif defined(__riscv) || defined(__riscv__)
|
| 814 |
+
#if __riscv_xlen == 64
|
| 815 |
+
#define V8_TARGET_ARCH_RISCV64 1
|
| 816 |
+
#elif __riscv_xlen == 32
|
| 817 |
+
#define V8_TARGET_ARCH_RISCV32 1
|
| 818 |
+
#endif
|
| 819 |
+
#else
|
| 820 |
+
#error Target architecture was not detected as supported by v8
|
| 821 |
+
#endif
|
| 822 |
+
#endif
|
| 823 |
+
|
| 824 |
+
// Determine architecture pointer size.
|
| 825 |
+
#if V8_TARGET_ARCH_IA32
|
| 826 |
+
#define V8_TARGET_ARCH_32_BIT 1
|
| 827 |
+
#elif V8_TARGET_ARCH_X64
|
| 828 |
+
#if !V8_TARGET_ARCH_32_BIT && !V8_TARGET_ARCH_64_BIT
|
| 829 |
+
#if defined(__x86_64__) && __SIZEOF_POINTER__ == 4 // Check for x32.
|
| 830 |
+
#define V8_TARGET_ARCH_32_BIT 1
|
| 831 |
+
#else
|
| 832 |
+
#define V8_TARGET_ARCH_64_BIT 1
|
| 833 |
+
#endif
|
| 834 |
+
#endif
|
| 835 |
+
#elif V8_TARGET_ARCH_ARM
|
| 836 |
+
#define V8_TARGET_ARCH_32_BIT 1
|
| 837 |
+
#elif V8_TARGET_ARCH_ARM64
|
| 838 |
+
#define V8_TARGET_ARCH_64_BIT 1
|
| 839 |
+
#elif V8_TARGET_ARCH_MIPS
|
| 840 |
+
#define V8_TARGET_ARCH_32_BIT 1
|
| 841 |
+
#elif V8_TARGET_ARCH_MIPS64
|
| 842 |
+
#define V8_TARGET_ARCH_64_BIT 1
|
| 843 |
+
#elif V8_TARGET_ARCH_LOONG64
|
| 844 |
+
#define V8_TARGET_ARCH_64_BIT 1
|
| 845 |
+
#elif V8_TARGET_ARCH_PPC
|
| 846 |
+
#define V8_TARGET_ARCH_32_BIT 1
|
| 847 |
+
#elif V8_TARGET_ARCH_PPC64
|
| 848 |
+
#define V8_TARGET_ARCH_64_BIT 1
|
| 849 |
+
#elif V8_TARGET_ARCH_S390
|
| 850 |
+
#if V8_TARGET_ARCH_S390X
|
| 851 |
+
#define V8_TARGET_ARCH_64_BIT 1
|
| 852 |
+
#else
|
| 853 |
+
#define V8_TARGET_ARCH_32_BIT 1
|
| 854 |
+
#endif
|
| 855 |
+
#elif V8_TARGET_ARCH_RISCV64
|
| 856 |
+
#define V8_TARGET_ARCH_64_BIT 1
|
| 857 |
+
#elif V8_TARGET_ARCH_RISCV32
|
| 858 |
+
#define V8_TARGET_ARCH_32_BIT 1
|
| 859 |
+
#else
|
| 860 |
+
#error Unknown target architecture pointer size
|
| 861 |
+
#endif
|
| 862 |
+
|
| 863 |
+
// Check for supported combinations of host and target architectures.
|
| 864 |
+
#if V8_TARGET_ARCH_IA32 && !V8_HOST_ARCH_IA32
|
| 865 |
+
#error Target architecture ia32 is only supported on ia32 host
|
| 866 |
+
#endif
|
| 867 |
+
#if (V8_TARGET_ARCH_X64 && V8_TARGET_ARCH_64_BIT && \
|
| 868 |
+
!((V8_HOST_ARCH_X64 || V8_HOST_ARCH_ARM64) && V8_HOST_ARCH_64_BIT))
|
| 869 |
+
#error Target architecture x64 is only supported on x64 and arm64 host
|
| 870 |
+
#endif
|
| 871 |
+
#if (V8_TARGET_ARCH_X64 && V8_TARGET_ARCH_32_BIT && \
|
| 872 |
+
!(V8_HOST_ARCH_X64 && V8_HOST_ARCH_32_BIT))
|
| 873 |
+
#error Target architecture x32 is only supported on x64 host with x32 support
|
| 874 |
+
#endif
|
| 875 |
+
#if (V8_TARGET_ARCH_ARM && !(V8_HOST_ARCH_IA32 || V8_HOST_ARCH_ARM))
|
| 876 |
+
#error Target architecture arm is only supported on arm and ia32 host
|
| 877 |
+
#endif
|
| 878 |
+
#if (V8_TARGET_ARCH_ARM64 && !(V8_HOST_ARCH_X64 || V8_HOST_ARCH_ARM64))
|
| 879 |
+
#error Target architecture arm64 is only supported on arm64 and x64 host
|
| 880 |
+
#endif
|
| 881 |
+
#if (V8_TARGET_ARCH_MIPS64 && !(V8_HOST_ARCH_X64 || V8_HOST_ARCH_MIPS64))
|
| 882 |
+
#error Target architecture mips64 is only supported on mips64 and x64 host
|
| 883 |
+
#endif
|
| 884 |
+
#if (V8_TARGET_ARCH_RISCV64 && !(V8_HOST_ARCH_X64 || V8_HOST_ARCH_RISCV64))
|
| 885 |
+
#error Target architecture riscv64 is only supported on riscv64 and x64 host
|
| 886 |
+
#endif
|
| 887 |
+
#if (V8_TARGET_ARCH_RISCV32 && !(V8_HOST_ARCH_IA32 || V8_HOST_ARCH_RISCV32))
|
| 888 |
+
#error Target architecture riscv32 is only supported on riscv32 and ia32 host
|
| 889 |
+
#endif
|
| 890 |
+
#if (V8_TARGET_ARCH_LOONG64 && !(V8_HOST_ARCH_X64 || V8_HOST_ARCH_LOONG64))
|
| 891 |
+
#error Target architecture loong64 is only supported on loong64 and x64 host
|
| 892 |
+
#endif
|
| 893 |
+
|
| 894 |
+
// Determine architecture endianness.
|
| 895 |
+
#if V8_TARGET_ARCH_IA32
|
| 896 |
+
#define V8_TARGET_LITTLE_ENDIAN 1
|
| 897 |
+
#elif V8_TARGET_ARCH_X64
|
| 898 |
+
#define V8_TARGET_LITTLE_ENDIAN 1
|
| 899 |
+
#elif V8_TARGET_ARCH_ARM
|
| 900 |
+
#define V8_TARGET_LITTLE_ENDIAN 1
|
| 901 |
+
#elif V8_TARGET_ARCH_ARM64
|
| 902 |
+
#define V8_TARGET_LITTLE_ENDIAN 1
|
| 903 |
+
#elif V8_TARGET_ARCH_LOONG64
|
| 904 |
+
#define V8_TARGET_LITTLE_ENDIAN 1
|
| 905 |
+
#elif V8_TARGET_ARCH_MIPS64
|
| 906 |
+
#if defined(__MIPSEB__) || defined(V8_TARGET_ARCH_MIPS64_BE)
|
| 907 |
+
#define V8_TARGET_BIG_ENDIAN 1
|
| 908 |
+
#else
|
| 909 |
+
#define V8_TARGET_LITTLE_ENDIAN 1
|
| 910 |
+
#endif
|
| 911 |
+
#elif defined(__BIG_ENDIAN__) // FOR PPCGR on AIX
|
| 912 |
+
#define V8_TARGET_BIG_ENDIAN 1
|
| 913 |
+
#elif V8_TARGET_ARCH_PPC_LE
|
| 914 |
+
#define V8_TARGET_LITTLE_ENDIAN 1
|
| 915 |
+
#elif V8_TARGET_ARCH_PPC_BE
|
| 916 |
+
#define V8_TARGET_BIG_ENDIAN 1
|
| 917 |
+
#elif V8_TARGET_ARCH_S390
|
| 918 |
+
#if V8_TARGET_ARCH_S390_LE_SIM
|
| 919 |
+
#define V8_TARGET_LITTLE_ENDIAN 1
|
| 920 |
+
#else
|
| 921 |
+
#define V8_TARGET_BIG_ENDIAN 1
|
| 922 |
+
#endif
|
| 923 |
+
#elif V8_TARGET_ARCH_RISCV32 || V8_TARGET_ARCH_RISCV64
|
| 924 |
+
#define V8_TARGET_LITTLE_ENDIAN 1
|
| 925 |
+
#elif defined(__BYTE_ORDER__)
|
| 926 |
+
#if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
|
| 927 |
+
#define V8_TARGET_BIG_ENDIAN 1
|
| 928 |
+
#else
|
| 929 |
+
#define V8_TARGET_LITTLE_ENDIAN 1
|
| 930 |
+
#endif
|
| 931 |
+
#else
|
| 932 |
+
#error Unknown target architecture endianness
|
| 933 |
+
#endif
|
| 934 |
+
|
| 935 |
+
#undef V8_HAS_CPP_ATTRIBUTE
|
| 936 |
+
|
| 937 |
+
#if !defined(V8_STATIC_ROOTS)
|
| 938 |
+
#define V8_STATIC_ROOTS_BOOL false
|
| 939 |
+
#else
|
| 940 |
+
#define V8_STATIC_ROOTS_BOOL true
|
| 941 |
+
#endif
|
| 942 |
+
|
| 943 |
+
#endif // V8CONFIG_H_
|
.nvm/versions/node/v20.20.2/include/node/zconf.h
ADDED
|
@@ -0,0 +1,558 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/* zconf.h -- configuration of the zlib compression library
|
| 2 |
+
* Copyright (C) 1995-2024 Jean-loup Gailly, Mark Adler
|
| 3 |
+
* For conditions of distribution and use, see copyright notice in zlib.h
|
| 4 |
+
*/
|
| 5 |
+
|
| 6 |
+
/* @(#) $Id$ */
|
| 7 |
+
|
| 8 |
+
#ifndef ZCONF_H
|
| 9 |
+
#define ZCONF_H
|
| 10 |
+
|
| 11 |
+
/*
|
| 12 |
+
* This library is also built as a part of AOSP, which does not need to include
|
| 13 |
+
* chromeconf.h. This config does not want chromeconf.h, so it can set this
|
| 14 |
+
* macro to opt out. While this works today, there's no guarantee that building
|
| 15 |
+
* zlib outside of Chromium keeps working in the future.
|
| 16 |
+
*/
|
| 17 |
+
#if !defined(CHROMIUM_ZLIB_NO_CHROMECONF)
|
| 18 |
+
/* This include does prefixing as below, but with an updated set of names. Also
|
| 19 |
+
* sets up export macros in component builds. */
|
| 20 |
+
//#include "chromeconf.h"
|
| 21 |
+
#endif
|
| 22 |
+
|
| 23 |
+
/*
|
| 24 |
+
* If you *really* need a unique prefix for all types and library functions,
|
| 25 |
+
* compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
|
| 26 |
+
* Even better than compiling with -DZ_PREFIX would be to use configure to set
|
| 27 |
+
* this permanently in zconf.h using "./configure --zprefix".
|
| 28 |
+
*/
|
| 29 |
+
#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */
|
| 30 |
+
# define Z_PREFIX_SET
|
| 31 |
+
|
| 32 |
+
/* all linked symbols and init macros */
|
| 33 |
+
# define _dist_code z__dist_code
|
| 34 |
+
# define _length_code z__length_code
|
| 35 |
+
# define _tr_align z__tr_align
|
| 36 |
+
# define _tr_flush_bits z__tr_flush_bits
|
| 37 |
+
# define _tr_flush_block z__tr_flush_block
|
| 38 |
+
# define _tr_init z__tr_init
|
| 39 |
+
# define _tr_stored_block z__tr_stored_block
|
| 40 |
+
# define _tr_tally z__tr_tally
|
| 41 |
+
# define adler32 z_adler32
|
| 42 |
+
# define adler32_combine z_adler32_combine
|
| 43 |
+
# define adler32_combine64 z_adler32_combine64
|
| 44 |
+
# define adler32_z z_adler32_z
|
| 45 |
+
# ifndef Z_SOLO
|
| 46 |
+
# define compress z_compress
|
| 47 |
+
# define compress2 z_compress2
|
| 48 |
+
# define compressBound z_compressBound
|
| 49 |
+
# endif
|
| 50 |
+
# define crc32 z_crc32
|
| 51 |
+
# define crc32_combine z_crc32_combine
|
| 52 |
+
# define crc32_combine64 z_crc32_combine64
|
| 53 |
+
# define crc32_combine_gen z_crc32_combine_gen
|
| 54 |
+
# define crc32_combine_gen64 z_crc32_combine_gen64
|
| 55 |
+
# define crc32_combine_op z_crc32_combine_op
|
| 56 |
+
# define crc32_z z_crc32_z
|
| 57 |
+
# define deflate z_deflate
|
| 58 |
+
# define deflateBound z_deflateBound
|
| 59 |
+
# define deflateCopy z_deflateCopy
|
| 60 |
+
# define deflateEnd z_deflateEnd
|
| 61 |
+
# define deflateGetDictionary z_deflateGetDictionary
|
| 62 |
+
# define deflateInit z_deflateInit
|
| 63 |
+
# define deflateInit2 z_deflateInit2
|
| 64 |
+
# define deflateInit2_ z_deflateInit2_
|
| 65 |
+
# define deflateInit_ z_deflateInit_
|
| 66 |
+
# define deflateParams z_deflateParams
|
| 67 |
+
# define deflatePending z_deflatePending
|
| 68 |
+
# define deflatePrime z_deflatePrime
|
| 69 |
+
# define deflateReset z_deflateReset
|
| 70 |
+
# define deflateResetKeep z_deflateResetKeep
|
| 71 |
+
# define deflateSetDictionary z_deflateSetDictionary
|
| 72 |
+
# define deflateSetHeader z_deflateSetHeader
|
| 73 |
+
# define deflateTune z_deflateTune
|
| 74 |
+
# define deflate_copyright z_deflate_copyright
|
| 75 |
+
# define get_crc_table z_get_crc_table
|
| 76 |
+
# ifndef Z_SOLO
|
| 77 |
+
# define gz_error z_gz_error
|
| 78 |
+
# define gz_intmax z_gz_intmax
|
| 79 |
+
# define gz_strwinerror z_gz_strwinerror
|
| 80 |
+
# define gzbuffer z_gzbuffer
|
| 81 |
+
# define gzclearerr z_gzclearerr
|
| 82 |
+
# define gzclose z_gzclose
|
| 83 |
+
# define gzclose_r z_gzclose_r
|
| 84 |
+
# define gzclose_w z_gzclose_w
|
| 85 |
+
# define gzdirect z_gzdirect
|
| 86 |
+
# define gzdopen z_gzdopen
|
| 87 |
+
# define gzeof z_gzeof
|
| 88 |
+
# define gzerror z_gzerror
|
| 89 |
+
# define gzflush z_gzflush
|
| 90 |
+
# define gzfread z_gzfread
|
| 91 |
+
# define gzfwrite z_gzfwrite
|
| 92 |
+
# define gzgetc z_gzgetc
|
| 93 |
+
# define gzgetc_ z_gzgetc_
|
| 94 |
+
# define gzgets z_gzgets
|
| 95 |
+
# define gzoffset z_gzoffset
|
| 96 |
+
# define gzoffset64 z_gzoffset64
|
| 97 |
+
# define gzopen z_gzopen
|
| 98 |
+
# define gzopen64 z_gzopen64
|
| 99 |
+
# ifdef _WIN32
|
| 100 |
+
# define gzopen_w z_gzopen_w
|
| 101 |
+
# endif
|
| 102 |
+
# define gzprintf z_gzprintf
|
| 103 |
+
# define gzputc z_gzputc
|
| 104 |
+
# define gzputs z_gzputs
|
| 105 |
+
# define gzread z_gzread
|
| 106 |
+
# define gzrewind z_gzrewind
|
| 107 |
+
# define gzseek z_gzseek
|
| 108 |
+
# define gzseek64 z_gzseek64
|
| 109 |
+
# define gzsetparams z_gzsetparams
|
| 110 |
+
# define gztell z_gztell
|
| 111 |
+
# define gztell64 z_gztell64
|
| 112 |
+
# define gzungetc z_gzungetc
|
| 113 |
+
# define gzvprintf z_gzvprintf
|
| 114 |
+
# define gzwrite z_gzwrite
|
| 115 |
+
# endif
|
| 116 |
+
# define inflate z_inflate
|
| 117 |
+
# define inflateBack z_inflateBack
|
| 118 |
+
# define inflateBackEnd z_inflateBackEnd
|
| 119 |
+
# define inflateBackInit z_inflateBackInit
|
| 120 |
+
# define inflateBackInit_ z_inflateBackInit_
|
| 121 |
+
# define inflateCodesUsed z_inflateCodesUsed
|
| 122 |
+
# define inflateCopy z_inflateCopy
|
| 123 |
+
# define inflateEnd z_inflateEnd
|
| 124 |
+
# define inflateGetDictionary z_inflateGetDictionary
|
| 125 |
+
# define inflateGetHeader z_inflateGetHeader
|
| 126 |
+
# define inflateInit z_inflateInit
|
| 127 |
+
# define inflateInit2 z_inflateInit2
|
| 128 |
+
# define inflateInit2_ z_inflateInit2_
|
| 129 |
+
# define inflateInit_ z_inflateInit_
|
| 130 |
+
# define inflateMark z_inflateMark
|
| 131 |
+
# define inflatePrime z_inflatePrime
|
| 132 |
+
# define inflateReset z_inflateReset
|
| 133 |
+
# define inflateReset2 z_inflateReset2
|
| 134 |
+
# define inflateResetKeep z_inflateResetKeep
|
| 135 |
+
# define inflateSetDictionary z_inflateSetDictionary
|
| 136 |
+
# define inflateSync z_inflateSync
|
| 137 |
+
# define inflateSyncPoint z_inflateSyncPoint
|
| 138 |
+
# define inflateUndermine z_inflateUndermine
|
| 139 |
+
# define inflateValidate z_inflateValidate
|
| 140 |
+
# define inflate_copyright z_inflate_copyright
|
| 141 |
+
# define inflate_fast z_inflate_fast
|
| 142 |
+
# define inflate_table z_inflate_table
|
| 143 |
+
# ifndef Z_SOLO
|
| 144 |
+
# define uncompress z_uncompress
|
| 145 |
+
# define uncompress2 z_uncompress2
|
| 146 |
+
# endif
|
| 147 |
+
# define zError z_zError
|
| 148 |
+
# ifndef Z_SOLO
|
| 149 |
+
# define zcalloc z_zcalloc
|
| 150 |
+
# define zcfree z_zcfree
|
| 151 |
+
# endif
|
| 152 |
+
# define zlibCompileFlags z_zlibCompileFlags
|
| 153 |
+
# define zlibVersion z_zlibVersion
|
| 154 |
+
|
| 155 |
+
/* all zlib typedefs in zlib.h and zconf.h */
|
| 156 |
+
# define Byte z_Byte
|
| 157 |
+
# define Bytef z_Bytef
|
| 158 |
+
# define alloc_func z_alloc_func
|
| 159 |
+
# define charf z_charf
|
| 160 |
+
# define free_func z_free_func
|
| 161 |
+
# ifndef Z_SOLO
|
| 162 |
+
# define gzFile z_gzFile
|
| 163 |
+
# endif
|
| 164 |
+
# define gz_header z_gz_header
|
| 165 |
+
# define gz_headerp z_gz_headerp
|
| 166 |
+
# define in_func z_in_func
|
| 167 |
+
# define intf z_intf
|
| 168 |
+
# define out_func z_out_func
|
| 169 |
+
# define uInt z_uInt
|
| 170 |
+
# define uIntf z_uIntf
|
| 171 |
+
# define uLong z_uLong
|
| 172 |
+
# define uLongf z_uLongf
|
| 173 |
+
# define voidp z_voidp
|
| 174 |
+
# define voidpc z_voidpc
|
| 175 |
+
# define voidpf z_voidpf
|
| 176 |
+
|
| 177 |
+
/* all zlib structs in zlib.h and zconf.h */
|
| 178 |
+
# define gz_header_s z_gz_header_s
|
| 179 |
+
# define internal_state z_internal_state
|
| 180 |
+
|
| 181 |
+
#endif
|
| 182 |
+
|
| 183 |
+
#if defined(__MSDOS__) && !defined(MSDOS)
|
| 184 |
+
# define MSDOS
|
| 185 |
+
#endif
|
| 186 |
+
#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
|
| 187 |
+
# define OS2
|
| 188 |
+
#endif
|
| 189 |
+
#if defined(_WINDOWS) && !defined(WINDOWS)
|
| 190 |
+
# define WINDOWS
|
| 191 |
+
#endif
|
| 192 |
+
#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
|
| 193 |
+
# ifndef WIN32
|
| 194 |
+
# define WIN32
|
| 195 |
+
# endif
|
| 196 |
+
#endif
|
| 197 |
+
#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
|
| 198 |
+
# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
|
| 199 |
+
# ifndef SYS16BIT
|
| 200 |
+
# define SYS16BIT
|
| 201 |
+
# endif
|
| 202 |
+
# endif
|
| 203 |
+
#endif
|
| 204 |
+
|
| 205 |
+
/*
|
| 206 |
+
* Compile with -DMAXSEG_64K if the alloc function cannot allocate more
|
| 207 |
+
* than 64k bytes at a time (needed on systems with 16-bit int).
|
| 208 |
+
*/
|
| 209 |
+
#ifdef SYS16BIT
|
| 210 |
+
# define MAXSEG_64K
|
| 211 |
+
#endif
|
| 212 |
+
#ifdef MSDOS
|
| 213 |
+
# define UNALIGNED_OK
|
| 214 |
+
#endif
|
| 215 |
+
|
| 216 |
+
#ifdef __STDC_VERSION__
|
| 217 |
+
# ifndef STDC
|
| 218 |
+
# define STDC
|
| 219 |
+
# endif
|
| 220 |
+
# if __STDC_VERSION__ >= 199901L
|
| 221 |
+
# ifndef STDC99
|
| 222 |
+
# define STDC99
|
| 223 |
+
# endif
|
| 224 |
+
# endif
|
| 225 |
+
#endif
|
| 226 |
+
#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
|
| 227 |
+
# define STDC
|
| 228 |
+
#endif
|
| 229 |
+
#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
|
| 230 |
+
# define STDC
|
| 231 |
+
#endif
|
| 232 |
+
#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
|
| 233 |
+
# define STDC
|
| 234 |
+
#endif
|
| 235 |
+
#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
|
| 236 |
+
# define STDC
|
| 237 |
+
#endif
|
| 238 |
+
|
| 239 |
+
#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
|
| 240 |
+
# define STDC
|
| 241 |
+
#endif
|
| 242 |
+
|
| 243 |
+
#ifndef STDC
|
| 244 |
+
# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
|
| 245 |
+
# define const /* note: need a more gentle solution here */
|
| 246 |
+
# endif
|
| 247 |
+
#endif
|
| 248 |
+
|
| 249 |
+
#if defined(ZLIB_CONST) && !defined(z_const)
|
| 250 |
+
# define z_const const
|
| 251 |
+
#else
|
| 252 |
+
# define z_const
|
| 253 |
+
#endif
|
| 254 |
+
|
| 255 |
+
#ifdef Z_SOLO
|
| 256 |
+
# ifdef _WIN64
|
| 257 |
+
typedef unsigned long long z_size_t;
|
| 258 |
+
# else
|
| 259 |
+
typedef unsigned long z_size_t;
|
| 260 |
+
# endif
|
| 261 |
+
#else
|
| 262 |
+
# define z_longlong long long
|
| 263 |
+
# if defined(NO_SIZE_T)
|
| 264 |
+
typedef unsigned NO_SIZE_T z_size_t;
|
| 265 |
+
# elif defined(STDC)
|
| 266 |
+
# include <stddef.h>
|
| 267 |
+
typedef size_t z_size_t;
|
| 268 |
+
# else
|
| 269 |
+
typedef unsigned long z_size_t;
|
| 270 |
+
# endif
|
| 271 |
+
# undef z_longlong
|
| 272 |
+
#endif
|
| 273 |
+
|
| 274 |
+
/* Maximum value for memLevel in deflateInit2 */
|
| 275 |
+
#ifndef MAX_MEM_LEVEL
|
| 276 |
+
# ifdef MAXSEG_64K
|
| 277 |
+
# define MAX_MEM_LEVEL 8
|
| 278 |
+
# else
|
| 279 |
+
# define MAX_MEM_LEVEL 9
|
| 280 |
+
# endif
|
| 281 |
+
#endif
|
| 282 |
+
|
| 283 |
+
/* Maximum value for windowBits in deflateInit2 and inflateInit2.
|
| 284 |
+
* WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
|
| 285 |
+
* created by gzip. (Files created by minigzip can still be extracted by
|
| 286 |
+
* gzip.)
|
| 287 |
+
*/
|
| 288 |
+
#ifndef MAX_WBITS
|
| 289 |
+
# define MAX_WBITS 15 /* 32K LZ77 window */
|
| 290 |
+
#endif
|
| 291 |
+
|
| 292 |
+
/* The memory requirements for deflate are (in bytes):
|
| 293 |
+
(1 << (windowBits+2)) + (1 << (memLevel+9))
|
| 294 |
+
that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
|
| 295 |
+
plus a few kilobytes for small objects. For example, if you want to reduce
|
| 296 |
+
the default memory requirements from 256K to 128K, compile with
|
| 297 |
+
make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
|
| 298 |
+
Of course this will generally degrade compression (there's no free lunch).
|
| 299 |
+
|
| 300 |
+
The memory requirements for inflate are (in bytes) 1 << windowBits
|
| 301 |
+
that is, 32K for windowBits=15 (default value) plus about 7 kilobytes
|
| 302 |
+
for small objects.
|
| 303 |
+
*/
|
| 304 |
+
|
| 305 |
+
/* Type declarations */
|
| 306 |
+
|
| 307 |
+
#ifndef OF /* function prototypes */
|
| 308 |
+
# ifdef STDC
|
| 309 |
+
# define OF(args) args
|
| 310 |
+
# else
|
| 311 |
+
# define OF(args) ()
|
| 312 |
+
# endif
|
| 313 |
+
#endif
|
| 314 |
+
|
| 315 |
+
/* The following definitions for FAR are needed only for MSDOS mixed
|
| 316 |
+
* model programming (small or medium model with some far allocations).
|
| 317 |
+
* This was tested only with MSC; for other MSDOS compilers you may have
|
| 318 |
+
* to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
|
| 319 |
+
* just define FAR to be empty.
|
| 320 |
+
*/
|
| 321 |
+
#ifdef SYS16BIT
|
| 322 |
+
# if defined(M_I86SM) || defined(M_I86MM)
|
| 323 |
+
/* MSC small or medium model */
|
| 324 |
+
# define SMALL_MEDIUM
|
| 325 |
+
# ifdef _MSC_VER
|
| 326 |
+
# define FAR _far
|
| 327 |
+
# else
|
| 328 |
+
# define FAR far
|
| 329 |
+
# endif
|
| 330 |
+
# endif
|
| 331 |
+
# if (defined(__SMALL__) || defined(__MEDIUM__))
|
| 332 |
+
/* Turbo C small or medium model */
|
| 333 |
+
# define SMALL_MEDIUM
|
| 334 |
+
# ifdef __BORLANDC__
|
| 335 |
+
# define FAR _far
|
| 336 |
+
# else
|
| 337 |
+
# define FAR far
|
| 338 |
+
# endif
|
| 339 |
+
# endif
|
| 340 |
+
#endif
|
| 341 |
+
|
| 342 |
+
#if defined(WINDOWS) || defined(WIN32)
|
| 343 |
+
/* If building or using zlib as a DLL, define ZLIB_DLL.
|
| 344 |
+
* This is not mandatory, but it offers a little performance increase.
|
| 345 |
+
*/
|
| 346 |
+
# ifdef ZLIB_DLL
|
| 347 |
+
# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
|
| 348 |
+
# ifdef ZLIB_INTERNAL
|
| 349 |
+
# define ZEXTERN extern __declspec(dllexport)
|
| 350 |
+
# else
|
| 351 |
+
# define ZEXTERN extern __declspec(dllimport)
|
| 352 |
+
# endif
|
| 353 |
+
# endif
|
| 354 |
+
# endif /* ZLIB_DLL */
|
| 355 |
+
/* If building or using zlib with the WINAPI/WINAPIV calling convention,
|
| 356 |
+
* define ZLIB_WINAPI.
|
| 357 |
+
* Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
|
| 358 |
+
*/
|
| 359 |
+
# ifdef ZLIB_WINAPI
|
| 360 |
+
# ifdef FAR
|
| 361 |
+
# undef FAR
|
| 362 |
+
# endif
|
| 363 |
+
# ifndef WIN32_LEAN_AND_MEAN
|
| 364 |
+
# define WIN32_LEAN_AND_MEAN
|
| 365 |
+
# endif
|
| 366 |
+
# include <windows.h>
|
| 367 |
+
/* No need for _export, use ZLIB.DEF instead. */
|
| 368 |
+
/* For complete Windows compatibility, use WINAPI, not __stdcall. */
|
| 369 |
+
# define ZEXPORT WINAPI
|
| 370 |
+
# ifdef WIN32
|
| 371 |
+
# define ZEXPORTVA WINAPIV
|
| 372 |
+
# else
|
| 373 |
+
# define ZEXPORTVA FAR CDECL
|
| 374 |
+
# endif
|
| 375 |
+
# endif
|
| 376 |
+
#endif
|
| 377 |
+
|
| 378 |
+
#if defined (__BEOS__)
|
| 379 |
+
# ifdef ZLIB_DLL
|
| 380 |
+
# ifdef ZLIB_INTERNAL
|
| 381 |
+
# define ZEXPORT __declspec(dllexport)
|
| 382 |
+
# define ZEXPORTVA __declspec(dllexport)
|
| 383 |
+
# else
|
| 384 |
+
# define ZEXPORT __declspec(dllimport)
|
| 385 |
+
# define ZEXPORTVA __declspec(dllimport)
|
| 386 |
+
# endif
|
| 387 |
+
# endif
|
| 388 |
+
#endif
|
| 389 |
+
|
| 390 |
+
#ifndef ZEXTERN
|
| 391 |
+
# define ZEXTERN extern
|
| 392 |
+
#endif
|
| 393 |
+
#ifndef ZEXPORT
|
| 394 |
+
# define ZEXPORT
|
| 395 |
+
#endif
|
| 396 |
+
#ifndef ZEXPORTVA
|
| 397 |
+
# define ZEXPORTVA
|
| 398 |
+
#endif
|
| 399 |
+
|
| 400 |
+
#ifndef FAR
|
| 401 |
+
# define FAR
|
| 402 |
+
#endif
|
| 403 |
+
#ifndef far
|
| 404 |
+
# define far
|
| 405 |
+
#endif
|
| 406 |
+
|
| 407 |
+
#if !defined(__MACTYPES__)
|
| 408 |
+
typedef unsigned char Byte; /* 8 bits */
|
| 409 |
+
#endif
|
| 410 |
+
typedef unsigned int uInt; /* 16 bits or more */
|
| 411 |
+
typedef unsigned long uLong; /* 32 bits or more */
|
| 412 |
+
|
| 413 |
+
#ifdef SMALL_MEDIUM
|
| 414 |
+
/* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
|
| 415 |
+
# define Bytef Byte FAR
|
| 416 |
+
#else
|
| 417 |
+
typedef Byte FAR Bytef;
|
| 418 |
+
#endif
|
| 419 |
+
typedef char FAR charf;
|
| 420 |
+
typedef int FAR intf;
|
| 421 |
+
typedef uInt FAR uIntf;
|
| 422 |
+
typedef uLong FAR uLongf;
|
| 423 |
+
|
| 424 |
+
#ifdef STDC
|
| 425 |
+
typedef void const *voidpc;
|
| 426 |
+
typedef void FAR *voidpf;
|
| 427 |
+
typedef void *voidp;
|
| 428 |
+
#else
|
| 429 |
+
typedef Byte const *voidpc;
|
| 430 |
+
typedef Byte FAR *voidpf;
|
| 431 |
+
typedef Byte *voidp;
|
| 432 |
+
#endif
|
| 433 |
+
|
| 434 |
+
#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC)
|
| 435 |
+
# include <limits.h>
|
| 436 |
+
# if (UINT_MAX == 0xffffffffUL)
|
| 437 |
+
# define Z_U4 unsigned
|
| 438 |
+
# elif (ULONG_MAX == 0xffffffffUL)
|
| 439 |
+
# define Z_U4 unsigned long
|
| 440 |
+
# elif (USHRT_MAX == 0xffffffffUL)
|
| 441 |
+
# define Z_U4 unsigned short
|
| 442 |
+
# endif
|
| 443 |
+
#endif
|
| 444 |
+
|
| 445 |
+
#ifdef Z_U4
|
| 446 |
+
typedef Z_U4 z_crc_t;
|
| 447 |
+
#else
|
| 448 |
+
typedef unsigned long z_crc_t;
|
| 449 |
+
#endif
|
| 450 |
+
|
| 451 |
+
#if !defined(_WIN32)
|
| 452 |
+
# define Z_HAVE_UNISTD_H
|
| 453 |
+
#endif
|
| 454 |
+
|
| 455 |
+
#ifdef HAVE_STDARG_H /* may be set to #if 1 by ./configure */
|
| 456 |
+
# define Z_HAVE_STDARG_H
|
| 457 |
+
#endif
|
| 458 |
+
|
| 459 |
+
#ifdef STDC
|
| 460 |
+
# ifndef Z_SOLO
|
| 461 |
+
# include <sys/types.h> /* for off_t */
|
| 462 |
+
# endif
|
| 463 |
+
#endif
|
| 464 |
+
|
| 465 |
+
#if defined(STDC) || defined(Z_HAVE_STDARG_H)
|
| 466 |
+
# ifndef Z_SOLO
|
| 467 |
+
# include <stdarg.h> /* for va_list */
|
| 468 |
+
# endif
|
| 469 |
+
#endif
|
| 470 |
+
|
| 471 |
+
#ifdef _WIN32
|
| 472 |
+
# ifndef Z_SOLO
|
| 473 |
+
# include <stddef.h> /* for wchar_t */
|
| 474 |
+
# endif
|
| 475 |
+
#endif
|
| 476 |
+
|
| 477 |
+
/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and
|
| 478 |
+
* "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even
|
| 479 |
+
* though the former does not conform to the LFS document), but considering
|
| 480 |
+
* both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as
|
| 481 |
+
* equivalently requesting no 64-bit operations
|
| 482 |
+
*/
|
| 483 |
+
#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1
|
| 484 |
+
# undef _LARGEFILE64_SOURCE
|
| 485 |
+
#endif
|
| 486 |
+
|
| 487 |
+
#ifndef Z_HAVE_UNISTD_H
|
| 488 |
+
# ifdef __WATCOMC__
|
| 489 |
+
# define Z_HAVE_UNISTD_H
|
| 490 |
+
# endif
|
| 491 |
+
#endif
|
| 492 |
+
#ifndef Z_HAVE_UNISTD_H
|
| 493 |
+
# if defined(_LARGEFILE64_SOURCE) && !defined(_WIN32)
|
| 494 |
+
# define Z_HAVE_UNISTD_H
|
| 495 |
+
# endif
|
| 496 |
+
#endif
|
| 497 |
+
#ifndef Z_SOLO
|
| 498 |
+
# if defined(Z_HAVE_UNISTD_H)
|
| 499 |
+
# include <unistd.h> /* for SEEK_*, off_t, and _LFS64_LARGEFILE */
|
| 500 |
+
# ifdef VMS
|
| 501 |
+
# include <unixio.h> /* for off_t */
|
| 502 |
+
# endif
|
| 503 |
+
# ifndef z_off_t
|
| 504 |
+
# define z_off_t off_t
|
| 505 |
+
# endif
|
| 506 |
+
# endif
|
| 507 |
+
#endif
|
| 508 |
+
|
| 509 |
+
#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0
|
| 510 |
+
# define Z_LFS64
|
| 511 |
+
#endif
|
| 512 |
+
|
| 513 |
+
#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64)
|
| 514 |
+
# define Z_LARGE64
|
| 515 |
+
#endif
|
| 516 |
+
|
| 517 |
+
#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64)
|
| 518 |
+
# define Z_WANT64
|
| 519 |
+
#endif
|
| 520 |
+
|
| 521 |
+
#if !defined(SEEK_SET) && !defined(Z_SOLO)
|
| 522 |
+
# define SEEK_SET 0 /* Seek from beginning of file. */
|
| 523 |
+
# define SEEK_CUR 1 /* Seek from current position. */
|
| 524 |
+
# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
|
| 525 |
+
#endif
|
| 526 |
+
|
| 527 |
+
#ifndef z_off_t
|
| 528 |
+
# define z_off_t long
|
| 529 |
+
#endif
|
| 530 |
+
|
| 531 |
+
#if !defined(_WIN32) && defined(Z_LARGE64)
|
| 532 |
+
# define z_off64_t off64_t
|
| 533 |
+
#else
|
| 534 |
+
# if defined(_WIN32) && !defined(__GNUC__)
|
| 535 |
+
# define z_off64_t __int64
|
| 536 |
+
# else
|
| 537 |
+
# define z_off64_t z_off_t
|
| 538 |
+
# endif
|
| 539 |
+
#endif
|
| 540 |
+
|
| 541 |
+
/* MVS linker does not support external names larger than 8 bytes */
|
| 542 |
+
#if defined(__MVS__)
|
| 543 |
+
#pragma map(deflateInit_,"DEIN")
|
| 544 |
+
#pragma map(deflateInit2_,"DEIN2")
|
| 545 |
+
#pragma map(deflateEnd,"DEEND")
|
| 546 |
+
#pragma map(deflateBound,"DEBND")
|
| 547 |
+
#pragma map(inflateInit_,"ININ")
|
| 548 |
+
#pragma map(inflateInit2_,"ININ2")
|
| 549 |
+
#pragma map(inflateEnd,"INEND")
|
| 550 |
+
#pragma map(inflateSync,"INSY")
|
| 551 |
+
#pragma map(inflateSetDictionary,"INSEDI")
|
| 552 |
+
#pragma map(compressBound,"CMBND")
|
| 553 |
+
#pragma map(inflate_table,"INTABL")
|
| 554 |
+
#pragma map(inflate_fast,"INFA")
|
| 555 |
+
#pragma map(inflate_copyright,"INCOPY")
|
| 556 |
+
#endif
|
| 557 |
+
|
| 558 |
+
#endif /* ZCONF_H */
|
.nvm/versions/node/v20.20.2/include/node/zlib.h
ADDED
|
@@ -0,0 +1,1967 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 1 |
+
/* zlib.h -- interface of the 'zlib' general purpose compression library
|
| 2 |
+
version 1.3.1, January 22nd, 2024
|
| 3 |
+
|
| 4 |
+
Copyright (C) 1995-2024 Jean-loup Gailly and Mark Adler
|
| 5 |
+
|
| 6 |
+
This software is provided 'as-is', without any express or implied
|
| 7 |
+
warranty. In no event will the authors be held liable for any damages
|
| 8 |
+
arising from the use of this software.
|
| 9 |
+
|
| 10 |
+
Permission is granted to anyone to use this software for any purpose,
|
| 11 |
+
including commercial applications, and to alter it and redistribute it
|
| 12 |
+
freely, subject to the following restrictions:
|
| 13 |
+
|
| 14 |
+
1. The origin of this software must not be misrepresented; you must not
|
| 15 |
+
claim that you wrote the original software. If you use this software
|
| 16 |
+
in a product, an acknowledgment in the product documentation would be
|
| 17 |
+
appreciated but is not required.
|
| 18 |
+
2. Altered source versions must be plainly marked as such, and must not be
|
| 19 |
+
misrepresented as being the original software.
|
| 20 |
+
3. This notice may not be removed or altered from any source distribution.
|
| 21 |
+
|
| 22 |
+
Jean-loup Gailly Mark Adler
|
| 23 |
+
jloup@gzip.org madler@alumni.caltech.edu
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
The data format used by the zlib library is described by RFCs (Request for
|
| 27 |
+
Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950
|
| 28 |
+
(zlib format), rfc1951 (deflate format) and rfc1952 (gzip format).
|
| 29 |
+
*/
|
| 30 |
+
|
| 31 |
+
#ifndef ZLIB_H
|
| 32 |
+
#define ZLIB_H
|
| 33 |
+
|
| 34 |
+
#include "zconf.h"
|
| 35 |
+
|
| 36 |
+
#ifdef __cplusplus
|
| 37 |
+
extern "C" {
|
| 38 |
+
#endif
|
| 39 |
+
|
| 40 |
+
#define ZLIB_VERSION "1.3.1"
|
| 41 |
+
#define ZLIB_VERNUM 0x1310
|
| 42 |
+
#define ZLIB_VER_MAJOR 1
|
| 43 |
+
#define ZLIB_VER_MINOR 3
|
| 44 |
+
#define ZLIB_VER_REVISION 1
|
| 45 |
+
#define ZLIB_VER_SUBREVISION 0
|
| 46 |
+
|
| 47 |
+
/*
|
| 48 |
+
The 'zlib' compression library provides in-memory compression and
|
| 49 |
+
decompression functions, including integrity checks of the uncompressed data.
|
| 50 |
+
This version of the library supports only one compression method (deflation)
|
| 51 |
+
but other algorithms will be added later and will have the same stream
|
| 52 |
+
interface.
|
| 53 |
+
|
| 54 |
+
Compression can be done in a single step if the buffers are large enough,
|
| 55 |
+
or can be done by repeated calls of the compression function. In the latter
|
| 56 |
+
case, the application must provide more input and/or consume the output
|
| 57 |
+
(providing more output space) before each call.
|
| 58 |
+
|
| 59 |
+
The compressed data format used by default by the in-memory functions is
|
| 60 |
+
the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
|
| 61 |
+
around a deflate stream, which is itself documented in RFC 1951.
|
| 62 |
+
|
| 63 |
+
The library also supports reading and writing files in gzip (.gz) format
|
| 64 |
+
with an interface similar to that of stdio using the functions that start
|
| 65 |
+
with "gz". The gzip format is different from the zlib format. gzip is a
|
| 66 |
+
gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
|
| 67 |
+
|
| 68 |
+
This library can optionally read and write gzip and raw deflate streams in
|
| 69 |
+
memory as well.
|
| 70 |
+
|
| 71 |
+
The zlib format was designed to be compact and fast for use in memory
|
| 72 |
+
and on communications channels. The gzip format was designed for single-
|
| 73 |
+
file compression on file systems, has a larger header than zlib to maintain
|
| 74 |
+
directory information, and uses a different, slower check method than zlib.
|
| 75 |
+
|
| 76 |
+
The library does not install any signal handler. The decoder checks
|
| 77 |
+
the consistency of the compressed data, so the library should never crash
|
| 78 |
+
even in the case of corrupted input.
|
| 79 |
+
*/
|
| 80 |
+
|
| 81 |
+
typedef voidpf (*alloc_func)(voidpf opaque, uInt items, uInt size);
|
| 82 |
+
typedef void (*free_func)(voidpf opaque, voidpf address);
|
| 83 |
+
|
| 84 |
+
struct internal_state;
|
| 85 |
+
|
| 86 |
+
typedef struct z_stream_s {
|
| 87 |
+
z_const Bytef *next_in; /* next input byte */
|
| 88 |
+
uInt avail_in; /* number of bytes available at next_in */
|
| 89 |
+
uLong total_in; /* total number of input bytes read so far */
|
| 90 |
+
|
| 91 |
+
Bytef *next_out; /* next output byte will go here */
|
| 92 |
+
uInt avail_out; /* remaining free space at next_out */
|
| 93 |
+
uLong total_out; /* total number of bytes output so far */
|
| 94 |
+
|
| 95 |
+
z_const char *msg; /* last error message, NULL if no error */
|
| 96 |
+
struct internal_state FAR *state; /* not visible by applications */
|
| 97 |
+
|
| 98 |
+
alloc_func zalloc; /* used to allocate the internal state */
|
| 99 |
+
free_func zfree; /* used to free the internal state */
|
| 100 |
+
voidpf opaque; /* private data object passed to zalloc and zfree */
|
| 101 |
+
|
| 102 |
+
int data_type; /* best guess about the data type: binary or text
|
| 103 |
+
for deflate, or the decoding state for inflate */
|
| 104 |
+
uLong adler; /* Adler-32 or CRC-32 value of the uncompressed data */
|
| 105 |
+
uLong reserved; /* reserved for future use */
|
| 106 |
+
} z_stream;
|
| 107 |
+
|
| 108 |
+
typedef z_stream FAR *z_streamp;
|
| 109 |
+
|
| 110 |
+
/*
|
| 111 |
+
gzip header information passed to and from zlib routines. See RFC 1952
|
| 112 |
+
for more details on the meanings of these fields.
|
| 113 |
+
*/
|
| 114 |
+
typedef struct gz_header_s {
|
| 115 |
+
int text; /* true if compressed data believed to be text */
|
| 116 |
+
uLong time; /* modification time */
|
| 117 |
+
int xflags; /* extra flags (not used when writing a gzip file) */
|
| 118 |
+
int os; /* operating system */
|
| 119 |
+
Bytef *extra; /* pointer to extra field or Z_NULL if none */
|
| 120 |
+
uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
|
| 121 |
+
uInt extra_max; /* space at extra (only when reading header) */
|
| 122 |
+
Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
|
| 123 |
+
uInt name_max; /* space at name (only when reading header) */
|
| 124 |
+
Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
|
| 125 |
+
uInt comm_max; /* space at comment (only when reading header) */
|
| 126 |
+
int hcrc; /* true if there was or will be a header crc */
|
| 127 |
+
int done; /* true when done reading gzip header (not used
|
| 128 |
+
when writing a gzip file) */
|
| 129 |
+
} gz_header;
|
| 130 |
+
|
| 131 |
+
typedef gz_header FAR *gz_headerp;
|
| 132 |
+
|
| 133 |
+
/*
|
| 134 |
+
The application must update next_in and avail_in when avail_in has dropped
|
| 135 |
+
to zero. It must update next_out and avail_out when avail_out has dropped
|
| 136 |
+
to zero. The application must initialize zalloc, zfree and opaque before
|
| 137 |
+
calling the init function. All other fields are set by the compression
|
| 138 |
+
library and must not be updated by the application.
|
| 139 |
+
|
| 140 |
+
The opaque value provided by the application will be passed as the first
|
| 141 |
+
parameter for calls of zalloc and zfree. This can be useful for custom
|
| 142 |
+
memory management. The compression library attaches no meaning to the
|
| 143 |
+
opaque value.
|
| 144 |
+
|
| 145 |
+
zalloc must return Z_NULL if there is not enough memory for the object.
|
| 146 |
+
If zlib is used in a multi-threaded application, zalloc and zfree must be
|
| 147 |
+
thread safe. In that case, zlib is thread-safe. When zalloc and zfree are
|
| 148 |
+
Z_NULL on entry to the initialization function, they are set to internal
|
| 149 |
+
routines that use the standard library functions malloc() and free().
|
| 150 |
+
|
| 151 |
+
On 16-bit systems, the functions zalloc and zfree must be able to allocate
|
| 152 |
+
exactly 65536 bytes, but will not be required to allocate more than this if
|
| 153 |
+
the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers
|
| 154 |
+
returned by zalloc for objects of exactly 65536 bytes *must* have their
|
| 155 |
+
offset normalized to zero. The default allocation function provided by this
|
| 156 |
+
library ensures this (see zutil.c). To reduce memory requirements and avoid
|
| 157 |
+
any allocation of 64K objects, at the expense of compression ratio, compile
|
| 158 |
+
the library with -DMAX_WBITS=14 (see zconf.h).
|
| 159 |
+
|
| 160 |
+
The fields total_in and total_out can be used for statistics or progress
|
| 161 |
+
reports. After compression, total_in holds the total size of the
|
| 162 |
+
uncompressed data and may be saved for use by the decompressor (particularly
|
| 163 |
+
if the decompressor wants to decompress everything in a single step).
|
| 164 |
+
*/
|
| 165 |
+
|
| 166 |
+
/* constants */
|
| 167 |
+
|
| 168 |
+
#define Z_NO_FLUSH 0
|
| 169 |
+
#define Z_PARTIAL_FLUSH 1
|
| 170 |
+
#define Z_SYNC_FLUSH 2
|
| 171 |
+
#define Z_FULL_FLUSH 3
|
| 172 |
+
#define Z_FINISH 4
|
| 173 |
+
#define Z_BLOCK 5
|
| 174 |
+
#define Z_TREES 6
|
| 175 |
+
/* Allowed flush values; see deflate() and inflate() below for details */
|
| 176 |
+
|
| 177 |
+
#define Z_OK 0
|
| 178 |
+
#define Z_STREAM_END 1
|
| 179 |
+
#define Z_NEED_DICT 2
|
| 180 |
+
#define Z_ERRNO (-1)
|
| 181 |
+
#define Z_STREAM_ERROR (-2)
|
| 182 |
+
#define Z_DATA_ERROR (-3)
|
| 183 |
+
#define Z_MEM_ERROR (-4)
|
| 184 |
+
#define Z_BUF_ERROR (-5)
|
| 185 |
+
#define Z_VERSION_ERROR (-6)
|
| 186 |
+
/* Return codes for the compression/decompression functions. Negative values
|
| 187 |
+
* are errors, positive values are used for special but normal events.
|
| 188 |
+
*/
|
| 189 |
+
|
| 190 |
+
#define Z_NO_COMPRESSION 0
|
| 191 |
+
#define Z_BEST_SPEED 1
|
| 192 |
+
#define Z_BEST_COMPRESSION 9
|
| 193 |
+
#define Z_DEFAULT_COMPRESSION (-1)
|
| 194 |
+
/* compression levels */
|
| 195 |
+
|
| 196 |
+
#define Z_FILTERED 1
|
| 197 |
+
#define Z_HUFFMAN_ONLY 2
|
| 198 |
+
#define Z_RLE 3
|
| 199 |
+
#define Z_FIXED 4
|
| 200 |
+
#define Z_DEFAULT_STRATEGY 0
|
| 201 |
+
/* compression strategy; see deflateInit2() below for details */
|
| 202 |
+
|
| 203 |
+
#define Z_BINARY 0
|
| 204 |
+
#define Z_TEXT 1
|
| 205 |
+
#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
|
| 206 |
+
#define Z_UNKNOWN 2
|
| 207 |
+
/* Possible values of the data_type field for deflate() */
|
| 208 |
+
|
| 209 |
+
#define Z_DEFLATED 8
|
| 210 |
+
/* The deflate compression method (the only one supported in this version) */
|
| 211 |
+
|
| 212 |
+
#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
|
| 213 |
+
|
| 214 |
+
#define zlib_version zlibVersion()
|
| 215 |
+
/* for compatibility with versions < 1.0.2 */
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
/* basic functions */
|
| 219 |
+
|
| 220 |
+
ZEXTERN const char * ZEXPORT zlibVersion(void);
|
| 221 |
+
/* The application can compare zlibVersion and ZLIB_VERSION for consistency.
|
| 222 |
+
If the first character differs, the library code actually used is not
|
| 223 |
+
compatible with the zlib.h header file used by the application. This check
|
| 224 |
+
is automatically made by deflateInit and inflateInit.
|
| 225 |
+
*/
|
| 226 |
+
|
| 227 |
+
/*
|
| 228 |
+
ZEXTERN int ZEXPORT deflateInit(z_streamp strm, int level);
|
| 229 |
+
|
| 230 |
+
Initializes the internal stream state for compression. The fields
|
| 231 |
+
zalloc, zfree and opaque must be initialized before by the caller. If
|
| 232 |
+
zalloc and zfree are set to Z_NULL, deflateInit updates them to use default
|
| 233 |
+
allocation functions. total_in, total_out, adler, and msg are initialized.
|
| 234 |
+
|
| 235 |
+
The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
|
| 236 |
+
1 gives best speed, 9 gives best compression, 0 gives no compression at all
|
| 237 |
+
(the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION
|
| 238 |
+
requests a default compromise between speed and compression (currently
|
| 239 |
+
equivalent to level 6).
|
| 240 |
+
|
| 241 |
+
deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
|
| 242 |
+
memory, Z_STREAM_ERROR if level is not a valid compression level, or
|
| 243 |
+
Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
|
| 244 |
+
with the version assumed by the caller (ZLIB_VERSION). msg is set to null
|
| 245 |
+
if there is no error message. deflateInit does not perform any compression:
|
| 246 |
+
this will be done by deflate().
|
| 247 |
+
*/
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
ZEXTERN int ZEXPORT deflate(z_streamp strm, int flush);
|
| 251 |
+
/*
|
| 252 |
+
deflate compresses as much data as possible, and stops when the input
|
| 253 |
+
buffer becomes empty or the output buffer becomes full. It may introduce
|
| 254 |
+
some output latency (reading input without producing any output) except when
|
| 255 |
+
forced to flush.
|
| 256 |
+
|
| 257 |
+
The detailed semantics are as follows. deflate performs one or both of the
|
| 258 |
+
following actions:
|
| 259 |
+
|
| 260 |
+
- Compress more input starting at next_in and update next_in and avail_in
|
| 261 |
+
accordingly. If not all input can be processed (because there is not
|
| 262 |
+
enough room in the output buffer), next_in and avail_in are updated and
|
| 263 |
+
processing will resume at this point for the next call of deflate().
|
| 264 |
+
|
| 265 |
+
- Generate more output starting at next_out and update next_out and avail_out
|
| 266 |
+
accordingly. This action is forced if the parameter flush is non zero.
|
| 267 |
+
Forcing flush frequently degrades the compression ratio, so this parameter
|
| 268 |
+
should be set only when necessary. Some output may be provided even if
|
| 269 |
+
flush is zero.
|
| 270 |
+
|
| 271 |
+
Before the call of deflate(), the application should ensure that at least
|
| 272 |
+
one of the actions is possible, by providing more input and/or consuming more
|
| 273 |
+
output, and updating avail_in or avail_out accordingly; avail_out should
|
| 274 |
+
never be zero before the call. The application can consume the compressed
|
| 275 |
+
output when it wants, for example when the output buffer is full (avail_out
|
| 276 |
+
== 0), or after each call of deflate(). If deflate returns Z_OK and with
|
| 277 |
+
zero avail_out, it must be called again after making room in the output
|
| 278 |
+
buffer because there might be more output pending. See deflatePending(),
|
| 279 |
+
which can be used if desired to determine whether or not there is more output
|
| 280 |
+
in that case.
|
| 281 |
+
|
| 282 |
+
Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
|
| 283 |
+
decide how much data to accumulate before producing output, in order to
|
| 284 |
+
maximize compression.
|
| 285 |
+
|
| 286 |
+
If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
|
| 287 |
+
flushed to the output buffer and the output is aligned on a byte boundary, so
|
| 288 |
+
that the decompressor can get all input data available so far. (In
|
| 289 |
+
particular avail_in is zero after the call if enough output space has been
|
| 290 |
+
provided before the call.) Flushing may degrade compression for some
|
| 291 |
+
compression algorithms and so it should be used only when necessary. This
|
| 292 |
+
completes the current deflate block and follows it with an empty stored block
|
| 293 |
+
that is three bits plus filler bits to the next byte, followed by four bytes
|
| 294 |
+
(00 00 ff ff).
|
| 295 |
+
|
| 296 |
+
If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the
|
| 297 |
+
output buffer, but the output is not aligned to a byte boundary. All of the
|
| 298 |
+
input data so far will be available to the decompressor, as for Z_SYNC_FLUSH.
|
| 299 |
+
This completes the current deflate block and follows it with an empty fixed
|
| 300 |
+
codes block that is 10 bits long. This assures that enough bytes are output
|
| 301 |
+
in order for the decompressor to finish the block before the empty fixed
|
| 302 |
+
codes block.
|
| 303 |
+
|
| 304 |
+
If flush is set to Z_BLOCK, a deflate block is completed and emitted, as
|
| 305 |
+
for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to
|
| 306 |
+
seven bits of the current block are held to be written as the next byte after
|
| 307 |
+
the next deflate block is completed. In this case, the decompressor may not
|
| 308 |
+
be provided enough bits at this point in order to complete decompression of
|
| 309 |
+
the data provided so far to the compressor. It may need to wait for the next
|
| 310 |
+
block to be emitted. This is for advanced applications that need to control
|
| 311 |
+
the emission of deflate blocks.
|
| 312 |
+
|
| 313 |
+
If flush is set to Z_FULL_FLUSH, all output is flushed as with
|
| 314 |
+
Z_SYNC_FLUSH, and the compression state is reset so that decompression can
|
| 315 |
+
restart from this point if previous compressed data has been damaged or if
|
| 316 |
+
random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
|
| 317 |
+
compression.
|
| 318 |
+
|
| 319 |
+
If deflate returns with avail_out == 0, this function must be called again
|
| 320 |
+
with the same value of the flush parameter and more output space (updated
|
| 321 |
+
avail_out), until the flush is complete (deflate returns with non-zero
|
| 322 |
+
avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
|
| 323 |
+
avail_out is greater than six when the flush marker begins, in order to avoid
|
| 324 |
+
repeated flush markers upon calling deflate() again when avail_out == 0.
|
| 325 |
+
|
| 326 |
+
If the parameter flush is set to Z_FINISH, pending input is processed,
|
| 327 |
+
pending output is flushed and deflate returns with Z_STREAM_END if there was
|
| 328 |
+
enough output space. If deflate returns with Z_OK or Z_BUF_ERROR, this
|
| 329 |
+
function must be called again with Z_FINISH and more output space (updated
|
| 330 |
+
avail_out) but no more input data, until it returns with Z_STREAM_END or an
|
| 331 |
+
error. After deflate has returned Z_STREAM_END, the only possible operations
|
| 332 |
+
on the stream are deflateReset or deflateEnd.
|
| 333 |
+
|
| 334 |
+
Z_FINISH can be used in the first deflate call after deflateInit if all the
|
| 335 |
+
compression is to be done in a single step. In order to complete in one
|
| 336 |
+
call, avail_out must be at least the value returned by deflateBound (see
|
| 337 |
+
below). Then deflate is guaranteed to return Z_STREAM_END. If not enough
|
| 338 |
+
output space is provided, deflate will not return Z_STREAM_END, and it must
|
| 339 |
+
be called again as described above.
|
| 340 |
+
|
| 341 |
+
deflate() sets strm->adler to the Adler-32 checksum of all input read
|
| 342 |
+
so far (that is, total_in bytes). If a gzip stream is being generated, then
|
| 343 |
+
strm->adler will be the CRC-32 checksum of the input read so far. (See
|
| 344 |
+
deflateInit2 below.)
|
| 345 |
+
|
| 346 |
+
deflate() may update strm->data_type if it can make a good guess about
|
| 347 |
+
the input data type (Z_BINARY or Z_TEXT). If in doubt, the data is
|
| 348 |
+
considered binary. This field is only for information purposes and does not
|
| 349 |
+
affect the compression algorithm in any manner.
|
| 350 |
+
|
| 351 |
+
deflate() returns Z_OK if some progress has been made (more input
|
| 352 |
+
processed or more output produced), Z_STREAM_END if all input has been
|
| 353 |
+
consumed and all output has been produced (only when flush is set to
|
| 354 |
+
Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
|
| 355 |
+
if next_in or next_out was Z_NULL or the state was inadvertently written over
|
| 356 |
+
by the application), or Z_BUF_ERROR if no progress is possible (for example
|
| 357 |
+
avail_in or avail_out was zero). Note that Z_BUF_ERROR is not fatal, and
|
| 358 |
+
deflate() can be called again with more input and more output space to
|
| 359 |
+
continue compressing.
|
| 360 |
+
*/
|
| 361 |
+
|
| 362 |
+
ZEXTERN int ZEXPORT deflateEnd(z_streamp strm);
|
| 363 |
+
/*
|
| 364 |
+
All dynamically allocated data structures for this stream are freed.
|
| 365 |
+
This function discards any unprocessed input and does not flush any pending
|
| 366 |
+
output.
|
| 367 |
+
|
| 368 |
+
deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
|
| 369 |
+
stream state was inconsistent, Z_DATA_ERROR if the stream was freed
|
| 370 |
+
prematurely (some input or output was discarded). In the error case, msg
|
| 371 |
+
may be set but then points to a static string (which must not be
|
| 372 |
+
deallocated).
|
| 373 |
+
*/
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
/*
|
| 377 |
+
ZEXTERN int ZEXPORT inflateInit(z_streamp strm);
|
| 378 |
+
|
| 379 |
+
Initializes the internal stream state for decompression. The fields
|
| 380 |
+
next_in, avail_in, zalloc, zfree and opaque must be initialized before by
|
| 381 |
+
the caller. In the current version of inflate, the provided input is not
|
| 382 |
+
read or consumed. The allocation of a sliding window will be deferred to
|
| 383 |
+
the first call of inflate (if the decompression does not complete on the
|
| 384 |
+
first call). If zalloc and zfree are set to Z_NULL, inflateInit updates
|
| 385 |
+
them to use default allocation functions. total_in, total_out, adler, and
|
| 386 |
+
msg are initialized.
|
| 387 |
+
|
| 388 |
+
inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
|
| 389 |
+
memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
|
| 390 |
+
version assumed by the caller, or Z_STREAM_ERROR if the parameters are
|
| 391 |
+
invalid, such as a null pointer to the structure. msg is set to null if
|
| 392 |
+
there is no error message. inflateInit does not perform any decompression.
|
| 393 |
+
Actual decompression will be done by inflate(). So next_in, and avail_in,
|
| 394 |
+
next_out, and avail_out are unused and unchanged. The current
|
| 395 |
+
implementation of inflateInit() does not process any header information --
|
| 396 |
+
that is deferred until inflate() is called.
|
| 397 |
+
*/
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
ZEXTERN int ZEXPORT inflate(z_streamp strm, int flush);
|
| 401 |
+
/*
|
| 402 |
+
inflate decompresses as much data as possible, and stops when the input
|
| 403 |
+
buffer becomes empty or the output buffer becomes full. It may introduce
|
| 404 |
+
some output latency (reading input without producing any output) except when
|
| 405 |
+
forced to flush.
|
| 406 |
+
|
| 407 |
+
The detailed semantics are as follows. inflate performs one or both of the
|
| 408 |
+
following actions:
|
| 409 |
+
|
| 410 |
+
- Decompress more input starting at next_in and update next_in and avail_in
|
| 411 |
+
accordingly. If not all input can be processed (because there is not
|
| 412 |
+
enough room in the output buffer), then next_in and avail_in are updated
|
| 413 |
+
accordingly, and processing will resume at this point for the next call of
|
| 414 |
+
inflate().
|
| 415 |
+
|
| 416 |
+
- Generate more output starting at next_out and update next_out and avail_out
|
| 417 |
+
accordingly. inflate() provides as much output as possible, until there is
|
| 418 |
+
no more input data or no more space in the output buffer (see below about
|
| 419 |
+
the flush parameter).
|
| 420 |
+
|
| 421 |
+
Before the call of inflate(), the application should ensure that at least
|
| 422 |
+
one of the actions is possible, by providing more input and/or consuming more
|
| 423 |
+
output, and updating the next_* and avail_* values accordingly. If the
|
| 424 |
+
caller of inflate() does not provide both available input and available
|
| 425 |
+
output space, it is possible that there will be no progress made. The
|
| 426 |
+
application can consume the uncompressed output when it wants, for example
|
| 427 |
+
when the output buffer is full (avail_out == 0), or after each call of
|
| 428 |
+
inflate(). If inflate returns Z_OK and with zero avail_out, it must be
|
| 429 |
+
called again after making room in the output buffer because there might be
|
| 430 |
+
more output pending.
|
| 431 |
+
|
| 432 |
+
The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH,
|
| 433 |
+
Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much
|
| 434 |
+
output as possible to the output buffer. Z_BLOCK requests that inflate()
|
| 435 |
+
stop if and when it gets to the next deflate block boundary. When decoding
|
| 436 |
+
the zlib or gzip format, this will cause inflate() to return immediately
|
| 437 |
+
after the header and before the first block. When doing a raw inflate,
|
| 438 |
+
inflate() will go ahead and process the first block, and will return when it
|
| 439 |
+
gets to the end of that block, or when it runs out of data.
|
| 440 |
+
|
| 441 |
+
The Z_BLOCK option assists in appending to or combining deflate streams.
|
| 442 |
+
To assist in this, on return inflate() always sets strm->data_type to the
|
| 443 |
+
number of unused bits in the last byte taken from strm->next_in, plus 64 if
|
| 444 |
+
inflate() is currently decoding the last block in the deflate stream, plus
|
| 445 |
+
128 if inflate() returned immediately after decoding an end-of-block code or
|
| 446 |
+
decoding the complete header up to just before the first byte of the deflate
|
| 447 |
+
stream. The end-of-block will not be indicated until all of the uncompressed
|
| 448 |
+
data from that block has been written to strm->next_out. The number of
|
| 449 |
+
unused bits may in general be greater than seven, except when bit 7 of
|
| 450 |
+
data_type is set, in which case the number of unused bits will be less than
|
| 451 |
+
eight. data_type is set as noted here every time inflate() returns for all
|
| 452 |
+
flush options, and so can be used to determine the amount of currently
|
| 453 |
+
consumed input in bits.
|
| 454 |
+
|
| 455 |
+
The Z_TREES option behaves as Z_BLOCK does, but it also returns when the
|
| 456 |
+
end of each deflate block header is reached, before any actual data in that
|
| 457 |
+
block is decoded. This allows the caller to determine the length of the
|
| 458 |
+
deflate block header for later use in random access within a deflate block.
|
| 459 |
+
256 is added to the value of strm->data_type when inflate() returns
|
| 460 |
+
immediately after reaching the end of the deflate block header.
|
| 461 |
+
|
| 462 |
+
inflate() should normally be called until it returns Z_STREAM_END or an
|
| 463 |
+
error. However if all decompression is to be performed in a single step (a
|
| 464 |
+
single call of inflate), the parameter flush should be set to Z_FINISH. In
|
| 465 |
+
this case all pending input is processed and all pending output is flushed;
|
| 466 |
+
avail_out must be large enough to hold all of the uncompressed data for the
|
| 467 |
+
operation to complete. (The size of the uncompressed data may have been
|
| 468 |
+
saved by the compressor for this purpose.) The use of Z_FINISH is not
|
| 469 |
+
required to perform an inflation in one step. However it may be used to
|
| 470 |
+
inform inflate that a faster approach can be used for the single inflate()
|
| 471 |
+
call. Z_FINISH also informs inflate to not maintain a sliding window if the
|
| 472 |
+
stream completes, which reduces inflate's memory footprint. If the stream
|
| 473 |
+
does not complete, either because not all of the stream is provided or not
|
| 474 |
+
enough output space is provided, then a sliding window will be allocated and
|
| 475 |
+
inflate() can be called again to continue the operation as if Z_NO_FLUSH had
|
| 476 |
+
been used.
|
| 477 |
+
|
| 478 |
+
In this implementation, inflate() always flushes as much output as
|
| 479 |
+
possible to the output buffer, and always uses the faster approach on the
|
| 480 |
+
first call. So the effects of the flush parameter in this implementation are
|
| 481 |
+
on the return value of inflate() as noted below, when inflate() returns early
|
| 482 |
+
when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of
|
| 483 |
+
memory for a sliding window when Z_FINISH is used.
|
| 484 |
+
|
| 485 |
+
If a preset dictionary is needed after this call (see inflateSetDictionary
|
| 486 |
+
below), inflate sets strm->adler to the Adler-32 checksum of the dictionary
|
| 487 |
+
chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
|
| 488 |
+
strm->adler to the Adler-32 checksum of all output produced so far (that is,
|
| 489 |
+
total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
|
| 490 |
+
below. At the end of the stream, inflate() checks that its computed Adler-32
|
| 491 |
+
checksum is equal to that saved by the compressor and returns Z_STREAM_END
|
| 492 |
+
only if the checksum is correct.
|
| 493 |
+
|
| 494 |
+
inflate() can decompress and check either zlib-wrapped or gzip-wrapped
|
| 495 |
+
deflate data. The header type is detected automatically, if requested when
|
| 496 |
+
initializing with inflateInit2(). Any information contained in the gzip
|
| 497 |
+
header is not retained unless inflateGetHeader() is used. When processing
|
| 498 |
+
gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output
|
| 499 |
+
produced so far. The CRC-32 is checked against the gzip trailer, as is the
|
| 500 |
+
uncompressed length, modulo 2^32.
|
| 501 |
+
|
| 502 |
+
inflate() returns Z_OK if some progress has been made (more input processed
|
| 503 |
+
or more output produced), Z_STREAM_END if the end of the compressed data has
|
| 504 |
+
been reached and all uncompressed output has been produced, Z_NEED_DICT if a
|
| 505 |
+
preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
|
| 506 |
+
corrupted (input stream not conforming to the zlib format or incorrect check
|
| 507 |
+
value, in which case strm->msg points to a string with a more specific
|
| 508 |
+
error), Z_STREAM_ERROR if the stream structure was inconsistent (for example
|
| 509 |
+
next_in or next_out was Z_NULL, or the state was inadvertently written over
|
| 510 |
+
by the application), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR
|
| 511 |
+
if no progress was possible or if there was not enough room in the output
|
| 512 |
+
buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
|
| 513 |
+
inflate() can be called again with more input and more output space to
|
| 514 |
+
continue decompressing. If Z_DATA_ERROR is returned, the application may
|
| 515 |
+
then call inflateSync() to look for a good compression block if a partial
|
| 516 |
+
recovery of the data is to be attempted.
|
| 517 |
+
*/
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
ZEXTERN int ZEXPORT inflateEnd(z_streamp strm);
|
| 521 |
+
/*
|
| 522 |
+
All dynamically allocated data structures for this stream are freed.
|
| 523 |
+
This function discards any unprocessed input and does not flush any pending
|
| 524 |
+
output.
|
| 525 |
+
|
| 526 |
+
inflateEnd returns Z_OK if success, or Z_STREAM_ERROR if the stream state
|
| 527 |
+
was inconsistent.
|
| 528 |
+
*/
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
/* Advanced functions */
|
| 532 |
+
|
| 533 |
+
/*
|
| 534 |
+
The following functions are needed only in some special applications.
|
| 535 |
+
*/
|
| 536 |
+
|
| 537 |
+
/*
|
| 538 |
+
ZEXTERN int ZEXPORT deflateInit2(z_streamp strm,
|
| 539 |
+
int level,
|
| 540 |
+
int method,
|
| 541 |
+
int windowBits,
|
| 542 |
+
int memLevel,
|
| 543 |
+
int strategy);
|
| 544 |
+
|
| 545 |
+
This is another version of deflateInit with more compression options. The
|
| 546 |
+
fields zalloc, zfree and opaque must be initialized before by the caller.
|
| 547 |
+
|
| 548 |
+
The method parameter is the compression method. It must be Z_DEFLATED in
|
| 549 |
+
this version of the library.
|
| 550 |
+
|
| 551 |
+
The windowBits parameter is the base two logarithm of the window size
|
| 552 |
+
(the size of the history buffer). It should be in the range 8..15 for this
|
| 553 |
+
version of the library. Larger values of this parameter result in better
|
| 554 |
+
compression at the expense of memory usage. The default value is 15 if
|
| 555 |
+
deflateInit is used instead.
|
| 556 |
+
|
| 557 |
+
For the current implementation of deflate(), a windowBits value of 8 (a
|
| 558 |
+
window size of 256 bytes) is not supported. As a result, a request for 8
|
| 559 |
+
will result in 9 (a 512-byte window). In that case, providing 8 to
|
| 560 |
+
inflateInit2() will result in an error when the zlib header with 9 is
|
| 561 |
+
checked against the initialization of inflate(). The remedy is to not use 8
|
| 562 |
+
with deflateInit2() with this initialization, or at least in that case use 9
|
| 563 |
+
with inflateInit2().
|
| 564 |
+
|
| 565 |
+
windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
|
| 566 |
+
determines the window size. deflate() will then generate raw deflate data
|
| 567 |
+
with no zlib header or trailer, and will not compute a check value.
|
| 568 |
+
|
| 569 |
+
windowBits can also be greater than 15 for optional gzip encoding. Add
|
| 570 |
+
16 to windowBits to write a simple gzip header and trailer around the
|
| 571 |
+
compressed data instead of a zlib wrapper. The gzip header will have no
|
| 572 |
+
file name, no extra data, no comment, no modification time (set to zero), no
|
| 573 |
+
header crc, and the operating system will be set to the appropriate value,
|
| 574 |
+
if the operating system was determined at compile time. If a gzip stream is
|
| 575 |
+
being written, strm->adler is a CRC-32 instead of an Adler-32.
|
| 576 |
+
|
| 577 |
+
For raw deflate or gzip encoding, a request for a 256-byte window is
|
| 578 |
+
rejected as invalid, since only the zlib header provides a means of
|
| 579 |
+
transmitting the window size to the decompressor.
|
| 580 |
+
|
| 581 |
+
The memLevel parameter specifies how much memory should be allocated
|
| 582 |
+
for the internal compression state. memLevel=1 uses minimum memory but is
|
| 583 |
+
slow and reduces compression ratio; memLevel=9 uses maximum memory for
|
| 584 |
+
optimal speed. The default value is 8. See zconf.h for total memory usage
|
| 585 |
+
as a function of windowBits and memLevel.
|
| 586 |
+
|
| 587 |
+
The strategy parameter is used to tune the compression algorithm. Use the
|
| 588 |
+
value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
|
| 589 |
+
filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
|
| 590 |
+
string match), or Z_RLE to limit match distances to one (run-length
|
| 591 |
+
encoding). Filtered data consists mostly of small values with a somewhat
|
| 592 |
+
random distribution. In this case, the compression algorithm is tuned to
|
| 593 |
+
compress them better. The effect of Z_FILTERED is to force more Huffman
|
| 594 |
+
coding and less string matching; it is somewhat intermediate between
|
| 595 |
+
Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as
|
| 596 |
+
fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The
|
| 597 |
+
strategy parameter only affects the compression ratio but not the
|
| 598 |
+
correctness of the compressed output even if it is not set appropriately.
|
| 599 |
+
Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler
|
| 600 |
+
decoder for special applications.
|
| 601 |
+
|
| 602 |
+
deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
|
| 603 |
+
memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid
|
| 604 |
+
method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is
|
| 605 |
+
incompatible with the version assumed by the caller (ZLIB_VERSION). msg is
|
| 606 |
+
set to null if there is no error message. deflateInit2 does not perform any
|
| 607 |
+
compression: this will be done by deflate().
|
| 608 |
+
*/
|
| 609 |
+
|
| 610 |
+
ZEXTERN int ZEXPORT deflateSetDictionary(z_streamp strm,
|
| 611 |
+
const Bytef *dictionary,
|
| 612 |
+
uInt dictLength);
|
| 613 |
+
/*
|
| 614 |
+
Initializes the compression dictionary from the given byte sequence
|
| 615 |
+
without producing any compressed output. When using the zlib format, this
|
| 616 |
+
function must be called immediately after deflateInit, deflateInit2 or
|
| 617 |
+
deflateReset, and before any call of deflate. When doing raw deflate, this
|
| 618 |
+
function must be called either before any call of deflate, or immediately
|
| 619 |
+
after the completion of a deflate block, i.e. after all input has been
|
| 620 |
+
consumed and all output has been delivered when using any of the flush
|
| 621 |
+
options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH. The
|
| 622 |
+
compressor and decompressor must use exactly the same dictionary (see
|
| 623 |
+
inflateSetDictionary).
|
| 624 |
+
|
| 625 |
+
The dictionary should consist of strings (byte sequences) that are likely
|
| 626 |
+
to be encountered later in the data to be compressed, with the most commonly
|
| 627 |
+
used strings preferably put towards the end of the dictionary. Using a
|
| 628 |
+
dictionary is most useful when the data to be compressed is short and can be
|
| 629 |
+
predicted with good accuracy; the data can then be compressed better than
|
| 630 |
+
with the default empty dictionary.
|
| 631 |
+
|
| 632 |
+
Depending on the size of the compression data structures selected by
|
| 633 |
+
deflateInit or deflateInit2, a part of the dictionary may in effect be
|
| 634 |
+
discarded, for example if the dictionary is larger than the window size
|
| 635 |
+
provided in deflateInit or deflateInit2. Thus the strings most likely to be
|
| 636 |
+
useful should be put at the end of the dictionary, not at the front. In
|
| 637 |
+
addition, the current implementation of deflate will use at most the window
|
| 638 |
+
size minus 262 bytes of the provided dictionary.
|
| 639 |
+
|
| 640 |
+
Upon return of this function, strm->adler is set to the Adler-32 value
|
| 641 |
+
of the dictionary; the decompressor may later use this value to determine
|
| 642 |
+
which dictionary has been used by the compressor. (The Adler-32 value
|
| 643 |
+
applies to the whole dictionary even if only a subset of the dictionary is
|
| 644 |
+
actually used by the compressor.) If a raw deflate was requested, then the
|
| 645 |
+
Adler-32 value is not computed and strm->adler is not set.
|
| 646 |
+
|
| 647 |
+
deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
|
| 648 |
+
parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is
|
| 649 |
+
inconsistent (for example if deflate has already been called for this stream
|
| 650 |
+
or if not at a block boundary for raw deflate). deflateSetDictionary does
|
| 651 |
+
not perform any compression: this will be done by deflate().
|
| 652 |
+
*/
|
| 653 |
+
|
| 654 |
+
ZEXTERN int ZEXPORT deflateGetDictionary(z_streamp strm,
|
| 655 |
+
Bytef *dictionary,
|
| 656 |
+
uInt *dictLength);
|
| 657 |
+
/*
|
| 658 |
+
Returns the sliding dictionary being maintained by deflate. dictLength is
|
| 659 |
+
set to the number of bytes in the dictionary, and that many bytes are copied
|
| 660 |
+
to dictionary. dictionary must have enough space, where 32768 bytes is
|
| 661 |
+
always enough. If deflateGetDictionary() is called with dictionary equal to
|
| 662 |
+
Z_NULL, then only the dictionary length is returned, and nothing is copied.
|
| 663 |
+
Similarly, if dictLength is Z_NULL, then it is not set.
|
| 664 |
+
|
| 665 |
+
deflateGetDictionary() may return a length less than the window size, even
|
| 666 |
+
when more than the window size in input has been provided. It may return up
|
| 667 |
+
to 258 bytes less in that case, due to how zlib's implementation of deflate
|
| 668 |
+
manages the sliding window and lookahead for matches, where matches can be
|
| 669 |
+
up to 258 bytes long. If the application needs the last window-size bytes of
|
| 670 |
+
input, then that would need to be saved by the application outside of zlib.
|
| 671 |
+
|
| 672 |
+
deflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the
|
| 673 |
+
stream state is inconsistent.
|
| 674 |
+
*/
|
| 675 |
+
|
| 676 |
+
ZEXTERN int ZEXPORT deflateCopy(z_streamp dest,
|
| 677 |
+
z_streamp source);
|
| 678 |
+
/*
|
| 679 |
+
Sets the destination stream as a complete copy of the source stream.
|
| 680 |
+
|
| 681 |
+
This function can be useful when several compression strategies will be
|
| 682 |
+
tried, for example when there are several ways of pre-processing the input
|
| 683 |
+
data with a filter. The streams that will be discarded should then be freed
|
| 684 |
+
by calling deflateEnd. Note that deflateCopy duplicates the internal
|
| 685 |
+
compression state which can be quite large, so this strategy is slow and can
|
| 686 |
+
consume lots of memory.
|
| 687 |
+
|
| 688 |
+
deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
|
| 689 |
+
enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
|
| 690 |
+
(such as zalloc being Z_NULL). msg is left unchanged in both source and
|
| 691 |
+
destination.
|
| 692 |
+
*/
|
| 693 |
+
|
| 694 |
+
ZEXTERN int ZEXPORT deflateReset(z_streamp strm);
|
| 695 |
+
/*
|
| 696 |
+
This function is equivalent to deflateEnd followed by deflateInit, but
|
| 697 |
+
does not free and reallocate the internal compression state. The stream
|
| 698 |
+
will leave the compression level and any other attributes that may have been
|
| 699 |
+
set unchanged. total_in, total_out, adler, and msg are initialized.
|
| 700 |
+
|
| 701 |
+
deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
|
| 702 |
+
stream state was inconsistent (such as zalloc or state being Z_NULL).
|
| 703 |
+
*/
|
| 704 |
+
|
| 705 |
+
ZEXTERN int ZEXPORT deflateParams(z_streamp strm,
|
| 706 |
+
int level,
|
| 707 |
+
int strategy);
|
| 708 |
+
/*
|
| 709 |
+
Dynamically update the compression level and compression strategy. The
|
| 710 |
+
interpretation of level and strategy is as in deflateInit2(). This can be
|
| 711 |
+
used to switch between compression and straight copy of the input data, or
|
| 712 |
+
to switch to a different kind of input data requiring a different strategy.
|
| 713 |
+
If the compression approach (which is a function of the level) or the
|
| 714 |
+
strategy is changed, and if there have been any deflate() calls since the
|
| 715 |
+
state was initialized or reset, then the input available so far is
|
| 716 |
+
compressed with the old level and strategy using deflate(strm, Z_BLOCK).
|
| 717 |
+
There are three approaches for the compression levels 0, 1..3, and 4..9
|
| 718 |
+
respectively. The new level and strategy will take effect at the next call
|
| 719 |
+
of deflate().
|
| 720 |
+
|
| 721 |
+
If a deflate(strm, Z_BLOCK) is performed by deflateParams(), and it does
|
| 722 |
+
not have enough output space to complete, then the parameter change will not
|
| 723 |
+
take effect. In this case, deflateParams() can be called again with the
|
| 724 |
+
same parameters and more output space to try again.
|
| 725 |
+
|
| 726 |
+
In order to assure a change in the parameters on the first try, the
|
| 727 |
+
deflate stream should be flushed using deflate() with Z_BLOCK or other flush
|
| 728 |
+
request until strm.avail_out is not zero, before calling deflateParams().
|
| 729 |
+
Then no more input data should be provided before the deflateParams() call.
|
| 730 |
+
If this is done, the old level and strategy will be applied to the data
|
| 731 |
+
compressed before deflateParams(), and the new level and strategy will be
|
| 732 |
+
applied to the data compressed after deflateParams().
|
| 733 |
+
|
| 734 |
+
deflateParams returns Z_OK on success, Z_STREAM_ERROR if the source stream
|
| 735 |
+
state was inconsistent or if a parameter was invalid, or Z_BUF_ERROR if
|
| 736 |
+
there was not enough output space to complete the compression of the
|
| 737 |
+
available input data before a change in the strategy or approach. Note that
|
| 738 |
+
in the case of a Z_BUF_ERROR, the parameters are not changed. A return
|
| 739 |
+
value of Z_BUF_ERROR is not fatal, in which case deflateParams() can be
|
| 740 |
+
retried with more output space.
|
| 741 |
+
*/
|
| 742 |
+
|
| 743 |
+
ZEXTERN int ZEXPORT deflateTune(z_streamp strm,
|
| 744 |
+
int good_length,
|
| 745 |
+
int max_lazy,
|
| 746 |
+
int nice_length,
|
| 747 |
+
int max_chain);
|
| 748 |
+
/*
|
| 749 |
+
Fine tune deflate's internal compression parameters. This should only be
|
| 750 |
+
used by someone who understands the algorithm used by zlib's deflate for
|
| 751 |
+
searching for the best matching string, and even then only by the most
|
| 752 |
+
fanatic optimizer trying to squeeze out the last compressed bit for their
|
| 753 |
+
specific input data. Read the deflate.c source code for the meaning of the
|
| 754 |
+
max_lazy, good_length, nice_length, and max_chain parameters.
|
| 755 |
+
|
| 756 |
+
deflateTune() can be called after deflateInit() or deflateInit2(), and
|
| 757 |
+
returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
|
| 758 |
+
*/
|
| 759 |
+
|
| 760 |
+
ZEXTERN uLong ZEXPORT deflateBound(z_streamp strm,
|
| 761 |
+
uLong sourceLen);
|
| 762 |
+
/*
|
| 763 |
+
deflateBound() returns an upper bound on the compressed size after
|
| 764 |
+
deflation of sourceLen bytes. It must be called after deflateInit() or
|
| 765 |
+
deflateInit2(), and after deflateSetHeader(), if used. This would be used
|
| 766 |
+
to allocate an output buffer for deflation in a single pass, and so would be
|
| 767 |
+
called before deflate(). If that first deflate() call is provided the
|
| 768 |
+
sourceLen input bytes, an output buffer allocated to the size returned by
|
| 769 |
+
deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed
|
| 770 |
+
to return Z_STREAM_END. Note that it is possible for the compressed size to
|
| 771 |
+
be larger than the value returned by deflateBound() if flush options other
|
| 772 |
+
than Z_FINISH or Z_NO_FLUSH are used.
|
| 773 |
+
*/
|
| 774 |
+
|
| 775 |
+
ZEXTERN int ZEXPORT deflatePending(z_streamp strm,
|
| 776 |
+
unsigned *pending,
|
| 777 |
+
int *bits);
|
| 778 |
+
/*
|
| 779 |
+
deflatePending() returns the number of bytes and bits of output that have
|
| 780 |
+
been generated, but not yet provided in the available output. The bytes not
|
| 781 |
+
provided would be due to the available output space having being consumed.
|
| 782 |
+
The number of bits of output not provided are between 0 and 7, where they
|
| 783 |
+
await more bits to join them in order to fill out a full byte. If pending
|
| 784 |
+
or bits are Z_NULL, then those values are not set.
|
| 785 |
+
|
| 786 |
+
deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source
|
| 787 |
+
stream state was inconsistent.
|
| 788 |
+
*/
|
| 789 |
+
|
| 790 |
+
ZEXTERN int ZEXPORT deflatePrime(z_streamp strm,
|
| 791 |
+
int bits,
|
| 792 |
+
int value);
|
| 793 |
+
/*
|
| 794 |
+
deflatePrime() inserts bits in the deflate output stream. The intent
|
| 795 |
+
is that this function is used to start off the deflate output with the bits
|
| 796 |
+
leftover from a previous deflate stream when appending to it. As such, this
|
| 797 |
+
function can only be used for raw deflate, and must be used before the first
|
| 798 |
+
deflate() call after a deflateInit2() or deflateReset(). bits must be less
|
| 799 |
+
than or equal to 16, and that many of the least significant bits of value
|
| 800 |
+
will be inserted in the output.
|
| 801 |
+
|
| 802 |
+
deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough
|
| 803 |
+
room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the
|
| 804 |
+
source stream state was inconsistent.
|
| 805 |
+
*/
|
| 806 |
+
|
| 807 |
+
ZEXTERN int ZEXPORT deflateSetHeader(z_streamp strm,
|
| 808 |
+
gz_headerp head);
|
| 809 |
+
/*
|
| 810 |
+
deflateSetHeader() provides gzip header information for when a gzip
|
| 811 |
+
stream is requested by deflateInit2(). deflateSetHeader() may be called
|
| 812 |
+
after deflateInit2() or deflateReset() and before the first call of
|
| 813 |
+
deflate(). The text, time, os, extra field, name, and comment information
|
| 814 |
+
in the provided gz_header structure are written to the gzip header (xflag is
|
| 815 |
+
ignored -- the extra flags are set according to the compression level). The
|
| 816 |
+
caller must assure that, if not Z_NULL, name and comment are terminated with
|
| 817 |
+
a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
|
| 818 |
+
available there. If hcrc is true, a gzip header crc is included. Note that
|
| 819 |
+
the current versions of the command-line version of gzip (up through version
|
| 820 |
+
1.3.x) do not support header crc's, and will report that it is a "multi-part
|
| 821 |
+
gzip file" and give up.
|
| 822 |
+
|
| 823 |
+
If deflateSetHeader is not used, the default gzip header has text false,
|
| 824 |
+
the time set to zero, and os set to the current operating system, with no
|
| 825 |
+
extra, name, or comment fields. The gzip header is returned to the default
|
| 826 |
+
state by deflateReset().
|
| 827 |
+
|
| 828 |
+
deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
|
| 829 |
+
stream state was inconsistent.
|
| 830 |
+
*/
|
| 831 |
+
|
| 832 |
+
/*
|
| 833 |
+
ZEXTERN int ZEXPORT inflateInit2(z_streamp strm,
|
| 834 |
+
int windowBits);
|
| 835 |
+
|
| 836 |
+
This is another version of inflateInit with an extra parameter. The
|
| 837 |
+
fields next_in, avail_in, zalloc, zfree and opaque must be initialized
|
| 838 |
+
before by the caller.
|
| 839 |
+
|
| 840 |
+
The windowBits parameter is the base two logarithm of the maximum window
|
| 841 |
+
size (the size of the history buffer). It should be in the range 8..15 for
|
| 842 |
+
this version of the library. The default value is 15 if inflateInit is used
|
| 843 |
+
instead. windowBits must be greater than or equal to the windowBits value
|
| 844 |
+
provided to deflateInit2() while compressing, or it must be equal to 15 if
|
| 845 |
+
deflateInit2() was not used. If a compressed stream with a larger window
|
| 846 |
+
size is given as input, inflate() will return with the error code
|
| 847 |
+
Z_DATA_ERROR instead of trying to allocate a larger window.
|
| 848 |
+
|
| 849 |
+
windowBits can also be zero to request that inflate use the window size in
|
| 850 |
+
the zlib header of the compressed stream.
|
| 851 |
+
|
| 852 |
+
windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
|
| 853 |
+
determines the window size. inflate() will then process raw deflate data,
|
| 854 |
+
not looking for a zlib or gzip header, not generating a check value, and not
|
| 855 |
+
looking for any check values for comparison at the end of the stream. This
|
| 856 |
+
is for use with other formats that use the deflate compressed data format
|
| 857 |
+
such as zip. Those formats provide their own check values. If a custom
|
| 858 |
+
format is developed using the raw deflate format for compressed data, it is
|
| 859 |
+
recommended that a check value such as an Adler-32 or a CRC-32 be applied to
|
| 860 |
+
the uncompressed data as is done in the zlib, gzip, and zip formats. For
|
| 861 |
+
most applications, the zlib format should be used as is. Note that comments
|
| 862 |
+
above on the use in deflateInit2() applies to the magnitude of windowBits.
|
| 863 |
+
|
| 864 |
+
windowBits can also be greater than 15 for optional gzip decoding. Add
|
| 865 |
+
32 to windowBits to enable zlib and gzip decoding with automatic header
|
| 866 |
+
detection, or add 16 to decode only the gzip format (the zlib format will
|
| 867 |
+
return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a
|
| 868 |
+
CRC-32 instead of an Adler-32. Unlike the gunzip utility and gzread() (see
|
| 869 |
+
below), inflate() will *not* automatically decode concatenated gzip members.
|
| 870 |
+
inflate() will return Z_STREAM_END at the end of the gzip member. The state
|
| 871 |
+
would need to be reset to continue decoding a subsequent gzip member. This
|
| 872 |
+
*must* be done if there is more data after a gzip member, in order for the
|
| 873 |
+
decompression to be compliant with the gzip standard (RFC 1952).
|
| 874 |
+
|
| 875 |
+
inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
|
| 876 |
+
memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
|
| 877 |
+
version assumed by the caller, or Z_STREAM_ERROR if the parameters are
|
| 878 |
+
invalid, such as a null pointer to the structure. msg is set to null if
|
| 879 |
+
there is no error message. inflateInit2 does not perform any decompression
|
| 880 |
+
apart from possibly reading the zlib header if present: actual decompression
|
| 881 |
+
will be done by inflate(). (So next_in and avail_in may be modified, but
|
| 882 |
+
next_out and avail_out are unused and unchanged.) The current implementation
|
| 883 |
+
of inflateInit2() does not process any header information -- that is
|
| 884 |
+
deferred until inflate() is called.
|
| 885 |
+
*/
|
| 886 |
+
|
| 887 |
+
ZEXTERN int ZEXPORT inflateSetDictionary(z_streamp strm,
|
| 888 |
+
const Bytef *dictionary,
|
| 889 |
+
uInt dictLength);
|
| 890 |
+
/*
|
| 891 |
+
Initializes the decompression dictionary from the given uncompressed byte
|
| 892 |
+
sequence. This function must be called immediately after a call of inflate,
|
| 893 |
+
if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
|
| 894 |
+
can be determined from the Adler-32 value returned by that call of inflate.
|
| 895 |
+
The compressor and decompressor must use exactly the same dictionary (see
|
| 896 |
+
deflateSetDictionary). For raw inflate, this function can be called at any
|
| 897 |
+
time to set the dictionary. If the provided dictionary is smaller than the
|
| 898 |
+
window and there is already data in the window, then the provided dictionary
|
| 899 |
+
will amend what's there. The application must insure that the dictionary
|
| 900 |
+
that was used for compression is provided.
|
| 901 |
+
|
| 902 |
+
inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
|
| 903 |
+
parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is
|
| 904 |
+
inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
|
| 905 |
+
expected one (incorrect Adler-32 value). inflateSetDictionary does not
|
| 906 |
+
perform any decompression: this will be done by subsequent calls of
|
| 907 |
+
inflate().
|
| 908 |
+
*/
|
| 909 |
+
|
| 910 |
+
ZEXTERN int ZEXPORT inflateGetDictionary(z_streamp strm,
|
| 911 |
+
Bytef *dictionary,
|
| 912 |
+
uInt *dictLength);
|
| 913 |
+
/*
|
| 914 |
+
Returns the sliding dictionary being maintained by inflate. dictLength is
|
| 915 |
+
set to the number of bytes in the dictionary, and that many bytes are copied
|
| 916 |
+
to dictionary. dictionary must have enough space, where 32768 bytes is
|
| 917 |
+
always enough. If inflateGetDictionary() is called with dictionary equal to
|
| 918 |
+
Z_NULL, then only the dictionary length is returned, and nothing is copied.
|
| 919 |
+
Similarly, if dictLength is Z_NULL, then it is not set.
|
| 920 |
+
|
| 921 |
+
inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the
|
| 922 |
+
stream state is inconsistent.
|
| 923 |
+
*/
|
| 924 |
+
|
| 925 |
+
ZEXTERN int ZEXPORT inflateSync(z_streamp strm);
|
| 926 |
+
/*
|
| 927 |
+
Skips invalid compressed data until a possible full flush point (see above
|
| 928 |
+
for the description of deflate with Z_FULL_FLUSH) can be found, or until all
|
| 929 |
+
available input is skipped. No output is provided.
|
| 930 |
+
|
| 931 |
+
inflateSync searches for a 00 00 FF FF pattern in the compressed data.
|
| 932 |
+
All full flush points have this pattern, but not all occurrences of this
|
| 933 |
+
pattern are full flush points.
|
| 934 |
+
|
| 935 |
+
inflateSync returns Z_OK if a possible full flush point has been found,
|
| 936 |
+
Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point
|
| 937 |
+
has been found, or Z_STREAM_ERROR if the stream structure was inconsistent.
|
| 938 |
+
In the success case, the application may save the current value of total_in
|
| 939 |
+
which indicates where valid compressed data was found. In the error case,
|
| 940 |
+
the application may repeatedly call inflateSync, providing more input each
|
| 941 |
+
time, until success or end of the input data.
|
| 942 |
+
*/
|
| 943 |
+
|
| 944 |
+
ZEXTERN int ZEXPORT inflateCopy(z_streamp dest,
|
| 945 |
+
z_streamp source);
|
| 946 |
+
/*
|
| 947 |
+
Sets the destination stream as a complete copy of the source stream.
|
| 948 |
+
|
| 949 |
+
This function can be useful when randomly accessing a large stream. The
|
| 950 |
+
first pass through the stream can periodically record the inflate state,
|
| 951 |
+
allowing restarting inflate at those points when randomly accessing the
|
| 952 |
+
stream.
|
| 953 |
+
|
| 954 |
+
inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
|
| 955 |
+
enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
|
| 956 |
+
(such as zalloc being Z_NULL). msg is left unchanged in both source and
|
| 957 |
+
destination.
|
| 958 |
+
*/
|
| 959 |
+
|
| 960 |
+
ZEXTERN int ZEXPORT inflateReset(z_streamp strm);
|
| 961 |
+
/*
|
| 962 |
+
This function is equivalent to inflateEnd followed by inflateInit,
|
| 963 |
+
but does not free and reallocate the internal decompression state. The
|
| 964 |
+
stream will keep attributes that may have been set by inflateInit2.
|
| 965 |
+
total_in, total_out, adler, and msg are initialized.
|
| 966 |
+
|
| 967 |
+
inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
|
| 968 |
+
stream state was inconsistent (such as zalloc or state being Z_NULL).
|
| 969 |
+
*/
|
| 970 |
+
|
| 971 |
+
ZEXTERN int ZEXPORT inflateReset2(z_streamp strm,
|
| 972 |
+
int windowBits);
|
| 973 |
+
/*
|
| 974 |
+
This function is the same as inflateReset, but it also permits changing
|
| 975 |
+
the wrap and window size requests. The windowBits parameter is interpreted
|
| 976 |
+
the same as it is for inflateInit2. If the window size is changed, then the
|
| 977 |
+
memory allocated for the window is freed, and the window will be reallocated
|
| 978 |
+
by inflate() if needed.
|
| 979 |
+
|
| 980 |
+
inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source
|
| 981 |
+
stream state was inconsistent (such as zalloc or state being Z_NULL), or if
|
| 982 |
+
the windowBits parameter is invalid.
|
| 983 |
+
*/
|
| 984 |
+
|
| 985 |
+
ZEXTERN int ZEXPORT inflatePrime(z_streamp strm,
|
| 986 |
+
int bits,
|
| 987 |
+
int value);
|
| 988 |
+
/*
|
| 989 |
+
This function inserts bits in the inflate input stream. The intent is
|
| 990 |
+
that this function is used to start inflating at a bit position in the
|
| 991 |
+
middle of a byte. The provided bits will be used before any bytes are used
|
| 992 |
+
from next_in. This function should only be used with raw inflate, and
|
| 993 |
+
should be used before the first inflate() call after inflateInit2() or
|
| 994 |
+
inflateReset(). bits must be less than or equal to 16, and that many of the
|
| 995 |
+
least significant bits of value will be inserted in the input.
|
| 996 |
+
|
| 997 |
+
If bits is negative, then the input stream bit buffer is emptied. Then
|
| 998 |
+
inflatePrime() can be called again to put bits in the buffer. This is used
|
| 999 |
+
to clear out bits leftover after feeding inflate a block description prior
|
| 1000 |
+
to feeding inflate codes.
|
| 1001 |
+
|
| 1002 |
+
inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
|
| 1003 |
+
stream state was inconsistent.
|
| 1004 |
+
*/
|
| 1005 |
+
|
| 1006 |
+
ZEXTERN long ZEXPORT inflateMark(z_streamp strm);
|
| 1007 |
+
/*
|
| 1008 |
+
This function returns two values, one in the lower 16 bits of the return
|
| 1009 |
+
value, and the other in the remaining upper bits, obtained by shifting the
|
| 1010 |
+
return value down 16 bits. If the upper value is -1 and the lower value is
|
| 1011 |
+
zero, then inflate() is currently decoding information outside of a block.
|
| 1012 |
+
If the upper value is -1 and the lower value is non-zero, then inflate is in
|
| 1013 |
+
the middle of a stored block, with the lower value equaling the number of
|
| 1014 |
+
bytes from the input remaining to copy. If the upper value is not -1, then
|
| 1015 |
+
it is the number of bits back from the current bit position in the input of
|
| 1016 |
+
the code (literal or length/distance pair) currently being processed. In
|
| 1017 |
+
that case the lower value is the number of bytes already emitted for that
|
| 1018 |
+
code.
|
| 1019 |
+
|
| 1020 |
+
A code is being processed if inflate is waiting for more input to complete
|
| 1021 |
+
decoding of the code, or if it has completed decoding but is waiting for
|
| 1022 |
+
more output space to write the literal or match data.
|
| 1023 |
+
|
| 1024 |
+
inflateMark() is used to mark locations in the input data for random
|
| 1025 |
+
access, which may be at bit positions, and to note those cases where the
|
| 1026 |
+
output of a code may span boundaries of random access blocks. The current
|
| 1027 |
+
location in the input stream can be determined from avail_in and data_type
|
| 1028 |
+
as noted in the description for the Z_BLOCK flush parameter for inflate.
|
| 1029 |
+
|
| 1030 |
+
inflateMark returns the value noted above, or -65536 if the provided
|
| 1031 |
+
source stream state was inconsistent.
|
| 1032 |
+
*/
|
| 1033 |
+
|
| 1034 |
+
ZEXTERN int ZEXPORT inflateGetHeader(z_streamp strm,
|
| 1035 |
+
gz_headerp head);
|
| 1036 |
+
/*
|
| 1037 |
+
inflateGetHeader() requests that gzip header information be stored in the
|
| 1038 |
+
provided gz_header structure. inflateGetHeader() may be called after
|
| 1039 |
+
inflateInit2() or inflateReset(), and before the first call of inflate().
|
| 1040 |
+
As inflate() processes the gzip stream, head->done is zero until the header
|
| 1041 |
+
is completed, at which time head->done is set to one. If a zlib stream is
|
| 1042 |
+
being decoded, then head->done is set to -1 to indicate that there will be
|
| 1043 |
+
no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be
|
| 1044 |
+
used to force inflate() to return immediately after header processing is
|
| 1045 |
+
complete and before any actual data is decompressed.
|
| 1046 |
+
|
| 1047 |
+
The text, time, xflags, and os fields are filled in with the gzip header
|
| 1048 |
+
contents. hcrc is set to true if there is a header CRC. (The header CRC
|
| 1049 |
+
was valid if done is set to one.) If extra is not Z_NULL, then extra_max
|
| 1050 |
+
contains the maximum number of bytes to write to extra. Once done is true,
|
| 1051 |
+
extra_len contains the actual extra field length, and extra contains the
|
| 1052 |
+
extra field, or that field truncated if extra_max is less than extra_len.
|
| 1053 |
+
If name is not Z_NULL, then up to name_max characters are written there,
|
| 1054 |
+
terminated with a zero unless the length is greater than name_max. If
|
| 1055 |
+
comment is not Z_NULL, then up to comm_max characters are written there,
|
| 1056 |
+
terminated with a zero unless the length is greater than comm_max. When any
|
| 1057 |
+
of extra, name, or comment are not Z_NULL and the respective field is not
|
| 1058 |
+
present in the header, then that field is set to Z_NULL to signal its
|
| 1059 |
+
absence. This allows the use of deflateSetHeader() with the returned
|
| 1060 |
+
structure to duplicate the header. However if those fields are set to
|
| 1061 |
+
allocated memory, then the application will need to save those pointers
|
| 1062 |
+
elsewhere so that they can be eventually freed.
|
| 1063 |
+
|
| 1064 |
+
If inflateGetHeader is not used, then the header information is simply
|
| 1065 |
+
discarded. The header is always checked for validity, including the header
|
| 1066 |
+
CRC if present. inflateReset() will reset the process to discard the header
|
| 1067 |
+
information. The application would need to call inflateGetHeader() again to
|
| 1068 |
+
retrieve the header from the next gzip stream.
|
| 1069 |
+
|
| 1070 |
+
inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
|
| 1071 |
+
stream state was inconsistent.
|
| 1072 |
+
*/
|
| 1073 |
+
|
| 1074 |
+
/*
|
| 1075 |
+
ZEXTERN int ZEXPORT inflateBackInit(z_streamp strm, int windowBits,
|
| 1076 |
+
unsigned char FAR *window);
|
| 1077 |
+
|
| 1078 |
+
Initialize the internal stream state for decompression using inflateBack()
|
| 1079 |
+
calls. The fields zalloc, zfree and opaque in strm must be initialized
|
| 1080 |
+
before the call. If zalloc and zfree are Z_NULL, then the default library-
|
| 1081 |
+
derived memory allocation routines are used. windowBits is the base two
|
| 1082 |
+
logarithm of the window size, in the range 8..15. window is a caller
|
| 1083 |
+
supplied buffer of that size. Except for special applications where it is
|
| 1084 |
+
assured that deflate was used with small window sizes, windowBits must be 15
|
| 1085 |
+
and a 32K byte window must be supplied to be able to decompress general
|
| 1086 |
+
deflate streams.
|
| 1087 |
+
|
| 1088 |
+
See inflateBack() for the usage of these routines.
|
| 1089 |
+
|
| 1090 |
+
inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
|
| 1091 |
+
the parameters are invalid, Z_MEM_ERROR if the internal state could not be
|
| 1092 |
+
allocated, or Z_VERSION_ERROR if the version of the library does not match
|
| 1093 |
+
the version of the header file.
|
| 1094 |
+
*/
|
| 1095 |
+
|
| 1096 |
+
typedef unsigned (*in_func)(void FAR *,
|
| 1097 |
+
z_const unsigned char FAR * FAR *);
|
| 1098 |
+
typedef int (*out_func)(void FAR *, unsigned char FAR *, unsigned);
|
| 1099 |
+
|
| 1100 |
+
ZEXTERN int ZEXPORT inflateBack(z_streamp strm,
|
| 1101 |
+
in_func in, void FAR *in_desc,
|
| 1102 |
+
out_func out, void FAR *out_desc);
|
| 1103 |
+
/*
|
| 1104 |
+
inflateBack() does a raw inflate with a single call using a call-back
|
| 1105 |
+
interface for input and output. This is potentially more efficient than
|
| 1106 |
+
inflate() for file i/o applications, in that it avoids copying between the
|
| 1107 |
+
output and the sliding window by simply making the window itself the output
|
| 1108 |
+
buffer. inflate() can be faster on modern CPUs when used with large
|
| 1109 |
+
buffers. inflateBack() trusts the application to not change the output
|
| 1110 |
+
buffer passed by the output function, at least until inflateBack() returns.
|
| 1111 |
+
|
| 1112 |
+
inflateBackInit() must be called first to allocate the internal state
|
| 1113 |
+
and to initialize the state with the user-provided window buffer.
|
| 1114 |
+
inflateBack() may then be used multiple times to inflate a complete, raw
|
| 1115 |
+
deflate stream with each call. inflateBackEnd() is then called to free the
|
| 1116 |
+
allocated state.
|
| 1117 |
+
|
| 1118 |
+
A raw deflate stream is one with no zlib or gzip header or trailer.
|
| 1119 |
+
This routine would normally be used in a utility that reads zip or gzip
|
| 1120 |
+
files and writes out uncompressed files. The utility would decode the
|
| 1121 |
+
header and process the trailer on its own, hence this routine expects only
|
| 1122 |
+
the raw deflate stream to decompress. This is different from the default
|
| 1123 |
+
behavior of inflate(), which expects a zlib header and trailer around the
|
| 1124 |
+
deflate stream.
|
| 1125 |
+
|
| 1126 |
+
inflateBack() uses two subroutines supplied by the caller that are then
|
| 1127 |
+
called by inflateBack() for input and output. inflateBack() calls those
|
| 1128 |
+
routines until it reads a complete deflate stream and writes out all of the
|
| 1129 |
+
uncompressed data, or until it encounters an error. The function's
|
| 1130 |
+
parameters and return types are defined above in the in_func and out_func
|
| 1131 |
+
typedefs. inflateBack() will call in(in_desc, &buf) which should return the
|
| 1132 |
+
number of bytes of provided input, and a pointer to that input in buf. If
|
| 1133 |
+
there is no input available, in() must return zero -- buf is ignored in that
|
| 1134 |
+
case -- and inflateBack() will return a buffer error. inflateBack() will
|
| 1135 |
+
call out(out_desc, buf, len) to write the uncompressed data buf[0..len-1].
|
| 1136 |
+
out() should return zero on success, or non-zero on failure. If out()
|
| 1137 |
+
returns non-zero, inflateBack() will return with an error. Neither in() nor
|
| 1138 |
+
out() are permitted to change the contents of the window provided to
|
| 1139 |
+
inflateBackInit(), which is also the buffer that out() uses to write from.
|
| 1140 |
+
The length written by out() will be at most the window size. Any non-zero
|
| 1141 |
+
amount of input may be provided by in().
|
| 1142 |
+
|
| 1143 |
+
For convenience, inflateBack() can be provided input on the first call by
|
| 1144 |
+
setting strm->next_in and strm->avail_in. If that input is exhausted, then
|
| 1145 |
+
in() will be called. Therefore strm->next_in must be initialized before
|
| 1146 |
+
calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
|
| 1147 |
+
immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
|
| 1148 |
+
must also be initialized, and then if strm->avail_in is not zero, input will
|
| 1149 |
+
initially be taken from strm->next_in[0 .. strm->avail_in - 1].
|
| 1150 |
+
|
| 1151 |
+
The in_desc and out_desc parameters of inflateBack() is passed as the
|
| 1152 |
+
first parameter of in() and out() respectively when they are called. These
|
| 1153 |
+
descriptors can be optionally used to pass any information that the caller-
|
| 1154 |
+
supplied in() and out() functions need to do their job.
|
| 1155 |
+
|
| 1156 |
+
On return, inflateBack() will set strm->next_in and strm->avail_in to
|
| 1157 |
+
pass back any unused input that was provided by the last in() call. The
|
| 1158 |
+
return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
|
| 1159 |
+
if in() or out() returned an error, Z_DATA_ERROR if there was a format error
|
| 1160 |
+
in the deflate stream (in which case strm->msg is set to indicate the nature
|
| 1161 |
+
of the error), or Z_STREAM_ERROR if the stream was not properly initialized.
|
| 1162 |
+
In the case of Z_BUF_ERROR, an input or output error can be distinguished
|
| 1163 |
+
using strm->next_in which will be Z_NULL only if in() returned an error. If
|
| 1164 |
+
strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning
|
| 1165 |
+
non-zero. (in() will always be called before out(), so strm->next_in is
|
| 1166 |
+
assured to be defined if out() returns non-zero.) Note that inflateBack()
|
| 1167 |
+
cannot return Z_OK.
|
| 1168 |
+
*/
|
| 1169 |
+
|
| 1170 |
+
ZEXTERN int ZEXPORT inflateBackEnd(z_streamp strm);
|
| 1171 |
+
/*
|
| 1172 |
+
All memory allocated by inflateBackInit() is freed.
|
| 1173 |
+
|
| 1174 |
+
inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
|
| 1175 |
+
state was inconsistent.
|
| 1176 |
+
*/
|
| 1177 |
+
|
| 1178 |
+
ZEXTERN uLong ZEXPORT zlibCompileFlags(void);
|
| 1179 |
+
/* Return flags indicating compile-time options.
|
| 1180 |
+
|
| 1181 |
+
Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
|
| 1182 |
+
1.0: size of uInt
|
| 1183 |
+
3.2: size of uLong
|
| 1184 |
+
5.4: size of voidpf (pointer)
|
| 1185 |
+
7.6: size of z_off_t
|
| 1186 |
+
|
| 1187 |
+
Compiler, assembler, and debug options:
|
| 1188 |
+
8: ZLIB_DEBUG
|
| 1189 |
+
9: ASMV or ASMINF -- use ASM code
|
| 1190 |
+
10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
|
| 1191 |
+
11: 0 (reserved)
|
| 1192 |
+
|
| 1193 |
+
One-time table building (smaller code, but not thread-safe if true):
|
| 1194 |
+
12: BUILDFIXED -- build static block decoding tables when needed
|
| 1195 |
+
13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
|
| 1196 |
+
14,15: 0 (reserved)
|
| 1197 |
+
|
| 1198 |
+
Library content (indicates missing functionality):
|
| 1199 |
+
16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
|
| 1200 |
+
deflate code when not needed)
|
| 1201 |
+
17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
|
| 1202 |
+
and decode gzip streams (to avoid linking crc code)
|
| 1203 |
+
18-19: 0 (reserved)
|
| 1204 |
+
|
| 1205 |
+
Operation variations (changes in library functionality):
|
| 1206 |
+
20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
|
| 1207 |
+
21: FASTEST -- deflate algorithm with only one, lowest compression level
|
| 1208 |
+
22,23: 0 (reserved)
|
| 1209 |
+
|
| 1210 |
+
The sprintf variant used by gzprintf (zero is best):
|
| 1211 |
+
24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
|
| 1212 |
+
25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
|
| 1213 |
+
26: 0 = returns value, 1 = void -- 1 means inferred string length returned
|
| 1214 |
+
|
| 1215 |
+
Remainder:
|
| 1216 |
+
27-31: 0 (reserved)
|
| 1217 |
+
*/
|
| 1218 |
+
|
| 1219 |
+
#ifndef Z_SOLO
|
| 1220 |
+
|
| 1221 |
+
/* utility functions */
|
| 1222 |
+
|
| 1223 |
+
/*
|
| 1224 |
+
The following utility functions are implemented on top of the basic
|
| 1225 |
+
stream-oriented functions. To simplify the interface, some default options
|
| 1226 |
+
are assumed (compression level and memory usage, standard memory allocation
|
| 1227 |
+
functions). The source code of these utility functions can be modified if
|
| 1228 |
+
you need special options.
|
| 1229 |
+
*/
|
| 1230 |
+
|
| 1231 |
+
ZEXTERN int ZEXPORT compress(Bytef *dest, uLongf *destLen,
|
| 1232 |
+
const Bytef *source, uLong sourceLen);
|
| 1233 |
+
/*
|
| 1234 |
+
Compresses the source buffer into the destination buffer. sourceLen is
|
| 1235 |
+
the byte length of the source buffer. Upon entry, destLen is the total size
|
| 1236 |
+
of the destination buffer, which must be at least the value returned by
|
| 1237 |
+
compressBound(sourceLen). Upon exit, destLen is the actual size of the
|
| 1238 |
+
compressed data. compress() is equivalent to compress2() with a level
|
| 1239 |
+
parameter of Z_DEFAULT_COMPRESSION.
|
| 1240 |
+
|
| 1241 |
+
compress returns Z_OK if success, Z_MEM_ERROR if there was not
|
| 1242 |
+
enough memory, Z_BUF_ERROR if there was not enough room in the output
|
| 1243 |
+
buffer.
|
| 1244 |
+
*/
|
| 1245 |
+
|
| 1246 |
+
ZEXTERN int ZEXPORT compress2(Bytef *dest, uLongf *destLen,
|
| 1247 |
+
const Bytef *source, uLong sourceLen,
|
| 1248 |
+
int level);
|
| 1249 |
+
/*
|
| 1250 |
+
Compresses the source buffer into the destination buffer. The level
|
| 1251 |
+
parameter has the same meaning as in deflateInit. sourceLen is the byte
|
| 1252 |
+
length of the source buffer. Upon entry, destLen is the total size of the
|
| 1253 |
+
destination buffer, which must be at least the value returned by
|
| 1254 |
+
compressBound(sourceLen). Upon exit, destLen is the actual size of the
|
| 1255 |
+
compressed data.
|
| 1256 |
+
|
| 1257 |
+
compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
|
| 1258 |
+
memory, Z_BUF_ERROR if there was not enough room in the output buffer,
|
| 1259 |
+
Z_STREAM_ERROR if the level parameter is invalid.
|
| 1260 |
+
*/
|
| 1261 |
+
|
| 1262 |
+
ZEXTERN uLong ZEXPORT compressBound(uLong sourceLen);
|
| 1263 |
+
/*
|
| 1264 |
+
compressBound() returns an upper bound on the compressed size after
|
| 1265 |
+
compress() or compress2() on sourceLen bytes. It would be used before a
|
| 1266 |
+
compress() or compress2() call to allocate the destination buffer.
|
| 1267 |
+
*/
|
| 1268 |
+
|
| 1269 |
+
ZEXTERN int ZEXPORT uncompress(Bytef *dest, uLongf *destLen,
|
| 1270 |
+
const Bytef *source, uLong sourceLen);
|
| 1271 |
+
/*
|
| 1272 |
+
Decompresses the source buffer into the destination buffer. sourceLen is
|
| 1273 |
+
the byte length of the source buffer. Upon entry, destLen is the total size
|
| 1274 |
+
of the destination buffer, which must be large enough to hold the entire
|
| 1275 |
+
uncompressed data. (The size of the uncompressed data must have been saved
|
| 1276 |
+
previously by the compressor and transmitted to the decompressor by some
|
| 1277 |
+
mechanism outside the scope of this compression library.) Upon exit, destLen
|
| 1278 |
+
is the actual size of the uncompressed data.
|
| 1279 |
+
|
| 1280 |
+
uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
|
| 1281 |
+
enough memory, Z_BUF_ERROR if there was not enough room in the output
|
| 1282 |
+
buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. In
|
| 1283 |
+
the case where there is not enough room, uncompress() will fill the output
|
| 1284 |
+
buffer with the uncompressed data up to that point.
|
| 1285 |
+
*/
|
| 1286 |
+
|
| 1287 |
+
ZEXTERN int ZEXPORT uncompress2(Bytef *dest, uLongf *destLen,
|
| 1288 |
+
const Bytef *source, uLong *sourceLen);
|
| 1289 |
+
/*
|
| 1290 |
+
Same as uncompress, except that sourceLen is a pointer, where the
|
| 1291 |
+
length of the source is *sourceLen. On return, *sourceLen is the number of
|
| 1292 |
+
source bytes consumed.
|
| 1293 |
+
*/
|
| 1294 |
+
|
| 1295 |
+
/* gzip file access functions */
|
| 1296 |
+
|
| 1297 |
+
/*
|
| 1298 |
+
This library supports reading and writing files in gzip (.gz) format with
|
| 1299 |
+
an interface similar to that of stdio, using the functions that start with
|
| 1300 |
+
"gz". The gzip format is different from the zlib format. gzip is a gzip
|
| 1301 |
+
wrapper, documented in RFC 1952, wrapped around a deflate stream.
|
| 1302 |
+
*/
|
| 1303 |
+
|
| 1304 |
+
typedef struct gzFile_s *gzFile; /* semi-opaque gzip file descriptor */
|
| 1305 |
+
|
| 1306 |
+
/*
|
| 1307 |
+
ZEXTERN gzFile ZEXPORT gzopen(const char *path, const char *mode);
|
| 1308 |
+
|
| 1309 |
+
Open the gzip (.gz) file at path for reading and decompressing, or
|
| 1310 |
+
compressing and writing. The mode parameter is as in fopen ("rb" or "wb")
|
| 1311 |
+
but can also include a compression level ("wb9") or a strategy: 'f' for
|
| 1312 |
+
filtered data as in "wb6f", 'h' for Huffman-only compression as in "wb1h",
|
| 1313 |
+
'R' for run-length encoding as in "wb1R", or 'F' for fixed code compression
|
| 1314 |
+
as in "wb9F". (See the description of deflateInit2 for more information
|
| 1315 |
+
about the strategy parameter.) 'T' will request transparent writing or
|
| 1316 |
+
appending with no compression and not using the gzip format.
|
| 1317 |
+
|
| 1318 |
+
"a" can be used instead of "w" to request that the gzip stream that will
|
| 1319 |
+
be written be appended to the file. "+" will result in an error, since
|
| 1320 |
+
reading and writing to the same gzip file is not supported. The addition of
|
| 1321 |
+
"x" when writing will create the file exclusively, which fails if the file
|
| 1322 |
+
already exists. On systems that support it, the addition of "e" when
|
| 1323 |
+
reading or writing will set the flag to close the file on an execve() call.
|
| 1324 |
+
|
| 1325 |
+
These functions, as well as gzip, will read and decode a sequence of gzip
|
| 1326 |
+
streams in a file. The append function of gzopen() can be used to create
|
| 1327 |
+
such a file. (Also see gzflush() for another way to do this.) When
|
| 1328 |
+
appending, gzopen does not test whether the file begins with a gzip stream,
|
| 1329 |
+
nor does it look for the end of the gzip streams to begin appending. gzopen
|
| 1330 |
+
will simply append a gzip stream to the existing file.
|
| 1331 |
+
|
| 1332 |
+
gzopen can be used to read a file which is not in gzip format; in this
|
| 1333 |
+
case gzread will directly read from the file without decompression. When
|
| 1334 |
+
reading, this will be detected automatically by looking for the magic two-
|
| 1335 |
+
byte gzip header.
|
| 1336 |
+
|
| 1337 |
+
gzopen returns NULL if the file could not be opened, if there was
|
| 1338 |
+
insufficient memory to allocate the gzFile state, or if an invalid mode was
|
| 1339 |
+
specified (an 'r', 'w', or 'a' was not provided, or '+' was provided).
|
| 1340 |
+
errno can be checked to determine if the reason gzopen failed was that the
|
| 1341 |
+
file could not be opened.
|
| 1342 |
+
*/
|
| 1343 |
+
|
| 1344 |
+
ZEXTERN gzFile ZEXPORT gzdopen(int fd, const char *mode);
|
| 1345 |
+
/*
|
| 1346 |
+
Associate a gzFile with the file descriptor fd. File descriptors are
|
| 1347 |
+
obtained from calls like open, dup, creat, pipe or fileno (if the file has
|
| 1348 |
+
been previously opened with fopen). The mode parameter is as in gzopen.
|
| 1349 |
+
|
| 1350 |
+
The next call of gzclose on the returned gzFile will also close the file
|
| 1351 |
+
descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor
|
| 1352 |
+
fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd,
|
| 1353 |
+
mode);. The duplicated descriptor should be saved to avoid a leak, since
|
| 1354 |
+
gzdopen does not close fd if it fails. If you are using fileno() to get the
|
| 1355 |
+
file descriptor from a FILE *, then you will have to use dup() to avoid
|
| 1356 |
+
double-close()ing the file descriptor. Both gzclose() and fclose() will
|
| 1357 |
+
close the associated file descriptor, so they need to have different file
|
| 1358 |
+
descriptors.
|
| 1359 |
+
|
| 1360 |
+
gzdopen returns NULL if there was insufficient memory to allocate the
|
| 1361 |
+
gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not
|
| 1362 |
+
provided, or '+' was provided), or if fd is -1. The file descriptor is not
|
| 1363 |
+
used until the next gz* read, write, seek, or close operation, so gzdopen
|
| 1364 |
+
will not detect if fd is invalid (unless fd is -1).
|
| 1365 |
+
*/
|
| 1366 |
+
|
| 1367 |
+
ZEXTERN int ZEXPORT gzbuffer(gzFile file, unsigned size);
|
| 1368 |
+
/*
|
| 1369 |
+
Set the internal buffer size used by this library's functions for file to
|
| 1370 |
+
size. The default buffer size is 8192 bytes. This function must be called
|
| 1371 |
+
after gzopen() or gzdopen(), and before any other calls that read or write
|
| 1372 |
+
the file. The buffer memory allocation is always deferred to the first read
|
| 1373 |
+
or write. Three times that size in buffer space is allocated. A larger
|
| 1374 |
+
buffer size of, for example, 64K or 128K bytes will noticeably increase the
|
| 1375 |
+
speed of decompression (reading).
|
| 1376 |
+
|
| 1377 |
+
The new buffer size also affects the maximum length for gzprintf().
|
| 1378 |
+
|
| 1379 |
+
gzbuffer() returns 0 on success, or -1 on failure, such as being called
|
| 1380 |
+
too late.
|
| 1381 |
+
*/
|
| 1382 |
+
|
| 1383 |
+
ZEXTERN int ZEXPORT gzsetparams(gzFile file, int level, int strategy);
|
| 1384 |
+
/*
|
| 1385 |
+
Dynamically update the compression level and strategy for file. See the
|
| 1386 |
+
description of deflateInit2 for the meaning of these parameters. Previously
|
| 1387 |
+
provided data is flushed before applying the parameter changes.
|
| 1388 |
+
|
| 1389 |
+
gzsetparams returns Z_OK if success, Z_STREAM_ERROR if the file was not
|
| 1390 |
+
opened for writing, Z_ERRNO if there is an error writing the flushed data,
|
| 1391 |
+
or Z_MEM_ERROR if there is a memory allocation error.
|
| 1392 |
+
*/
|
| 1393 |
+
|
| 1394 |
+
ZEXTERN int ZEXPORT gzread(gzFile file, voidp buf, unsigned len);
|
| 1395 |
+
/*
|
| 1396 |
+
Read and decompress up to len uncompressed bytes from file into buf. If
|
| 1397 |
+
the input file is not in gzip format, gzread copies the given number of
|
| 1398 |
+
bytes into the buffer directly from the file.
|
| 1399 |
+
|
| 1400 |
+
After reaching the end of a gzip stream in the input, gzread will continue
|
| 1401 |
+
to read, looking for another gzip stream. Any number of gzip streams may be
|
| 1402 |
+
concatenated in the input file, and will all be decompressed by gzread().
|
| 1403 |
+
If something other than a gzip stream is encountered after a gzip stream,
|
| 1404 |
+
that remaining trailing garbage is ignored (and no error is returned).
|
| 1405 |
+
|
| 1406 |
+
gzread can be used to read a gzip file that is being concurrently written.
|
| 1407 |
+
Upon reaching the end of the input, gzread will return with the available
|
| 1408 |
+
data. If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then
|
| 1409 |
+
gzclearerr can be used to clear the end of file indicator in order to permit
|
| 1410 |
+
gzread to be tried again. Z_OK indicates that a gzip stream was completed
|
| 1411 |
+
on the last gzread. Z_BUF_ERROR indicates that the input file ended in the
|
| 1412 |
+
middle of a gzip stream. Note that gzread does not return -1 in the event
|
| 1413 |
+
of an incomplete gzip stream. This error is deferred until gzclose(), which
|
| 1414 |
+
will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip
|
| 1415 |
+
stream. Alternatively, gzerror can be used before gzclose to detect this
|
| 1416 |
+
case.
|
| 1417 |
+
|
| 1418 |
+
gzread returns the number of uncompressed bytes actually read, less than
|
| 1419 |
+
len for end of file, or -1 for error. If len is too large to fit in an int,
|
| 1420 |
+
then nothing is read, -1 is returned, and the error state is set to
|
| 1421 |
+
Z_STREAM_ERROR.
|
| 1422 |
+
*/
|
| 1423 |
+
|
| 1424 |
+
ZEXTERN z_size_t ZEXPORT gzfread(voidp buf, z_size_t size, z_size_t nitems,
|
| 1425 |
+
gzFile file);
|
| 1426 |
+
/*
|
| 1427 |
+
Read and decompress up to nitems items of size size from file into buf,
|
| 1428 |
+
otherwise operating as gzread() does. This duplicates the interface of
|
| 1429 |
+
stdio's fread(), with size_t request and return types. If the library
|
| 1430 |
+
defines size_t, then z_size_t is identical to size_t. If not, then z_size_t
|
| 1431 |
+
is an unsigned integer type that can contain a pointer.
|
| 1432 |
+
|
| 1433 |
+
gzfread() returns the number of full items read of size size, or zero if
|
| 1434 |
+
the end of the file was reached and a full item could not be read, or if
|
| 1435 |
+
there was an error. gzerror() must be consulted if zero is returned in
|
| 1436 |
+
order to determine if there was an error. If the multiplication of size and
|
| 1437 |
+
nitems overflows, i.e. the product does not fit in a z_size_t, then nothing
|
| 1438 |
+
is read, zero is returned, and the error state is set to Z_STREAM_ERROR.
|
| 1439 |
+
|
| 1440 |
+
In the event that the end of file is reached and only a partial item is
|
| 1441 |
+
available at the end, i.e. the remaining uncompressed data length is not a
|
| 1442 |
+
multiple of size, then the final partial item is nevertheless read into buf
|
| 1443 |
+
and the end-of-file flag is set. The length of the partial item read is not
|
| 1444 |
+
provided, but could be inferred from the result of gztell(). This behavior
|
| 1445 |
+
is the same as the behavior of fread() implementations in common libraries,
|
| 1446 |
+
but it prevents the direct use of gzfread() to read a concurrently written
|
| 1447 |
+
file, resetting and retrying on end-of-file, when size is not 1.
|
| 1448 |
+
*/
|
| 1449 |
+
|
| 1450 |
+
ZEXTERN int ZEXPORT gzwrite(gzFile file, voidpc buf, unsigned len);
|
| 1451 |
+
/*
|
| 1452 |
+
Compress and write the len uncompressed bytes at buf to file. gzwrite
|
| 1453 |
+
returns the number of uncompressed bytes written or 0 in case of error.
|
| 1454 |
+
*/
|
| 1455 |
+
|
| 1456 |
+
ZEXTERN z_size_t ZEXPORT gzfwrite(voidpc buf, z_size_t size,
|
| 1457 |
+
z_size_t nitems, gzFile file);
|
| 1458 |
+
/*
|
| 1459 |
+
Compress and write nitems items of size size from buf to file, duplicating
|
| 1460 |
+
the interface of stdio's fwrite(), with size_t request and return types. If
|
| 1461 |
+
the library defines size_t, then z_size_t is identical to size_t. If not,
|
| 1462 |
+
then z_size_t is an unsigned integer type that can contain a pointer.
|
| 1463 |
+
|
| 1464 |
+
gzfwrite() returns the number of full items written of size size, or zero
|
| 1465 |
+
if there was an error. If the multiplication of size and nitems overflows,
|
| 1466 |
+
i.e. the product does not fit in a z_size_t, then nothing is written, zero
|
| 1467 |
+
is returned, and the error state is set to Z_STREAM_ERROR.
|
| 1468 |
+
*/
|
| 1469 |
+
|
| 1470 |
+
ZEXTERN int ZEXPORTVA gzprintf(gzFile file, const char *format, ...);
|
| 1471 |
+
/*
|
| 1472 |
+
Convert, format, compress, and write the arguments (...) to file under
|
| 1473 |
+
control of the string format, as in fprintf. gzprintf returns the number of
|
| 1474 |
+
uncompressed bytes actually written, or a negative zlib error code in case
|
| 1475 |
+
of error. The number of uncompressed bytes written is limited to 8191, or
|
| 1476 |
+
one less than the buffer size given to gzbuffer(). The caller should assure
|
| 1477 |
+
that this limit is not exceeded. If it is exceeded, then gzprintf() will
|
| 1478 |
+
return an error (0) with nothing written. In this case, there may also be a
|
| 1479 |
+
buffer overflow with unpredictable consequences, which is possible only if
|
| 1480 |
+
zlib was compiled with the insecure functions sprintf() or vsprintf(),
|
| 1481 |
+
because the secure snprintf() or vsnprintf() functions were not available.
|
| 1482 |
+
This can be determined using zlibCompileFlags().
|
| 1483 |
+
*/
|
| 1484 |
+
|
| 1485 |
+
ZEXTERN int ZEXPORT gzputs(gzFile file, const char *s);
|
| 1486 |
+
/*
|
| 1487 |
+
Compress and write the given null-terminated string s to file, excluding
|
| 1488 |
+
the terminating null character.
|
| 1489 |
+
|
| 1490 |
+
gzputs returns the number of characters written, or -1 in case of error.
|
| 1491 |
+
*/
|
| 1492 |
+
|
| 1493 |
+
ZEXTERN char * ZEXPORT gzgets(gzFile file, char *buf, int len);
|
| 1494 |
+
/*
|
| 1495 |
+
Read and decompress bytes from file into buf, until len-1 characters are
|
| 1496 |
+
read, or until a newline character is read and transferred to buf, or an
|
| 1497 |
+
end-of-file condition is encountered. If any characters are read or if len
|
| 1498 |
+
is one, the string is terminated with a null character. If no characters
|
| 1499 |
+
are read due to an end-of-file or len is less than one, then the buffer is
|
| 1500 |
+
left untouched.
|
| 1501 |
+
|
| 1502 |
+
gzgets returns buf which is a null-terminated string, or it returns NULL
|
| 1503 |
+
for end-of-file or in case of error. If there was an error, the contents at
|
| 1504 |
+
buf are indeterminate.
|
| 1505 |
+
*/
|
| 1506 |
+
|
| 1507 |
+
ZEXTERN int ZEXPORT gzputc(gzFile file, int c);
|
| 1508 |
+
/*
|
| 1509 |
+
Compress and write c, converted to an unsigned char, into file. gzputc
|
| 1510 |
+
returns the value that was written, or -1 in case of error.
|
| 1511 |
+
*/
|
| 1512 |
+
|
| 1513 |
+
ZEXTERN int ZEXPORT gzgetc(gzFile file);
|
| 1514 |
+
/*
|
| 1515 |
+
Read and decompress one byte from file. gzgetc returns this byte or -1
|
| 1516 |
+
in case of end of file or error. This is implemented as a macro for speed.
|
| 1517 |
+
As such, it does not do all of the checking the other functions do. I.e.
|
| 1518 |
+
it does not check to see if file is NULL, nor whether the structure file
|
| 1519 |
+
points to has been clobbered or not.
|
| 1520 |
+
*/
|
| 1521 |
+
|
| 1522 |
+
ZEXTERN int ZEXPORT gzungetc(int c, gzFile file);
|
| 1523 |
+
/*
|
| 1524 |
+
Push c back onto the stream for file to be read as the first character on
|
| 1525 |
+
the next read. At least one character of push-back is always allowed.
|
| 1526 |
+
gzungetc() returns the character pushed, or -1 on failure. gzungetc() will
|
| 1527 |
+
fail if c is -1, and may fail if a character has been pushed but not read
|
| 1528 |
+
yet. If gzungetc is used immediately after gzopen or gzdopen, at least the
|
| 1529 |
+
output buffer size of pushed characters is allowed. (See gzbuffer above.)
|
| 1530 |
+
The pushed character will be discarded if the stream is repositioned with
|
| 1531 |
+
gzseek() or gzrewind().
|
| 1532 |
+
*/
|
| 1533 |
+
|
| 1534 |
+
ZEXTERN int ZEXPORT gzflush(gzFile file, int flush);
|
| 1535 |
+
/*
|
| 1536 |
+
Flush all pending output to file. The parameter flush is as in the
|
| 1537 |
+
deflate() function. The return value is the zlib error number (see function
|
| 1538 |
+
gzerror below). gzflush is only permitted when writing.
|
| 1539 |
+
|
| 1540 |
+
If the flush parameter is Z_FINISH, the remaining data is written and the
|
| 1541 |
+
gzip stream is completed in the output. If gzwrite() is called again, a new
|
| 1542 |
+
gzip stream will be started in the output. gzread() is able to read such
|
| 1543 |
+
concatenated gzip streams.
|
| 1544 |
+
|
| 1545 |
+
gzflush should be called only when strictly necessary because it will
|
| 1546 |
+
degrade compression if called too often.
|
| 1547 |
+
*/
|
| 1548 |
+
|
| 1549 |
+
/*
|
| 1550 |
+
ZEXTERN z_off_t ZEXPORT gzseek(gzFile file,
|
| 1551 |
+
z_off_t offset, int whence);
|
| 1552 |
+
|
| 1553 |
+
Set the starting position to offset relative to whence for the next gzread
|
| 1554 |
+
or gzwrite on file. The offset represents a number of bytes in the
|
| 1555 |
+
uncompressed data stream. The whence parameter is defined as in lseek(2);
|
| 1556 |
+
the value SEEK_END is not supported.
|
| 1557 |
+
|
| 1558 |
+
If the file is opened for reading, this function is emulated but can be
|
| 1559 |
+
extremely slow. If the file is opened for writing, only forward seeks are
|
| 1560 |
+
supported; gzseek then compresses a sequence of zeroes up to the new
|
| 1561 |
+
starting position.
|
| 1562 |
+
|
| 1563 |
+
gzseek returns the resulting offset location as measured in bytes from
|
| 1564 |
+
the beginning of the uncompressed stream, or -1 in case of error, in
|
| 1565 |
+
particular if the file is opened for writing and the new starting position
|
| 1566 |
+
would be before the current position.
|
| 1567 |
+
*/
|
| 1568 |
+
|
| 1569 |
+
ZEXTERN int ZEXPORT gzrewind(gzFile file);
|
| 1570 |
+
/*
|
| 1571 |
+
Rewind file. This function is supported only for reading.
|
| 1572 |
+
|
| 1573 |
+
gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET).
|
| 1574 |
+
*/
|
| 1575 |
+
|
| 1576 |
+
/*
|
| 1577 |
+
ZEXTERN z_off_t ZEXPORT gztell(gzFile file);
|
| 1578 |
+
|
| 1579 |
+
Return the starting position for the next gzread or gzwrite on file.
|
| 1580 |
+
This position represents a number of bytes in the uncompressed data stream,
|
| 1581 |
+
and is zero when starting, even if appending or reading a gzip stream from
|
| 1582 |
+
the middle of a file using gzdopen().
|
| 1583 |
+
|
| 1584 |
+
gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
|
| 1585 |
+
*/
|
| 1586 |
+
|
| 1587 |
+
/*
|
| 1588 |
+
ZEXTERN z_off_t ZEXPORT gzoffset(gzFile file);
|
| 1589 |
+
|
| 1590 |
+
Return the current compressed (actual) read or write offset of file. This
|
| 1591 |
+
offset includes the count of bytes that precede the gzip stream, for example
|
| 1592 |
+
when appending or when using gzdopen() for reading. When reading, the
|
| 1593 |
+
offset does not include as yet unused buffered input. This information can
|
| 1594 |
+
be used for a progress indicator. On error, gzoffset() returns -1.
|
| 1595 |
+
*/
|
| 1596 |
+
|
| 1597 |
+
ZEXTERN int ZEXPORT gzeof(gzFile file);
|
| 1598 |
+
/*
|
| 1599 |
+
Return true (1) if the end-of-file indicator for file has been set while
|
| 1600 |
+
reading, false (0) otherwise. Note that the end-of-file indicator is set
|
| 1601 |
+
only if the read tried to go past the end of the input, but came up short.
|
| 1602 |
+
Therefore, just like feof(), gzeof() may return false even if there is no
|
| 1603 |
+
more data to read, in the event that the last read request was for the exact
|
| 1604 |
+
number of bytes remaining in the input file. This will happen if the input
|
| 1605 |
+
file size is an exact multiple of the buffer size.
|
| 1606 |
+
|
| 1607 |
+
If gzeof() returns true, then the read functions will return no more data,
|
| 1608 |
+
unless the end-of-file indicator is reset by gzclearerr() and the input file
|
| 1609 |
+
has grown since the previous end of file was detected.
|
| 1610 |
+
*/
|
| 1611 |
+
|
| 1612 |
+
ZEXTERN int ZEXPORT gzdirect(gzFile file);
|
| 1613 |
+
/*
|
| 1614 |
+
Return true (1) if file is being copied directly while reading, or false
|
| 1615 |
+
(0) if file is a gzip stream being decompressed.
|
| 1616 |
+
|
| 1617 |
+
If the input file is empty, gzdirect() will return true, since the input
|
| 1618 |
+
does not contain a gzip stream.
|
| 1619 |
+
|
| 1620 |
+
If gzdirect() is used immediately after gzopen() or gzdopen() it will
|
| 1621 |
+
cause buffers to be allocated to allow reading the file to determine if it
|
| 1622 |
+
is a gzip file. Therefore if gzbuffer() is used, it should be called before
|
| 1623 |
+
gzdirect().
|
| 1624 |
+
|
| 1625 |
+
When writing, gzdirect() returns true (1) if transparent writing was
|
| 1626 |
+
requested ("wT" for the gzopen() mode), or false (0) otherwise. (Note:
|
| 1627 |
+
gzdirect() is not needed when writing. Transparent writing must be
|
| 1628 |
+
explicitly requested, so the application already knows the answer. When
|
| 1629 |
+
linking statically, using gzdirect() will include all of the zlib code for
|
| 1630 |
+
gzip file reading and decompression, which may not be desired.)
|
| 1631 |
+
*/
|
| 1632 |
+
|
| 1633 |
+
ZEXTERN int ZEXPORT gzclose(gzFile file);
|
| 1634 |
+
/*
|
| 1635 |
+
Flush all pending output for file, if necessary, close file and
|
| 1636 |
+
deallocate the (de)compression state. Note that once file is closed, you
|
| 1637 |
+
cannot call gzerror with file, since its structures have been deallocated.
|
| 1638 |
+
gzclose must not be called more than once on the same file, just as free
|
| 1639 |
+
must not be called more than once on the same allocation.
|
| 1640 |
+
|
| 1641 |
+
gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a
|
| 1642 |
+
file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the
|
| 1643 |
+
last read ended in the middle of a gzip stream, or Z_OK on success.
|
| 1644 |
+
*/
|
| 1645 |
+
|
| 1646 |
+
ZEXTERN int ZEXPORT gzclose_r(gzFile file);
|
| 1647 |
+
ZEXTERN int ZEXPORT gzclose_w(gzFile file);
|
| 1648 |
+
/*
|
| 1649 |
+
Same as gzclose(), but gzclose_r() is only for use when reading, and
|
| 1650 |
+
gzclose_w() is only for use when writing or appending. The advantage to
|
| 1651 |
+
using these instead of gzclose() is that they avoid linking in zlib
|
| 1652 |
+
compression or decompression code that is not used when only reading or only
|
| 1653 |
+
writing respectively. If gzclose() is used, then both compression and
|
| 1654 |
+
decompression code will be included the application when linking to a static
|
| 1655 |
+
zlib library.
|
| 1656 |
+
*/
|
| 1657 |
+
|
| 1658 |
+
ZEXTERN const char * ZEXPORT gzerror(gzFile file, int *errnum);
|
| 1659 |
+
/*
|
| 1660 |
+
Return the error message for the last error which occurred on file.
|
| 1661 |
+
errnum is set to zlib error number. If an error occurred in the file system
|
| 1662 |
+
and not in the compression library, errnum is set to Z_ERRNO and the
|
| 1663 |
+
application may consult errno to get the exact error code.
|
| 1664 |
+
|
| 1665 |
+
The application must not modify the returned string. Future calls to
|
| 1666 |
+
this function may invalidate the previously returned string. If file is
|
| 1667 |
+
closed, then the string previously returned by gzerror will no longer be
|
| 1668 |
+
available.
|
| 1669 |
+
|
| 1670 |
+
gzerror() should be used to distinguish errors from end-of-file for those
|
| 1671 |
+
functions above that do not distinguish those cases in their return values.
|
| 1672 |
+
*/
|
| 1673 |
+
|
| 1674 |
+
ZEXTERN void ZEXPORT gzclearerr(gzFile file);
|
| 1675 |
+
/*
|
| 1676 |
+
Clear the error and end-of-file flags for file. This is analogous to the
|
| 1677 |
+
clearerr() function in stdio. This is useful for continuing to read a gzip
|
| 1678 |
+
file that is being written concurrently.
|
| 1679 |
+
*/
|
| 1680 |
+
|
| 1681 |
+
#endif /* !Z_SOLO */
|
| 1682 |
+
|
| 1683 |
+
/* checksum functions */
|
| 1684 |
+
|
| 1685 |
+
/*
|
| 1686 |
+
These functions are not related to compression but are exported
|
| 1687 |
+
anyway because they might be useful in applications using the compression
|
| 1688 |
+
library.
|
| 1689 |
+
*/
|
| 1690 |
+
|
| 1691 |
+
ZEXTERN uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len);
|
| 1692 |
+
/*
|
| 1693 |
+
Update a running Adler-32 checksum with the bytes buf[0..len-1] and
|
| 1694 |
+
return the updated checksum. An Adler-32 value is in the range of a 32-bit
|
| 1695 |
+
unsigned integer. If buf is Z_NULL, this function returns the required
|
| 1696 |
+
initial value for the checksum.
|
| 1697 |
+
|
| 1698 |
+
An Adler-32 checksum is almost as reliable as a CRC-32 but can be computed
|
| 1699 |
+
much faster.
|
| 1700 |
+
|
| 1701 |
+
Usage example:
|
| 1702 |
+
|
| 1703 |
+
uLong adler = adler32(0L, Z_NULL, 0);
|
| 1704 |
+
|
| 1705 |
+
while (read_buffer(buffer, length) != EOF) {
|
| 1706 |
+
adler = adler32(adler, buffer, length);
|
| 1707 |
+
}
|
| 1708 |
+
if (adler != original_adler) error();
|
| 1709 |
+
*/
|
| 1710 |
+
|
| 1711 |
+
ZEXTERN uLong ZEXPORT adler32_z(uLong adler, const Bytef *buf,
|
| 1712 |
+
z_size_t len);
|
| 1713 |
+
/*
|
| 1714 |
+
Same as adler32(), but with a size_t length.
|
| 1715 |
+
*/
|
| 1716 |
+
|
| 1717 |
+
/*
|
| 1718 |
+
ZEXTERN uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2,
|
| 1719 |
+
z_off_t len2);
|
| 1720 |
+
|
| 1721 |
+
Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
|
| 1722 |
+
and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
|
| 1723 |
+
each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
|
| 1724 |
+
seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. Note
|
| 1725 |
+
that the z_off_t type (like off_t) is a signed integer. If len2 is
|
| 1726 |
+
negative, the result has no meaning or utility.
|
| 1727 |
+
*/
|
| 1728 |
+
|
| 1729 |
+
ZEXTERN uLong ZEXPORT crc32(uLong crc, const Bytef *buf, uInt len);
|
| 1730 |
+
/*
|
| 1731 |
+
Update a running CRC-32 with the bytes buf[0..len-1] and return the
|
| 1732 |
+
updated CRC-32. A CRC-32 value is in the range of a 32-bit unsigned integer.
|
| 1733 |
+
If buf is Z_NULL, this function returns the required initial value for the
|
| 1734 |
+
crc. Pre- and post-conditioning (one's complement) is performed within this
|
| 1735 |
+
function so it shouldn't be done by the application.
|
| 1736 |
+
|
| 1737 |
+
Usage example:
|
| 1738 |
+
|
| 1739 |
+
uLong crc = crc32(0L, Z_NULL, 0);
|
| 1740 |
+
|
| 1741 |
+
while (read_buffer(buffer, length) != EOF) {
|
| 1742 |
+
crc = crc32(crc, buffer, length);
|
| 1743 |
+
}
|
| 1744 |
+
if (crc != original_crc) error();
|
| 1745 |
+
*/
|
| 1746 |
+
|
| 1747 |
+
ZEXTERN uLong ZEXPORT crc32_z(uLong crc, const Bytef *buf,
|
| 1748 |
+
z_size_t len);
|
| 1749 |
+
/*
|
| 1750 |
+
Same as crc32(), but with a size_t length.
|
| 1751 |
+
*/
|
| 1752 |
+
|
| 1753 |
+
/*
|
| 1754 |
+
ZEXTERN uLong ZEXPORT crc32_combine(uLong crc1, uLong crc2, z_off_t len2);
|
| 1755 |
+
|
| 1756 |
+
Combine two CRC-32 check values into one. For two sequences of bytes,
|
| 1757 |
+
seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
|
| 1758 |
+
calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
|
| 1759 |
+
check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
|
| 1760 |
+
len2. len2 must be non-negative.
|
| 1761 |
+
*/
|
| 1762 |
+
|
| 1763 |
+
/*
|
| 1764 |
+
ZEXTERN uLong ZEXPORT crc32_combine_gen(z_off_t len2);
|
| 1765 |
+
|
| 1766 |
+
Return the operator corresponding to length len2, to be used with
|
| 1767 |
+
crc32_combine_op(). len2 must be non-negative.
|
| 1768 |
+
*/
|
| 1769 |
+
|
| 1770 |
+
ZEXTERN uLong ZEXPORT crc32_combine_op(uLong crc1, uLong crc2, uLong op);
|
| 1771 |
+
/*
|
| 1772 |
+
Give the same result as crc32_combine(), using op in place of len2. op is
|
| 1773 |
+
is generated from len2 by crc32_combine_gen(). This will be faster than
|
| 1774 |
+
crc32_combine() if the generated op is used more than once.
|
| 1775 |
+
*/
|
| 1776 |
+
|
| 1777 |
+
|
| 1778 |
+
/* various hacks, don't look :) */
|
| 1779 |
+
|
| 1780 |
+
/* deflateInit and inflateInit are macros to allow checking the zlib version
|
| 1781 |
+
* and the compiler's view of z_stream:
|
| 1782 |
+
*/
|
| 1783 |
+
ZEXTERN int ZEXPORT deflateInit_(z_streamp strm, int level,
|
| 1784 |
+
const char *version, int stream_size);
|
| 1785 |
+
ZEXTERN int ZEXPORT inflateInit_(z_streamp strm,
|
| 1786 |
+
const char *version, int stream_size);
|
| 1787 |
+
ZEXTERN int ZEXPORT deflateInit2_(z_streamp strm, int level, int method,
|
| 1788 |
+
int windowBits, int memLevel,
|
| 1789 |
+
int strategy, const char *version,
|
| 1790 |
+
int stream_size);
|
| 1791 |
+
ZEXTERN int ZEXPORT inflateInit2_(z_streamp strm, int windowBits,
|
| 1792 |
+
const char *version, int stream_size);
|
| 1793 |
+
ZEXTERN int ZEXPORT inflateBackInit_(z_streamp strm, int windowBits,
|
| 1794 |
+
unsigned char FAR *window,
|
| 1795 |
+
const char *version,
|
| 1796 |
+
int stream_size);
|
| 1797 |
+
#ifdef Z_PREFIX_SET
|
| 1798 |
+
# define z_deflateInit(strm, level) \
|
| 1799 |
+
deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream))
|
| 1800 |
+
# define z_inflateInit(strm) \
|
| 1801 |
+
inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream))
|
| 1802 |
+
# define z_deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
|
| 1803 |
+
deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
|
| 1804 |
+
(strategy), ZLIB_VERSION, (int)sizeof(z_stream))
|
| 1805 |
+
# define z_inflateInit2(strm, windowBits) \
|
| 1806 |
+
inflateInit2_((strm), (windowBits), ZLIB_VERSION, \
|
| 1807 |
+
(int)sizeof(z_stream))
|
| 1808 |
+
# define z_inflateBackInit(strm, windowBits, window) \
|
| 1809 |
+
inflateBackInit_((strm), (windowBits), (window), \
|
| 1810 |
+
ZLIB_VERSION, (int)sizeof(z_stream))
|
| 1811 |
+
#else
|
| 1812 |
+
# define deflateInit(strm, level) \
|
| 1813 |
+
deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream))
|
| 1814 |
+
# define inflateInit(strm) \
|
| 1815 |
+
inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream))
|
| 1816 |
+
# define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
|
| 1817 |
+
deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
|
| 1818 |
+
(strategy), ZLIB_VERSION, (int)sizeof(z_stream))
|
| 1819 |
+
# define inflateInit2(strm, windowBits) \
|
| 1820 |
+
inflateInit2_((strm), (windowBits), ZLIB_VERSION, \
|
| 1821 |
+
(int)sizeof(z_stream))
|
| 1822 |
+
# define inflateBackInit(strm, windowBits, window) \
|
| 1823 |
+
inflateBackInit_((strm), (windowBits), (window), \
|
| 1824 |
+
ZLIB_VERSION, (int)sizeof(z_stream))
|
| 1825 |
+
#endif
|
| 1826 |
+
|
| 1827 |
+
#ifndef Z_SOLO
|
| 1828 |
+
|
| 1829 |
+
/* gzgetc() macro and its supporting function and exposed data structure. Note
|
| 1830 |
+
* that the real internal state is much larger than the exposed structure.
|
| 1831 |
+
* This abbreviated structure exposes just enough for the gzgetc() macro. The
|
| 1832 |
+
* user should not mess with these exposed elements, since their names or
|
| 1833 |
+
* behavior could change in the future, perhaps even capriciously. They can
|
| 1834 |
+
* only be used by the gzgetc() macro. You have been warned.
|
| 1835 |
+
*/
|
| 1836 |
+
struct gzFile_s {
|
| 1837 |
+
unsigned have;
|
| 1838 |
+
unsigned char *next;
|
| 1839 |
+
z_off64_t pos;
|
| 1840 |
+
};
|
| 1841 |
+
ZEXTERN int ZEXPORT gzgetc_(gzFile file); /* backward compatibility */
|
| 1842 |
+
#ifdef Z_PREFIX_SET
|
| 1843 |
+
# undef z_gzgetc
|
| 1844 |
+
# define z_gzgetc(g) \
|
| 1845 |
+
((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g))
|
| 1846 |
+
#elif defined(Z_CR_PREFIX_SET)
|
| 1847 |
+
# undef gzgetc
|
| 1848 |
+
# define gzgetc(g) \
|
| 1849 |
+
((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) \
|
| 1850 |
+
: (Cr_z_gzgetc)(g))
|
| 1851 |
+
#else
|
| 1852 |
+
# define gzgetc(g) \
|
| 1853 |
+
((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g))
|
| 1854 |
+
#endif
|
| 1855 |
+
|
| 1856 |
+
/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or
|
| 1857 |
+
* change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if
|
| 1858 |
+
* both are true, the application gets the *64 functions, and the regular
|
| 1859 |
+
* functions are changed to 64 bits) -- in case these are set on systems
|
| 1860 |
+
* without large file support, _LFS64_LARGEFILE must also be true
|
| 1861 |
+
*/
|
| 1862 |
+
#ifdef Z_LARGE64
|
| 1863 |
+
ZEXTERN gzFile ZEXPORT gzopen64(const char *, const char *);
|
| 1864 |
+
ZEXTERN z_off64_t ZEXPORT gzseek64(gzFile, z_off64_t, int);
|
| 1865 |
+
ZEXTERN z_off64_t ZEXPORT gztell64(gzFile);
|
| 1866 |
+
ZEXTERN z_off64_t ZEXPORT gzoffset64(gzFile);
|
| 1867 |
+
ZEXTERN uLong ZEXPORT adler32_combine64(uLong, uLong, z_off64_t);
|
| 1868 |
+
ZEXTERN uLong ZEXPORT crc32_combine64(uLong, uLong, z_off64_t);
|
| 1869 |
+
ZEXTERN uLong ZEXPORT crc32_combine_gen64(z_off64_t);
|
| 1870 |
+
#endif
|
| 1871 |
+
|
| 1872 |
+
#if !defined(ZLIB_INTERNAL) && defined(Z_WANT64)
|
| 1873 |
+
# ifdef Z_PREFIX_SET
|
| 1874 |
+
# define z_gzopen z_gzopen64
|
| 1875 |
+
# define z_gzseek z_gzseek64
|
| 1876 |
+
# define z_gztell z_gztell64
|
| 1877 |
+
# define z_gzoffset z_gzoffset64
|
| 1878 |
+
# define z_adler32_combine z_adler32_combine64
|
| 1879 |
+
# define z_crc32_combine z_crc32_combine64
|
| 1880 |
+
# define z_crc32_combine_gen z_crc32_combine_gen64
|
| 1881 |
+
# else
|
| 1882 |
+
# ifdef gzopen
|
| 1883 |
+
# undef gzopen
|
| 1884 |
+
# endif
|
| 1885 |
+
# define gzopen gzopen64
|
| 1886 |
+
# ifdef gzseek
|
| 1887 |
+
# undef gzseek
|
| 1888 |
+
# endif
|
| 1889 |
+
# define gzseek gzseek64
|
| 1890 |
+
# ifdef gztell
|
| 1891 |
+
# undef gztell
|
| 1892 |
+
# endif
|
| 1893 |
+
# define gztell gztell64
|
| 1894 |
+
# ifdef gzoffset
|
| 1895 |
+
# undef gzoffset
|
| 1896 |
+
# endif
|
| 1897 |
+
# define gzoffset gzoffset64
|
| 1898 |
+
# ifdef adler32_combine
|
| 1899 |
+
# undef adler32_combine
|
| 1900 |
+
# endif
|
| 1901 |
+
# define adler32_combine adler32_combine64
|
| 1902 |
+
# ifdef crc32_combine
|
| 1903 |
+
# undef crc32_combine
|
| 1904 |
+
# endif
|
| 1905 |
+
# ifdef crc32_combine64
|
| 1906 |
+
# undef crc32_combine64
|
| 1907 |
+
# endif
|
| 1908 |
+
# ifdef crc32_combine_gen
|
| 1909 |
+
# undef crc32_combine_gen
|
| 1910 |
+
# endif
|
| 1911 |
+
# ifdef crc32_combine_op
|
| 1912 |
+
# undef crc32_combine_op
|
| 1913 |
+
# endif
|
| 1914 |
+
# endif
|
| 1915 |
+
# ifndef Z_LARGE64
|
| 1916 |
+
ZEXTERN gzFile ZEXPORT gzopen64(const char *, const char *);
|
| 1917 |
+
ZEXTERN z_off_t ZEXPORT gzseek64(gzFile, z_off_t, int);
|
| 1918 |
+
ZEXTERN z_off_t ZEXPORT gztell64(gzFile);
|
| 1919 |
+
ZEXTERN z_off_t ZEXPORT gzoffset64(gzFile);
|
| 1920 |
+
ZEXTERN uLong ZEXPORT adler32_combine64(uLong, uLong, z_off_t);
|
| 1921 |
+
ZEXTERN uLong ZEXPORT crc32_combine64(uLong, uLong, z_off_t);
|
| 1922 |
+
ZEXTERN uLong ZEXPORT crc32_combine_gen64(z_off_t);
|
| 1923 |
+
# endif
|
| 1924 |
+
#else
|
| 1925 |
+
ZEXTERN gzFile ZEXPORT gzopen(const char *, const char *);
|
| 1926 |
+
ZEXTERN z_off_t ZEXPORT gzseek(gzFile, z_off_t, int);
|
| 1927 |
+
ZEXTERN z_off_t ZEXPORT gztell(gzFile);
|
| 1928 |
+
ZEXTERN z_off_t ZEXPORT gzoffset(gzFile);
|
| 1929 |
+
ZEXTERN uLong ZEXPORT adler32_combine(uLong, uLong, z_off_t);
|
| 1930 |
+
ZEXTERN uLong ZEXPORT crc32_combine(uLong, uLong, z_off_t);
|
| 1931 |
+
ZEXTERN uLong ZEXPORT crc32_combine_gen(z_off_t);
|
| 1932 |
+
#endif
|
| 1933 |
+
|
| 1934 |
+
#else /* Z_SOLO */
|
| 1935 |
+
|
| 1936 |
+
ZEXTERN uLong ZEXPORT adler32_combine(uLong, uLong, z_off_t);
|
| 1937 |
+
ZEXTERN uLong ZEXPORT crc32_combine(uLong, uLong, z_off_t);
|
| 1938 |
+
ZEXTERN uLong ZEXPORT crc32_combine_gen(z_off_t);
|
| 1939 |
+
|
| 1940 |
+
#endif /* !Z_SOLO */
|
| 1941 |
+
|
| 1942 |
+
/* undocumented functions */
|
| 1943 |
+
ZEXTERN const char * ZEXPORT zError(int);
|
| 1944 |
+
ZEXTERN int ZEXPORT inflateSyncPoint(z_streamp);
|
| 1945 |
+
ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table(void);
|
| 1946 |
+
ZEXTERN int ZEXPORT inflateUndermine(z_streamp, int);
|
| 1947 |
+
ZEXTERN int ZEXPORT inflateValidate(z_streamp, int);
|
| 1948 |
+
ZEXTERN unsigned long ZEXPORT inflateCodesUsed(z_streamp);
|
| 1949 |
+
ZEXTERN int ZEXPORT inflateResetKeep(z_streamp);
|
| 1950 |
+
ZEXTERN int ZEXPORT deflateResetKeep(z_streamp);
|
| 1951 |
+
#if defined(_WIN32) && !defined(Z_SOLO)
|
| 1952 |
+
ZEXTERN gzFile ZEXPORT gzopen_w(const wchar_t *path,
|
| 1953 |
+
const char *mode);
|
| 1954 |
+
#endif
|
| 1955 |
+
#if defined(STDC) || defined(Z_HAVE_STDARG_H)
|
| 1956 |
+
# ifndef Z_SOLO
|
| 1957 |
+
ZEXTERN int ZEXPORTVA gzvprintf(gzFile file,
|
| 1958 |
+
const char *format,
|
| 1959 |
+
va_list va);
|
| 1960 |
+
# endif
|
| 1961 |
+
#endif
|
| 1962 |
+
|
| 1963 |
+
#ifdef __cplusplus
|
| 1964 |
+
}
|
| 1965 |
+
#endif
|
| 1966 |
+
|
| 1967 |
+
#endif /* ZLIB_H */
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Filesystem MCP Server
|
| 2 |
+
|
| 3 |
+
Node.js server implementing Model Context Protocol (MCP) for filesystem operations.
|
| 4 |
+
|
| 5 |
+
Published on npm as [`@modelcontextprotocol/server-filesystem`](https://www.npmjs.com/package/@modelcontextprotocol/server-filesystem).
|
| 6 |
+
|
| 7 |
+
## Features
|
| 8 |
+
|
| 9 |
+
- Read/write files
|
| 10 |
+
- Create/list/delete directories
|
| 11 |
+
- Move files/directories
|
| 12 |
+
- Search files
|
| 13 |
+
- Get file metadata
|
| 14 |
+
- Dynamic directory access control via [Roots](https://modelcontextprotocol.io/docs/learn/client-concepts#roots)
|
| 15 |
+
|
| 16 |
+
## Directory Access Control
|
| 17 |
+
|
| 18 |
+
The server uses a flexible directory access control system. Directories can be specified via command-line arguments or dynamically via [Roots](https://modelcontextprotocol.io/docs/learn/client-concepts#roots).
|
| 19 |
+
|
| 20 |
+
### Method 1: Command-line Arguments
|
| 21 |
+
Specify Allowed directories when starting the server:
|
| 22 |
+
```bash
|
| 23 |
+
mcp-server-filesystem /path/to/dir1 /path/to/dir2
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
### Method 2: MCP Roots (Recommended)
|
| 27 |
+
MCP clients that support [Roots](https://modelcontextprotocol.io/docs/learn/client-concepts#roots) can dynamically update the Allowed directories.
|
| 28 |
+
|
| 29 |
+
Roots notified by Client to Server, completely replace any server-side Allowed directories when provided.
|
| 30 |
+
|
| 31 |
+
**Important**: If server starts without command-line arguments AND client doesn't support roots protocol (or provides empty roots), the server will throw an error during initialization.
|
| 32 |
+
|
| 33 |
+
This is the recommended method, as this enables runtime directory updates via `roots/list_changed` notifications without server restart, providing a more flexible and modern integration experience.
|
| 34 |
+
|
| 35 |
+
### How It Works
|
| 36 |
+
|
| 37 |
+
The server's directory access control follows this flow:
|
| 38 |
+
|
| 39 |
+
1. **Server Startup**
|
| 40 |
+
- Server starts with directories from command-line arguments (if provided)
|
| 41 |
+
- If no arguments provided, server starts with empty allowed directories
|
| 42 |
+
|
| 43 |
+
2. **Client Connection & Initialization**
|
| 44 |
+
- Client connects and sends `initialize` request with capabilities
|
| 45 |
+
- Server checks if client supports roots protocol (`capabilities.roots`)
|
| 46 |
+
|
| 47 |
+
3. **Roots Protocol Handling** (if client supports roots)
|
| 48 |
+
- **On initialization**: Server requests roots from client via `roots/list`
|
| 49 |
+
- Client responds with its configured roots
|
| 50 |
+
- Server replaces ALL allowed directories with client's roots
|
| 51 |
+
- **On runtime updates**: Client can send `notifications/roots/list_changed`
|
| 52 |
+
- Server requests updated roots and replaces allowed directories again
|
| 53 |
+
|
| 54 |
+
4. **Fallback Behavior** (if client doesn't support roots)
|
| 55 |
+
- Server continues using command-line directories only
|
| 56 |
+
- No dynamic updates possible
|
| 57 |
+
|
| 58 |
+
5. **Access Control**
|
| 59 |
+
- All filesystem operations are restricted to allowed directories
|
| 60 |
+
- Use `list_allowed_directories` tool to see current directories
|
| 61 |
+
- Server requires at least ONE allowed directory to operate
|
| 62 |
+
|
| 63 |
+
**Note**: The server will only allow operations within directories specified either via `args` or via Roots.
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
## API
|
| 68 |
+
|
| 69 |
+
### Tools
|
| 70 |
+
|
| 71 |
+
- **read_text_file**
|
| 72 |
+
- Read complete contents of a file as text
|
| 73 |
+
- Inputs:
|
| 74 |
+
- `path` (string)
|
| 75 |
+
- `head` (number, optional): First N lines
|
| 76 |
+
- `tail` (number, optional): Last N lines
|
| 77 |
+
- Always treats the file as UTF-8 text regardless of extension
|
| 78 |
+
- Cannot specify both `head` and `tail` simultaneously
|
| 79 |
+
|
| 80 |
+
- **read_media_file**
|
| 81 |
+
- Read a file and return it as a base64-encoded content block with its MIME type
|
| 82 |
+
- Inputs:
|
| 83 |
+
- `path` (string)
|
| 84 |
+
- Streams the file and returns base64 data with the corresponding MIME type. Image and
|
| 85 |
+
audio files are returned as `image`/`audio` content; any other file type is returned as
|
| 86 |
+
an embedded `resource` (a valid MCP content block for arbitrary binary data)
|
| 87 |
+
|
| 88 |
+
- **read_multiple_files**
|
| 89 |
+
- Read multiple files simultaneously
|
| 90 |
+
- Input: `paths` (string[])
|
| 91 |
+
- Failed reads won't stop the entire operation
|
| 92 |
+
|
| 93 |
+
- **write_file**
|
| 94 |
+
- Create new file or overwrite existing (exercise caution with this)
|
| 95 |
+
- Inputs:
|
| 96 |
+
- `path` (string): File location
|
| 97 |
+
- `content` (string): File content
|
| 98 |
+
|
| 99 |
+
- **edit_file**
|
| 100 |
+
- Make selective edits using advanced pattern matching and formatting
|
| 101 |
+
- Features:
|
| 102 |
+
- Line-based and multi-line content matching
|
| 103 |
+
- Whitespace normalization with indentation preservation
|
| 104 |
+
- Multiple simultaneous edits with correct positioning
|
| 105 |
+
- Indentation style detection and preservation
|
| 106 |
+
- Git-style diff output with context
|
| 107 |
+
- Preview changes with dry run mode
|
| 108 |
+
- Inputs:
|
| 109 |
+
- `path` (string): File to edit
|
| 110 |
+
- `edits` (array): List of edit operations
|
| 111 |
+
- `oldText` (string): Text to search for (can be substring)
|
| 112 |
+
- `newText` (string): Text to replace with
|
| 113 |
+
- `dryRun` (boolean): Preview changes without applying (default: false)
|
| 114 |
+
- Returns detailed diff and match information for dry runs, otherwise applies changes
|
| 115 |
+
- Best Practice: Always use dryRun first to preview changes before applying them
|
| 116 |
+
|
| 117 |
+
- **create_directory**
|
| 118 |
+
- Create new directory or ensure it exists
|
| 119 |
+
- Input: `path` (string)
|
| 120 |
+
- Creates parent directories if needed
|
| 121 |
+
- Succeeds silently if directory exists
|
| 122 |
+
|
| 123 |
+
- **list_directory**
|
| 124 |
+
- List directory contents with [FILE] or [DIR] prefixes
|
| 125 |
+
- Input: `path` (string)
|
| 126 |
+
|
| 127 |
+
- **list_directory_with_sizes**
|
| 128 |
+
- List directory contents with [FILE] or [DIR] prefixes, including file sizes
|
| 129 |
+
- Inputs:
|
| 130 |
+
- `path` (string): Directory path to list
|
| 131 |
+
- `sortBy` (string, optional): Sort entries by "name" or "size" (default: "name")
|
| 132 |
+
- Returns detailed listing with file sizes and summary statistics
|
| 133 |
+
- Shows total files, directories, and combined size
|
| 134 |
+
|
| 135 |
+
- **move_file**
|
| 136 |
+
- Move or rename files and directories
|
| 137 |
+
- Inputs:
|
| 138 |
+
- `source` (string)
|
| 139 |
+
- `destination` (string)
|
| 140 |
+
- Fails if destination exists
|
| 141 |
+
|
| 142 |
+
- **search_files**
|
| 143 |
+
- Recursively search for files/directories that match or do not match patterns
|
| 144 |
+
- Inputs:
|
| 145 |
+
- `path` (string): Starting directory
|
| 146 |
+
- `pattern` (string): Search pattern
|
| 147 |
+
- `excludePatterns` (string[]): Exclude any patterns.
|
| 148 |
+
- Glob-style pattern matching
|
| 149 |
+
- Returns full paths to matches
|
| 150 |
+
|
| 151 |
+
- **directory_tree**
|
| 152 |
+
- Get recursive JSON tree structure of directory contents
|
| 153 |
+
- Inputs:
|
| 154 |
+
- `path` (string): Starting directory
|
| 155 |
+
- `excludePatterns` (string[]): Exclude any patterns. Glob formats are supported.
|
| 156 |
+
- Returns:
|
| 157 |
+
- JSON array where each entry contains:
|
| 158 |
+
- `name` (string): File/directory name
|
| 159 |
+
- `type` ('file'|'directory'): Entry type
|
| 160 |
+
- `children` (array): Present only for directories
|
| 161 |
+
- Empty array for empty directories
|
| 162 |
+
- Omitted for files
|
| 163 |
+
- Output is formatted with 2-space indentation for readability
|
| 164 |
+
|
| 165 |
+
- **get_file_info**
|
| 166 |
+
- Get detailed file/directory metadata
|
| 167 |
+
- Input: `path` (string)
|
| 168 |
+
- Returns:
|
| 169 |
+
- Size
|
| 170 |
+
- Creation time
|
| 171 |
+
- Modified time
|
| 172 |
+
- Access time
|
| 173 |
+
- Type (file/directory)
|
| 174 |
+
- Permissions
|
| 175 |
+
|
| 176 |
+
- **list_allowed_directories**
|
| 177 |
+
- List all directories the server is allowed to access
|
| 178 |
+
- No input required
|
| 179 |
+
- Returns:
|
| 180 |
+
- Directories that this server can read/write from
|
| 181 |
+
|
| 182 |
+
### Tool annotations (MCP hints)
|
| 183 |
+
|
| 184 |
+
This server sets [MCP ToolAnnotations](https://modelcontextprotocol.io/specification/2025-03-26/server/tools#toolannotations)
|
| 185 |
+
on each tool so clients can:
|
| 186 |
+
|
| 187 |
+
- Distinguish **read‑only** tools from write‑capable tools.
|
| 188 |
+
- Understand which write operations are **idempotent** (safe to retry with the same arguments).
|
| 189 |
+
- Highlight operations that may be **destructive** (overwriting or heavily mutating data).
|
| 190 |
+
- Signal that a tool does **not** reach an open or external world (every filesystem tool sets `openWorldHint: false`).
|
| 191 |
+
|
| 192 |
+
The mapping for filesystem tools is:
|
| 193 |
+
|
| 194 |
+
| Tool | readOnlyHint | idempotentHint | destructiveHint | Notes |
|
| 195 |
+
|-----------------------------|--------------|----------------|-----------------|--------------------------------------------------|
|
| 196 |
+
| `read_text_file` | `true` | – | – | Pure read |
|
| 197 |
+
| `read_media_file` | `true` | – | – | Pure read |
|
| 198 |
+
| `read_multiple_files` | `true` | – | – | Pure read |
|
| 199 |
+
| `list_directory` | `true` | – | – | Pure read |
|
| 200 |
+
| `list_directory_with_sizes` | `true` | – | – | Pure read |
|
| 201 |
+
| `directory_tree` | `true` | – | – | Pure read |
|
| 202 |
+
| `search_files` | `true` | – | – | Pure read |
|
| 203 |
+
| `get_file_info` | `true` | – | – | Pure read |
|
| 204 |
+
| `list_allowed_directories` | `true` | – | – | Pure read |
|
| 205 |
+
| `create_directory` | `false` | `true` | `false` | Re‑creating the same dir is a no‑op |
|
| 206 |
+
| `write_file` | `false` | `true` | `true` | Overwrites existing files |
|
| 207 |
+
| `edit_file` | `false` | `false` | `true` | Re‑applying edits can fail or double‑apply |
|
| 208 |
+
| `move_file` | `false` | `false` | `true` | Deletes source file |
|
| 209 |
+
|
| 210 |
+
> Note: `idempotentHint` and `destructiveHint` are meaningful only when `readOnlyHint` is `false`, as defined by the MCP spec. Every tool also sets `openWorldHint: false` — this server only accesses the local filesystem within its allowed directories, never an open or external world.
|
| 211 |
+
|
| 212 |
+
## Usage with Claude Desktop
|
| 213 |
+
Add this to your `claude_desktop_config.json`:
|
| 214 |
+
|
| 215 |
+
Note: you can provide sandboxed directories to the server by mounting them to `/projects`. Adding the `ro` flag will make the directory readonly by the server.
|
| 216 |
+
|
| 217 |
+
### Docker
|
| 218 |
+
Note: all directories must be mounted to `/projects` by default.
|
| 219 |
+
|
| 220 |
+
```json
|
| 221 |
+
{
|
| 222 |
+
"mcpServers": {
|
| 223 |
+
"filesystem": {
|
| 224 |
+
"command": "docker",
|
| 225 |
+
"args": [
|
| 226 |
+
"run",
|
| 227 |
+
"-i",
|
| 228 |
+
"--rm",
|
| 229 |
+
"--mount", "type=bind,src=/Users/username/Desktop,dst=/projects/Desktop",
|
| 230 |
+
"--mount", "type=bind,src=/path/to/other/allowed/dir,dst=/projects/other/allowed/dir,ro",
|
| 231 |
+
"--mount", "type=bind,src=/path/to/file.txt,dst=/projects/path/to/file.txt",
|
| 232 |
+
"mcp/filesystem",
|
| 233 |
+
"/projects"
|
| 234 |
+
]
|
| 235 |
+
}
|
| 236 |
+
}
|
| 237 |
+
}
|
| 238 |
+
```
|
| 239 |
+
|
| 240 |
+
### NPX
|
| 241 |
+
|
| 242 |
+
```json
|
| 243 |
+
{
|
| 244 |
+
"mcpServers": {
|
| 245 |
+
"filesystem": {
|
| 246 |
+
"command": "npx",
|
| 247 |
+
"args": [
|
| 248 |
+
"-y",
|
| 249 |
+
"@modelcontextprotocol/server-filesystem",
|
| 250 |
+
"/Users/username/Desktop",
|
| 251 |
+
"/path/to/other/allowed/dir"
|
| 252 |
+
]
|
| 253 |
+
}
|
| 254 |
+
}
|
| 255 |
+
}
|
| 256 |
+
```
|
| 257 |
+
|
| 258 |
+
On Windows, use `cmd /c` to launch `npx`:
|
| 259 |
+
|
| 260 |
+
```json
|
| 261 |
+
{
|
| 262 |
+
"mcpServers": {
|
| 263 |
+
"filesystem": {
|
| 264 |
+
"command": "cmd",
|
| 265 |
+
"args": [
|
| 266 |
+
"/c",
|
| 267 |
+
"npx",
|
| 268 |
+
"-y",
|
| 269 |
+
"@modelcontextprotocol/server-filesystem",
|
| 270 |
+
"/Users/username/Desktop",
|
| 271 |
+
"/path/to/other/allowed/dir"
|
| 272 |
+
]
|
| 273 |
+
}
|
| 274 |
+
}
|
| 275 |
+
}
|
| 276 |
+
```
|
| 277 |
+
|
| 278 |
+
## Usage with VS Code
|
| 279 |
+
|
| 280 |
+
For quick installation, click the installation buttons below...
|
| 281 |
+
|
| 282 |
+
[](https://insiders.vscode.dev/redirect/mcp/install?name=filesystem&config=%7B%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40modelcontextprotocol%2Fserver-filesystem%22%2C%22%24%7BworkspaceFolder%7D%22%5D%7D) [](https://insiders.vscode.dev/redirect/mcp/install?name=filesystem&config=%7B%22command%22%3A%22npx%22%2C%22args%22%3A%5B%22-y%22%2C%22%40modelcontextprotocol%2Fserver-filesystem%22%2C%22%24%7BworkspaceFolder%7D%22%5D%7D&quality=insiders)
|
| 283 |
+
|
| 284 |
+
[](https://insiders.vscode.dev/redirect/mcp/install?name=filesystem&config=%7B%22command%22%3A%22docker%22%2C%22args%22%3A%5B%22run%22%2C%22-i%22%2C%22--rm%22%2C%22--mount%22%2C%22type%3Dbind%2Csrc%3D%24%7BworkspaceFolder%7D%2Cdst%3D%2Fprojects%2Fworkspace%22%2C%22mcp%2Ffilesystem%22%2C%22%2Fprojects%22%5D%7D) [](https://insiders.vscode.dev/redirect/mcp/install?name=filesystem&config=%7B%22command%22%3A%22docker%22%2C%22args%22%3A%5B%22run%22%2C%22-i%22%2C%22--rm%22%2C%22--mount%22%2C%22type%3Dbind%2Csrc%3D%24%7BworkspaceFolder%7D%2Cdst%3D%2Fprojects%2Fworkspace%22%2C%22mcp%2Ffilesystem%22%2C%22%2Fprojects%22%5D%7D&quality=insiders)
|
| 285 |
+
|
| 286 |
+
For manual installation, you can configure the MCP server using one of these methods:
|
| 287 |
+
|
| 288 |
+
**Method 1: User Configuration (Recommended)**
|
| 289 |
+
Add the configuration to your user-level MCP configuration file. Open the Command Palette (`Ctrl + Shift + P`) and run `MCP: Open User Configuration`. This will open your user `mcp.json` file where you can add the server configuration.
|
| 290 |
+
|
| 291 |
+
**Method 2: Workspace Configuration**
|
| 292 |
+
Alternatively, you can add the configuration to a file called `.vscode/mcp.json` in your workspace. This will allow you to share the configuration with others.
|
| 293 |
+
|
| 294 |
+
> For more details about MCP configuration in VS Code, see the [official VS Code MCP documentation](https://code.visualstudio.com/docs/copilot/customization/mcp-servers).
|
| 295 |
+
|
| 296 |
+
You can provide sandboxed directories to the server by mounting them to `/projects`. Adding the `ro` flag will make the directory readonly by the server.
|
| 297 |
+
|
| 298 |
+
### Docker
|
| 299 |
+
Note: all directories must be mounted to `/projects` by default.
|
| 300 |
+
|
| 301 |
+
```json
|
| 302 |
+
{
|
| 303 |
+
"servers": {
|
| 304 |
+
"filesystem": {
|
| 305 |
+
"command": "docker",
|
| 306 |
+
"args": [
|
| 307 |
+
"run",
|
| 308 |
+
"-i",
|
| 309 |
+
"--rm",
|
| 310 |
+
"--mount", "type=bind,src=${workspaceFolder},dst=/projects/workspace",
|
| 311 |
+
"mcp/filesystem",
|
| 312 |
+
"/projects"
|
| 313 |
+
]
|
| 314 |
+
}
|
| 315 |
+
}
|
| 316 |
+
}
|
| 317 |
+
```
|
| 318 |
+
|
| 319 |
+
### NPX
|
| 320 |
+
|
| 321 |
+
```json
|
| 322 |
+
{
|
| 323 |
+
"servers": {
|
| 324 |
+
"filesystem": {
|
| 325 |
+
"command": "npx",
|
| 326 |
+
"args": [
|
| 327 |
+
"-y",
|
| 328 |
+
"@modelcontextprotocol/server-filesystem",
|
| 329 |
+
"${workspaceFolder}"
|
| 330 |
+
]
|
| 331 |
+
}
|
| 332 |
+
}
|
| 333 |
+
}
|
| 334 |
+
```
|
| 335 |
+
|
| 336 |
+
On Windows, use:
|
| 337 |
+
|
| 338 |
+
```json
|
| 339 |
+
{
|
| 340 |
+
"servers": {
|
| 341 |
+
"filesystem": {
|
| 342 |
+
"command": "cmd",
|
| 343 |
+
"args": [
|
| 344 |
+
"/c",
|
| 345 |
+
"npx",
|
| 346 |
+
"-y",
|
| 347 |
+
"@modelcontextprotocol/server-filesystem",
|
| 348 |
+
"${workspaceFolder}"
|
| 349 |
+
]
|
| 350 |
+
}
|
| 351 |
+
}
|
| 352 |
+
}
|
| 353 |
+
```
|
| 354 |
+
|
| 355 |
+
## Build
|
| 356 |
+
|
| 357 |
+
Docker build:
|
| 358 |
+
|
| 359 |
+
```bash
|
| 360 |
+
docker build -t mcp/filesystem -f src/filesystem/Dockerfile .
|
| 361 |
+
```
|
| 362 |
+
|
| 363 |
+
## License
|
| 364 |
+
|
| 365 |
+
This MCP server is licensed under the MIT License. This means you are free to use, modify, and distribute the software, subject to the terms and conditions of the MIT License. For more details, please see the LICENSE file in the project repository.
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/dist/index.js
ADDED
|
@@ -0,0 +1,637 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env node
|
| 2 |
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
| 3 |
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
| 4 |
+
import { RootsListChangedNotificationSchema, } from "@modelcontextprotocol/sdk/types.js";
|
| 5 |
+
import fs from "fs/promises";
|
| 6 |
+
import { createReadStream } from "fs";
|
| 7 |
+
import path from "path";
|
| 8 |
+
import { pathToFileURL } from "url";
|
| 9 |
+
import { z } from "zod";
|
| 10 |
+
import { minimatch } from "minimatch";
|
| 11 |
+
import { normalizePath, expandHome } from './path-utils.js';
|
| 12 |
+
import { getValidRootDirectories } from './roots-utils.js';
|
| 13 |
+
import {
|
| 14 |
+
// Function imports
|
| 15 |
+
formatSize, validatePath, getFileStats, readFileContent, writeFileContent, moveFile, searchFilesWithValidation, applyFileEdits, tailFile, headFile, setAllowedDirectories, } from './lib.js';
|
| 16 |
+
// Command line argument parsing
|
| 17 |
+
const args = process.argv.slice(2);
|
| 18 |
+
if (args.length === 0) {
|
| 19 |
+
console.error("Usage: mcp-server-filesystem [allowed-directory] [additional-directories...]");
|
| 20 |
+
console.error("Note: Allowed directories can be provided via:");
|
| 21 |
+
console.error(" 1. Command-line arguments (shown above)");
|
| 22 |
+
console.error(" 2. MCP roots protocol (if client supports it)");
|
| 23 |
+
console.error("At least one directory must be provided by EITHER method for the server to operate.");
|
| 24 |
+
}
|
| 25 |
+
// Store allowed directories in normalized and resolved form
|
| 26 |
+
// We store BOTH the original path AND the resolved path to handle symlinks correctly
|
| 27 |
+
// This fixes the macOS /tmp -> /private/tmp symlink issue where users specify /tmp
|
| 28 |
+
// but the resolved path is /private/tmp
|
| 29 |
+
let allowedDirectories = (await Promise.all(args.map(async (dir) => {
|
| 30 |
+
const expanded = expandHome(dir);
|
| 31 |
+
const absolute = path.resolve(expanded);
|
| 32 |
+
const normalizedOriginal = normalizePath(absolute);
|
| 33 |
+
try {
|
| 34 |
+
// Security: Resolve symlinks in allowed directories during startup
|
| 35 |
+
// This ensures we know the real paths and can validate against them later
|
| 36 |
+
const resolved = await fs.realpath(absolute);
|
| 37 |
+
const normalizedResolved = normalizePath(resolved);
|
| 38 |
+
// Return both original and resolved paths if they differ
|
| 39 |
+
// This allows matching against either /tmp or /private/tmp on macOS
|
| 40 |
+
if (normalizedOriginal !== normalizedResolved) {
|
| 41 |
+
return [normalizedOriginal, normalizedResolved];
|
| 42 |
+
}
|
| 43 |
+
return [normalizedResolved];
|
| 44 |
+
}
|
| 45 |
+
catch (error) {
|
| 46 |
+
// If we can't resolve (doesn't exist), use the normalized absolute path
|
| 47 |
+
// This allows configuring allowed dirs that will be created later
|
| 48 |
+
return [normalizedOriginal];
|
| 49 |
+
}
|
| 50 |
+
}))).flat();
|
| 51 |
+
// Filter to only accessible directories, warn about inaccessible ones
|
| 52 |
+
const accessibleDirectories = [];
|
| 53 |
+
for (const dir of allowedDirectories) {
|
| 54 |
+
try {
|
| 55 |
+
const stats = await fs.stat(dir);
|
| 56 |
+
if (stats.isDirectory()) {
|
| 57 |
+
accessibleDirectories.push(dir);
|
| 58 |
+
}
|
| 59 |
+
else {
|
| 60 |
+
console.error(`Warning: ${dir} is not a directory, skipping`);
|
| 61 |
+
}
|
| 62 |
+
}
|
| 63 |
+
catch (error) {
|
| 64 |
+
console.error(`Warning: Cannot access directory ${dir}, skipping`);
|
| 65 |
+
}
|
| 66 |
+
}
|
| 67 |
+
// Exit only if ALL paths are inaccessible (and some were specified)
|
| 68 |
+
if (accessibleDirectories.length === 0 && allowedDirectories.length > 0) {
|
| 69 |
+
console.error("Error: None of the specified directories are accessible");
|
| 70 |
+
process.exit(1);
|
| 71 |
+
}
|
| 72 |
+
allowedDirectories = accessibleDirectories;
|
| 73 |
+
// Initialize the global allowedDirectories in lib.ts
|
| 74 |
+
setAllowedDirectories(allowedDirectories);
|
| 75 |
+
// Schema definitions
|
| 76 |
+
const ReadTextFileArgsSchema = z.object({
|
| 77 |
+
path: z.string(),
|
| 78 |
+
tail: z.number().optional().describe('If provided, returns only the last N lines of the file'),
|
| 79 |
+
head: z.number().optional().describe('If provided, returns only the first N lines of the file')
|
| 80 |
+
});
|
| 81 |
+
const ReadMediaFileArgsSchema = z.object({
|
| 82 |
+
path: z.string()
|
| 83 |
+
});
|
| 84 |
+
const ReadMultipleFilesArgsSchema = z.object({
|
| 85 |
+
paths: z
|
| 86 |
+
.array(z.string())
|
| 87 |
+
.min(1, "At least one file path must be provided")
|
| 88 |
+
.describe("Array of file paths to read. Each path must be a string pointing to a valid file within allowed directories."),
|
| 89 |
+
});
|
| 90 |
+
const WriteFileArgsSchema = z.object({
|
| 91 |
+
path: z.string(),
|
| 92 |
+
content: z.string(),
|
| 93 |
+
});
|
| 94 |
+
const EditOperation = z.object({
|
| 95 |
+
oldText: z.string().describe('Text to search for - must match exactly'),
|
| 96 |
+
newText: z.string().describe('Text to replace with')
|
| 97 |
+
});
|
| 98 |
+
const EditFileArgsSchema = z.object({
|
| 99 |
+
path: z.string(),
|
| 100 |
+
edits: z.array(EditOperation),
|
| 101 |
+
dryRun: z.boolean().default(false).describe('Preview changes using git-style diff format')
|
| 102 |
+
});
|
| 103 |
+
const CreateDirectoryArgsSchema = z.object({
|
| 104 |
+
path: z.string(),
|
| 105 |
+
});
|
| 106 |
+
const ListDirectoryArgsSchema = z.object({
|
| 107 |
+
path: z.string(),
|
| 108 |
+
});
|
| 109 |
+
const ListDirectoryWithSizesArgsSchema = z.object({
|
| 110 |
+
path: z.string(),
|
| 111 |
+
sortBy: z.enum(['name', 'size']).optional().default('name').describe('Sort entries by name or size'),
|
| 112 |
+
});
|
| 113 |
+
const DirectoryTreeArgsSchema = z.object({
|
| 114 |
+
path: z.string(),
|
| 115 |
+
excludePatterns: z.array(z.string()).optional().default([])
|
| 116 |
+
});
|
| 117 |
+
const MoveFileArgsSchema = z.object({
|
| 118 |
+
source: z.string(),
|
| 119 |
+
destination: z.string(),
|
| 120 |
+
});
|
| 121 |
+
const SearchFilesArgsSchema = z.object({
|
| 122 |
+
path: z.string(),
|
| 123 |
+
pattern: z.string(),
|
| 124 |
+
excludePatterns: z.array(z.string()).optional().default([])
|
| 125 |
+
});
|
| 126 |
+
const GetFileInfoArgsSchema = z.object({
|
| 127 |
+
path: z.string(),
|
| 128 |
+
});
|
| 129 |
+
// Server setup
|
| 130 |
+
const server = new McpServer({
|
| 131 |
+
name: "secure-filesystem-server",
|
| 132 |
+
version: "0.2.0",
|
| 133 |
+
});
|
| 134 |
+
// Reads a file as a stream of buffers, concatenates them, and then encodes
|
| 135 |
+
// the result to a Base64 string. This is a memory-efficient way to handle
|
| 136 |
+
// binary data from a stream before the final encoding.
|
| 137 |
+
async function readFileAsBase64Stream(filePath) {
|
| 138 |
+
return new Promise((resolve, reject) => {
|
| 139 |
+
const stream = createReadStream(filePath);
|
| 140 |
+
const chunks = [];
|
| 141 |
+
stream.on('data', (chunk) => {
|
| 142 |
+
chunks.push(chunk);
|
| 143 |
+
});
|
| 144 |
+
stream.on('end', () => {
|
| 145 |
+
const finalBuffer = Buffer.concat(chunks);
|
| 146 |
+
resolve(finalBuffer.toString('base64'));
|
| 147 |
+
});
|
| 148 |
+
stream.on('error', (err) => reject(err));
|
| 149 |
+
});
|
| 150 |
+
}
|
| 151 |
+
// Tool registrations
|
| 152 |
+
// read_file (deprecated) and read_text_file
|
| 153 |
+
const readTextFileHandler = async (args) => {
|
| 154 |
+
const validPath = await validatePath(args.path);
|
| 155 |
+
if (args.head && args.tail) {
|
| 156 |
+
throw new Error("Cannot specify both head and tail parameters simultaneously");
|
| 157 |
+
}
|
| 158 |
+
let content;
|
| 159 |
+
if (args.tail) {
|
| 160 |
+
content = await tailFile(validPath, args.tail);
|
| 161 |
+
}
|
| 162 |
+
else if (args.head) {
|
| 163 |
+
content = await headFile(validPath, args.head);
|
| 164 |
+
}
|
| 165 |
+
else {
|
| 166 |
+
content = await readFileContent(validPath);
|
| 167 |
+
}
|
| 168 |
+
return {
|
| 169 |
+
content: [{ type: "text", text: content }],
|
| 170 |
+
structuredContent: { content }
|
| 171 |
+
};
|
| 172 |
+
};
|
| 173 |
+
server.registerTool("read_file", {
|
| 174 |
+
title: "Read File (Deprecated)",
|
| 175 |
+
description: "Read the complete contents of a file as text. DEPRECATED: Use read_text_file instead.",
|
| 176 |
+
inputSchema: ReadTextFileArgsSchema.shape,
|
| 177 |
+
outputSchema: { content: z.string() },
|
| 178 |
+
annotations: { readOnlyHint: true, openWorldHint: false }
|
| 179 |
+
}, readTextFileHandler);
|
| 180 |
+
server.registerTool("read_text_file", {
|
| 181 |
+
title: "Read Text File",
|
| 182 |
+
description: "Read the complete contents of a file from the file system as text. " +
|
| 183 |
+
"Handles various text encodings and provides detailed error messages " +
|
| 184 |
+
"if the file cannot be read. Use this tool when you need to examine " +
|
| 185 |
+
"the contents of a single file. Use the 'head' parameter to read only " +
|
| 186 |
+
"the first N lines of a file, or the 'tail' parameter to read only " +
|
| 187 |
+
"the last N lines of a file. Operates on the file as text regardless of extension. " +
|
| 188 |
+
"Only works within allowed directories.",
|
| 189 |
+
inputSchema: {
|
| 190 |
+
path: z.string(),
|
| 191 |
+
tail: z.number().optional().describe("If provided, returns only the last N lines of the file"),
|
| 192 |
+
head: z.number().optional().describe("If provided, returns only the first N lines of the file")
|
| 193 |
+
},
|
| 194 |
+
outputSchema: { content: z.string() },
|
| 195 |
+
annotations: { readOnlyHint: true, openWorldHint: false }
|
| 196 |
+
}, readTextFileHandler);
|
| 197 |
+
server.registerTool("read_media_file", {
|
| 198 |
+
title: "Read Media File",
|
| 199 |
+
description: "Read a file and return it as a base64-encoded content block with its MIME type. " +
|
| 200 |
+
"Image and audio files are returned as image/audio content; any other file type is " +
|
| 201 |
+
"returned as an embedded resource. Only works within allowed directories.",
|
| 202 |
+
inputSchema: {
|
| 203 |
+
path: z.string()
|
| 204 |
+
},
|
| 205 |
+
outputSchema: {
|
| 206 |
+
content: z.array(z.union([
|
| 207 |
+
z.object({
|
| 208 |
+
type: z.enum(["image", "audio"]),
|
| 209 |
+
data: z.string(),
|
| 210 |
+
mimeType: z.string()
|
| 211 |
+
}),
|
| 212 |
+
z.object({
|
| 213 |
+
type: z.literal("resource"),
|
| 214 |
+
resource: z.object({
|
| 215 |
+
uri: z.string(),
|
| 216 |
+
// Optional, matching the SDK's BlobResourceContents shape (the handler always sets it).
|
| 217 |
+
mimeType: z.string().optional(),
|
| 218 |
+
blob: z.string()
|
| 219 |
+
})
|
| 220 |
+
})
|
| 221 |
+
]))
|
| 222 |
+
},
|
| 223 |
+
annotations: { readOnlyHint: true, openWorldHint: false }
|
| 224 |
+
}, async (args) => {
|
| 225 |
+
const validPath = await validatePath(args.path);
|
| 226 |
+
const extension = path.extname(validPath).toLowerCase();
|
| 227 |
+
const mimeTypes = {
|
| 228 |
+
".png": "image/png",
|
| 229 |
+
".jpg": "image/jpeg",
|
| 230 |
+
".jpeg": "image/jpeg",
|
| 231 |
+
".gif": "image/gif",
|
| 232 |
+
".webp": "image/webp",
|
| 233 |
+
".bmp": "image/bmp",
|
| 234 |
+
".svg": "image/svg+xml",
|
| 235 |
+
".mp3": "audio/mpeg",
|
| 236 |
+
".wav": "audio/wav",
|
| 237 |
+
".ogg": "audio/ogg",
|
| 238 |
+
".flac": "audio/flac",
|
| 239 |
+
};
|
| 240 |
+
const mimeType = mimeTypes[extension] || "application/octet-stream";
|
| 241 |
+
const data = await readFileAsBase64Stream(validPath);
|
| 242 |
+
// Map the MIME type to a valid MCP content block. The spec only allows
|
| 243 |
+
// text, image, audio, resource_link, and resource — so non-image/audio
|
| 244 |
+
// binaries are returned as an embedded resource (NOT type:"blob", which the
|
| 245 |
+
// SDK content-block union rejects on schema validation).
|
| 246 |
+
const contentItem = mimeType.startsWith("image/")
|
| 247 |
+
? { type: "image", data, mimeType }
|
| 248 |
+
: mimeType.startsWith("audio/")
|
| 249 |
+
? { type: "audio", data, mimeType }
|
| 250 |
+
: {
|
| 251 |
+
type: "resource",
|
| 252 |
+
resource: { uri: pathToFileURL(validPath).href, mimeType, blob: data }
|
| 253 |
+
};
|
| 254 |
+
return {
|
| 255 |
+
content: [contentItem],
|
| 256 |
+
structuredContent: { content: [contentItem] }
|
| 257 |
+
};
|
| 258 |
+
});
|
| 259 |
+
server.registerTool("read_multiple_files", {
|
| 260 |
+
title: "Read Multiple Files",
|
| 261 |
+
description: "Read the contents of multiple files simultaneously. This is more " +
|
| 262 |
+
"efficient than reading files one by one when you need to analyze " +
|
| 263 |
+
"or compare multiple files. Each file's content is returned with its " +
|
| 264 |
+
"path as a reference. Failed reads for individual files won't stop " +
|
| 265 |
+
"the entire operation. Only works within allowed directories.",
|
| 266 |
+
inputSchema: {
|
| 267 |
+
paths: z.array(z.string())
|
| 268 |
+
.min(1)
|
| 269 |
+
.describe("Array of file paths to read. Each path must be a string pointing to a valid file within allowed directories.")
|
| 270 |
+
},
|
| 271 |
+
outputSchema: { content: z.string() },
|
| 272 |
+
annotations: { readOnlyHint: true, openWorldHint: false }
|
| 273 |
+
}, async (args) => {
|
| 274 |
+
const results = await Promise.all(args.paths.map(async (filePath) => {
|
| 275 |
+
try {
|
| 276 |
+
const validPath = await validatePath(filePath);
|
| 277 |
+
const content = await readFileContent(validPath);
|
| 278 |
+
return `${filePath}:\n${content}\n`;
|
| 279 |
+
}
|
| 280 |
+
catch (error) {
|
| 281 |
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
| 282 |
+
return `${filePath}: Error - ${errorMessage}`;
|
| 283 |
+
}
|
| 284 |
+
}));
|
| 285 |
+
const text = results.join("\n---\n");
|
| 286 |
+
return {
|
| 287 |
+
content: [{ type: "text", text }],
|
| 288 |
+
structuredContent: { content: text }
|
| 289 |
+
};
|
| 290 |
+
});
|
| 291 |
+
server.registerTool("write_file", {
|
| 292 |
+
title: "Write File",
|
| 293 |
+
description: "Create a new file or completely overwrite an existing file with new content. " +
|
| 294 |
+
"Use with caution as it will overwrite existing files without warning. " +
|
| 295 |
+
"Handles text content with proper encoding. Only works within allowed directories.",
|
| 296 |
+
inputSchema: {
|
| 297 |
+
path: z.string(),
|
| 298 |
+
content: z.string()
|
| 299 |
+
},
|
| 300 |
+
outputSchema: { content: z.string() },
|
| 301 |
+
annotations: { readOnlyHint: false, idempotentHint: true, destructiveHint: true, openWorldHint: false }
|
| 302 |
+
}, async (args) => {
|
| 303 |
+
const validPath = await validatePath(args.path);
|
| 304 |
+
await writeFileContent(validPath, args.content);
|
| 305 |
+
const text = `Successfully wrote to ${args.path}`;
|
| 306 |
+
return {
|
| 307 |
+
content: [{ type: "text", text }],
|
| 308 |
+
structuredContent: { content: text }
|
| 309 |
+
};
|
| 310 |
+
});
|
| 311 |
+
server.registerTool("edit_file", {
|
| 312 |
+
title: "Edit File",
|
| 313 |
+
description: "Make line-based edits to a text file. Each edit replaces exact line sequences " +
|
| 314 |
+
"with new content. Returns a git-style diff showing the changes made. " +
|
| 315 |
+
"Only works within allowed directories.",
|
| 316 |
+
inputSchema: {
|
| 317 |
+
path: z.string(),
|
| 318 |
+
edits: z.array(z.object({
|
| 319 |
+
oldText: z.string().describe("Text to search for - must match exactly"),
|
| 320 |
+
newText: z.string().describe("Text to replace with")
|
| 321 |
+
})),
|
| 322 |
+
dryRun: z.boolean().default(false).describe("Preview changes using git-style diff format")
|
| 323 |
+
},
|
| 324 |
+
outputSchema: { content: z.string() },
|
| 325 |
+
annotations: { readOnlyHint: false, idempotentHint: false, destructiveHint: true, openWorldHint: false }
|
| 326 |
+
}, async (args) => {
|
| 327 |
+
const validPath = await validatePath(args.path);
|
| 328 |
+
const result = await applyFileEdits(validPath, args.edits, args.dryRun);
|
| 329 |
+
return {
|
| 330 |
+
content: [{ type: "text", text: result }],
|
| 331 |
+
structuredContent: { content: result }
|
| 332 |
+
};
|
| 333 |
+
});
|
| 334 |
+
server.registerTool("create_directory", {
|
| 335 |
+
title: "Create Directory",
|
| 336 |
+
description: "Create a new directory or ensure a directory exists. Can create multiple " +
|
| 337 |
+
"nested directories in one operation. If the directory already exists, " +
|
| 338 |
+
"this operation will succeed silently. Perfect for setting up directory " +
|
| 339 |
+
"structures for projects or ensuring required paths exist. Only works within allowed directories.",
|
| 340 |
+
inputSchema: {
|
| 341 |
+
path: z.string()
|
| 342 |
+
},
|
| 343 |
+
outputSchema: { content: z.string() },
|
| 344 |
+
annotations: { readOnlyHint: false, idempotentHint: true, destructiveHint: false, openWorldHint: false }
|
| 345 |
+
}, async (args) => {
|
| 346 |
+
const validPath = await validatePath(args.path);
|
| 347 |
+
await fs.mkdir(validPath, { recursive: true });
|
| 348 |
+
const text = `Successfully created directory ${args.path}`;
|
| 349 |
+
return {
|
| 350 |
+
content: [{ type: "text", text }],
|
| 351 |
+
structuredContent: { content: text }
|
| 352 |
+
};
|
| 353 |
+
});
|
| 354 |
+
server.registerTool("list_directory", {
|
| 355 |
+
title: "List Directory",
|
| 356 |
+
description: "Get a detailed listing of all files and directories in a specified path. " +
|
| 357 |
+
"Results clearly distinguish between files and directories with [FILE] and [DIR] " +
|
| 358 |
+
"prefixes. This tool is essential for understanding directory structure and " +
|
| 359 |
+
"finding specific files within a directory. Only works within allowed directories.",
|
| 360 |
+
inputSchema: {
|
| 361 |
+
path: z.string()
|
| 362 |
+
},
|
| 363 |
+
outputSchema: { content: z.string() },
|
| 364 |
+
annotations: { readOnlyHint: true, openWorldHint: false }
|
| 365 |
+
}, async (args) => {
|
| 366 |
+
const validPath = await validatePath(args.path);
|
| 367 |
+
const entries = await fs.readdir(validPath, { withFileTypes: true });
|
| 368 |
+
const formatted = entries
|
| 369 |
+
.map((entry) => `${entry.isDirectory() ? "[DIR]" : "[FILE]"} ${entry.name}`)
|
| 370 |
+
.join("\n");
|
| 371 |
+
return {
|
| 372 |
+
content: [{ type: "text", text: formatted }],
|
| 373 |
+
structuredContent: { content: formatted }
|
| 374 |
+
};
|
| 375 |
+
});
|
| 376 |
+
server.registerTool("list_directory_with_sizes", {
|
| 377 |
+
title: "List Directory with Sizes",
|
| 378 |
+
description: "Get a detailed listing of all files and directories in a specified path, including sizes. " +
|
| 379 |
+
"Results clearly distinguish between files and directories with [FILE] and [DIR] " +
|
| 380 |
+
"prefixes. This tool is useful for understanding directory structure and " +
|
| 381 |
+
"finding specific files within a directory. Only works within allowed directories.",
|
| 382 |
+
inputSchema: {
|
| 383 |
+
path: z.string(),
|
| 384 |
+
sortBy: z.enum(["name", "size"]).optional().default("name").describe("Sort entries by name or size")
|
| 385 |
+
},
|
| 386 |
+
outputSchema: { content: z.string() },
|
| 387 |
+
annotations: { readOnlyHint: true, openWorldHint: false }
|
| 388 |
+
}, async (args) => {
|
| 389 |
+
const validPath = await validatePath(args.path);
|
| 390 |
+
const entries = await fs.readdir(validPath, { withFileTypes: true });
|
| 391 |
+
// Get detailed information for each entry
|
| 392 |
+
const detailedEntries = await Promise.all(entries.map(async (entry) => {
|
| 393 |
+
const entryPath = path.join(validPath, entry.name);
|
| 394 |
+
try {
|
| 395 |
+
const stats = await fs.stat(entryPath);
|
| 396 |
+
return {
|
| 397 |
+
name: entry.name,
|
| 398 |
+
isDirectory: entry.isDirectory(),
|
| 399 |
+
size: stats.size,
|
| 400 |
+
mtime: stats.mtime
|
| 401 |
+
};
|
| 402 |
+
}
|
| 403 |
+
catch (error) {
|
| 404 |
+
return {
|
| 405 |
+
name: entry.name,
|
| 406 |
+
isDirectory: entry.isDirectory(),
|
| 407 |
+
size: 0,
|
| 408 |
+
mtime: new Date(0)
|
| 409 |
+
};
|
| 410 |
+
}
|
| 411 |
+
}));
|
| 412 |
+
// Sort entries based on sortBy parameter
|
| 413 |
+
const sortedEntries = [...detailedEntries].sort((a, b) => {
|
| 414 |
+
if (args.sortBy === 'size') {
|
| 415 |
+
return b.size - a.size; // Descending by size
|
| 416 |
+
}
|
| 417 |
+
// Default sort by name
|
| 418 |
+
return a.name.localeCompare(b.name);
|
| 419 |
+
});
|
| 420 |
+
// Format the output
|
| 421 |
+
const formattedEntries = sortedEntries.map(entry => `${entry.isDirectory ? "[DIR]" : "[FILE]"} ${entry.name.padEnd(30)} ${entry.isDirectory ? "" : formatSize(entry.size).padStart(10)}`);
|
| 422 |
+
// Add summary
|
| 423 |
+
const totalFiles = detailedEntries.filter(e => !e.isDirectory).length;
|
| 424 |
+
const totalDirs = detailedEntries.filter(e => e.isDirectory).length;
|
| 425 |
+
const totalSize = detailedEntries.reduce((sum, entry) => sum + (entry.isDirectory ? 0 : entry.size), 0);
|
| 426 |
+
const summary = [
|
| 427 |
+
"",
|
| 428 |
+
`Total: ${totalFiles} files, ${totalDirs} directories`,
|
| 429 |
+
`Combined size: ${formatSize(totalSize)}`
|
| 430 |
+
];
|
| 431 |
+
const text = [...formattedEntries, ...summary].join("\n");
|
| 432 |
+
const contentBlock = { type: "text", text };
|
| 433 |
+
return {
|
| 434 |
+
content: [contentBlock],
|
| 435 |
+
structuredContent: { content: text }
|
| 436 |
+
};
|
| 437 |
+
});
|
| 438 |
+
server.registerTool("directory_tree", {
|
| 439 |
+
title: "Directory Tree",
|
| 440 |
+
description: "Get a recursive tree view of files and directories as a JSON structure. " +
|
| 441 |
+
"Each entry includes 'name', 'type' (file/directory), and 'children' for directories. " +
|
| 442 |
+
"Files have no children array, while directories always have a children array (which may be empty). " +
|
| 443 |
+
"The output is formatted with 2-space indentation for readability. Only works within allowed directories.",
|
| 444 |
+
inputSchema: {
|
| 445 |
+
path: z.string(),
|
| 446 |
+
excludePatterns: z.array(z.string()).optional().default([])
|
| 447 |
+
},
|
| 448 |
+
outputSchema: { content: z.string() },
|
| 449 |
+
annotations: { readOnlyHint: true, openWorldHint: false }
|
| 450 |
+
}, async (args) => {
|
| 451 |
+
const rootPath = args.path;
|
| 452 |
+
async function buildTree(currentPath, excludePatterns = []) {
|
| 453 |
+
const validPath = await validatePath(currentPath);
|
| 454 |
+
const entries = await fs.readdir(validPath, { withFileTypes: true });
|
| 455 |
+
const result = [];
|
| 456 |
+
for (const entry of entries) {
|
| 457 |
+
const relativePath = path.relative(rootPath, path.join(currentPath, entry.name));
|
| 458 |
+
const shouldExclude = excludePatterns.some(pattern => {
|
| 459 |
+
if (pattern.includes('*')) {
|
| 460 |
+
return minimatch(relativePath, pattern, { dot: true });
|
| 461 |
+
}
|
| 462 |
+
// For files: match exact name or as part of path
|
| 463 |
+
// For directories: match as directory path
|
| 464 |
+
return minimatch(relativePath, pattern, { dot: true }) ||
|
| 465 |
+
minimatch(relativePath, `**/${pattern}`, { dot: true }) ||
|
| 466 |
+
minimatch(relativePath, `**/${pattern}/**`, { dot: true });
|
| 467 |
+
});
|
| 468 |
+
if (shouldExclude)
|
| 469 |
+
continue;
|
| 470 |
+
const entryData = {
|
| 471 |
+
name: entry.name,
|
| 472 |
+
type: entry.isDirectory() ? 'directory' : 'file'
|
| 473 |
+
};
|
| 474 |
+
if (entry.isDirectory()) {
|
| 475 |
+
const subPath = path.join(currentPath, entry.name);
|
| 476 |
+
entryData.children = await buildTree(subPath, excludePatterns);
|
| 477 |
+
}
|
| 478 |
+
result.push(entryData);
|
| 479 |
+
}
|
| 480 |
+
return result;
|
| 481 |
+
}
|
| 482 |
+
const treeData = await buildTree(rootPath, args.excludePatterns);
|
| 483 |
+
const text = JSON.stringify(treeData, null, 2);
|
| 484 |
+
const contentBlock = { type: "text", text };
|
| 485 |
+
return {
|
| 486 |
+
content: [contentBlock],
|
| 487 |
+
structuredContent: { content: text }
|
| 488 |
+
};
|
| 489 |
+
});
|
| 490 |
+
server.registerTool("move_file", {
|
| 491 |
+
title: "Move File",
|
| 492 |
+
description: "Move or rename files and directories. Can move files between directories " +
|
| 493 |
+
"and rename them in a single operation. If the destination exists, the " +
|
| 494 |
+
"operation will fail. Works across different directories and can be used " +
|
| 495 |
+
"for simple renaming within the same directory. Both source and destination must be within allowed directories.",
|
| 496 |
+
inputSchema: {
|
| 497 |
+
source: z.string(),
|
| 498 |
+
destination: z.string()
|
| 499 |
+
},
|
| 500 |
+
outputSchema: { content: z.string() },
|
| 501 |
+
annotations: { readOnlyHint: false, idempotentHint: false, destructiveHint: true, openWorldHint: false }
|
| 502 |
+
}, async (args) => {
|
| 503 |
+
const validSourcePath = await validatePath(args.source);
|
| 504 |
+
const validDestPath = await validatePath(args.destination);
|
| 505 |
+
await moveFile(validSourcePath, validDestPath);
|
| 506 |
+
const text = `Successfully moved ${args.source} to ${args.destination}`;
|
| 507 |
+
const contentBlock = { type: "text", text };
|
| 508 |
+
return {
|
| 509 |
+
content: [contentBlock],
|
| 510 |
+
structuredContent: { content: text }
|
| 511 |
+
};
|
| 512 |
+
});
|
| 513 |
+
server.registerTool("search_files", {
|
| 514 |
+
title: "Search Files",
|
| 515 |
+
description: "Recursively search for files and directories matching a pattern. " +
|
| 516 |
+
"The patterns should be glob-style patterns that match paths relative to the working directory. " +
|
| 517 |
+
"Use pattern like '*.ext' to match files in current directory, and '**/*.ext' to match files in all subdirectories. " +
|
| 518 |
+
"Returns full paths to all matching items. Great for finding files when you don't know their exact location. " +
|
| 519 |
+
"Only searches within allowed directories.",
|
| 520 |
+
inputSchema: {
|
| 521 |
+
path: z.string(),
|
| 522 |
+
pattern: z.string(),
|
| 523 |
+
excludePatterns: z.array(z.string()).optional().default([])
|
| 524 |
+
},
|
| 525 |
+
outputSchema: { content: z.string() },
|
| 526 |
+
annotations: { readOnlyHint: true, openWorldHint: false }
|
| 527 |
+
}, async (args) => {
|
| 528 |
+
const validPath = await validatePath(args.path);
|
| 529 |
+
const results = await searchFilesWithValidation(validPath, args.pattern, allowedDirectories, { excludePatterns: args.excludePatterns });
|
| 530 |
+
const text = results.length > 0 ? results.join("\n") : "No matches found";
|
| 531 |
+
return {
|
| 532 |
+
content: [{ type: "text", text }],
|
| 533 |
+
structuredContent: { content: text }
|
| 534 |
+
};
|
| 535 |
+
});
|
| 536 |
+
server.registerTool("get_file_info", {
|
| 537 |
+
title: "Get File Info",
|
| 538 |
+
description: "Retrieve detailed metadata about a file or directory. Returns comprehensive " +
|
| 539 |
+
"information including size, creation time, last modified time, permissions, " +
|
| 540 |
+
"and type. This tool is perfect for understanding file characteristics " +
|
| 541 |
+
"without reading the actual content. Only works within allowed directories.",
|
| 542 |
+
inputSchema: {
|
| 543 |
+
path: z.string()
|
| 544 |
+
},
|
| 545 |
+
outputSchema: { content: z.string() },
|
| 546 |
+
annotations: { readOnlyHint: true, openWorldHint: false }
|
| 547 |
+
}, async (args) => {
|
| 548 |
+
const validPath = await validatePath(args.path);
|
| 549 |
+
const info = await getFileStats(validPath);
|
| 550 |
+
const text = Object.entries(info)
|
| 551 |
+
.map(([key, value]) => `${key}: ${value}`)
|
| 552 |
+
.join("\n");
|
| 553 |
+
return {
|
| 554 |
+
content: [{ type: "text", text }],
|
| 555 |
+
structuredContent: { content: text }
|
| 556 |
+
};
|
| 557 |
+
});
|
| 558 |
+
server.registerTool("list_allowed_directories", {
|
| 559 |
+
title: "List Allowed Directories",
|
| 560 |
+
description: "Returns the list of directories that this server is allowed to access. " +
|
| 561 |
+
"Subdirectories within these allowed directories are also accessible. " +
|
| 562 |
+
"Use this to understand which directories and their nested paths are available " +
|
| 563 |
+
"before trying to access files.",
|
| 564 |
+
inputSchema: {},
|
| 565 |
+
outputSchema: { content: z.string() },
|
| 566 |
+
annotations: { readOnlyHint: true, openWorldHint: false }
|
| 567 |
+
}, async () => {
|
| 568 |
+
const text = `Allowed directories:\n${allowedDirectories.join('\n')}`;
|
| 569 |
+
return {
|
| 570 |
+
content: [{ type: "text", text }],
|
| 571 |
+
structuredContent: { content: text }
|
| 572 |
+
};
|
| 573 |
+
});
|
| 574 |
+
// Updates allowed directories based on MCP client roots
|
| 575 |
+
async function updateAllowedDirectoriesFromRoots(requestedRoots) {
|
| 576 |
+
const validatedRootDirs = await getValidRootDirectories(requestedRoots);
|
| 577 |
+
if (validatedRootDirs.length > 0) {
|
| 578 |
+
allowedDirectories = [...validatedRootDirs];
|
| 579 |
+
setAllowedDirectories(allowedDirectories); // Update the global state in lib.ts
|
| 580 |
+
console.error(`Updated allowed directories from MCP roots: ${validatedRootDirs.length} valid directories`);
|
| 581 |
+
}
|
| 582 |
+
else {
|
| 583 |
+
console.error("No valid root directories provided by client");
|
| 584 |
+
}
|
| 585 |
+
}
|
| 586 |
+
// Handles dynamic roots updates during runtime, when client sends "roots/list_changed" notification, server fetches the updated roots and replaces all allowed directories with the new roots.
|
| 587 |
+
server.server.setNotificationHandler(RootsListChangedNotificationSchema, async () => {
|
| 588 |
+
try {
|
| 589 |
+
// Request the updated roots list from the client
|
| 590 |
+
const response = await server.server.listRoots();
|
| 591 |
+
if (response && 'roots' in response) {
|
| 592 |
+
await updateAllowedDirectoriesFromRoots(response.roots);
|
| 593 |
+
}
|
| 594 |
+
}
|
| 595 |
+
catch (error) {
|
| 596 |
+
console.error("Failed to request roots from client:", error instanceof Error ? error.message : String(error));
|
| 597 |
+
}
|
| 598 |
+
});
|
| 599 |
+
// Handles post-initialization setup, specifically checking for and fetching MCP roots.
|
| 600 |
+
server.server.oninitialized = async () => {
|
| 601 |
+
const clientCapabilities = server.server.getClientCapabilities();
|
| 602 |
+
if (clientCapabilities?.roots) {
|
| 603 |
+
try {
|
| 604 |
+
const response = await server.server.listRoots();
|
| 605 |
+
if (response && 'roots' in response) {
|
| 606 |
+
await updateAllowedDirectoriesFromRoots(response.roots);
|
| 607 |
+
}
|
| 608 |
+
else {
|
| 609 |
+
console.error("Client returned no roots set, keeping current settings");
|
| 610 |
+
}
|
| 611 |
+
}
|
| 612 |
+
catch (error) {
|
| 613 |
+
console.error("Failed to request initial roots from client:", error instanceof Error ? error.message : String(error));
|
| 614 |
+
}
|
| 615 |
+
}
|
| 616 |
+
else {
|
| 617 |
+
if (allowedDirectories.length > 0) {
|
| 618 |
+
console.error("Client does not support MCP Roots, using allowed directories set from server args:", allowedDirectories);
|
| 619 |
+
}
|
| 620 |
+
else {
|
| 621 |
+
throw new Error(`Server cannot operate: No allowed directories available. Server was started without command-line directories and client either does not support MCP roots protocol or provided empty roots. Please either: 1) Start server with directory arguments, or 2) Use a client that supports MCP roots protocol and provides valid root directories.`);
|
| 622 |
+
}
|
| 623 |
+
}
|
| 624 |
+
};
|
| 625 |
+
// Start server
|
| 626 |
+
async function runServer() {
|
| 627 |
+
const transport = new StdioServerTransport();
|
| 628 |
+
await server.connect(transport);
|
| 629 |
+
console.error("Secure MCP Filesystem Server running on stdio");
|
| 630 |
+
if (allowedDirectories.length === 0) {
|
| 631 |
+
console.error("Started without allowed directories - waiting for client to provide roots via MCP protocol");
|
| 632 |
+
}
|
| 633 |
+
}
|
| 634 |
+
runServer().catch((error) => {
|
| 635 |
+
console.error("Fatal error running server:", error);
|
| 636 |
+
process.exit(1);
|
| 637 |
+
});
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/dist/lib.js
ADDED
|
@@ -0,0 +1,393 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import fs from "fs/promises";
|
| 2 |
+
import path from "path";
|
| 3 |
+
import { randomBytes } from 'crypto';
|
| 4 |
+
import { StringDecoder } from 'string_decoder';
|
| 5 |
+
import { createTwoFilesPatch } from 'diff';
|
| 6 |
+
import { minimatch } from 'minimatch';
|
| 7 |
+
import { normalizePath, expandHome } from './path-utils.js';
|
| 8 |
+
import { isPathWithinAllowedDirectories } from './path-validation.js';
|
| 9 |
+
// Global allowed directories - set by the main module
|
| 10 |
+
let allowedDirectories = [];
|
| 11 |
+
// Function to set allowed directories from the main module
|
| 12 |
+
export function setAllowedDirectories(directories) {
|
| 13 |
+
allowedDirectories = [...directories];
|
| 14 |
+
}
|
| 15 |
+
// Function to get current allowed directories
|
| 16 |
+
export function getAllowedDirectories() {
|
| 17 |
+
return [...allowedDirectories];
|
| 18 |
+
}
|
| 19 |
+
// Pure Utility Functions
|
| 20 |
+
export function formatSize(bytes) {
|
| 21 |
+
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
| 22 |
+
if (bytes <= 0)
|
| 23 |
+
return '0 B';
|
| 24 |
+
const i = Math.floor(Math.log(bytes) / Math.log(1024));
|
| 25 |
+
if (i < 0 || i === 0)
|
| 26 |
+
return `${bytes} ${units[0]}`;
|
| 27 |
+
const unitIndex = Math.min(i, units.length - 1);
|
| 28 |
+
return `${(bytes / Math.pow(1024, unitIndex)).toFixed(2)} ${units[unitIndex]}`;
|
| 29 |
+
}
|
| 30 |
+
export function normalizeLineEndings(text) {
|
| 31 |
+
return text.replace(/\r\n/g, '\n');
|
| 32 |
+
}
|
| 33 |
+
export function createUnifiedDiff(originalContent, newContent, filepath = 'file') {
|
| 34 |
+
// Ensure consistent line endings for diff
|
| 35 |
+
const normalizedOriginal = normalizeLineEndings(originalContent);
|
| 36 |
+
const normalizedNew = normalizeLineEndings(newContent);
|
| 37 |
+
return createTwoFilesPatch(filepath, filepath, normalizedOriginal, normalizedNew, 'original', 'modified');
|
| 38 |
+
}
|
| 39 |
+
// Helper function to resolve relative paths against allowed directories
|
| 40 |
+
function resolveRelativePathAgainstAllowedDirectories(relativePath) {
|
| 41 |
+
if (allowedDirectories.length === 0) {
|
| 42 |
+
// Fallback to process.cwd() if no allowed directories are set
|
| 43 |
+
return path.resolve(process.cwd(), relativePath);
|
| 44 |
+
}
|
| 45 |
+
// Try to resolve relative path against each allowed directory
|
| 46 |
+
for (const allowedDir of allowedDirectories) {
|
| 47 |
+
const candidate = path.resolve(allowedDir, relativePath);
|
| 48 |
+
const normalizedCandidate = normalizePath(candidate);
|
| 49 |
+
// Check if the resulting path lies within any allowed directory
|
| 50 |
+
if (isPathWithinAllowedDirectories(normalizedCandidate, allowedDirectories)) {
|
| 51 |
+
return candidate;
|
| 52 |
+
}
|
| 53 |
+
}
|
| 54 |
+
// If no valid resolution found, use the first allowed directory as base
|
| 55 |
+
// This provides a consistent fallback behavior
|
| 56 |
+
return path.resolve(allowedDirectories[0], relativePath);
|
| 57 |
+
}
|
| 58 |
+
// Security & Validation Functions
|
| 59 |
+
async function resolveUnicodeEquivalentPath(absolutePath) {
|
| 60 |
+
const allowedDirectory = [...allowedDirectories]
|
| 61 |
+
.sort((left, right) => right.length - left.length)
|
| 62 |
+
.find(directory => isPathWithinAllowedDirectories(normalizePath(absolutePath), [directory]));
|
| 63 |
+
if (!allowedDirectory) {
|
| 64 |
+
return absolutePath;
|
| 65 |
+
}
|
| 66 |
+
let currentPath = await fs.realpath(allowedDirectory);
|
| 67 |
+
const relativeParts = path.relative(allowedDirectory, absolutePath).split(path.sep).filter(Boolean);
|
| 68 |
+
for (let index = 0; index < relativeParts.length; index++) {
|
| 69 |
+
const requestedPart = relativeParts[index];
|
| 70 |
+
const entries = (await fs.readdir(currentPath)) ?? [];
|
| 71 |
+
const exactMatch = entries.find(entry => entry === requestedPart);
|
| 72 |
+
const equivalentMatches = exactMatch
|
| 73 |
+
? [exactMatch]
|
| 74 |
+
: entries.filter(entry => entry.normalize('NFC') === requestedPart.normalize('NFC'));
|
| 75 |
+
if (equivalentMatches.length > 1) {
|
| 76 |
+
throw new Error(`Ambiguous Unicode path component: ${requestedPart}`);
|
| 77 |
+
}
|
| 78 |
+
if (equivalentMatches.length === 0) {
|
| 79 |
+
// Nothing below this point exists yet, so there are no symlinks left to
|
| 80 |
+
// resolve. currentPath is already realpath'd and inside an allowed
|
| 81 |
+
// directory; append the missing tail so create_directory can mkdir -p it.
|
| 82 |
+
return path.join(currentPath, ...relativeParts.slice(index));
|
| 83 |
+
}
|
| 84 |
+
currentPath = await fs.realpath(path.join(currentPath, equivalentMatches[0]));
|
| 85 |
+
if (!isPathWithinAllowedDirectories(normalizePath(currentPath), allowedDirectories)) {
|
| 86 |
+
throw new Error(`Access denied - symlink target outside allowed directories: ${currentPath} not in ${allowedDirectories.join(', ')}`);
|
| 87 |
+
}
|
| 88 |
+
}
|
| 89 |
+
return currentPath;
|
| 90 |
+
}
|
| 91 |
+
export async function validatePath(requestedPath) {
|
| 92 |
+
const expandedPath = expandHome(requestedPath);
|
| 93 |
+
// Do not silently reinterpret a Windows drive path as a relative POSIX path.
|
| 94 |
+
// This would create a literal filename such as `C:\\Users\\...` inside the
|
| 95 |
+
// allowed root and report success for the wrong location.
|
| 96 |
+
if (process.platform !== 'win32' && /^(?:[A-Za-z]:)(?:[\\/]|$)/.test(expandedPath)) {
|
| 97 |
+
throw new Error(`Access denied - Windows-style path received on a POSIX host: ${requestedPath}`);
|
| 98 |
+
}
|
| 99 |
+
const absolute = path.isAbsolute(expandedPath)
|
| 100 |
+
? path.resolve(expandedPath)
|
| 101 |
+
: resolveRelativePathAgainstAllowedDirectories(expandedPath);
|
| 102 |
+
const normalizedRequested = normalizePath(absolute);
|
| 103 |
+
// Security: Check if path is within allowed directories before any file operations
|
| 104 |
+
const isAllowed = isPathWithinAllowedDirectories(normalizedRequested, allowedDirectories);
|
| 105 |
+
if (!isAllowed) {
|
| 106 |
+
throw new Error(`Access denied - path outside allowed directories: ${absolute} not in ${allowedDirectories.join(', ')}`);
|
| 107 |
+
}
|
| 108 |
+
// Security: Handle symlinks by checking their real path to prevent symlink attacks
|
| 109 |
+
// This prevents attackers from creating symlinks that point outside allowed directories
|
| 110 |
+
try {
|
| 111 |
+
const realPath = await fs.realpath(absolute);
|
| 112 |
+
const normalizedReal = normalizePath(realPath);
|
| 113 |
+
if (!isPathWithinAllowedDirectories(normalizedReal, allowedDirectories)) {
|
| 114 |
+
throw new Error(`Access denied - symlink target outside allowed directories: ${realPath} not in ${allowedDirectories.join(', ')}`);
|
| 115 |
+
}
|
| 116 |
+
return realPath;
|
| 117 |
+
}
|
| 118 |
+
catch (error) {
|
| 119 |
+
// Security: For new files that don't exist yet, verify parent directory
|
| 120 |
+
// This ensures we can't create files in unauthorized locations
|
| 121 |
+
if (error.code === 'ENOENT') {
|
| 122 |
+
try {
|
| 123 |
+
return await resolveUnicodeEquivalentPath(absolute);
|
| 124 |
+
}
|
| 125 |
+
catch (resolutionError) {
|
| 126 |
+
if (resolutionError.code === 'ENOENT') {
|
| 127 |
+
throw new Error(`Parent directory does not exist: ${path.dirname(absolute)}`);
|
| 128 |
+
}
|
| 129 |
+
throw resolutionError;
|
| 130 |
+
}
|
| 131 |
+
}
|
| 132 |
+
throw error;
|
| 133 |
+
}
|
| 134 |
+
}
|
| 135 |
+
// File Operations
|
| 136 |
+
export async function getFileStats(filePath) {
|
| 137 |
+
const stats = await fs.stat(filePath);
|
| 138 |
+
return {
|
| 139 |
+
size: stats.size,
|
| 140 |
+
created: stats.birthtime,
|
| 141 |
+
modified: stats.mtime,
|
| 142 |
+
accessed: stats.atime,
|
| 143 |
+
isDirectory: stats.isDirectory(),
|
| 144 |
+
isFile: stats.isFile(),
|
| 145 |
+
permissions: stats.mode.toString(8).slice(-3),
|
| 146 |
+
};
|
| 147 |
+
}
|
| 148 |
+
export async function readFileContent(filePath, encoding = 'utf-8') {
|
| 149 |
+
return await fs.readFile(filePath, encoding);
|
| 150 |
+
}
|
| 151 |
+
export async function writeFileContent(filePath, content) {
|
| 152 |
+
try {
|
| 153 |
+
// Security: 'wx' flag ensures exclusive creation - fails if file/symlink exists,
|
| 154 |
+
// preventing writes through pre-existing symlinks
|
| 155 |
+
await fs.writeFile(filePath, content, { encoding: "utf-8", flag: 'wx' });
|
| 156 |
+
}
|
| 157 |
+
catch (error) {
|
| 158 |
+
if (error.code === 'EEXIST') {
|
| 159 |
+
// Security: Use atomic rename to prevent race conditions where symlinks
|
| 160 |
+
// could be created between validation and write. Rename operations
|
| 161 |
+
// replace the target file atomically and don't follow symlinks.
|
| 162 |
+
const origStats = await fs.stat(filePath);
|
| 163 |
+
const tempPath = `${filePath}.${randomBytes(16).toString('hex')}.tmp`;
|
| 164 |
+
try {
|
| 165 |
+
await fs.writeFile(tempPath, content, 'utf-8');
|
| 166 |
+
await fs.rename(tempPath, filePath);
|
| 167 |
+
}
|
| 168 |
+
catch (renameError) {
|
| 169 |
+
try {
|
| 170 |
+
await fs.unlink(tempPath);
|
| 171 |
+
}
|
| 172 |
+
catch { }
|
| 173 |
+
throw renameError;
|
| 174 |
+
}
|
| 175 |
+
// Restore original permission bits since the atomic rename replaces the
|
| 176 |
+
// inode and the temp file has default (0644) permissions. Mask off the
|
| 177 |
+
// file-type bits; POSIX leaves them unspecified for chmod. A chmod
|
| 178 |
+
// failure must not fail the write, which has already succeeded.
|
| 179 |
+
try {
|
| 180 |
+
await fs.chmod(filePath, origStats.mode & 0o777);
|
| 181 |
+
}
|
| 182 |
+
catch { }
|
| 183 |
+
}
|
| 184 |
+
else {
|
| 185 |
+
throw error;
|
| 186 |
+
}
|
| 187 |
+
}
|
| 188 |
+
}
|
| 189 |
+
export async function moveFile(sourcePath, destinationPath) {
|
| 190 |
+
// The move_file tool contract (and README) state the operation fails if the
|
| 191 |
+
// destination already exists. fs.rename would silently overwrite it, which is
|
| 192 |
+
// a data-loss bug, so reject up front when anything - file, directory, or
|
| 193 |
+
// symlink - occupies the target. lstat is used so an existing symlink at the
|
| 194 |
+
// destination is detected rather than followed.
|
| 195 |
+
try {
|
| 196 |
+
await fs.lstat(destinationPath);
|
| 197 |
+
}
|
| 198 |
+
catch (error) {
|
| 199 |
+
if (error.code === 'ENOENT') {
|
| 200 |
+
await fs.rename(sourcePath, destinationPath);
|
| 201 |
+
return;
|
| 202 |
+
}
|
| 203 |
+
throw error;
|
| 204 |
+
}
|
| 205 |
+
throw new Error(`Destination already exists: ${destinationPath}`);
|
| 206 |
+
}
|
| 207 |
+
export async function applyFileEdits(filePath, edits, dryRun = false) {
|
| 208 |
+
// Read file content and normalize line endings
|
| 209 |
+
const content = normalizeLineEndings(await fs.readFile(filePath, 'utf-8'));
|
| 210 |
+
// Apply edits sequentially
|
| 211 |
+
let modifiedContent = content;
|
| 212 |
+
for (const edit of edits) {
|
| 213 |
+
const normalizedOld = normalizeLineEndings(edit.oldText);
|
| 214 |
+
const normalizedNew = normalizeLineEndings(edit.newText);
|
| 215 |
+
// If exact match exists, use it
|
| 216 |
+
if (modifiedContent.includes(normalizedOld)) {
|
| 217 |
+
modifiedContent = modifiedContent.replace(normalizedOld, () => normalizedNew);
|
| 218 |
+
continue;
|
| 219 |
+
}
|
| 220 |
+
// Otherwise, try line-by-line matching with flexibility for whitespace
|
| 221 |
+
const oldLines = normalizedOld.split('\n');
|
| 222 |
+
const contentLines = modifiedContent.split('\n');
|
| 223 |
+
let matchFound = false;
|
| 224 |
+
for (let i = 0; i <= contentLines.length - oldLines.length; i++) {
|
| 225 |
+
const potentialMatch = contentLines.slice(i, i + oldLines.length);
|
| 226 |
+
// Compare lines with normalized whitespace
|
| 227 |
+
const isMatch = oldLines.every((oldLine, j) => {
|
| 228 |
+
const contentLine = potentialMatch[j];
|
| 229 |
+
return oldLine.trim() === contentLine.trim();
|
| 230 |
+
});
|
| 231 |
+
if (isMatch) {
|
| 232 |
+
// Preserve original indentation of first line
|
| 233 |
+
const originalIndent = contentLines[i].match(/^\s*/)?.[0] || '';
|
| 234 |
+
const newLines = normalizedNew.split('\n').map((line, j) => {
|
| 235 |
+
if (j === 0)
|
| 236 |
+
return originalIndent + line.trimStart();
|
| 237 |
+
// For subsequent lines, try to preserve relative indentation
|
| 238 |
+
const oldIndent = oldLines[j]?.match(/^\s*/)?.[0] || '';
|
| 239 |
+
const newIndent = line.match(/^\s*/)?.[0] || '';
|
| 240 |
+
if (oldIndent && newIndent) {
|
| 241 |
+
const relativeIndent = newIndent.length - oldIndent.length;
|
| 242 |
+
return originalIndent + ' '.repeat(Math.max(0, relativeIndent)) + line.trimStart();
|
| 243 |
+
}
|
| 244 |
+
return line;
|
| 245 |
+
});
|
| 246 |
+
contentLines.splice(i, oldLines.length, ...newLines);
|
| 247 |
+
modifiedContent = contentLines.join('\n');
|
| 248 |
+
matchFound = true;
|
| 249 |
+
break;
|
| 250 |
+
}
|
| 251 |
+
}
|
| 252 |
+
if (!matchFound) {
|
| 253 |
+
throw new Error(`Could not find exact match for edit:\n${edit.oldText}`);
|
| 254 |
+
}
|
| 255 |
+
}
|
| 256 |
+
// Create unified diff
|
| 257 |
+
const diff = createUnifiedDiff(content, modifiedContent, filePath);
|
| 258 |
+
// Format diff with appropriate number of backticks
|
| 259 |
+
let numBackticks = 3;
|
| 260 |
+
while (diff.includes('`'.repeat(numBackticks))) {
|
| 261 |
+
numBackticks++;
|
| 262 |
+
}
|
| 263 |
+
const formattedDiff = `${'`'.repeat(numBackticks)}diff\n${diff}${'`'.repeat(numBackticks)}\n\n`;
|
| 264 |
+
if (!dryRun) {
|
| 265 |
+
// Security: Use atomic rename to prevent race conditions where symlinks
|
| 266 |
+
// could be created between validation and write. Rename operations
|
| 267 |
+
// replace the target file atomically and don't follow symlinks.
|
| 268 |
+
const origStats = await fs.stat(filePath);
|
| 269 |
+
const tempPath = `${filePath}.${randomBytes(16).toString('hex')}.tmp`;
|
| 270 |
+
try {
|
| 271 |
+
await fs.writeFile(tempPath, modifiedContent, 'utf-8');
|
| 272 |
+
await fs.rename(tempPath, filePath);
|
| 273 |
+
}
|
| 274 |
+
catch (error) {
|
| 275 |
+
try {
|
| 276 |
+
await fs.unlink(tempPath);
|
| 277 |
+
}
|
| 278 |
+
catch { }
|
| 279 |
+
throw error;
|
| 280 |
+
}
|
| 281 |
+
// Restore original permission bits since the atomic rename replaces the
|
| 282 |
+
// inode and the temp file has default (0644) permissions. Mask off the
|
| 283 |
+
// file-type bits; POSIX leaves them unspecified for chmod. A chmod
|
| 284 |
+
// failure must not fail the write, which has already succeeded.
|
| 285 |
+
try {
|
| 286 |
+
await fs.chmod(filePath, origStats.mode & 0o777);
|
| 287 |
+
}
|
| 288 |
+
catch { }
|
| 289 |
+
}
|
| 290 |
+
return formattedDiff;
|
| 291 |
+
}
|
| 292 |
+
// Memory-efficient implementation to get the last N lines of a file
|
| 293 |
+
export async function tailFile(filePath, numLines) {
|
| 294 |
+
const CHUNK_SIZE = 1024; // Read 1KB at a time
|
| 295 |
+
const stats = await fs.stat(filePath);
|
| 296 |
+
const fileSize = stats.size;
|
| 297 |
+
if (fileSize === 0)
|
| 298 |
+
return '';
|
| 299 |
+
// Open file for reading
|
| 300 |
+
const fileHandle = await fs.open(filePath, 'r');
|
| 301 |
+
try {
|
| 302 |
+
const chunks = [];
|
| 303 |
+
let position = fileSize;
|
| 304 |
+
const chunk = Buffer.alloc(CHUNK_SIZE);
|
| 305 |
+
let newlinesFound = 0;
|
| 306 |
+
// Read chunks from the end of the file until we have enough lines
|
| 307 |
+
while (position > 0 && newlinesFound < numLines) {
|
| 308 |
+
const size = Math.min(CHUNK_SIZE, position);
|
| 309 |
+
position -= size;
|
| 310 |
+
const { bytesRead } = await fileHandle.read(chunk, 0, size, position);
|
| 311 |
+
if (!bytesRead)
|
| 312 |
+
break;
|
| 313 |
+
const readData = Buffer.from(chunk.subarray(0, bytesRead));
|
| 314 |
+
chunks.unshift(readData);
|
| 315 |
+
for (const byte of readData) {
|
| 316 |
+
if (byte === 0x0a)
|
| 317 |
+
newlinesFound++;
|
| 318 |
+
}
|
| 319 |
+
}
|
| 320 |
+
const text = normalizeLineEndings(Buffer.concat(chunks).toString('utf-8'));
|
| 321 |
+
return text.split('\n').slice(-numLines).join('\n');
|
| 322 |
+
}
|
| 323 |
+
finally {
|
| 324 |
+
await fileHandle.close();
|
| 325 |
+
}
|
| 326 |
+
}
|
| 327 |
+
// New function to get the first N lines of a file
|
| 328 |
+
export async function headFile(filePath, numLines) {
|
| 329 |
+
const fileHandle = await fs.open(filePath, 'r');
|
| 330 |
+
try {
|
| 331 |
+
const lines = [];
|
| 332 |
+
let buffer = '';
|
| 333 |
+
let bytesRead = 0;
|
| 334 |
+
const chunk = Buffer.alloc(1024); // 1KB buffer
|
| 335 |
+
const decoder = new StringDecoder('utf-8');
|
| 336 |
+
// Read chunks and count lines until we have enough or reach EOF
|
| 337 |
+
while (lines.length < numLines) {
|
| 338 |
+
const result = await fileHandle.read(chunk, 0, chunk.length, bytesRead);
|
| 339 |
+
if (result.bytesRead === 0)
|
| 340 |
+
break; // End of file
|
| 341 |
+
bytesRead += result.bytesRead;
|
| 342 |
+
buffer += decoder.write(chunk.subarray(0, result.bytesRead));
|
| 343 |
+
const newLineIndex = buffer.lastIndexOf('\n');
|
| 344 |
+
if (newLineIndex !== -1) {
|
| 345 |
+
const completeLines = buffer.slice(0, newLineIndex).split('\n');
|
| 346 |
+
buffer = buffer.slice(newLineIndex + 1);
|
| 347 |
+
for (const line of completeLines) {
|
| 348 |
+
lines.push(line);
|
| 349 |
+
if (lines.length >= numLines)
|
| 350 |
+
break;
|
| 351 |
+
}
|
| 352 |
+
}
|
| 353 |
+
}
|
| 354 |
+
buffer += decoder.end();
|
| 355 |
+
// If there is leftover content and we still need lines, add it
|
| 356 |
+
if (buffer.length > 0 && lines.length < numLines) {
|
| 357 |
+
lines.push(buffer);
|
| 358 |
+
}
|
| 359 |
+
return lines.join('\n');
|
| 360 |
+
}
|
| 361 |
+
finally {
|
| 362 |
+
await fileHandle.close();
|
| 363 |
+
}
|
| 364 |
+
}
|
| 365 |
+
export async function searchFilesWithValidation(rootPath, pattern, allowedDirectories, options = {}) {
|
| 366 |
+
const { excludePatterns = [] } = options;
|
| 367 |
+
const results = [];
|
| 368 |
+
async function search(currentPath) {
|
| 369 |
+
const entries = await fs.readdir(currentPath, { withFileTypes: true });
|
| 370 |
+
for (const entry of entries) {
|
| 371 |
+
const fullPath = path.join(currentPath, entry.name);
|
| 372 |
+
try {
|
| 373 |
+
await validatePath(fullPath);
|
| 374 |
+
const relativePath = path.relative(rootPath, fullPath);
|
| 375 |
+
const shouldExclude = excludePatterns.some(excludePattern => minimatch(relativePath, excludePattern, { dot: true }));
|
| 376 |
+
if (shouldExclude)
|
| 377 |
+
continue;
|
| 378 |
+
// Use glob matching for the search pattern
|
| 379 |
+
if (minimatch(relativePath, pattern, { dot: true })) {
|
| 380 |
+
results.push(fullPath);
|
| 381 |
+
}
|
| 382 |
+
if (entry.isDirectory()) {
|
| 383 |
+
await search(fullPath);
|
| 384 |
+
}
|
| 385 |
+
}
|
| 386 |
+
catch {
|
| 387 |
+
continue;
|
| 388 |
+
}
|
| 389 |
+
}
|
| 390 |
+
}
|
| 391 |
+
await search(rootPath);
|
| 392 |
+
return results;
|
| 393 |
+
}
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/dist/path-utils.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import path from "path";
|
| 2 |
+
import os from 'os';
|
| 3 |
+
/**
|
| 4 |
+
* Converts WSL or Unix-style Windows paths to Windows format
|
| 5 |
+
* @param p The path to convert
|
| 6 |
+
* @returns Converted Windows path
|
| 7 |
+
*/
|
| 8 |
+
export function convertToWindowsPath(p) {
|
| 9 |
+
// Handle WSL paths (/mnt/c/...)
|
| 10 |
+
// NEVER convert WSL paths - they are valid Linux paths that work with Node.js fs operations in WSL
|
| 11 |
+
// Converting them to Windows format (C:\...) breaks fs operations inside WSL
|
| 12 |
+
if (p.startsWith('/mnt/')) {
|
| 13 |
+
return p; // Leave WSL paths unchanged
|
| 14 |
+
}
|
| 15 |
+
// Handle Unix-style Windows paths (/c/...)
|
| 16 |
+
// Only convert when running on Windows
|
| 17 |
+
if (p.match(/^\/[a-zA-Z]\//) && process.platform === 'win32') {
|
| 18 |
+
const driveLetter = p.charAt(1).toUpperCase();
|
| 19 |
+
const pathPart = p.slice(2).replace(/\//g, '\\');
|
| 20 |
+
return `${driveLetter}:${pathPart}`;
|
| 21 |
+
}
|
| 22 |
+
// Handle standard Windows paths, ensuring backslashes
|
| 23 |
+
if (p.match(/^[a-zA-Z]:/)) {
|
| 24 |
+
return p.replace(/\//g, '\\');
|
| 25 |
+
}
|
| 26 |
+
// Leave non-Windows paths unchanged
|
| 27 |
+
return p;
|
| 28 |
+
}
|
| 29 |
+
/**
|
| 30 |
+
* Normalizes path by standardizing format while preserving OS-specific behavior
|
| 31 |
+
* @param p The path to normalize
|
| 32 |
+
* @returns Normalized path
|
| 33 |
+
*/
|
| 34 |
+
export function normalizePath(p) {
|
| 35 |
+
// Remove any surrounding quotes and whitespace
|
| 36 |
+
p = p.trim().replace(/^["']|["']$/g, '');
|
| 37 |
+
// Check if this is a Unix path that should not be converted
|
| 38 |
+
// WSL paths (/mnt/) should ALWAYS be preserved as they work correctly in WSL with Node.js fs
|
| 39 |
+
// Regular Unix paths should also be preserved
|
| 40 |
+
const isUnixPath = p.startsWith('/') && (
|
| 41 |
+
// Always preserve WSL paths (/mnt/c/, /mnt/d/, etc.)
|
| 42 |
+
p.match(/^\/mnt\/[a-z]\//i) ||
|
| 43 |
+
// On non-Windows platforms, treat all absolute paths as Unix paths
|
| 44 |
+
(process.platform !== 'win32') ||
|
| 45 |
+
// On Windows, preserve Unix paths that aren't Unix-style Windows paths (/c/, /d/, etc.)
|
| 46 |
+
(process.platform === 'win32' && !p.match(/^\/[a-zA-Z]\//)));
|
| 47 |
+
if (isUnixPath) {
|
| 48 |
+
// For Unix paths, just normalize without converting to Windows format
|
| 49 |
+
// Replace double slashes with single slashes and remove trailing slashes
|
| 50 |
+
return p.replace(/\/+/g, '/').replace(/(?<!^)\/$/, '');
|
| 51 |
+
}
|
| 52 |
+
// Convert Unix-style Windows paths (/c/, /d/) to Windows format if on Windows
|
| 53 |
+
// This function will now leave /mnt/ paths unchanged
|
| 54 |
+
p = convertToWindowsPath(p);
|
| 55 |
+
// Handle double backslashes, preserving leading UNC \\
|
| 56 |
+
if (p.startsWith('\\\\')) {
|
| 57 |
+
// For UNC paths, first normalize any excessive leading backslashes to exactly \\
|
| 58 |
+
// Then normalize double backslashes in the rest of the path
|
| 59 |
+
let uncPath = p;
|
| 60 |
+
// Replace multiple leading backslashes with exactly two
|
| 61 |
+
uncPath = uncPath.replace(/^\\{2,}/, '\\\\');
|
| 62 |
+
// Now normalize any remaining double backslashes in the rest of the path
|
| 63 |
+
const restOfPath = uncPath.substring(2).replace(/\\\\/g, '\\');
|
| 64 |
+
p = '\\\\' + restOfPath;
|
| 65 |
+
}
|
| 66 |
+
else {
|
| 67 |
+
// For non-UNC paths, normalize all double backslashes
|
| 68 |
+
p = p.replace(/\\\\/g, '\\');
|
| 69 |
+
}
|
| 70 |
+
// On Windows, if we have a bare drive letter (e.g. "C:"), append a separator
|
| 71 |
+
// so path.normalize doesn't return "C:." which can break path validation.
|
| 72 |
+
if (process.platform === 'win32' && /^[a-zA-Z]:$/.test(p)) {
|
| 73 |
+
p = p + path.sep;
|
| 74 |
+
}
|
| 75 |
+
// Use Node's path normalization, which handles . and .. segments
|
| 76 |
+
let normalized = path.normalize(p);
|
| 77 |
+
// Fix UNC paths after normalization (path.normalize can remove a leading backslash)
|
| 78 |
+
if (p.startsWith('\\\\') && !normalized.startsWith('\\\\')) {
|
| 79 |
+
normalized = '\\' + normalized;
|
| 80 |
+
}
|
| 81 |
+
// Handle Windows paths: convert slashes and ensure drive letter is capitalized
|
| 82 |
+
if (normalized.match(/^[a-zA-Z]:/)) {
|
| 83 |
+
let result = normalized.replace(/\//g, '\\');
|
| 84 |
+
// Capitalize drive letter if present
|
| 85 |
+
if (/^[a-z]:/.test(result)) {
|
| 86 |
+
result = result.charAt(0).toUpperCase() + result.slice(1);
|
| 87 |
+
}
|
| 88 |
+
return result;
|
| 89 |
+
}
|
| 90 |
+
// On Windows, convert forward slashes to backslashes for relative paths
|
| 91 |
+
// On Linux/Unix, preserve forward slashes
|
| 92 |
+
if (process.platform === 'win32') {
|
| 93 |
+
return normalized.replace(/\//g, '\\');
|
| 94 |
+
}
|
| 95 |
+
// On non-Windows platforms, keep the normalized path as-is
|
| 96 |
+
return normalized;
|
| 97 |
+
}
|
| 98 |
+
/**
|
| 99 |
+
* Expands home directory tildes in paths
|
| 100 |
+
* @param filepath The path to expand
|
| 101 |
+
* @returns Expanded path
|
| 102 |
+
*/
|
| 103 |
+
export function expandHome(filepath) {
|
| 104 |
+
if (filepath.startsWith('~/') || filepath === '~') {
|
| 105 |
+
return path.join(os.homedir(), filepath.slice(1));
|
| 106 |
+
}
|
| 107 |
+
return filepath;
|
| 108 |
+
}
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/dist/path-validation.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import path from 'path';
|
| 2 |
+
/**
|
| 3 |
+
* Checks if an absolute path is within any of the allowed directories.
|
| 4 |
+
*
|
| 5 |
+
* @param absolutePath - The absolute path to check (will be normalized)
|
| 6 |
+
* @param allowedDirectories - Array of absolute allowed directory paths (will be normalized)
|
| 7 |
+
* @returns true if the path is within an allowed directory, false otherwise
|
| 8 |
+
* @throws Error if given relative paths after normalization
|
| 9 |
+
*/
|
| 10 |
+
export function isPathWithinAllowedDirectories(absolutePath, allowedDirectories) {
|
| 11 |
+
// Type validation
|
| 12 |
+
if (typeof absolutePath !== 'string' || !Array.isArray(allowedDirectories)) {
|
| 13 |
+
return false;
|
| 14 |
+
}
|
| 15 |
+
// Reject empty inputs
|
| 16 |
+
if (!absolutePath || allowedDirectories.length === 0) {
|
| 17 |
+
return false;
|
| 18 |
+
}
|
| 19 |
+
// Reject null bytes (forbidden in paths)
|
| 20 |
+
if (absolutePath.includes('\x00')) {
|
| 21 |
+
return false;
|
| 22 |
+
}
|
| 23 |
+
// Normalize the input path
|
| 24 |
+
let normalizedPath;
|
| 25 |
+
try {
|
| 26 |
+
normalizedPath = path.resolve(path.normalize(absolutePath));
|
| 27 |
+
}
|
| 28 |
+
catch {
|
| 29 |
+
return false;
|
| 30 |
+
}
|
| 31 |
+
// Verify it's absolute after normalization
|
| 32 |
+
if (!path.isAbsolute(normalizedPath)) {
|
| 33 |
+
throw new Error('Path must be absolute after normalization');
|
| 34 |
+
}
|
| 35 |
+
// Check against each allowed directory
|
| 36 |
+
return allowedDirectories.some(dir => {
|
| 37 |
+
if (typeof dir !== 'string' || !dir) {
|
| 38 |
+
return false;
|
| 39 |
+
}
|
| 40 |
+
// Reject null bytes in allowed dirs
|
| 41 |
+
if (dir.includes('\x00')) {
|
| 42 |
+
return false;
|
| 43 |
+
}
|
| 44 |
+
// Normalize the allowed directory
|
| 45 |
+
let normalizedDir;
|
| 46 |
+
try {
|
| 47 |
+
normalizedDir = path.resolve(path.normalize(dir));
|
| 48 |
+
}
|
| 49 |
+
catch {
|
| 50 |
+
return false;
|
| 51 |
+
}
|
| 52 |
+
// Verify allowed directory is absolute after normalization
|
| 53 |
+
if (!path.isAbsolute(normalizedDir)) {
|
| 54 |
+
throw new Error('Allowed directories must be absolute paths after normalization');
|
| 55 |
+
}
|
| 56 |
+
// Check if normalizedPath is within normalizedDir
|
| 57 |
+
// Path is inside if it's the same or a subdirectory
|
| 58 |
+
if (normalizedPath === normalizedDir) {
|
| 59 |
+
return true;
|
| 60 |
+
}
|
| 61 |
+
// Special case for root directory to avoid double slash
|
| 62 |
+
// On Windows, we need to check if both paths are on the same drive
|
| 63 |
+
if (normalizedDir === path.sep) {
|
| 64 |
+
return normalizedPath.startsWith(path.sep);
|
| 65 |
+
}
|
| 66 |
+
// On Windows, also check for drive root (e.g., "C:\")
|
| 67 |
+
if (path.sep === '\\' && normalizedDir.match(/^[A-Za-z]:\\?$/)) {
|
| 68 |
+
// Ensure both paths are on the same drive
|
| 69 |
+
const dirDrive = normalizedDir.charAt(0).toLowerCase();
|
| 70 |
+
const pathDrive = normalizedPath.charAt(0).toLowerCase();
|
| 71 |
+
return pathDrive === dirDrive && normalizedPath.startsWith(normalizedDir.replace(/\\?$/, '\\'));
|
| 72 |
+
}
|
| 73 |
+
return normalizedPath.startsWith(normalizedDir + path.sep);
|
| 74 |
+
});
|
| 75 |
+
}
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/dist/roots-utils.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { promises as fs } from 'fs';
|
| 2 |
+
import path from 'path';
|
| 3 |
+
import os from 'os';
|
| 4 |
+
import { normalizePath } from './path-utils.js';
|
| 5 |
+
import { fileURLToPath } from "url";
|
| 6 |
+
/**
|
| 7 |
+
* Converts a root URI to a normalized directory path with basic security validation.
|
| 8 |
+
* @param rootUri - File URI (file://...) or plain directory path
|
| 9 |
+
* @returns Promise resolving to validated path or null if invalid
|
| 10 |
+
*/
|
| 11 |
+
async function parseRootUri(rootUri) {
|
| 12 |
+
try {
|
| 13 |
+
const rawPath = rootUri.startsWith('file://') ? fileURLToPath(rootUri) : rootUri;
|
| 14 |
+
const expandedPath = rawPath.startsWith('~/') || rawPath === '~'
|
| 15 |
+
? path.join(os.homedir(), rawPath.slice(1))
|
| 16 |
+
: rawPath;
|
| 17 |
+
const absolutePath = path.resolve(expandedPath);
|
| 18 |
+
const resolvedPath = await fs.realpath(absolutePath);
|
| 19 |
+
return normalizePath(resolvedPath);
|
| 20 |
+
}
|
| 21 |
+
catch {
|
| 22 |
+
return null; // Path doesn't exist or other error
|
| 23 |
+
}
|
| 24 |
+
}
|
| 25 |
+
/**
|
| 26 |
+
* Formats error message for directory validation failures.
|
| 27 |
+
* @param dir - Directory path that failed validation
|
| 28 |
+
* @param error - Error that occurred during validation
|
| 29 |
+
* @param reason - Specific reason for failure
|
| 30 |
+
* @returns Formatted error message
|
| 31 |
+
*/
|
| 32 |
+
function formatDirectoryError(dir, error, reason) {
|
| 33 |
+
if (reason) {
|
| 34 |
+
return `Skipping ${reason}: ${dir}`;
|
| 35 |
+
}
|
| 36 |
+
const message = error instanceof Error ? error.message : String(error);
|
| 37 |
+
return `Skipping invalid directory: ${dir} due to error: ${message}`;
|
| 38 |
+
}
|
| 39 |
+
/**
|
| 40 |
+
* Resolves requested root directories from MCP root specifications.
|
| 41 |
+
*
|
| 42 |
+
* Converts root URI specifications (file:// URIs or plain paths) into normalized
|
| 43 |
+
* directory paths, validating that each path exists and is a directory.
|
| 44 |
+
* Includes symlink resolution for security.
|
| 45 |
+
*
|
| 46 |
+
* @param requestedRoots - Array of root specifications with URI and optional name
|
| 47 |
+
* @returns Promise resolving to array of validated directory paths
|
| 48 |
+
*/
|
| 49 |
+
export async function getValidRootDirectories(requestedRoots) {
|
| 50 |
+
const validatedDirectories = [];
|
| 51 |
+
for (const requestedRoot of requestedRoots) {
|
| 52 |
+
const resolvedPath = await parseRootUri(requestedRoot.uri);
|
| 53 |
+
if (!resolvedPath) {
|
| 54 |
+
console.error(formatDirectoryError(requestedRoot.uri, undefined, 'invalid path or inaccessible'));
|
| 55 |
+
continue;
|
| 56 |
+
}
|
| 57 |
+
try {
|
| 58 |
+
const stats = await fs.stat(resolvedPath);
|
| 59 |
+
if (stats.isDirectory()) {
|
| 60 |
+
validatedDirectories.push(resolvedPath);
|
| 61 |
+
}
|
| 62 |
+
else {
|
| 63 |
+
console.error(formatDirectoryError(resolvedPath, undefined, 'non-directory root'));
|
| 64 |
+
}
|
| 65 |
+
}
|
| 66 |
+
catch (error) {
|
| 67 |
+
console.error(formatDirectoryError(resolvedPath, error));
|
| 68 |
+
}
|
| 69 |
+
}
|
| 70 |
+
return validatedDirectories;
|
| 71 |
+
}
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/.bin/node-which
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env node
|
| 2 |
+
var which = require("../")
|
| 3 |
+
if (process.argv.length < 3)
|
| 4 |
+
usage()
|
| 5 |
+
|
| 6 |
+
function usage () {
|
| 7 |
+
console.error('usage: which [-as] program ...')
|
| 8 |
+
process.exit(1)
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
var all = false
|
| 12 |
+
var silent = false
|
| 13 |
+
var dashdash = false
|
| 14 |
+
var args = process.argv.slice(2).filter(function (arg) {
|
| 15 |
+
if (dashdash || !/^-/.test(arg))
|
| 16 |
+
return true
|
| 17 |
+
|
| 18 |
+
if (arg === '--') {
|
| 19 |
+
dashdash = true
|
| 20 |
+
return false
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
var flags = arg.substr(1).split('')
|
| 24 |
+
for (var f = 0; f < flags.length; f++) {
|
| 25 |
+
var flag = flags[f]
|
| 26 |
+
switch (flag) {
|
| 27 |
+
case 's':
|
| 28 |
+
silent = true
|
| 29 |
+
break
|
| 30 |
+
case 'a':
|
| 31 |
+
all = true
|
| 32 |
+
break
|
| 33 |
+
default:
|
| 34 |
+
console.error('which: illegal option -- ' + flag)
|
| 35 |
+
usage()
|
| 36 |
+
}
|
| 37 |
+
}
|
| 38 |
+
return false
|
| 39 |
+
})
|
| 40 |
+
|
| 41 |
+
process.exit(args.reduce(function (pv, current) {
|
| 42 |
+
try {
|
| 43 |
+
var f = which.sync(current, { all: all })
|
| 44 |
+
if (all)
|
| 45 |
+
f = f.join('\n')
|
| 46 |
+
if (!silent)
|
| 47 |
+
console.log(f)
|
| 48 |
+
return pv;
|
| 49 |
+
} catch (e) {
|
| 50 |
+
return 1;
|
| 51 |
+
}
|
| 52 |
+
}, 0))
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2022 - present, Yusuke Wada and Hono contributors
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/README.md
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Node.js Adapter for Hono
|
| 2 |
+
|
| 3 |
+
This adapter `@hono/node-server` allows you to run your Hono application on Node.js.
|
| 4 |
+
Initially, Hono wasn't designed for Node.js, but with this adapter, you can now use Hono on Node.js. It utilizes web standard APIs implemented in Node.js.
|
| 5 |
+
|
| 6 |
+
## Benchmarks
|
| 7 |
+
|
| 8 |
+
Hono is 3.1 times faster than Express.
|
| 9 |
+
|
| 10 |
+
Express v5:
|
| 11 |
+
|
| 12 |
+
```txt
|
| 13 |
+
$ bombardier -d 10s --fasthttp http://localhost:3000/
|
| 14 |
+
|
| 15 |
+
Statistics Avg Stdev Max
|
| 16 |
+
Reqs/sec 24380.41 1409.74 26604.88
|
| 17 |
+
Latency 5.12ms 2.95ms 305.21ms
|
| 18 |
+
HTTP codes:
|
| 19 |
+
1xx - 0, 2xx - 243915, 3xx - 0, 4xx - 0, 5xx - 0
|
| 20 |
+
others - 0
|
| 21 |
+
Throughput: 6.98MB/s
|
| 22 |
+
```
|
| 23 |
+
|
| 24 |
+
Hono + `@hono/node-server`:
|
| 25 |
+
|
| 26 |
+
```txt
|
| 27 |
+
$ bombardier -d 10s --fasthttp http://localhost:3000/
|
| 28 |
+
|
| 29 |
+
Statistics Avg Stdev Max
|
| 30 |
+
Reqs/sec 74428.96 3815.27 88228.32
|
| 31 |
+
Latency 1.68ms 621.25us 106.20ms
|
| 32 |
+
HTTP codes:
|
| 33 |
+
1xx - 0, 2xx - 744378, 3xx - 0, 4xx - 0, 5xx - 0
|
| 34 |
+
others - 0
|
| 35 |
+
Throughput: 16.82MB/s
|
| 36 |
+
```
|
| 37 |
+
|
| 38 |
+
## Requirements
|
| 39 |
+
|
| 40 |
+
It works on Node.js versions greater than 20.x.
|
| 41 |
+
|
| 42 |
+
## Installation
|
| 43 |
+
|
| 44 |
+
You can install it from the npm registry:
|
| 45 |
+
|
| 46 |
+
```sh
|
| 47 |
+
npm install @hono/node-server
|
| 48 |
+
pnpm add @hono/node-server
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
## Usage
|
| 52 |
+
|
| 53 |
+
Just import `@hono/node-server` at the top and write the code as usual.
|
| 54 |
+
The same code that runs on Cloudflare Workers, Deno, and Bun will work.
|
| 55 |
+
|
| 56 |
+
```ts
|
| 57 |
+
import { serve } from '@hono/node-server'
|
| 58 |
+
import { Hono } from 'hono'
|
| 59 |
+
|
| 60 |
+
const app = new Hono()
|
| 61 |
+
app.get('/', (c) => c.text('Hono meets Node.js'))
|
| 62 |
+
|
| 63 |
+
serve(app, (info) => {
|
| 64 |
+
console.log(`Listening on http://localhost:${info.port}`) // Listening on http://localhost:3000
|
| 65 |
+
})
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
## WebSocket
|
| 69 |
+
|
| 70 |
+
You can upgrade WebSocket connections with `upgradeWebSocket` from `@hono/node-server`.
|
| 71 |
+
To enable this, install `ws` (and `@types/ws`) in your project, then create and provide a `WebSocketServer` as shown in the example below.
|
| 72 |
+
|
| 73 |
+
```ts
|
| 74 |
+
import { serve, upgradeWebSocket } from '@hono/node-server'
|
| 75 |
+
import { WebSocketServer } from 'ws'
|
| 76 |
+
import { Hono } from 'hono'
|
| 77 |
+
|
| 78 |
+
const app = new Hono()
|
| 79 |
+
|
| 80 |
+
app.get(
|
| 81 |
+
'/ws',
|
| 82 |
+
upgradeWebSocket(() => ({
|
| 83 |
+
onMessage(event, ws) {
|
| 84 |
+
ws.send(event.data)
|
| 85 |
+
},
|
| 86 |
+
}))
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
const wss = new WebSocketServer({ noServer: true })
|
| 90 |
+
serve({
|
| 91 |
+
fetch: app.fetch,
|
| 92 |
+
websocket: { server: wss },
|
| 93 |
+
})
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
For example, run it using `ts-node`. Then an HTTP server will be launched. The default port is `3000`.
|
| 97 |
+
|
| 98 |
+
```sh
|
| 99 |
+
ts-node ./index.ts
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
Open `http://localhost:3000` with your browser.
|
| 103 |
+
|
| 104 |
+
## Options
|
| 105 |
+
|
| 106 |
+
### `port`
|
| 107 |
+
|
| 108 |
+
```ts
|
| 109 |
+
serve({
|
| 110 |
+
fetch: app.fetch,
|
| 111 |
+
port: 8787, // Port number, default is 3000
|
| 112 |
+
})
|
| 113 |
+
```
|
| 114 |
+
|
| 115 |
+
### `createServer`
|
| 116 |
+
|
| 117 |
+
```ts
|
| 118 |
+
import { createServer } from 'node:https'
|
| 119 |
+
import fs from 'node:fs'
|
| 120 |
+
|
| 121 |
+
//...
|
| 122 |
+
|
| 123 |
+
serve({
|
| 124 |
+
fetch: app.fetch,
|
| 125 |
+
createServer: createServer,
|
| 126 |
+
serverOptions: {
|
| 127 |
+
key: fs.readFileSync('test/fixtures/keys/agent1-key.pem'),
|
| 128 |
+
cert: fs.readFileSync('test/fixtures/keys/agent1-cert.pem'),
|
| 129 |
+
},
|
| 130 |
+
})
|
| 131 |
+
```
|
| 132 |
+
|
| 133 |
+
### `overrideGlobalObjects`
|
| 134 |
+
|
| 135 |
+
The default value is `true`. The Node.js Adapter rewrites the global Request/Response and uses a lightweight Request/Response to improve performance. If you don't want to do that, set `false`.
|
| 136 |
+
|
| 137 |
+
```ts
|
| 138 |
+
serve({
|
| 139 |
+
fetch: app.fetch,
|
| 140 |
+
overrideGlobalObjects: false,
|
| 141 |
+
})
|
| 142 |
+
```
|
| 143 |
+
|
| 144 |
+
### `autoCleanupIncoming`
|
| 145 |
+
|
| 146 |
+
The default value is `true`. The Node.js Adapter automatically cleans up (explicitly call `destroy()` method) if application is not finished to consume the incoming request. If you don't want to do that, set `false`.
|
| 147 |
+
|
| 148 |
+
If the application accepts connections from arbitrary clients, this cleanup must be done otherwise incomplete requests from clients may cause the application to stop responding. If your application only accepts connections from trusted clients, such as in a reverse proxy environment and there is no process that returns a response without reading the body of the POST request all the way through, you can improve performance by setting it to `false`.
|
| 149 |
+
|
| 150 |
+
```ts
|
| 151 |
+
serve({
|
| 152 |
+
fetch: app.fetch,
|
| 153 |
+
autoCleanupIncoming: false,
|
| 154 |
+
})
|
| 155 |
+
```
|
| 156 |
+
|
| 157 |
+
### `websocket`
|
| 158 |
+
|
| 159 |
+
provide a websocket server to enable websocket support.
|
| 160 |
+
|
| 161 |
+
```ts
|
| 162 |
+
import { serve, upgradeWebSocket } from '@hono/node-server'
|
| 163 |
+
import { WebSocketServer } from 'ws'
|
| 164 |
+
|
| 165 |
+
// ...
|
| 166 |
+
const wss = new WebSocketServer({ noServer: true })
|
| 167 |
+
|
| 168 |
+
serve({
|
| 169 |
+
fetch: app.fetch,
|
| 170 |
+
websocket: { server: wss },
|
| 171 |
+
})
|
| 172 |
+
```
|
| 173 |
+
|
| 174 |
+
## Middleware
|
| 175 |
+
|
| 176 |
+
Most built-in middleware also works with Node.js.
|
| 177 |
+
Read [the documentation](https://hono.dev/middleware/builtin/basic-auth) and use the Middleware of your liking.
|
| 178 |
+
|
| 179 |
+
```ts
|
| 180 |
+
import { serve } from '@hono/node-server'
|
| 181 |
+
import { Hono } from 'hono'
|
| 182 |
+
import { prettyJSON } from 'hono/pretty-json'
|
| 183 |
+
|
| 184 |
+
const app = new Hono()
|
| 185 |
+
|
| 186 |
+
app.get('*', prettyJSON())
|
| 187 |
+
app.get('/', (c) => c.json({ 'Hono meets': 'Node.js' }))
|
| 188 |
+
|
| 189 |
+
serve(app)
|
| 190 |
+
```
|
| 191 |
+
|
| 192 |
+
## Serve Static Middleware
|
| 193 |
+
|
| 194 |
+
Use Serve Static Middleware that has been created for Node.js.
|
| 195 |
+
|
| 196 |
+
```ts
|
| 197 |
+
import { serveStatic } from '@hono/node-server/serve-static'
|
| 198 |
+
|
| 199 |
+
//...
|
| 200 |
+
|
| 201 |
+
app.use('/static/*', serveStatic({ root: './' }))
|
| 202 |
+
```
|
| 203 |
+
|
| 204 |
+
If using a relative path, `root` will be relative to the current working directory from which the app was started.
|
| 205 |
+
|
| 206 |
+
This can cause confusion when running your application locally.
|
| 207 |
+
|
| 208 |
+
Imagine your project structure is:
|
| 209 |
+
|
| 210 |
+
```
|
| 211 |
+
my-hono-project/
|
| 212 |
+
src/
|
| 213 |
+
index.ts
|
| 214 |
+
static/
|
| 215 |
+
index.html
|
| 216 |
+
```
|
| 217 |
+
|
| 218 |
+
Typically, you would run your app from the project's root directory (`my-hono-project`),
|
| 219 |
+
so you would need the following code to serve the `static` folder:
|
| 220 |
+
|
| 221 |
+
```ts
|
| 222 |
+
app.use('/static/*', serveStatic({ root: './static' }))
|
| 223 |
+
```
|
| 224 |
+
|
| 225 |
+
Notice that `root` here is not relative to `src/index.ts`, rather to `my-hono-project`.
|
| 226 |
+
|
| 227 |
+
### Options
|
| 228 |
+
|
| 229 |
+
#### `allowPercentInPath`
|
| 230 |
+
|
| 231 |
+
By default, `serveStatic` skips request paths that still contain `%` after routing. This prevents a second decoding step from serving a file under a different path than the one checked by route middleware. Set `allowPercentInPath: true` to keep the previous behavior when serving files whose names contain percent signs.
|
| 232 |
+
|
| 233 |
+
If you restrict access to only some paths under `root` (for example, `/static/admin/*`), enabling this option may let requests bypass those restrictions. Apply access control to the same route pattern as `serveStatic` (for example, `/static/*`), before the static middleware:
|
| 234 |
+
|
| 235 |
+
```ts
|
| 236 |
+
app.use('/static/*', authMiddleware)
|
| 237 |
+
app.use('/static/*', serveStatic({ root: './static', allowPercentInPath: true }))
|
| 238 |
+
```
|
| 239 |
+
|
| 240 |
+
#### `rewriteRequestPath`
|
| 241 |
+
|
| 242 |
+
If you want to serve files in `./.foojs` with the request path `/__foo/*`, you can write like the following.
|
| 243 |
+
|
| 244 |
+
```ts
|
| 245 |
+
app.use(
|
| 246 |
+
'/__foo/*',
|
| 247 |
+
serveStatic({
|
| 248 |
+
root: './.foojs/',
|
| 249 |
+
rewriteRequestPath: (path: string) => path.replace(/^\/__foo/, ''),
|
| 250 |
+
})
|
| 251 |
+
)
|
| 252 |
+
```
|
| 253 |
+
|
| 254 |
+
#### `onFound`
|
| 255 |
+
|
| 256 |
+
You can specify handling when the requested file is found with `onFound`.
|
| 257 |
+
|
| 258 |
+
```ts
|
| 259 |
+
app.use(
|
| 260 |
+
'/static/*',
|
| 261 |
+
serveStatic({
|
| 262 |
+
// ...
|
| 263 |
+
onFound: (_path, c) => {
|
| 264 |
+
c.header('Cache-Control', `public, immutable, max-age=31536000`)
|
| 265 |
+
},
|
| 266 |
+
})
|
| 267 |
+
)
|
| 268 |
+
```
|
| 269 |
+
|
| 270 |
+
#### `onNotFound`
|
| 271 |
+
|
| 272 |
+
The `onNotFound` is useful for debugging. You can write a handle for when a file is not found.
|
| 273 |
+
|
| 274 |
+
```ts
|
| 275 |
+
app.use(
|
| 276 |
+
'/static/*',
|
| 277 |
+
serveStatic({
|
| 278 |
+
root: './non-existent-dir',
|
| 279 |
+
onNotFound: (path, c) => {
|
| 280 |
+
console.log(`${path} is not found, request to ${c.req.path}`)
|
| 281 |
+
},
|
| 282 |
+
})
|
| 283 |
+
)
|
| 284 |
+
```
|
| 285 |
+
|
| 286 |
+
#### `precompressed`
|
| 287 |
+
|
| 288 |
+
The `precompressed` option checks if files with extensions like `.br` or `.gz` are available and serves them based on the `Accept-Encoding` header. It prioritizes Brotli, then Zstd, and Gzip. If none are available, it serves the original file.
|
| 289 |
+
|
| 290 |
+
```ts
|
| 291 |
+
app.use(
|
| 292 |
+
'/static/*',
|
| 293 |
+
serveStatic({
|
| 294 |
+
precompressed: true,
|
| 295 |
+
})
|
| 296 |
+
)
|
| 297 |
+
```
|
| 298 |
+
|
| 299 |
+
## ConnInfo Helper
|
| 300 |
+
|
| 301 |
+
You can use the [ConnInfo Helper](https://hono.dev/docs/helpers/conninfo) by importing `getConnInfo` from `@hono/node-server/conninfo`.
|
| 302 |
+
|
| 303 |
+
```ts
|
| 304 |
+
import { getConnInfo } from '@hono/node-server/conninfo'
|
| 305 |
+
|
| 306 |
+
app.get('/', (c) => {
|
| 307 |
+
const info = getConnInfo(c) // info is `ConnInfo`
|
| 308 |
+
return c.text(`Your remote address is ${info.remote.address}`)
|
| 309 |
+
})
|
| 310 |
+
```
|
| 311 |
+
|
| 312 |
+
## Accessing Node.js API
|
| 313 |
+
|
| 314 |
+
You can access the Node.js API from `c.env` in Node.js. For example, if you want to specify a type, you can write the following.
|
| 315 |
+
|
| 316 |
+
```ts
|
| 317 |
+
import { serve } from '@hono/node-server'
|
| 318 |
+
import type { HttpBindings } from '@hono/node-server'
|
| 319 |
+
import { Hono } from 'hono'
|
| 320 |
+
|
| 321 |
+
const app = new Hono<{ Bindings: HttpBindings }>()
|
| 322 |
+
|
| 323 |
+
app.get('/', (c) => {
|
| 324 |
+
return c.json({
|
| 325 |
+
remoteAddress: c.env.incoming.socket.remoteAddress,
|
| 326 |
+
})
|
| 327 |
+
})
|
| 328 |
+
|
| 329 |
+
serve(app)
|
| 330 |
+
```
|
| 331 |
+
|
| 332 |
+
The APIs that you can get from `c.env` are as follows.
|
| 333 |
+
|
| 334 |
+
```ts
|
| 335 |
+
type HttpBindings = {
|
| 336 |
+
incoming: IncomingMessage
|
| 337 |
+
outgoing: ServerResponse
|
| 338 |
+
}
|
| 339 |
+
|
| 340 |
+
type Http2Bindings = {
|
| 341 |
+
incoming: Http2ServerRequest
|
| 342 |
+
outgoing: Http2ServerResponse
|
| 343 |
+
}
|
| 344 |
+
```
|
| 345 |
+
|
| 346 |
+
## Early Hints Middleware
|
| 347 |
+
|
| 348 |
+
You can send HTTP 103 Early Hints to instruct browsers to preload or preconnect resources before the final response is prepared. The middleware is supported under Node.js bindings (HTTP/1.1 and HTTP/2).
|
| 349 |
+
|
| 350 |
+
### Usage
|
| 351 |
+
|
| 352 |
+
Import `earlyHints` from `@hono/node-server/early-hints`:
|
| 353 |
+
|
| 354 |
+
#### Static links
|
| 355 |
+
|
| 356 |
+
```ts
|
| 357 |
+
import { serve } from '@hono/node-server'
|
| 358 |
+
import { earlyHints } from '@hono/node-server/early-hints'
|
| 359 |
+
import { Hono } from 'hono'
|
| 360 |
+
|
| 361 |
+
const app = new Hono()
|
| 362 |
+
|
| 363 |
+
app.use(
|
| 364 |
+
earlyHints({
|
| 365 |
+
link: '</styles.css>; rel=preload; as=style',
|
| 366 |
+
})
|
| 367 |
+
)
|
| 368 |
+
|
| 369 |
+
app.get('/', (c) => {
|
| 370 |
+
return c.html('<!DOCTYPE html><html><body><h1>Hello Hono!</h1></body></html>')
|
| 371 |
+
})
|
| 372 |
+
|
| 373 |
+
serve(app)
|
| 374 |
+
```
|
| 375 |
+
|
| 376 |
+
#### Dynamic links
|
| 377 |
+
|
| 378 |
+
```ts
|
| 379 |
+
app.use(
|
| 380 |
+
earlyHints({
|
| 381 |
+
link: (c) =>
|
| 382 |
+
c.req.query('theme') === 'dark'
|
| 383 |
+
? '</dark.css>; rel=preload; as=style'
|
| 384 |
+
: '</light.css>; rel=preload; as=style',
|
| 385 |
+
})
|
| 386 |
+
)
|
| 387 |
+
```
|
| 388 |
+
|
| 389 |
+
> [!NOTE]
|
| 390 |
+
> Early Hints are sent only for requests that look like document navigations. If `Sec-Fetch-Mode` or `Sec-Fetch-Dest` is present with a value other than `navigate` or `document`, for example a `fetch()` or XHR call from a browser, a subresource request, or an iframe navigation, the middleware skips the hints and continues to the handler. Requests without these headers, such as `curl` or `fetch()` from a JavaScript runtime, are treated as navigations and do receive Early Hints.
|
| 391 |
+
|
| 392 |
+
## Direct response from Node.js API
|
| 393 |
+
|
| 394 |
+
You can directly respond to the client from the Node.js API.
|
| 395 |
+
In that case, the response from Hono should be ignored, so return `RESPONSE_ALREADY_SENT`.
|
| 396 |
+
|
| 397 |
+
> [!NOTE]
|
| 398 |
+
> This feature can be used when migrating existing Node.js applications to Hono, but we recommend using Hono's API for new applications.
|
| 399 |
+
|
| 400 |
+
```ts
|
| 401 |
+
import { serve } from '@hono/node-server'
|
| 402 |
+
import type { HttpBindings } from '@hono/node-server'
|
| 403 |
+
import { RESPONSE_ALREADY_SENT } from '@hono/node-server/utils/response'
|
| 404 |
+
import { Hono } from 'hono'
|
| 405 |
+
|
| 406 |
+
const app = new Hono<{ Bindings: HttpBindings }>()
|
| 407 |
+
|
| 408 |
+
app.get('/', (c) => {
|
| 409 |
+
const { outgoing } = c.env
|
| 410 |
+
outgoing.writeHead(200, { 'Content-Type': 'text/plain' })
|
| 411 |
+
outgoing.end('Hello World\n')
|
| 412 |
+
|
| 413 |
+
return RESPONSE_ALREADY_SENT
|
| 414 |
+
})
|
| 415 |
+
|
| 416 |
+
serve(app)
|
| 417 |
+
```
|
| 418 |
+
|
| 419 |
+
## Listen to a UNIX domain socket
|
| 420 |
+
|
| 421 |
+
You can configure the HTTP server to listen to a UNIX domain socket instead of a TCP port.
|
| 422 |
+
|
| 423 |
+
```ts
|
| 424 |
+
import { createAdaptorServer } from '@hono/node-server'
|
| 425 |
+
|
| 426 |
+
// ...
|
| 427 |
+
|
| 428 |
+
const socketPath = '/tmp/example.sock'
|
| 429 |
+
|
| 430 |
+
const server = createAdaptorServer(app)
|
| 431 |
+
server.listen(socketPath, () => {
|
| 432 |
+
console.log(`Listening on ${socketPath}`)
|
| 433 |
+
})
|
| 434 |
+
```
|
| 435 |
+
|
| 436 |
+
## Related projects
|
| 437 |
+
|
| 438 |
+
- Hono - <https://hono.dev>
|
| 439 |
+
- Hono GitHub repository - <https://github.com/honojs/hono>
|
| 440 |
+
|
| 441 |
+
## Authors
|
| 442 |
+
|
| 443 |
+
- Yusuke Wada <https://github.com/yusukebe>
|
| 444 |
+
- Taku Amano <https://github.com/usualoma>
|
| 445 |
+
|
| 446 |
+
## License
|
| 447 |
+
|
| 448 |
+
MIT
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/conninfo.cjs
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
| 2 |
+
|
| 3 |
+
//#region src/conninfo.ts
|
| 4 |
+
/**
|
| 5 |
+
* ConnInfo Helper for Node.js
|
| 6 |
+
* @param c Context
|
| 7 |
+
* @returns ConnInfo
|
| 8 |
+
*/
|
| 9 |
+
const getConnInfo = (c) => {
|
| 10 |
+
const bindings = c.env.server ? c.env.server : c.env;
|
| 11 |
+
const address = bindings.incoming.socket.remoteAddress;
|
| 12 |
+
const port = bindings.incoming.socket.remotePort;
|
| 13 |
+
const family = bindings.incoming.socket.remoteFamily;
|
| 14 |
+
return { remote: {
|
| 15 |
+
address,
|
| 16 |
+
port,
|
| 17 |
+
addressType: family === "IPv4" ? "IPv4" : family === "IPv6" ? "IPv6" : void 0
|
| 18 |
+
} };
|
| 19 |
+
};
|
| 20 |
+
|
| 21 |
+
//#endregion
|
| 22 |
+
exports.getConnInfo = getConnInfo;
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/conninfo.d.cts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { GetConnInfo } from "hono/conninfo";
|
| 2 |
+
|
| 3 |
+
//#region src/conninfo.d.ts
|
| 4 |
+
/**
|
| 5 |
+
* ConnInfo Helper for Node.js
|
| 6 |
+
* @param c Context
|
| 7 |
+
* @returns ConnInfo
|
| 8 |
+
*/
|
| 9 |
+
declare const getConnInfo: GetConnInfo;
|
| 10 |
+
//#endregion
|
| 11 |
+
export { getConnInfo };
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/conninfo.d.mts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { GetConnInfo } from "hono/conninfo";
|
| 2 |
+
|
| 3 |
+
//#region src/conninfo.d.ts
|
| 4 |
+
/**
|
| 5 |
+
* ConnInfo Helper for Node.js
|
| 6 |
+
* @param c Context
|
| 7 |
+
* @returns ConnInfo
|
| 8 |
+
*/
|
| 9 |
+
declare const getConnInfo: GetConnInfo;
|
| 10 |
+
//#endregion
|
| 11 |
+
export { getConnInfo };
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/conninfo.mjs
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//#region src/conninfo.ts
|
| 2 |
+
/**
|
| 3 |
+
* ConnInfo Helper for Node.js
|
| 4 |
+
* @param c Context
|
| 5 |
+
* @returns ConnInfo
|
| 6 |
+
*/
|
| 7 |
+
const getConnInfo = (c) => {
|
| 8 |
+
const bindings = c.env.server ? c.env.server : c.env;
|
| 9 |
+
const address = bindings.incoming.socket.remoteAddress;
|
| 10 |
+
const port = bindings.incoming.socket.remotePort;
|
| 11 |
+
const family = bindings.incoming.socket.remoteFamily;
|
| 12 |
+
return { remote: {
|
| 13 |
+
address,
|
| 14 |
+
port,
|
| 15 |
+
addressType: family === "IPv4" ? "IPv4" : family === "IPv6" ? "IPv6" : void 0
|
| 16 |
+
} };
|
| 17 |
+
};
|
| 18 |
+
|
| 19 |
+
//#endregion
|
| 20 |
+
export { getConnInfo };
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/constants-BLSFu_RU.mjs
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//#region src/utils/response/constants.ts
|
| 2 |
+
const X_ALREADY_SENT = "x-hono-already-sent";
|
| 3 |
+
|
| 4 |
+
//#endregion
|
| 5 |
+
export { X_ALREADY_SENT as t };
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/constants-BXAKTxRC.cjs
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
//#region src/utils/response/constants.ts
|
| 3 |
+
const X_ALREADY_SENT = "x-hono-already-sent";
|
| 4 |
+
|
| 5 |
+
//#endregion
|
| 6 |
+
Object.defineProperty(exports, 'X_ALREADY_SENT', {
|
| 7 |
+
enumerable: true,
|
| 8 |
+
get: function () {
|
| 9 |
+
return X_ALREADY_SENT;
|
| 10 |
+
}
|
| 11 |
+
});
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/early-hints.cjs
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
| 2 |
+
|
| 3 |
+
//#region src/early-hints.ts
|
| 4 |
+
/**
|
| 5 |
+
* Early Hints middleware for Node.js
|
| 6 |
+
* Automatically sends a 103 Early Hints informational response with the specified Link header(s).
|
| 7 |
+
*
|
| 8 |
+
* @param options EarlyHintsOptions
|
| 9 |
+
* @returns MiddlewareHandler
|
| 10 |
+
*/
|
| 11 |
+
const earlyHints = (options) => {
|
| 12 |
+
let warned = false;
|
| 13 |
+
return async (c, next) => {
|
| 14 |
+
const mode = c.req.header("Sec-Fetch-Mode");
|
| 15 |
+
const dest = c.req.header("Sec-Fetch-Dest");
|
| 16 |
+
if (mode && mode !== "navigate" || dest && dest !== "document") return next();
|
| 17 |
+
const env = c.env || {};
|
| 18 |
+
const outgoing = ("server" in env ? env.server : env)?.outgoing;
|
| 19 |
+
if (typeof outgoing?.writeEarlyHints !== "function") {
|
| 20 |
+
if (!warned) {
|
| 21 |
+
console.warn("Early Hints Middleware is not supported because writeEarlyHints is not defined.");
|
| 22 |
+
warned = true;
|
| 23 |
+
}
|
| 24 |
+
return await next();
|
| 25 |
+
}
|
| 26 |
+
if (!outgoing.headersSent) {
|
| 27 |
+
const link = typeof options.link === "function" ? options.link(c) : options.link;
|
| 28 |
+
if (link !== void 0 && (Array.isArray(link) ? link.length > 0 : Boolean(link))) outgoing.writeEarlyHints({ link });
|
| 29 |
+
}
|
| 30 |
+
await next();
|
| 31 |
+
};
|
| 32 |
+
};
|
| 33 |
+
|
| 34 |
+
//#endregion
|
| 35 |
+
exports.earlyHints = earlyHints;
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/early-hints.d.cts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { Context, Env, MiddlewareHandler } from "hono";
|
| 2 |
+
|
| 3 |
+
//#region src/early-hints.d.ts
|
| 4 |
+
type EarlyHintsOptions<E extends Env = Env> = {
|
| 5 |
+
link: string | string[] | ((c: Context<E>) => string | string[] | undefined);
|
| 6 |
+
};
|
| 7 |
+
/**
|
| 8 |
+
* Early Hints middleware for Node.js
|
| 9 |
+
* Automatically sends a 103 Early Hints informational response with the specified Link header(s).
|
| 10 |
+
*
|
| 11 |
+
* @param options EarlyHintsOptions
|
| 12 |
+
* @returns MiddlewareHandler
|
| 13 |
+
*/
|
| 14 |
+
declare const earlyHints: <E extends Env = any>(options: EarlyHintsOptions<E>) => MiddlewareHandler<E>;
|
| 15 |
+
//#endregion
|
| 16 |
+
export { EarlyHintsOptions, earlyHints };
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/early-hints.d.mts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { Context, Env, MiddlewareHandler } from "hono";
|
| 2 |
+
|
| 3 |
+
//#region src/early-hints.d.ts
|
| 4 |
+
type EarlyHintsOptions<E extends Env = Env> = {
|
| 5 |
+
link: string | string[] | ((c: Context<E>) => string | string[] | undefined);
|
| 6 |
+
};
|
| 7 |
+
/**
|
| 8 |
+
* Early Hints middleware for Node.js
|
| 9 |
+
* Automatically sends a 103 Early Hints informational response with the specified Link header(s).
|
| 10 |
+
*
|
| 11 |
+
* @param options EarlyHintsOptions
|
| 12 |
+
* @returns MiddlewareHandler
|
| 13 |
+
*/
|
| 14 |
+
declare const earlyHints: <E extends Env = any>(options: EarlyHintsOptions<E>) => MiddlewareHandler<E>;
|
| 15 |
+
//#endregion
|
| 16 |
+
export { EarlyHintsOptions, earlyHints };
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/early-hints.mjs
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//#region src/early-hints.ts
|
| 2 |
+
/**
|
| 3 |
+
* Early Hints middleware for Node.js
|
| 4 |
+
* Automatically sends a 103 Early Hints informational response with the specified Link header(s).
|
| 5 |
+
*
|
| 6 |
+
* @param options EarlyHintsOptions
|
| 7 |
+
* @returns MiddlewareHandler
|
| 8 |
+
*/
|
| 9 |
+
const earlyHints = (options) => {
|
| 10 |
+
let warned = false;
|
| 11 |
+
return async (c, next) => {
|
| 12 |
+
const mode = c.req.header("Sec-Fetch-Mode");
|
| 13 |
+
const dest = c.req.header("Sec-Fetch-Dest");
|
| 14 |
+
if (mode && mode !== "navigate" || dest && dest !== "document") return next();
|
| 15 |
+
const env = c.env || {};
|
| 16 |
+
const outgoing = ("server" in env ? env.server : env)?.outgoing;
|
| 17 |
+
if (typeof outgoing?.writeEarlyHints !== "function") {
|
| 18 |
+
if (!warned) {
|
| 19 |
+
console.warn("Early Hints Middleware is not supported because writeEarlyHints is not defined.");
|
| 20 |
+
warned = true;
|
| 21 |
+
}
|
| 22 |
+
return await next();
|
| 23 |
+
}
|
| 24 |
+
if (!outgoing.headersSent) {
|
| 25 |
+
const link = typeof options.link === "function" ? options.link(c) : options.link;
|
| 26 |
+
if (link !== void 0 && (Array.isArray(link) ? link.length > 0 : Boolean(link))) outgoing.writeEarlyHints({ link });
|
| 27 |
+
}
|
| 28 |
+
await next();
|
| 29 |
+
};
|
| 30 |
+
};
|
| 31 |
+
|
| 32 |
+
//#endregion
|
| 33 |
+
export { earlyHints };
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/index.cjs
ADDED
|
@@ -0,0 +1,1340 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
| 2 |
+
const require_constants = require('./constants-BXAKTxRC.cjs');
|
| 3 |
+
let node_http = require("node:http");
|
| 4 |
+
let node_http2 = require("node:http2");
|
| 5 |
+
let node_stream = require("node:stream");
|
| 6 |
+
let hono_ws = require("hono/ws");
|
| 7 |
+
|
| 8 |
+
//#region src/error.ts
|
| 9 |
+
var RequestError = class extends Error {
|
| 10 |
+
constructor(message, options) {
|
| 11 |
+
super(message, options);
|
| 12 |
+
this.name = "RequestError";
|
| 13 |
+
}
|
| 14 |
+
};
|
| 15 |
+
|
| 16 |
+
//#endregion
|
| 17 |
+
//#region src/headers.ts
|
| 18 |
+
const nonJoinedHeaders = new Set([
|
| 19 |
+
"age",
|
| 20 |
+
"authorization",
|
| 21 |
+
"content-length",
|
| 22 |
+
"content-type",
|
| 23 |
+
"etag",
|
| 24 |
+
"expires",
|
| 25 |
+
"from",
|
| 26 |
+
"host",
|
| 27 |
+
"if-modified-since",
|
| 28 |
+
"if-unmodified-since",
|
| 29 |
+
"last-modified",
|
| 30 |
+
"location",
|
| 31 |
+
"max-forwards",
|
| 32 |
+
"proxy-authorization",
|
| 33 |
+
"referer",
|
| 34 |
+
"retry-after",
|
| 35 |
+
"server",
|
| 36 |
+
"user-agent"
|
| 37 |
+
]);
|
| 38 |
+
const validHeaderName = /^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/;
|
| 39 |
+
const isHttpWhitespace = (code) => code === 9 || code === 10 || code === 13 || code === 32;
|
| 40 |
+
const normalizeHeaderValue = (value) => {
|
| 41 |
+
if (!isHttpWhitespace(value.charCodeAt(0)) && !isHttpWhitespace(value.charCodeAt(value.length - 1))) return value;
|
| 42 |
+
let start = 0;
|
| 43 |
+
let end = value.length;
|
| 44 |
+
while (start < end && isHttpWhitespace(value.charCodeAt(start))) start++;
|
| 45 |
+
while (end > start && isHttpWhitespace(value.charCodeAt(end - 1))) end--;
|
| 46 |
+
return value.slice(start, end);
|
| 47 |
+
};
|
| 48 |
+
const forbiddenHeaderValue = /[\0\r\n]/;
|
| 49 |
+
const GlobalHeaders = globalThis.Headers;
|
| 50 |
+
const materializeHeaders = (rawHeaders, HeadersCtor = GlobalHeaders) => {
|
| 51 |
+
const headers = new HeadersCtor();
|
| 52 |
+
for (let i = 0; i < rawHeaders.length; i += 2) {
|
| 53 |
+
const name = rawHeaders[i];
|
| 54 |
+
if (!name.startsWith(":")) headers.append(name, rawHeaders[i + 1]);
|
| 55 |
+
}
|
| 56 |
+
return headers;
|
| 57 |
+
};
|
| 58 |
+
var RequestHeaders = class {
|
| 59 |
+
#incoming;
|
| 60 |
+
#rawHeaders;
|
| 61 |
+
#headers;
|
| 62 |
+
#invalidValue;
|
| 63 |
+
constructor(incoming) {
|
| 64 |
+
this.#incoming = incoming;
|
| 65 |
+
if (incoming instanceof node_http2.Http2ServerRequest) this.#rawHeaders = incoming.rawHeaders.slice();
|
| 66 |
+
}
|
| 67 |
+
get #lazyRawHeaders() {
|
| 68 |
+
return this.#rawHeaders ??= this.#incoming.rawHeaders.slice();
|
| 69 |
+
}
|
| 70 |
+
get #native() {
|
| 71 |
+
if (!this.#headers) {
|
| 72 |
+
this.#headers = materializeHeaders(this.#lazyRawHeaders);
|
| 73 |
+
this.#rawHeaders = void 0;
|
| 74 |
+
}
|
| 75 |
+
return this.#headers;
|
| 76 |
+
}
|
| 77 |
+
#normalizedName(name) {
|
| 78 |
+
if (typeof name !== "string") return;
|
| 79 |
+
if (!validHeaderName.test(name)) throw new TypeError(`Invalid header name: ${name}`);
|
| 80 |
+
return name.toLowerCase();
|
| 81 |
+
}
|
| 82 |
+
#lookupHttp1(lowerName) {
|
| 83 |
+
const headers = this.#incoming instanceof node_http2.Http2ServerRequest ? void 0 : this.#incoming.headers;
|
| 84 |
+
if (!headers || nonJoinedHeaders.has(lowerName) || lowerName === "set-cookie" || lowerName === "__proto__") return;
|
| 85 |
+
if (!Object.hasOwn(headers, lowerName)) return null;
|
| 86 |
+
const rawValue = headers[lowerName];
|
| 87 |
+
if (typeof rawValue === "string") {
|
| 88 |
+
const value = normalizeHeaderValue(rawValue);
|
| 89 |
+
return forbiddenHeaderValue.test(value) ? void 0 : value;
|
| 90 |
+
}
|
| 91 |
+
}
|
| 92 |
+
#lookup(rawHeaders, lowerName) {
|
| 93 |
+
const separator = lowerName === "cookie" ? "; " : ", ";
|
| 94 |
+
let value = null;
|
| 95 |
+
for (let i = 0; i < rawHeaders.length; i += 2) {
|
| 96 |
+
const rawName = rawHeaders[i];
|
| 97 |
+
if (rawName.length === lowerName.length && rawName.toLowerCase() === lowerName) {
|
| 98 |
+
const rawValue = normalizeHeaderValue(rawHeaders[i + 1]);
|
| 99 |
+
if (forbiddenHeaderValue.test(rawValue)) {
|
| 100 |
+
this.#invalidValue = true;
|
| 101 |
+
return;
|
| 102 |
+
}
|
| 103 |
+
value = value === null ? rawValue : value + separator + rawValue;
|
| 104 |
+
}
|
| 105 |
+
}
|
| 106 |
+
return value;
|
| 107 |
+
}
|
| 108 |
+
append(name, value) {
|
| 109 |
+
this.#native.append(name, value);
|
| 110 |
+
}
|
| 111 |
+
delete(name) {
|
| 112 |
+
this.#native.delete(name);
|
| 113 |
+
}
|
| 114 |
+
get(name) {
|
| 115 |
+
const lowerName = this.#normalizedName(name);
|
| 116 |
+
if (lowerName && !this.#headers && !this.#invalidValue) {
|
| 117 |
+
const http1Value = this.#lookupHttp1(lowerName);
|
| 118 |
+
if (http1Value !== void 0) return http1Value;
|
| 119 |
+
const value = this.#lookup(this.#lazyRawHeaders, lowerName);
|
| 120 |
+
if (value !== void 0) return value;
|
| 121 |
+
}
|
| 122 |
+
return this.#native.get(name);
|
| 123 |
+
}
|
| 124 |
+
has(name) {
|
| 125 |
+
const lowerName = this.#normalizedName(name);
|
| 126 |
+
if (lowerName && !this.#headers && !this.#invalidValue) {
|
| 127 |
+
const http1Value = this.#lookupHttp1(lowerName);
|
| 128 |
+
if (http1Value !== void 0) return http1Value !== null;
|
| 129 |
+
const value = this.#lookup(this.#lazyRawHeaders, lowerName);
|
| 130 |
+
if (value !== void 0) return value !== null;
|
| 131 |
+
}
|
| 132 |
+
return this.#native.has(name);
|
| 133 |
+
}
|
| 134 |
+
set(name, value) {
|
| 135 |
+
this.#native.set(name, value);
|
| 136 |
+
}
|
| 137 |
+
getSetCookie() {
|
| 138 |
+
return this.#native.getSetCookie();
|
| 139 |
+
}
|
| 140 |
+
keys() {
|
| 141 |
+
return this.#native.keys();
|
| 142 |
+
}
|
| 143 |
+
values() {
|
| 144 |
+
return this.#native.values();
|
| 145 |
+
}
|
| 146 |
+
entries() {
|
| 147 |
+
return this.#native.entries();
|
| 148 |
+
}
|
| 149 |
+
forEach(callback, thisArg) {
|
| 150 |
+
this.#native.forEach((value, key) => {
|
| 151 |
+
callback.call(thisArg, value, key, this);
|
| 152 |
+
});
|
| 153 |
+
}
|
| 154 |
+
[Symbol.iterator]() {
|
| 155 |
+
return this.entries();
|
| 156 |
+
}
|
| 157 |
+
};
|
| 158 |
+
Object.defineProperty(RequestHeaders.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
|
| 159 |
+
return `Headers (lightweight) ${inspectFn(Object.fromEntries(this), {
|
| 160 |
+
...options,
|
| 161 |
+
depth: depth == null ? null : depth - 1
|
| 162 |
+
})}`;
|
| 163 |
+
} });
|
| 164 |
+
Object.setPrototypeOf(RequestHeaders.prototype, GlobalHeaders.prototype);
|
| 165 |
+
const newHeadersFromIncoming = (incoming) => globalThis.Headers === GlobalHeaders ? new RequestHeaders(incoming) : materializeHeaders(incoming.rawHeaders, globalThis.Headers);
|
| 166 |
+
|
| 167 |
+
//#endregion
|
| 168 |
+
//#region src/url.ts
|
| 169 |
+
const reValidRequestUrl = /^\/[!#$&-;=?-\[\]_a-z~]*$/;
|
| 170 |
+
const reDotSegment = /\/\.\.?(?:[/?#]|$)/;
|
| 171 |
+
const reValidHost = /^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/;
|
| 172 |
+
const buildUrl = (scheme, host, incomingUrl) => {
|
| 173 |
+
const url = `${scheme}://${host}${incomingUrl}`;
|
| 174 |
+
if (!reValidHost.test(host)) {
|
| 175 |
+
const urlObj = new URL(url);
|
| 176 |
+
if (urlObj.hostname.length !== host.length && urlObj.hostname !== (host.includes(":") ? host.replace(/:\d+$/, "") : host).toLowerCase()) throw new RequestError("Invalid host header");
|
| 177 |
+
return urlObj.href;
|
| 178 |
+
} else if (incomingUrl.length === 0) return url + "/";
|
| 179 |
+
else {
|
| 180 |
+
if (incomingUrl.charCodeAt(0) !== 47) throw new RequestError("Invalid URL");
|
| 181 |
+
if (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) return new URL(url).href;
|
| 182 |
+
return url;
|
| 183 |
+
}
|
| 184 |
+
};
|
| 185 |
+
|
| 186 |
+
//#endregion
|
| 187 |
+
//#region src/request.ts
|
| 188 |
+
const toRequestError = (e) => {
|
| 189 |
+
if (e instanceof RequestError) return e;
|
| 190 |
+
return new RequestError(e.message, { cause: e });
|
| 191 |
+
};
|
| 192 |
+
const GlobalRequest = global.Request;
|
| 193 |
+
var Request$1 = class extends GlobalRequest {
|
| 194 |
+
constructor(input, options) {
|
| 195 |
+
if (typeof input === "object" && getRequestCache in input) {
|
| 196 |
+
const hasReplacementBody = options !== void 0 && "body" in options && options.body != null;
|
| 197 |
+
if (input[bodyConsumedDirectlyKey] && !hasReplacementBody) throw new TypeError("Cannot construct a Request with a Request object that has already been used.");
|
| 198 |
+
input = input[getRequestCache]();
|
| 199 |
+
}
|
| 200 |
+
if (typeof (options?.body)?.getReader !== "undefined") options.duplex ??= "half";
|
| 201 |
+
super(input, options);
|
| 202 |
+
}
|
| 203 |
+
};
|
| 204 |
+
const wrapBodyStream = Symbol("wrapBodyStream");
|
| 205 |
+
const byteExactEncodings = new Set([
|
| 206 |
+
"latin1",
|
| 207 |
+
"binary",
|
| 208 |
+
"hex",
|
| 209 |
+
"base64",
|
| 210 |
+
"base64url"
|
| 211 |
+
]);
|
| 212 |
+
const isByteExactEncoding = (encoding) => encoding === null || byteExactEncodings.has(encoding);
|
| 213 |
+
const bodyBufferedBeforeDisconnectKey = Symbol("bodyBufferedBeforeDisconnect");
|
| 214 |
+
const bodyBufferedLengthBeforeDisconnectKey = Symbol("bodyBufferedLengthBeforeDisconnect");
|
| 215 |
+
const toBufferChunk = (chunk, encoding) => Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding ?? "utf8");
|
| 216 |
+
const isRecoverableDisconnectedIncoming = (incoming) => !(incoming instanceof node_http2.Http2ServerRequest) && !!incoming.complete && !!incoming.readableAborted && typeof incoming.read === "function" && isByteExactEncoding(incoming.readableEncoding);
|
| 217 |
+
const recordBodyBufferedBeforeDisconnect = (incoming) => {
|
| 218 |
+
if (incoming.readableDidRead || !isRecoverableDisconnectedIncoming(incoming)) return;
|
| 219 |
+
const incomingWithRecovery = incoming;
|
| 220 |
+
incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] ??= incoming.readableLength;
|
| 221 |
+
};
|
| 222 |
+
const readBodyBufferedBeforeDisconnect = (incoming, chunks) => {
|
| 223 |
+
if (incoming.readableDidRead && !chunks || !isRecoverableDisconnectedIncoming(incoming)) return;
|
| 224 |
+
const incomingWithRecovery = incoming;
|
| 225 |
+
if (incomingWithRecovery[bodyBufferedBeforeDisconnectKey] !== void 0) return incomingWithRecovery[bodyBufferedBeforeDisconnectKey];
|
| 226 |
+
let result;
|
| 227 |
+
const errored = incoming.errored;
|
| 228 |
+
if (errored && errored.code !== "ECONNRESET") result = errored;
|
| 229 |
+
else if (incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] !== void 0 && incoming.readableLength !== incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey]) result = newBodyUnusableError();
|
| 230 |
+
else {
|
| 231 |
+
const bodyChunks = chunks ?? [];
|
| 232 |
+
const chunk = incoming.read();
|
| 233 |
+
if (chunk !== null) bodyChunks.push(toBufferChunk(chunk, incoming.readableEncoding));
|
| 234 |
+
const buffer = bodyChunks.length === 1 ? bodyChunks[0] : Buffer.concat(bodyChunks);
|
| 235 |
+
result = buffer;
|
| 236 |
+
const contentLength = incoming.headers["content-length"];
|
| 237 |
+
if (typeof contentLength === "string" && /^\d+$/.test(contentLength)) {
|
| 238 |
+
const expectedLength = Number(contentLength);
|
| 239 |
+
if (Number.isSafeInteger(expectedLength) && buffer.length !== expectedLength) result = newBodyUnusableError();
|
| 240 |
+
}
|
| 241 |
+
}
|
| 242 |
+
incomingWithRecovery[bodyBufferedBeforeDisconnectKey] = result;
|
| 243 |
+
return result;
|
| 244 |
+
};
|
| 245 |
+
const enqueueBufferedBody = (controller, buffered) => {
|
| 246 |
+
if (buffered instanceof Error) {
|
| 247 |
+
controller.error(buffered);
|
| 248 |
+
return;
|
| 249 |
+
}
|
| 250 |
+
if (buffered.length > 0) controller.enqueue(buffered);
|
| 251 |
+
controller.close();
|
| 252 |
+
};
|
| 253 |
+
const newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
|
| 254 |
+
const init = {
|
| 255 |
+
method,
|
| 256 |
+
headers,
|
| 257 |
+
signal: abortController.signal
|
| 258 |
+
};
|
| 259 |
+
if (method === "TRACE") {
|
| 260 |
+
init.method = "GET";
|
| 261 |
+
const req = new Request$1(url, init);
|
| 262 |
+
Object.defineProperty(req, "method", { get() {
|
| 263 |
+
return "TRACE";
|
| 264 |
+
} });
|
| 265 |
+
return req;
|
| 266 |
+
}
|
| 267 |
+
if (!(method === "GET" || method === "HEAD")) if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) init.body = new ReadableStream({ start(controller) {
|
| 268 |
+
controller.enqueue(incoming.rawBody);
|
| 269 |
+
controller.close();
|
| 270 |
+
} });
|
| 271 |
+
else if (incoming[wrapBodyStream]) {
|
| 272 |
+
let reader;
|
| 273 |
+
init.body = new ReadableStream({ async pull(controller) {
|
| 274 |
+
try {
|
| 275 |
+
if (!reader) {
|
| 276 |
+
const buffered = readBodyBufferedBeforeDisconnect(incoming);
|
| 277 |
+
if (buffered !== void 0) {
|
| 278 |
+
enqueueBufferedBody(controller, buffered);
|
| 279 |
+
return;
|
| 280 |
+
}
|
| 281 |
+
}
|
| 282 |
+
reader ||= node_stream.Readable.toWeb(incoming).getReader();
|
| 283 |
+
const { done, value } = await reader.read();
|
| 284 |
+
if (done) controller.close();
|
| 285 |
+
else controller.enqueue(value);
|
| 286 |
+
} catch (error) {
|
| 287 |
+
controller.error(error);
|
| 288 |
+
}
|
| 289 |
+
} });
|
| 290 |
+
} else {
|
| 291 |
+
const buffered = readBodyBufferedBeforeDisconnect(incoming);
|
| 292 |
+
if (buffered !== void 0) init.body = new ReadableStream({ start(controller) {
|
| 293 |
+
enqueueBufferedBody(controller, buffered);
|
| 294 |
+
} });
|
| 295 |
+
else init.body = node_stream.Readable.toWeb(incoming);
|
| 296 |
+
}
|
| 297 |
+
return new Request$1(url, init);
|
| 298 |
+
};
|
| 299 |
+
const getRequestCache = Symbol("getRequestCache");
|
| 300 |
+
const requestCache = Symbol("requestCache");
|
| 301 |
+
const incomingKey = Symbol("incomingKey");
|
| 302 |
+
const urlKey = Symbol("urlKey");
|
| 303 |
+
const methodKey = Symbol("methodKey");
|
| 304 |
+
const headersKey = Symbol("headersKey");
|
| 305 |
+
const abortControllerKey = Symbol("abortControllerKey");
|
| 306 |
+
const getAbortController = Symbol("getAbortController");
|
| 307 |
+
const abortRequest = Symbol("abortRequest");
|
| 308 |
+
const bodyBufferKey = Symbol("bodyBuffer");
|
| 309 |
+
const bodyReadPromiseKey = Symbol("bodyReadPromise");
|
| 310 |
+
const bodyConsumedDirectlyKey = Symbol("bodyConsumedDirectly");
|
| 311 |
+
const bodyLockReaderKey = Symbol("bodyLockReader");
|
| 312 |
+
const abortReasonKey = Symbol("abortReason");
|
| 313 |
+
const newBodyUnusableError = () => {
|
| 314 |
+
return /* @__PURE__ */ new TypeError("Body is unusable");
|
| 315 |
+
};
|
| 316 |
+
const rejectBodyUnusable = () => {
|
| 317 |
+
return Promise.reject(newBodyUnusableError());
|
| 318 |
+
};
|
| 319 |
+
const textDecoder = new TextDecoder();
|
| 320 |
+
const consumeBodyDirectOnce = (request) => {
|
| 321 |
+
if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
|
| 322 |
+
request[bodyConsumedDirectlyKey] = true;
|
| 323 |
+
};
|
| 324 |
+
const toArrayBuffer = (buf) => {
|
| 325 |
+
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
|
| 326 |
+
};
|
| 327 |
+
const contentType = (request) => {
|
| 328 |
+
return (request[headersKey] ||= newHeadersFromIncoming(request[incomingKey])).get("content-type") || "";
|
| 329 |
+
};
|
| 330 |
+
const methodTokenRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
| 331 |
+
const normalizeIncomingMethod = (method) => {
|
| 332 |
+
if (typeof method !== "string" || method.length === 0) return "GET";
|
| 333 |
+
switch (method) {
|
| 334 |
+
case "DELETE":
|
| 335 |
+
case "GET":
|
| 336 |
+
case "HEAD":
|
| 337 |
+
case "OPTIONS":
|
| 338 |
+
case "PATCH":
|
| 339 |
+
case "POST":
|
| 340 |
+
case "PUT":
|
| 341 |
+
case "QUERY": return method;
|
| 342 |
+
}
|
| 343 |
+
const upper = method.toUpperCase();
|
| 344 |
+
switch (upper) {
|
| 345 |
+
case "DELETE":
|
| 346 |
+
case "GET":
|
| 347 |
+
case "HEAD":
|
| 348 |
+
case "OPTIONS":
|
| 349 |
+
case "POST":
|
| 350 |
+
case "PUT": return upper;
|
| 351 |
+
default: return method;
|
| 352 |
+
}
|
| 353 |
+
};
|
| 354 |
+
const validateDirectReadMethod = (method) => {
|
| 355 |
+
if (!methodTokenRegExp.test(method)) return /* @__PURE__ */ new TypeError(`'${method}' is not a valid HTTP method.`);
|
| 356 |
+
const normalized = method.toUpperCase();
|
| 357 |
+
if (normalized === "CONNECT" || normalized === "TRACK" || normalized === "TRACE" && method !== "TRACE") return /* @__PURE__ */ new TypeError(`'${method}' HTTP method is unsupported.`);
|
| 358 |
+
};
|
| 359 |
+
const readBodyWithFastPath = (request, method, fromBuffer) => {
|
| 360 |
+
if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
|
| 361 |
+
const methodName = request.method;
|
| 362 |
+
if (methodName === "GET" || methodName === "HEAD") return request[getRequestCache]()[method]();
|
| 363 |
+
const methodValidationError = validateDirectReadMethod(methodName);
|
| 364 |
+
if (methodValidationError) return Promise.reject(methodValidationError);
|
| 365 |
+
if (request[requestCache]) {
|
| 366 |
+
if (methodName !== "TRACE") return request[requestCache][method]();
|
| 367 |
+
}
|
| 368 |
+
const alreadyUsedError = consumeBodyDirectOnce(request);
|
| 369 |
+
if (alreadyUsedError) return alreadyUsedError;
|
| 370 |
+
const raw = readRawBodyIfAvailable(request);
|
| 371 |
+
if (raw) {
|
| 372 |
+
const result = Promise.resolve(fromBuffer(raw, request));
|
| 373 |
+
request[bodyBufferKey] = void 0;
|
| 374 |
+
return result;
|
| 375 |
+
}
|
| 376 |
+
return readBodyDirect(request).then((buf) => {
|
| 377 |
+
const result = fromBuffer(buf, request);
|
| 378 |
+
request[bodyBufferKey] = void 0;
|
| 379 |
+
return result;
|
| 380 |
+
});
|
| 381 |
+
};
|
| 382 |
+
const readRawBodyIfAvailable = (request) => {
|
| 383 |
+
const incoming = request[incomingKey];
|
| 384 |
+
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) return incoming.rawBody;
|
| 385 |
+
};
|
| 386 |
+
const normalizeAbortError = (request, incoming) => {
|
| 387 |
+
if (incoming.errored) return incoming.errored;
|
| 388 |
+
const reason = request[abortReasonKey];
|
| 389 |
+
if (reason !== void 0) return reason instanceof Error ? reason : new Error(String(reason));
|
| 390 |
+
return /* @__PURE__ */ new Error("Client connection prematurely closed.");
|
| 391 |
+
};
|
| 392 |
+
const readBodyDirect = (request) => {
|
| 393 |
+
if (request[bodyBufferKey]) return Promise.resolve(request[bodyBufferKey]);
|
| 394 |
+
if (request[bodyReadPromiseKey]) return request[bodyReadPromiseKey];
|
| 395 |
+
const incoming = request[incomingKey];
|
| 396 |
+
if (incoming.readableDidRead) return rejectBodyUnusable();
|
| 397 |
+
const buffered = readBodyBufferedBeforeDisconnect(incoming);
|
| 398 |
+
if (buffered !== void 0) {
|
| 399 |
+
if (buffered instanceof Error) return Promise.reject(buffered);
|
| 400 |
+
request[bodyBufferKey] = buffered;
|
| 401 |
+
return Promise.resolve(buffered);
|
| 402 |
+
}
|
| 403 |
+
const promise = new Promise((resolve, reject) => {
|
| 404 |
+
const chunks = [];
|
| 405 |
+
let settled = false;
|
| 406 |
+
const finish = (callback) => {
|
| 407 |
+
if (settled) return;
|
| 408 |
+
settled = true;
|
| 409 |
+
cleanup();
|
| 410 |
+
callback();
|
| 411 |
+
};
|
| 412 |
+
const recoverCompleteBodyAfterDisconnect = (error) => {
|
| 413 |
+
const streamError = incoming.errored ?? error;
|
| 414 |
+
if (!isRecoverableDisconnectedIncoming(incoming) || streamError && streamError.code !== "ECONNRESET") return false;
|
| 415 |
+
finish(() => {
|
| 416 |
+
const recovered = readBodyBufferedBeforeDisconnect(incoming, chunks);
|
| 417 |
+
if (recovered instanceof Error) reject(recovered);
|
| 418 |
+
else if (recovered === void 0) reject(error ?? normalizeAbortError(request, incoming));
|
| 419 |
+
else {
|
| 420 |
+
request[bodyBufferKey] = recovered;
|
| 421 |
+
resolve(recovered);
|
| 422 |
+
}
|
| 423 |
+
});
|
| 424 |
+
return true;
|
| 425 |
+
};
|
| 426 |
+
const onData = (chunk) => {
|
| 427 |
+
chunks.push(toBufferChunk(chunk, incoming.readableEncoding));
|
| 428 |
+
};
|
| 429 |
+
const onEnd = () => {
|
| 430 |
+
finish(() => {
|
| 431 |
+
const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
|
| 432 |
+
request[bodyBufferKey] = buffer;
|
| 433 |
+
resolve(buffer);
|
| 434 |
+
});
|
| 435 |
+
};
|
| 436 |
+
const onError = (error) => {
|
| 437 |
+
if (recoverCompleteBodyAfterDisconnect(error)) return;
|
| 438 |
+
finish(() => {
|
| 439 |
+
reject(error);
|
| 440 |
+
});
|
| 441 |
+
};
|
| 442 |
+
const onClose = () => {
|
| 443 |
+
if (incoming.readableEnded) {
|
| 444 |
+
onEnd();
|
| 445 |
+
return;
|
| 446 |
+
}
|
| 447 |
+
if (recoverCompleteBodyAfterDisconnect()) return;
|
| 448 |
+
finish(() => {
|
| 449 |
+
reject(normalizeAbortError(request, incoming));
|
| 450 |
+
});
|
| 451 |
+
};
|
| 452 |
+
const cleanup = () => {
|
| 453 |
+
incoming.off("data", onData);
|
| 454 |
+
incoming.off("end", onEnd);
|
| 455 |
+
incoming.off("error", onError);
|
| 456 |
+
incoming.off("close", onClose);
|
| 457 |
+
request[bodyReadPromiseKey] = void 0;
|
| 458 |
+
};
|
| 459 |
+
incoming.on("data", onData);
|
| 460 |
+
incoming.on("end", onEnd);
|
| 461 |
+
incoming.on("error", onError);
|
| 462 |
+
incoming.on("close", onClose);
|
| 463 |
+
queueMicrotask(() => {
|
| 464 |
+
if (settled) return;
|
| 465 |
+
if (incoming.readableEnded) onEnd();
|
| 466 |
+
else if (incoming.errored) onError(incoming.errored);
|
| 467 |
+
else if (incoming.destroyed) onClose();
|
| 468 |
+
});
|
| 469 |
+
});
|
| 470 |
+
request[bodyReadPromiseKey] = promise;
|
| 471 |
+
return promise;
|
| 472 |
+
};
|
| 473 |
+
const requestPrototype = {
|
| 474 |
+
get method() {
|
| 475 |
+
return this[methodKey];
|
| 476 |
+
},
|
| 477 |
+
get url() {
|
| 478 |
+
return this[urlKey];
|
| 479 |
+
},
|
| 480 |
+
get headers() {
|
| 481 |
+
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
|
| 482 |
+
},
|
| 483 |
+
[abortRequest](reason) {
|
| 484 |
+
if (this[abortReasonKey] === void 0) this[abortReasonKey] = reason;
|
| 485 |
+
const abortController = this[abortControllerKey];
|
| 486 |
+
if (abortController && !abortController.signal.aborted) abortController.abort(reason);
|
| 487 |
+
},
|
| 488 |
+
[getAbortController]() {
|
| 489 |
+
this[abortControllerKey] ||= new AbortController();
|
| 490 |
+
if (this[abortReasonKey] !== void 0 && !this[abortControllerKey].signal.aborted) this[abortControllerKey].abort(this[abortReasonKey]);
|
| 491 |
+
return this[abortControllerKey];
|
| 492 |
+
},
|
| 493 |
+
[getRequestCache]() {
|
| 494 |
+
const abortController = this[getAbortController]();
|
| 495 |
+
if (this[requestCache]) return this[requestCache];
|
| 496 |
+
const method = this.method;
|
| 497 |
+
if (this[bodyConsumedDirectlyKey] && !(method === "GET" || method === "HEAD")) {
|
| 498 |
+
this[bodyBufferKey] = void 0;
|
| 499 |
+
const init = {
|
| 500 |
+
method: method === "TRACE" ? "GET" : method,
|
| 501 |
+
headers: this.headers,
|
| 502 |
+
signal: abortController.signal
|
| 503 |
+
};
|
| 504 |
+
if (method !== "TRACE") {
|
| 505 |
+
init.body = new ReadableStream({ start(c) {
|
| 506 |
+
c.close();
|
| 507 |
+
} });
|
| 508 |
+
init.duplex = "half";
|
| 509 |
+
}
|
| 510 |
+
const req = new Request$1(this[urlKey], init);
|
| 511 |
+
if (method === "TRACE") Object.defineProperty(req, "method", { get() {
|
| 512 |
+
return "TRACE";
|
| 513 |
+
} });
|
| 514 |
+
return this[requestCache] = req;
|
| 515 |
+
}
|
| 516 |
+
return this[requestCache] = newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], abortController);
|
| 517 |
+
},
|
| 518 |
+
get body() {
|
| 519 |
+
if (!this[bodyConsumedDirectlyKey]) return this[getRequestCache]().body;
|
| 520 |
+
const request = this[getRequestCache]();
|
| 521 |
+
if (!this[bodyLockReaderKey] && request.body) this[bodyLockReaderKey] = request.body.getReader();
|
| 522 |
+
return request.body;
|
| 523 |
+
},
|
| 524 |
+
get bodyUsed() {
|
| 525 |
+
if (this[bodyConsumedDirectlyKey]) return true;
|
| 526 |
+
if (this[requestCache]) return this[requestCache].bodyUsed;
|
| 527 |
+
return false;
|
| 528 |
+
}
|
| 529 |
+
};
|
| 530 |
+
Object.defineProperty(requestPrototype, "signal", { get() {
|
| 531 |
+
return this[getAbortController]().signal;
|
| 532 |
+
} });
|
| 533 |
+
[
|
| 534 |
+
"cache",
|
| 535 |
+
"credentials",
|
| 536 |
+
"destination",
|
| 537 |
+
"integrity",
|
| 538 |
+
"mode",
|
| 539 |
+
"redirect",
|
| 540 |
+
"referrer",
|
| 541 |
+
"referrerPolicy",
|
| 542 |
+
"keepalive"
|
| 543 |
+
].forEach((k) => {
|
| 544 |
+
Object.defineProperty(requestPrototype, k, { get() {
|
| 545 |
+
return this[getRequestCache]()[k];
|
| 546 |
+
} });
|
| 547 |
+
});
|
| 548 |
+
["clone", "formData"].forEach((k) => {
|
| 549 |
+
Object.defineProperty(requestPrototype, k, { value: function() {
|
| 550 |
+
if (this[bodyConsumedDirectlyKey]) {
|
| 551 |
+
if (k === "clone") throw newBodyUnusableError();
|
| 552 |
+
return rejectBodyUnusable();
|
| 553 |
+
}
|
| 554 |
+
return this[getRequestCache]()[k]();
|
| 555 |
+
} });
|
| 556 |
+
});
|
| 557 |
+
Object.defineProperty(requestPrototype, "text", { value: function() {
|
| 558 |
+
return readBodyWithFastPath(this, "text", (buf) => textDecoder.decode(buf));
|
| 559 |
+
} });
|
| 560 |
+
Object.defineProperty(requestPrototype, "arrayBuffer", { value: function() {
|
| 561 |
+
return readBodyWithFastPath(this, "arrayBuffer", (buf) => toArrayBuffer(buf));
|
| 562 |
+
} });
|
| 563 |
+
Object.defineProperty(requestPrototype, "blob", { value: function() {
|
| 564 |
+
return readBodyWithFastPath(this, "blob", (buf, request) => {
|
| 565 |
+
const type = contentType(request);
|
| 566 |
+
const init = type ? { headers: { "content-type": type } } : void 0;
|
| 567 |
+
return new Response(buf, init).blob();
|
| 568 |
+
});
|
| 569 |
+
} });
|
| 570 |
+
Object.defineProperty(requestPrototype, "json", { value: function() {
|
| 571 |
+
if (this[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
|
| 572 |
+
return this.text().then(JSON.parse);
|
| 573 |
+
} });
|
| 574 |
+
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
|
| 575 |
+
return `Request (lightweight) ${inspectFn({
|
| 576 |
+
method: this.method,
|
| 577 |
+
url: this.url,
|
| 578 |
+
headers: this.headers,
|
| 579 |
+
nativeRequest: this[requestCache]
|
| 580 |
+
}, {
|
| 581 |
+
...options,
|
| 582 |
+
depth: depth == null ? null : depth - 1
|
| 583 |
+
})}`;
|
| 584 |
+
} });
|
| 585 |
+
Object.setPrototypeOf(requestPrototype, Request$1.prototype);
|
| 586 |
+
const newRequest = (incoming, defaultHostname) => {
|
| 587 |
+
const req = Object.create(requestPrototype);
|
| 588 |
+
req[incomingKey] = incoming;
|
| 589 |
+
req[methodKey] = normalizeIncomingMethod(incoming.method);
|
| 590 |
+
const incomingUrl = incoming.url || "";
|
| 591 |
+
if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
|
| 592 |
+
if (incoming instanceof node_http2.Http2ServerRequest) throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
| 593 |
+
try {
|
| 594 |
+
req[urlKey] = new URL(incomingUrl).href;
|
| 595 |
+
} catch (e) {
|
| 596 |
+
throw new RequestError("Invalid absolute URL", { cause: e });
|
| 597 |
+
}
|
| 598 |
+
return req;
|
| 599 |
+
}
|
| 600 |
+
const host = (incoming instanceof node_http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
|
| 601 |
+
if (!host) throw new RequestError("Missing host header");
|
| 602 |
+
let scheme;
|
| 603 |
+
if (incoming instanceof node_http2.Http2ServerRequest) {
|
| 604 |
+
scheme = incoming.scheme;
|
| 605 |
+
if (!(scheme === "http" || scheme === "https")) throw new RequestError("Unsupported scheme");
|
| 606 |
+
} else scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
|
| 607 |
+
try {
|
| 608 |
+
req[urlKey] = buildUrl(scheme, host, incomingUrl);
|
| 609 |
+
} catch (e) {
|
| 610 |
+
if (e instanceof RequestError) throw e;
|
| 611 |
+
else throw new RequestError("Invalid URL", { cause: e });
|
| 612 |
+
}
|
| 613 |
+
return req;
|
| 614 |
+
};
|
| 615 |
+
|
| 616 |
+
//#endregion
|
| 617 |
+
//#region src/response.ts
|
| 618 |
+
const defaultContentType = "text/plain; charset=UTF-8";
|
| 619 |
+
const responseCache = Symbol("responseCache");
|
| 620 |
+
const getResponseCache = Symbol("getResponseCache");
|
| 621 |
+
const cacheKey = Symbol("cache");
|
| 622 |
+
const GlobalResponse = global.Response;
|
| 623 |
+
var Response$1 = class Response$1 {
|
| 624 |
+
#body;
|
| 625 |
+
#init;
|
| 626 |
+
[getResponseCache]() {
|
| 627 |
+
const cache = this[cacheKey];
|
| 628 |
+
const liveHeaders = cache && cache[2] instanceof Headers ? cache[2] : void 0;
|
| 629 |
+
delete this[cacheKey];
|
| 630 |
+
return this[responseCache] ||= new GlobalResponse(this.#body, liveHeaders ? {
|
| 631 |
+
status: this.#init?.status,
|
| 632 |
+
statusText: this.#init?.statusText,
|
| 633 |
+
headers: liveHeaders
|
| 634 |
+
} : this.#init);
|
| 635 |
+
}
|
| 636 |
+
constructor(body, init) {
|
| 637 |
+
let headers;
|
| 638 |
+
this.#body = body;
|
| 639 |
+
if (init instanceof GlobalResponse) {
|
| 640 |
+
const cachedGlobalResponse = init[responseCache];
|
| 641 |
+
if (cachedGlobalResponse) {
|
| 642 |
+
this.#init = cachedGlobalResponse;
|
| 643 |
+
this[getResponseCache]();
|
| 644 |
+
return;
|
| 645 |
+
}
|
| 646 |
+
this.#init = init instanceof Response$1 ? init.#init : init;
|
| 647 |
+
headers = new Headers(init.headers);
|
| 648 |
+
} else this.#init = init;
|
| 649 |
+
if (body == null || typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [
|
| 650 |
+
init?.status || 200,
|
| 651 |
+
body ?? null,
|
| 652 |
+
headers || init?.headers
|
| 653 |
+
];
|
| 654 |
+
}
|
| 655 |
+
get headers() {
|
| 656 |
+
const cache = this[cacheKey];
|
| 657 |
+
if (cache) {
|
| 658 |
+
if (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || (cache[1] === null ? void 0 : { "content-type": defaultContentType }));
|
| 659 |
+
return cache[2];
|
| 660 |
+
}
|
| 661 |
+
return this[getResponseCache]().headers;
|
| 662 |
+
}
|
| 663 |
+
get status() {
|
| 664 |
+
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
|
| 665 |
+
}
|
| 666 |
+
get ok() {
|
| 667 |
+
const status = this.status;
|
| 668 |
+
return status >= 200 && status < 300;
|
| 669 |
+
}
|
| 670 |
+
};
|
| 671 |
+
[
|
| 672 |
+
"body",
|
| 673 |
+
"bodyUsed",
|
| 674 |
+
"redirected",
|
| 675 |
+
"statusText",
|
| 676 |
+
"trailers",
|
| 677 |
+
"type",
|
| 678 |
+
"url"
|
| 679 |
+
].forEach((k) => {
|
| 680 |
+
Object.defineProperty(Response$1.prototype, k, { get() {
|
| 681 |
+
return this[getResponseCache]()[k];
|
| 682 |
+
} });
|
| 683 |
+
});
|
| 684 |
+
[
|
| 685 |
+
"arrayBuffer",
|
| 686 |
+
"blob",
|
| 687 |
+
"clone",
|
| 688 |
+
"formData",
|
| 689 |
+
"json",
|
| 690 |
+
"text"
|
| 691 |
+
].forEach((k) => {
|
| 692 |
+
Object.defineProperty(Response$1.prototype, k, { value: function() {
|
| 693 |
+
return this[getResponseCache]()[k]();
|
| 694 |
+
} });
|
| 695 |
+
});
|
| 696 |
+
Object.defineProperty(Response$1.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
|
| 697 |
+
return `Response (lightweight) ${inspectFn({
|
| 698 |
+
status: this.status,
|
| 699 |
+
headers: this.headers,
|
| 700 |
+
ok: this.ok,
|
| 701 |
+
nativeResponse: this[responseCache]
|
| 702 |
+
}, {
|
| 703 |
+
...options,
|
| 704 |
+
depth: depth == null ? null : depth - 1
|
| 705 |
+
})}`;
|
| 706 |
+
} });
|
| 707 |
+
Object.setPrototypeOf(Response$1, GlobalResponse);
|
| 708 |
+
Object.setPrototypeOf(Response$1.prototype, GlobalResponse.prototype);
|
| 709 |
+
const validRedirectUrl = /^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/;
|
| 710 |
+
const parseRedirectUrl = (url) => {
|
| 711 |
+
if (url instanceof URL) return url.href;
|
| 712 |
+
if (validRedirectUrl.test(url)) return url;
|
| 713 |
+
return new URL(url).href;
|
| 714 |
+
};
|
| 715 |
+
const validRedirectStatuses = new Set([
|
| 716 |
+
301,
|
| 717 |
+
302,
|
| 718 |
+
303,
|
| 719 |
+
307,
|
| 720 |
+
308
|
| 721 |
+
]);
|
| 722 |
+
Object.defineProperty(Response$1, "redirect", {
|
| 723 |
+
value: function redirect(url, status = 302) {
|
| 724 |
+
if (!validRedirectStatuses.has(status)) throw new RangeError("Invalid status code");
|
| 725 |
+
return new Response$1(null, {
|
| 726 |
+
status,
|
| 727 |
+
headers: { location: parseRedirectUrl(url) }
|
| 728 |
+
});
|
| 729 |
+
},
|
| 730 |
+
writable: true,
|
| 731 |
+
configurable: true
|
| 732 |
+
});
|
| 733 |
+
Object.defineProperty(Response$1, "json", {
|
| 734 |
+
value: function json(data, init) {
|
| 735 |
+
const body = JSON.stringify(data);
|
| 736 |
+
if (body === void 0) throw new TypeError("The data is not JSON serializable");
|
| 737 |
+
const initHeaders = init?.headers;
|
| 738 |
+
let headers;
|
| 739 |
+
if (initHeaders) {
|
| 740 |
+
headers = new Headers(initHeaders);
|
| 741 |
+
if (!headers.has("content-type")) headers.set("content-type", "application/json");
|
| 742 |
+
} else headers = { "content-type": "application/json" };
|
| 743 |
+
return new Response$1(body, {
|
| 744 |
+
status: init?.status ?? 200,
|
| 745 |
+
statusText: init?.statusText,
|
| 746 |
+
headers
|
| 747 |
+
});
|
| 748 |
+
},
|
| 749 |
+
writable: true,
|
| 750 |
+
configurable: true
|
| 751 |
+
});
|
| 752 |
+
|
| 753 |
+
//#endregion
|
| 754 |
+
//#region src/utils.ts
|
| 755 |
+
async function readWithoutBlocking(readPromise) {
|
| 756 |
+
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
|
| 757 |
+
}
|
| 758 |
+
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
|
| 759 |
+
const cancel = (error) => {
|
| 760 |
+
reader.cancel(error).catch(() => {});
|
| 761 |
+
};
|
| 762 |
+
writable.on("close", cancel);
|
| 763 |
+
writable.on("error", cancel);
|
| 764 |
+
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
|
| 765 |
+
return reader.closed.finally(() => {
|
| 766 |
+
writable.off("close", cancel);
|
| 767 |
+
writable.off("error", cancel);
|
| 768 |
+
});
|
| 769 |
+
function handleStreamError(error) {
|
| 770 |
+
if (error) writable.destroy(error);
|
| 771 |
+
}
|
| 772 |
+
function onDrain() {
|
| 773 |
+
reader.read().then(flow, handleStreamError);
|
| 774 |
+
}
|
| 775 |
+
function flow({ done, value }) {
|
| 776 |
+
try {
|
| 777 |
+
if (done) writable.end();
|
| 778 |
+
else if (!writable.write(value)) writable.once("drain", onDrain);
|
| 779 |
+
else return reader.read().then(flow, handleStreamError);
|
| 780 |
+
} catch (e) {
|
| 781 |
+
handleStreamError(e);
|
| 782 |
+
}
|
| 783 |
+
}
|
| 784 |
+
}
|
| 785 |
+
function writeFromReadableStream(stream, writable) {
|
| 786 |
+
if (stream.locked) throw new TypeError("ReadableStream is locked.");
|
| 787 |
+
else if (writable.destroyed) return;
|
| 788 |
+
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
|
| 789 |
+
}
|
| 790 |
+
const buildOutgoingHttpHeaders = (headers, defaultContentType) => {
|
| 791 |
+
const res = {};
|
| 792 |
+
if (!(headers instanceof Headers)) headers = new Headers(headers ?? void 0);
|
| 793 |
+
if (headers.has("set-cookie")) {
|
| 794 |
+
const cookies = [];
|
| 795 |
+
for (const [k, v] of headers) if (k === "set-cookie") cookies.push(v);
|
| 796 |
+
else res[k] = v;
|
| 797 |
+
if (cookies.length > 0) res["set-cookie"] = cookies;
|
| 798 |
+
} else for (const [k, v] of headers) res[k] = v;
|
| 799 |
+
if (defaultContentType) res["content-type"] ??= defaultContentType;
|
| 800 |
+
return res;
|
| 801 |
+
};
|
| 802 |
+
|
| 803 |
+
//#endregion
|
| 804 |
+
//#region src/listener.ts
|
| 805 |
+
const outgoingEnded = Symbol("outgoingEnded");
|
| 806 |
+
const incomingDraining = Symbol("incomingDraining");
|
| 807 |
+
const DRAIN_TIMEOUT_MS = 500;
|
| 808 |
+
const MAX_DRAIN_BYTES = 64 * 1024 * 1024;
|
| 809 |
+
const drainIncoming = (incoming) => {
|
| 810 |
+
const incomingWithDrainState = incoming;
|
| 811 |
+
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) return;
|
| 812 |
+
incomingWithDrainState[incomingDraining] = true;
|
| 813 |
+
if (incoming instanceof node_http2.Http2ServerRequest) {
|
| 814 |
+
try {
|
| 815 |
+
incoming.stream?.close?.(node_http2.constants.NGHTTP2_NO_ERROR);
|
| 816 |
+
} catch {}
|
| 817 |
+
return;
|
| 818 |
+
}
|
| 819 |
+
let bytesRead = 0;
|
| 820 |
+
const cleanup = () => {
|
| 821 |
+
clearTimeout(timer);
|
| 822 |
+
incoming.off("data", onData);
|
| 823 |
+
incoming.off("end", cleanup);
|
| 824 |
+
incoming.off("error", cleanup);
|
| 825 |
+
};
|
| 826 |
+
const forceClose = () => {
|
| 827 |
+
cleanup();
|
| 828 |
+
const socket = incoming.socket;
|
| 829 |
+
if (socket && !socket.destroyed) {
|
| 830 |
+
if (typeof socket.destroySoon === "function") socket.destroySoon();
|
| 831 |
+
else if (typeof socket.destroy === "function") socket.destroy();
|
| 832 |
+
}
|
| 833 |
+
};
|
| 834 |
+
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
|
| 835 |
+
timer.unref?.();
|
| 836 |
+
const onData = (chunk) => {
|
| 837 |
+
bytesRead += chunk.length;
|
| 838 |
+
if (bytesRead > MAX_DRAIN_BYTES) forceClose();
|
| 839 |
+
};
|
| 840 |
+
incoming.on("data", onData);
|
| 841 |
+
incoming.on("end", cleanup);
|
| 842 |
+
incoming.on("error", cleanup);
|
| 843 |
+
incoming.resume();
|
| 844 |
+
};
|
| 845 |
+
const makeCloseHandler = (req, incoming, outgoing, needsBodyCleanup) => () => {
|
| 846 |
+
if (incoming.errored) {
|
| 847 |
+
recordBodyBufferedBeforeDisconnect(incoming);
|
| 848 |
+
req[abortRequest](incoming.errored.toString());
|
| 849 |
+
} else if (!outgoing.writableFinished) {
|
| 850 |
+
recordBodyBufferedBeforeDisconnect(incoming);
|
| 851 |
+
req[abortRequest]("Client connection prematurely closed.");
|
| 852 |
+
}
|
| 853 |
+
if (needsBodyCleanup && !incoming.readableEnded) setTimeout(() => {
|
| 854 |
+
if (!incoming.readableEnded) setTimeout(() => {
|
| 855 |
+
drainIncoming(incoming);
|
| 856 |
+
});
|
| 857 |
+
});
|
| 858 |
+
};
|
| 859 |
+
const isImmediateCacheableResponse = (res) => {
|
| 860 |
+
if (!(cacheKey in res)) return false;
|
| 861 |
+
const body = res[cacheKey][1];
|
| 862 |
+
return body === null || typeof body === "string" || body instanceof Uint8Array;
|
| 863 |
+
};
|
| 864 |
+
const handleRequestError = () => new Response(null, { status: 400 });
|
| 865 |
+
const handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 });
|
| 866 |
+
const handleResponseError = (e, outgoing) => {
|
| 867 |
+
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
|
| 868 |
+
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") console.info("The user aborted a request.");
|
| 869 |
+
else {
|
| 870 |
+
console.error(e);
|
| 871 |
+
if (!outgoing.headersSent) {
|
| 872 |
+
if (outgoing instanceof node_http.ServerResponse) outgoing._contentLength = null;
|
| 873 |
+
outgoing.writeHead(500, { "Content-Type": "text/plain" });
|
| 874 |
+
}
|
| 875 |
+
outgoing.end(`Error: ${err.message}`);
|
| 876 |
+
outgoing.destroy(err);
|
| 877 |
+
}
|
| 878 |
+
};
|
| 879 |
+
const flushHeaders = (outgoing) => {
|
| 880 |
+
if ("flushHeaders" in outgoing && outgoing.writable) outgoing.flushHeaders();
|
| 881 |
+
};
|
| 882 |
+
const trySetContentLength = (outgoing, status, length) => {
|
| 883 |
+
const http1 = outgoing;
|
| 884 |
+
if (http1._contentLength === null && http1._hasBody && http1.useChunkedEncodingByDefault && !http1._removedContLen && status >= 200 && status !== 204 && status !== 304 && !outgoing.hasHeader("content-length") && !outgoing.hasHeader("transfer-encoding") && !outgoing.hasHeader("trailer")) {
|
| 885 |
+
http1._contentLength = length;
|
| 886 |
+
return true;
|
| 887 |
+
}
|
| 888 |
+
return false;
|
| 889 |
+
};
|
| 890 |
+
const writeDefaultHeaders = (outgoing, status, length) => {
|
| 891 |
+
if (trySetContentLength(outgoing, status, length)) outgoing.writeHead(status, { "Content-Type": defaultContentType });
|
| 892 |
+
else outgoing.writeHead(status, {
|
| 893 |
+
"Content-Type": defaultContentType,
|
| 894 |
+
"Content-Length": length
|
| 895 |
+
});
|
| 896 |
+
};
|
| 897 |
+
const responseViaCache = async (res, outgoing) => {
|
| 898 |
+
let [status, body, header] = res[cacheKey];
|
| 899 |
+
if (!header) {
|
| 900 |
+
if (body === null) {
|
| 901 |
+
outgoing.writeHead(status);
|
| 902 |
+
outgoing.end();
|
| 903 |
+
} else if (typeof body === "string") {
|
| 904 |
+
writeDefaultHeaders(outgoing, status, Buffer.byteLength(body));
|
| 905 |
+
outgoing.end(body);
|
| 906 |
+
} else if (body instanceof Uint8Array) {
|
| 907 |
+
writeDefaultHeaders(outgoing, status, body.byteLength);
|
| 908 |
+
outgoing.end(body);
|
| 909 |
+
} else if (body instanceof Blob) {
|
| 910 |
+
writeDefaultHeaders(outgoing, status, body.size);
|
| 911 |
+
outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
| 912 |
+
} else {
|
| 913 |
+
outgoing.writeHead(status, { "Content-Type": defaultContentType });
|
| 914 |
+
flushHeaders(outgoing);
|
| 915 |
+
await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
|
| 916 |
+
}
|
| 917 |
+
outgoing[outgoingEnded]?.();
|
| 918 |
+
return;
|
| 919 |
+
}
|
| 920 |
+
let hasContentLength = false;
|
| 921 |
+
let plainHeaders = false;
|
| 922 |
+
let canAutoLength = true;
|
| 923 |
+
if (header instanceof Headers) {
|
| 924 |
+
hasContentLength = header.has("content-length");
|
| 925 |
+
header = buildOutgoingHttpHeaders(header, body === null ? void 0 : defaultContentType);
|
| 926 |
+
} else if (Array.isArray(header)) {
|
| 927 |
+
const headerObj = new Headers(header);
|
| 928 |
+
hasContentLength = headerObj.has("content-length");
|
| 929 |
+
header = buildOutgoingHttpHeaders(headerObj, body === null ? void 0 : defaultContentType);
|
| 930 |
+
} else {
|
| 931 |
+
plainHeaders = true;
|
| 932 |
+
for (const key in header) {
|
| 933 |
+
if (key.length === 14 && key.toLowerCase() === "content-length") {
|
| 934 |
+
hasContentLength = true;
|
| 935 |
+
break;
|
| 936 |
+
}
|
| 937 |
+
if (key.length === 17 && key.toLowerCase() === "transfer-encoding" || key.length === 7 && key.toLowerCase() === "trailer") canAutoLength = false;
|
| 938 |
+
}
|
| 939 |
+
}
|
| 940 |
+
if (!hasContentLength) {
|
| 941 |
+
let length;
|
| 942 |
+
if (typeof body === "string") length = Buffer.byteLength(body);
|
| 943 |
+
else if (body instanceof Uint8Array) length = body.byteLength;
|
| 944 |
+
else if (body instanceof Blob) length = body.size;
|
| 945 |
+
if (length !== void 0 && (!plainHeaders || !canAutoLength || !trySetContentLength(outgoing, status, length))) {
|
| 946 |
+
if (plainHeaders) header = { ...header };
|
| 947 |
+
header["Content-Length"] = length;
|
| 948 |
+
}
|
| 949 |
+
}
|
| 950 |
+
outgoing.writeHead(status, header);
|
| 951 |
+
if (body == null) outgoing.end();
|
| 952 |
+
else if (typeof body === "string" || body instanceof Uint8Array) outgoing.end(body);
|
| 953 |
+
else if (body instanceof Blob) outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
| 954 |
+
else {
|
| 955 |
+
flushHeaders(outgoing);
|
| 956 |
+
await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
|
| 957 |
+
}
|
| 958 |
+
outgoing[outgoingEnded]?.();
|
| 959 |
+
};
|
| 960 |
+
const isPromise = (res) => typeof res.then === "function";
|
| 961 |
+
const responseViaResponseObject = async (res, outgoing, options = {}) => {
|
| 962 |
+
if (isPromise(res)) if (options.errorHandler) try {
|
| 963 |
+
res = await res;
|
| 964 |
+
} catch (err) {
|
| 965 |
+
const errRes = await options.errorHandler(err);
|
| 966 |
+
if (!errRes) return;
|
| 967 |
+
res = errRes;
|
| 968 |
+
}
|
| 969 |
+
else res = await res.catch(handleFetchError);
|
| 970 |
+
if (cacheKey in res) return responseViaCache(res, outgoing);
|
| 971 |
+
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers, res.body === null ? void 0 : defaultContentType);
|
| 972 |
+
if (res.body) {
|
| 973 |
+
const reader = res.body.getReader();
|
| 974 |
+
const values = [];
|
| 975 |
+
let done = false;
|
| 976 |
+
let currentReadPromise = void 0;
|
| 977 |
+
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
|
| 978 |
+
let maxReadCount = 2;
|
| 979 |
+
for (let i = 0; i < maxReadCount; i++) {
|
| 980 |
+
currentReadPromise ||= reader.read();
|
| 981 |
+
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
|
| 982 |
+
console.error(e);
|
| 983 |
+
done = true;
|
| 984 |
+
});
|
| 985 |
+
if (!chunk) {
|
| 986 |
+
if (i === 1) {
|
| 987 |
+
await new Promise((resolve) => setTimeout(resolve));
|
| 988 |
+
maxReadCount = 3;
|
| 989 |
+
continue;
|
| 990 |
+
}
|
| 991 |
+
break;
|
| 992 |
+
}
|
| 993 |
+
currentReadPromise = void 0;
|
| 994 |
+
if (chunk.value) values.push(chunk.value);
|
| 995 |
+
if (chunk.done) {
|
| 996 |
+
done = true;
|
| 997 |
+
break;
|
| 998 |
+
}
|
| 999 |
+
}
|
| 1000 |
+
if (done && !("content-length" in resHeaderRecord)) resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
|
| 1001 |
+
}
|
| 1002 |
+
outgoing.writeHead(res.status, resHeaderRecord);
|
| 1003 |
+
values.forEach((value) => {
|
| 1004 |
+
outgoing.write(value);
|
| 1005 |
+
});
|
| 1006 |
+
if (done) outgoing.end();
|
| 1007 |
+
else {
|
| 1008 |
+
if (values.length === 0) flushHeaders(outgoing);
|
| 1009 |
+
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
|
| 1010 |
+
}
|
| 1011 |
+
} else if (resHeaderRecord[require_constants.X_ALREADY_SENT]) {} else {
|
| 1012 |
+
outgoing.writeHead(res.status, resHeaderRecord);
|
| 1013 |
+
outgoing.end();
|
| 1014 |
+
}
|
| 1015 |
+
outgoing[outgoingEnded]?.();
|
| 1016 |
+
};
|
| 1017 |
+
const getRequestListener = (fetchCallback, options = {}) => {
|
| 1018 |
+
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
|
| 1019 |
+
if (options.overrideGlobalObjects !== false && global.Request !== Request$1) {
|
| 1020 |
+
Object.defineProperty(global, "Request", { value: Request$1 });
|
| 1021 |
+
Object.defineProperty(global, "Response", { value: Response$1 });
|
| 1022 |
+
}
|
| 1023 |
+
return async (incoming, outgoing) => {
|
| 1024 |
+
let res, req;
|
| 1025 |
+
let needsBodyCleanup = false;
|
| 1026 |
+
let closeHandlerAttached = false;
|
| 1027 |
+
const ensureCloseHandler = () => {
|
| 1028 |
+
if (!req || closeHandlerAttached) return;
|
| 1029 |
+
closeHandlerAttached = true;
|
| 1030 |
+
outgoing.on("close", makeCloseHandler(req, incoming, outgoing, needsBodyCleanup));
|
| 1031 |
+
};
|
| 1032 |
+
try {
|
| 1033 |
+
req = newRequest(incoming, options.hostname);
|
| 1034 |
+
needsBodyCleanup = autoCleanupIncoming && !(incoming.method === "GET" || incoming.method === "HEAD");
|
| 1035 |
+
if (needsBodyCleanup) {
|
| 1036 |
+
incoming[wrapBodyStream] = true;
|
| 1037 |
+
if (incoming instanceof node_http2.Http2ServerRequest) outgoing[outgoingEnded] = () => {
|
| 1038 |
+
if (!incoming.readableEnded) setTimeout(() => {
|
| 1039 |
+
if (!incoming.readableEnded) setTimeout(() => {
|
| 1040 |
+
incoming.destroy();
|
| 1041 |
+
outgoing.destroy();
|
| 1042 |
+
});
|
| 1043 |
+
});
|
| 1044 |
+
};
|
| 1045 |
+
}
|
| 1046 |
+
res = fetchCallback(req, {
|
| 1047 |
+
incoming,
|
| 1048 |
+
outgoing
|
| 1049 |
+
});
|
| 1050 |
+
if (!isPromise(res) && isImmediateCacheableResponse(res)) {
|
| 1051 |
+
if (needsBodyCleanup && !incoming.readableEnded) outgoing.once("finish", () => {
|
| 1052 |
+
if (!incoming.readableEnded) drainIncoming(incoming);
|
| 1053 |
+
});
|
| 1054 |
+
return responseViaCache(res, outgoing);
|
| 1055 |
+
}
|
| 1056 |
+
ensureCloseHandler();
|
| 1057 |
+
} catch (e) {
|
| 1058 |
+
if (!res) if (options.errorHandler) {
|
| 1059 |
+
ensureCloseHandler();
|
| 1060 |
+
res = await options.errorHandler(req ? e : toRequestError(e));
|
| 1061 |
+
if (!res) return;
|
| 1062 |
+
} else if (!req) res = handleRequestError();
|
| 1063 |
+
else res = handleFetchError(e);
|
| 1064 |
+
else return handleResponseError(e, outgoing);
|
| 1065 |
+
}
|
| 1066 |
+
try {
|
| 1067 |
+
return await responseViaResponseObject(res, outgoing, options);
|
| 1068 |
+
} catch (e) {
|
| 1069 |
+
return handleResponseError(e, outgoing);
|
| 1070 |
+
}
|
| 1071 |
+
};
|
| 1072 |
+
};
|
| 1073 |
+
|
| 1074 |
+
//#endregion
|
| 1075 |
+
//#region src/websocket.ts
|
| 1076 |
+
/**
|
| 1077 |
+
* @link https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
|
| 1078 |
+
*/
|
| 1079 |
+
const CloseEvent = globalThis.CloseEvent ?? class extends Event {
|
| 1080 |
+
#eventInitDict;
|
| 1081 |
+
constructor(type, eventInitDict = {}) {
|
| 1082 |
+
super(type, eventInitDict);
|
| 1083 |
+
this.#eventInitDict = eventInitDict;
|
| 1084 |
+
}
|
| 1085 |
+
get wasClean() {
|
| 1086 |
+
return this.#eventInitDict.wasClean ?? false;
|
| 1087 |
+
}
|
| 1088 |
+
get code() {
|
| 1089 |
+
return this.#eventInitDict.code ?? 0;
|
| 1090 |
+
}
|
| 1091 |
+
get reason() {
|
| 1092 |
+
return this.#eventInitDict.reason ?? "";
|
| 1093 |
+
}
|
| 1094 |
+
};
|
| 1095 |
+
/**
|
| 1096 |
+
* Node.js has no global `ErrorEvent`, unlike `Event`/`MessageEvent`/`CloseEvent`.
|
| 1097 |
+
* @link https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent
|
| 1098 |
+
*/
|
| 1099 |
+
const ErrorEvent = globalThis.ErrorEvent ?? class extends Event {
|
| 1100 |
+
#eventInitDict;
|
| 1101 |
+
constructor(type, eventInitDict = {}) {
|
| 1102 |
+
super(type, eventInitDict);
|
| 1103 |
+
this.#eventInitDict = eventInitDict;
|
| 1104 |
+
}
|
| 1105 |
+
get message() {
|
| 1106 |
+
return this.#eventInitDict.message ?? "";
|
| 1107 |
+
}
|
| 1108 |
+
get filename() {
|
| 1109 |
+
return this.#eventInitDict.filename ?? "";
|
| 1110 |
+
}
|
| 1111 |
+
get lineno() {
|
| 1112 |
+
return this.#eventInitDict.lineno ?? 0;
|
| 1113 |
+
}
|
| 1114 |
+
get colno() {
|
| 1115 |
+
return this.#eventInitDict.colno ?? 0;
|
| 1116 |
+
}
|
| 1117 |
+
get error() {
|
| 1118 |
+
return this.#eventInitDict.error ?? null;
|
| 1119 |
+
}
|
| 1120 |
+
};
|
| 1121 |
+
const generateConnectionSymbol = () => Symbol("connection");
|
| 1122 |
+
const CONNECTION_SYMBOL_KEY = Symbol("CONNECTION_SYMBOL_KEY");
|
| 1123 |
+
const WAIT_FOR_WEBSOCKET_SYMBOL = Symbol("WAIT_FOR_WEBSOCKET_SYMBOL");
|
| 1124 |
+
const responseHeadersToSkip = new Set([
|
| 1125 |
+
"connection",
|
| 1126 |
+
"content-length",
|
| 1127 |
+
"keep-alive",
|
| 1128 |
+
"proxy-authenticate",
|
| 1129 |
+
"proxy-authorization",
|
| 1130 |
+
"te",
|
| 1131 |
+
"trailer",
|
| 1132 |
+
"transfer-encoding",
|
| 1133 |
+
"upgrade",
|
| 1134 |
+
"sec-websocket-accept",
|
| 1135 |
+
"sec-websocket-extensions",
|
| 1136 |
+
"sec-websocket-protocol"
|
| 1137 |
+
]);
|
| 1138 |
+
const appendResponseHeaders = (headers, responseHeaders) => {
|
| 1139 |
+
if (!responseHeaders) return;
|
| 1140 |
+
responseHeaders.forEach((value, key) => {
|
| 1141 |
+
if (responseHeadersToSkip.has(key.toLowerCase())) return;
|
| 1142 |
+
headers.push(`${key}: ${value}`);
|
| 1143 |
+
});
|
| 1144 |
+
};
|
| 1145 |
+
const rejectUpgradeRequest = (socket, status, responseHeaders) => {
|
| 1146 |
+
const responseLines = ["Connection: close", "Content-Length: 0"];
|
| 1147 |
+
appendResponseHeaders(responseLines, responseHeaders);
|
| 1148 |
+
socket.end(`HTTP/1.1 ${status.toString()} ${node_http.STATUS_CODES[status] ?? ""}\r\n${responseLines.join("\r\n")}\r\n\r
|
| 1149 |
+
`);
|
| 1150 |
+
};
|
| 1151 |
+
const createUpgradeRequest = (request) => {
|
| 1152 |
+
const protocol = request.socket.encrypted ? "https" : "http";
|
| 1153 |
+
const url = new URL(request.url ?? "/", `${protocol}://${request.headers.host ?? "localhost"}`);
|
| 1154 |
+
const headers = new Headers();
|
| 1155 |
+
for (const key in request.headers) {
|
| 1156 |
+
const value = request.headers[key];
|
| 1157 |
+
if (!value) continue;
|
| 1158 |
+
headers.append(key, Array.isArray(value) ? value[0] : value);
|
| 1159 |
+
}
|
| 1160 |
+
return new Request(url, { headers });
|
| 1161 |
+
};
|
| 1162 |
+
const setupWebSocket = (options) => {
|
| 1163 |
+
const { server, fetchCallback, wss } = options;
|
| 1164 |
+
const waiterMap = /* @__PURE__ */ new Map();
|
| 1165 |
+
wss.on("connection", (ws, request) => {
|
| 1166 |
+
const waiter = waiterMap.get(request);
|
| 1167 |
+
if (waiter) {
|
| 1168 |
+
waiter.resolve(ws);
|
| 1169 |
+
waiterMap.delete(request);
|
| 1170 |
+
}
|
| 1171 |
+
});
|
| 1172 |
+
const rejectWaiter = (request) => {
|
| 1173 |
+
const waiter = waiterMap.get(request);
|
| 1174 |
+
if (waiter) {
|
| 1175 |
+
waiterMap.delete(request);
|
| 1176 |
+
waiter.reject(/* @__PURE__ */ new Error("WebSocket handshake aborted"));
|
| 1177 |
+
}
|
| 1178 |
+
};
|
| 1179 |
+
const waitForWebSocket = (request, connectionSymbol) => {
|
| 1180 |
+
return new Promise((resolve, reject) => {
|
| 1181 |
+
waiterMap.set(request, {
|
| 1182 |
+
resolve,
|
| 1183 |
+
reject,
|
| 1184 |
+
connectionSymbol
|
| 1185 |
+
});
|
| 1186 |
+
});
|
| 1187 |
+
};
|
| 1188 |
+
server.on("upgrade", async (request, socket, head) => {
|
| 1189 |
+
if (request.headers.upgrade?.toLowerCase() !== "websocket") return;
|
| 1190 |
+
const env = {
|
| 1191 |
+
incoming: request,
|
| 1192 |
+
outgoing: void 0,
|
| 1193 |
+
wss,
|
| 1194 |
+
[WAIT_FOR_WEBSOCKET_SYMBOL]: waitForWebSocket
|
| 1195 |
+
};
|
| 1196 |
+
let status = 400;
|
| 1197 |
+
let responseHeaders;
|
| 1198 |
+
try {
|
| 1199 |
+
const response = await fetchCallback(createUpgradeRequest(request), env);
|
| 1200 |
+
if (response instanceof Response) {
|
| 1201 |
+
status = response.status;
|
| 1202 |
+
responseHeaders = response.headers;
|
| 1203 |
+
}
|
| 1204 |
+
} catch {
|
| 1205 |
+
if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, 500);
|
| 1206 |
+
return;
|
| 1207 |
+
}
|
| 1208 |
+
const waiter = waiterMap.get(request);
|
| 1209 |
+
if (!waiter || waiter.connectionSymbol !== env[CONNECTION_SYMBOL_KEY]) {
|
| 1210 |
+
rejectWaiter(request);
|
| 1211 |
+
if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, status, responseHeaders);
|
| 1212 |
+
return;
|
| 1213 |
+
}
|
| 1214 |
+
const addResponseHeaders = (headers) => {
|
| 1215 |
+
appendResponseHeaders(headers, responseHeaders);
|
| 1216 |
+
};
|
| 1217 |
+
const reclaimWaiterOnClose = () => rejectWaiter(request);
|
| 1218 |
+
socket.once("close", reclaimWaiterOnClose);
|
| 1219 |
+
wss.on("headers", addResponseHeaders);
|
| 1220 |
+
try {
|
| 1221 |
+
wss.handleUpgrade(request, socket, head, (ws) => {
|
| 1222 |
+
socket.off("close", reclaimWaiterOnClose);
|
| 1223 |
+
wss.emit("connection", ws, request);
|
| 1224 |
+
});
|
| 1225 |
+
} finally {
|
| 1226 |
+
wss.off("headers", addResponseHeaders);
|
| 1227 |
+
}
|
| 1228 |
+
});
|
| 1229 |
+
server.on("close", () => {
|
| 1230 |
+
wss.close();
|
| 1231 |
+
});
|
| 1232 |
+
};
|
| 1233 |
+
const upgradeWebSocket = (0, hono_ws.defineWebSocketHelper)(async (c, events, options) => {
|
| 1234 |
+
if (c.req.header("upgrade")?.toLowerCase() !== "websocket") return;
|
| 1235 |
+
const env = c.env;
|
| 1236 |
+
const waitForWebSocket = env[WAIT_FOR_WEBSOCKET_SYMBOL];
|
| 1237 |
+
if (!waitForWebSocket || !env.incoming) return new Response(null, { status: 500 });
|
| 1238 |
+
const connectionSymbol = generateConnectionSymbol();
|
| 1239 |
+
env[CONNECTION_SYMBOL_KEY] = connectionSymbol;
|
| 1240 |
+
(async () => {
|
| 1241 |
+
let ws;
|
| 1242 |
+
try {
|
| 1243 |
+
ws = await waitForWebSocket(env.incoming, connectionSymbol);
|
| 1244 |
+
} catch {
|
| 1245 |
+
return;
|
| 1246 |
+
}
|
| 1247 |
+
const messagesReceivedInStarting = [];
|
| 1248 |
+
const bufferMessage = (data, isBinary) => {
|
| 1249 |
+
messagesReceivedInStarting.push([data, isBinary]);
|
| 1250 |
+
};
|
| 1251 |
+
ws.on("message", bufferMessage);
|
| 1252 |
+
const ctx = {
|
| 1253 |
+
binaryType: "arraybuffer",
|
| 1254 |
+
close(code, reason) {
|
| 1255 |
+
ws.close(code, reason);
|
| 1256 |
+
},
|
| 1257 |
+
protocol: ws.protocol,
|
| 1258 |
+
raw: ws,
|
| 1259 |
+
get readyState() {
|
| 1260 |
+
return ws.readyState;
|
| 1261 |
+
},
|
| 1262 |
+
send(source, opts) {
|
| 1263 |
+
ws.send(source, { compress: opts?.compress });
|
| 1264 |
+
},
|
| 1265 |
+
url: new URL(c.req.url)
|
| 1266 |
+
};
|
| 1267 |
+
try {
|
| 1268 |
+
events?.onOpen?.(new Event("open"), ctx);
|
| 1269 |
+
} catch (e) {
|
| 1270 |
+
(options?.onError ?? console.error)(e);
|
| 1271 |
+
}
|
| 1272 |
+
const handleMessage = (data, isBinary) => {
|
| 1273 |
+
const datas = Array.isArray(data) ? data : [data];
|
| 1274 |
+
for (const data of datas) try {
|
| 1275 |
+
events?.onMessage?.(new MessageEvent("message", { data: isBinary ? data instanceof ArrayBuffer ? data : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength) : typeof data === "string" ? data : Buffer.from(data).toString("utf-8") }), ctx);
|
| 1276 |
+
} catch (e) {
|
| 1277 |
+
(options?.onError ?? console.error)(e);
|
| 1278 |
+
}
|
| 1279 |
+
};
|
| 1280 |
+
ws.off("message", bufferMessage);
|
| 1281 |
+
for (const message of messagesReceivedInStarting) handleMessage(...message);
|
| 1282 |
+
ws.on("message", (data, isBinary) => {
|
| 1283 |
+
handleMessage(data, isBinary);
|
| 1284 |
+
});
|
| 1285 |
+
ws.on("close", (code, reason) => {
|
| 1286 |
+
try {
|
| 1287 |
+
events?.onClose?.(new CloseEvent("close", {
|
| 1288 |
+
code,
|
| 1289 |
+
reason: reason.toString()
|
| 1290 |
+
}), ctx);
|
| 1291 |
+
} catch (e) {
|
| 1292 |
+
(options?.onError ?? console.error)(e);
|
| 1293 |
+
}
|
| 1294 |
+
});
|
| 1295 |
+
ws.on("error", (error) => {
|
| 1296 |
+
try {
|
| 1297 |
+
events?.onError?.(new ErrorEvent("error", { error }), ctx);
|
| 1298 |
+
} catch (e) {
|
| 1299 |
+
(options?.onError ?? console.error)(e);
|
| 1300 |
+
}
|
| 1301 |
+
});
|
| 1302 |
+
})();
|
| 1303 |
+
return new Response();
|
| 1304 |
+
});
|
| 1305 |
+
|
| 1306 |
+
//#endregion
|
| 1307 |
+
//#region src/server.ts
|
| 1308 |
+
const createAdaptorServer = (options) => {
|
| 1309 |
+
const fetchCallback = options.fetch;
|
| 1310 |
+
const requestListener = getRequestListener(fetchCallback, {
|
| 1311 |
+
hostname: options.hostname,
|
| 1312 |
+
overrideGlobalObjects: options.overrideGlobalObjects,
|
| 1313 |
+
autoCleanupIncoming: options.autoCleanupIncoming
|
| 1314 |
+
});
|
| 1315 |
+
const server = (options.createServer || node_http.createServer)(options.serverOptions || {}, requestListener);
|
| 1316 |
+
if (options.websocket && options.websocket.server) {
|
| 1317 |
+
if (options.websocket.server.options.noServer !== true) throw new Error("WebSocket server must be created with { noServer: true } option");
|
| 1318 |
+
setupWebSocket({
|
| 1319 |
+
server,
|
| 1320 |
+
fetchCallback,
|
| 1321 |
+
wss: options.websocket.server
|
| 1322 |
+
});
|
| 1323 |
+
}
|
| 1324 |
+
return server;
|
| 1325 |
+
};
|
| 1326 |
+
const serve = (options, listeningListener) => {
|
| 1327 |
+
const server = createAdaptorServer(options);
|
| 1328 |
+
server.listen(options?.port ?? 3e3, options.hostname, () => {
|
| 1329 |
+
const serverInfo = server.address();
|
| 1330 |
+
listeningListener && listeningListener(serverInfo);
|
| 1331 |
+
});
|
| 1332 |
+
return server;
|
| 1333 |
+
};
|
| 1334 |
+
|
| 1335 |
+
//#endregion
|
| 1336 |
+
exports.RequestError = RequestError;
|
| 1337 |
+
exports.createAdaptorServer = createAdaptorServer;
|
| 1338 |
+
exports.getRequestListener = getRequestListener;
|
| 1339 |
+
exports.serve = serve;
|
| 1340 |
+
exports.upgradeWebSocket = upgradeWebSocket;
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/index.d.cts
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { AddressInfo } from "node:net";
|
| 2 |
+
import { IncomingMessage, Server, ServerOptions, ServerResponse, createServer } from "node:http";
|
| 3 |
+
import { Http2SecureServer, Http2Server, Http2ServerRequest, Http2ServerResponse, SecureServerOptions, ServerOptions as ServerOptions$1, createSecureServer, createServer as createServer$1 } from "node:http2";
|
| 4 |
+
import { ServerOptions as ServerOptions$2, createServer as createServer$2 } from "node:https";
|
| 5 |
+
import { Duplex } from "node:stream";
|
| 6 |
+
import { UpgradeWebSocket } from "hono/ws";
|
| 7 |
+
|
| 8 |
+
//#region src/websocket-types.d.ts
|
| 9 |
+
type WSReadyState = 0 | 1 | 2 | 3;
|
| 10 |
+
type WebSocketData = string | ArrayBuffer | Uint8Array | readonly Uint8Array[];
|
| 11 |
+
type WebSocketSendOptions = {
|
| 12 |
+
compress?: boolean;
|
| 13 |
+
};
|
| 14 |
+
interface WebSocketLike {
|
| 15 |
+
protocol: string;
|
| 16 |
+
readyState: WSReadyState;
|
| 17 |
+
close(code?: number, reason?: string): void;
|
| 18 |
+
send(data: string | ArrayBuffer | ArrayBufferView, options?: WebSocketSendOptions): void;
|
| 19 |
+
on(event: 'message', listener: (data: WebSocketData, isBinary: boolean) => void): this;
|
| 20 |
+
on(event: 'close', listener: (code: number, reason: Uint8Array) => void): this;
|
| 21 |
+
on(event: 'error', listener: (error: unknown) => void): this;
|
| 22 |
+
off(event: 'message', listener: (data: WebSocketData, isBinary: boolean) => void): this;
|
| 23 |
+
}
|
| 24 |
+
interface WebSocketServerLike {
|
| 25 |
+
options: {
|
| 26 |
+
noServer?: boolean;
|
| 27 |
+
};
|
| 28 |
+
on(event: 'connection', listener: (ws: WebSocketLike, request: IncomingMessage) => void): this;
|
| 29 |
+
on(event: 'headers', listener: (headers: string[]) => void): this;
|
| 30 |
+
off(event: 'headers', listener: (headers: string[]) => void): this;
|
| 31 |
+
emit(event: 'connection', ws: WebSocketLike, request: IncomingMessage): boolean;
|
| 32 |
+
handleUpgrade(request: IncomingMessage, socket: Duplex, head: Buffer, callback: (ws: WebSocketLike) => void): void;
|
| 33 |
+
close(): void;
|
| 34 |
+
}
|
| 35 |
+
//#endregion
|
| 36 |
+
//#region src/types.d.ts
|
| 37 |
+
type HttpBindings = {
|
| 38 |
+
incoming: IncomingMessage;
|
| 39 |
+
outgoing: ServerResponse;
|
| 40 |
+
};
|
| 41 |
+
type Http2Bindings = {
|
| 42 |
+
incoming: Http2ServerRequest;
|
| 43 |
+
outgoing: Http2ServerResponse;
|
| 44 |
+
};
|
| 45 |
+
type FetchCallback = (request: Request, env: HttpBindings | Http2Bindings) => Promise<unknown> | unknown;
|
| 46 |
+
type ServerType = Server | Http2Server | Http2SecureServer;
|
| 47 |
+
type createHttpOptions = {
|
| 48 |
+
serverOptions?: ServerOptions;
|
| 49 |
+
createServer?: typeof createServer;
|
| 50 |
+
};
|
| 51 |
+
type createHttpsOptions = {
|
| 52 |
+
serverOptions?: ServerOptions$2;
|
| 53 |
+
createServer?: typeof createServer$2;
|
| 54 |
+
};
|
| 55 |
+
type createHttp2Options = {
|
| 56 |
+
serverOptions?: ServerOptions$1;
|
| 57 |
+
createServer?: typeof createServer$1;
|
| 58 |
+
};
|
| 59 |
+
type createSecureHttp2Options = {
|
| 60 |
+
serverOptions?: SecureServerOptions;
|
| 61 |
+
createServer?: typeof createSecureServer;
|
| 62 |
+
};
|
| 63 |
+
type ServerOptions$3 = createHttpOptions | createHttpsOptions | createHttp2Options | createSecureHttp2Options;
|
| 64 |
+
type Options = {
|
| 65 |
+
fetch: FetchCallback;
|
| 66 |
+
overrideGlobalObjects?: boolean;
|
| 67 |
+
autoCleanupIncoming?: boolean;
|
| 68 |
+
port?: number;
|
| 69 |
+
hostname?: string;
|
| 70 |
+
websocket?: {
|
| 71 |
+
server: WebSocketServerLike;
|
| 72 |
+
};
|
| 73 |
+
} & ServerOptions$3;
|
| 74 |
+
type CustomErrorHandler = (err: unknown) => void | Response | Promise<void | Response>;
|
| 75 |
+
//#endregion
|
| 76 |
+
//#region src/server.d.ts
|
| 77 |
+
declare const createAdaptorServer: (options: Options) => ServerType;
|
| 78 |
+
declare const serve: (options: Options, listeningListener?: (info: AddressInfo) => void) => ServerType;
|
| 79 |
+
//#endregion
|
| 80 |
+
//#region src/websocket.d.ts
|
| 81 |
+
type UpgradeWebSocketOptions = {
|
| 82 |
+
onError: (err: unknown) => void;
|
| 83 |
+
};
|
| 84 |
+
declare const upgradeWebSocket: UpgradeWebSocket<WebSocketLike, UpgradeWebSocketOptions>;
|
| 85 |
+
//#endregion
|
| 86 |
+
//#region src/listener.d.ts
|
| 87 |
+
declare const getRequestListener: (fetchCallback: FetchCallback, options?: {
|
| 88 |
+
hostname?: string;
|
| 89 |
+
errorHandler?: CustomErrorHandler;
|
| 90 |
+
overrideGlobalObjects?: boolean;
|
| 91 |
+
autoCleanupIncoming?: boolean;
|
| 92 |
+
}) => (incoming: IncomingMessage | Http2ServerRequest, outgoing: ServerResponse | Http2ServerResponse) => Promise<void>;
|
| 93 |
+
//#endregion
|
| 94 |
+
//#region src/error.d.ts
|
| 95 |
+
declare class RequestError extends Error {
|
| 96 |
+
constructor(message: string, options?: {
|
| 97 |
+
cause?: unknown;
|
| 98 |
+
});
|
| 99 |
+
}
|
| 100 |
+
//#endregion
|
| 101 |
+
export { type Http2Bindings, type HttpBindings, RequestError, type ServerType, type WebSocketData, type WebSocketLike, type WebSocketServerLike, createAdaptorServer, getRequestListener, serve, upgradeWebSocket };
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/index.d.mts
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { IncomingMessage, Server, ServerOptions, ServerResponse, createServer } from "node:http";
|
| 2 |
+
import { Http2SecureServer, Http2Server, Http2ServerRequest, Http2ServerResponse, SecureServerOptions, ServerOptions as ServerOptions$1, createSecureServer, createServer as createServer$1 } from "node:http2";
|
| 3 |
+
import { Duplex } from "node:stream";
|
| 4 |
+
import { UpgradeWebSocket } from "hono/ws";
|
| 5 |
+
import { AddressInfo } from "node:net";
|
| 6 |
+
import { ServerOptions as ServerOptions$2, createServer as createServer$2 } from "node:https";
|
| 7 |
+
|
| 8 |
+
//#region src/websocket-types.d.ts
|
| 9 |
+
type WSReadyState = 0 | 1 | 2 | 3;
|
| 10 |
+
type WebSocketData = string | ArrayBuffer | Uint8Array | readonly Uint8Array[];
|
| 11 |
+
type WebSocketSendOptions = {
|
| 12 |
+
compress?: boolean;
|
| 13 |
+
};
|
| 14 |
+
interface WebSocketLike {
|
| 15 |
+
protocol: string;
|
| 16 |
+
readyState: WSReadyState;
|
| 17 |
+
close(code?: number, reason?: string): void;
|
| 18 |
+
send(data: string | ArrayBuffer | ArrayBufferView, options?: WebSocketSendOptions): void;
|
| 19 |
+
on(event: 'message', listener: (data: WebSocketData, isBinary: boolean) => void): this;
|
| 20 |
+
on(event: 'close', listener: (code: number, reason: Uint8Array) => void): this;
|
| 21 |
+
on(event: 'error', listener: (error: unknown) => void): this;
|
| 22 |
+
off(event: 'message', listener: (data: WebSocketData, isBinary: boolean) => void): this;
|
| 23 |
+
}
|
| 24 |
+
interface WebSocketServerLike {
|
| 25 |
+
options: {
|
| 26 |
+
noServer?: boolean;
|
| 27 |
+
};
|
| 28 |
+
on(event: 'connection', listener: (ws: WebSocketLike, request: IncomingMessage) => void): this;
|
| 29 |
+
on(event: 'headers', listener: (headers: string[]) => void): this;
|
| 30 |
+
off(event: 'headers', listener: (headers: string[]) => void): this;
|
| 31 |
+
emit(event: 'connection', ws: WebSocketLike, request: IncomingMessage): boolean;
|
| 32 |
+
handleUpgrade(request: IncomingMessage, socket: Duplex, head: Buffer, callback: (ws: WebSocketLike) => void): void;
|
| 33 |
+
close(): void;
|
| 34 |
+
}
|
| 35 |
+
//#endregion
|
| 36 |
+
//#region src/types.d.ts
|
| 37 |
+
type HttpBindings = {
|
| 38 |
+
incoming: IncomingMessage;
|
| 39 |
+
outgoing: ServerResponse;
|
| 40 |
+
};
|
| 41 |
+
type Http2Bindings = {
|
| 42 |
+
incoming: Http2ServerRequest;
|
| 43 |
+
outgoing: Http2ServerResponse;
|
| 44 |
+
};
|
| 45 |
+
type FetchCallback = (request: Request, env: HttpBindings | Http2Bindings) => Promise<unknown> | unknown;
|
| 46 |
+
type ServerType = Server | Http2Server | Http2SecureServer;
|
| 47 |
+
type createHttpOptions = {
|
| 48 |
+
serverOptions?: ServerOptions;
|
| 49 |
+
createServer?: typeof createServer;
|
| 50 |
+
};
|
| 51 |
+
type createHttpsOptions = {
|
| 52 |
+
serverOptions?: ServerOptions$2;
|
| 53 |
+
createServer?: typeof createServer$2;
|
| 54 |
+
};
|
| 55 |
+
type createHttp2Options = {
|
| 56 |
+
serverOptions?: ServerOptions$1;
|
| 57 |
+
createServer?: typeof createServer$1;
|
| 58 |
+
};
|
| 59 |
+
type createSecureHttp2Options = {
|
| 60 |
+
serverOptions?: SecureServerOptions;
|
| 61 |
+
createServer?: typeof createSecureServer;
|
| 62 |
+
};
|
| 63 |
+
type ServerOptions$3 = createHttpOptions | createHttpsOptions | createHttp2Options | createSecureHttp2Options;
|
| 64 |
+
type Options = {
|
| 65 |
+
fetch: FetchCallback;
|
| 66 |
+
overrideGlobalObjects?: boolean;
|
| 67 |
+
autoCleanupIncoming?: boolean;
|
| 68 |
+
port?: number;
|
| 69 |
+
hostname?: string;
|
| 70 |
+
websocket?: {
|
| 71 |
+
server: WebSocketServerLike;
|
| 72 |
+
};
|
| 73 |
+
} & ServerOptions$3;
|
| 74 |
+
type CustomErrorHandler = (err: unknown) => void | Response | Promise<void | Response>;
|
| 75 |
+
//#endregion
|
| 76 |
+
//#region src/server.d.ts
|
| 77 |
+
declare const createAdaptorServer: (options: Options) => ServerType;
|
| 78 |
+
declare const serve: (options: Options, listeningListener?: (info: AddressInfo) => void) => ServerType;
|
| 79 |
+
//#endregion
|
| 80 |
+
//#region src/websocket.d.ts
|
| 81 |
+
type UpgradeWebSocketOptions = {
|
| 82 |
+
onError: (err: unknown) => void;
|
| 83 |
+
};
|
| 84 |
+
declare const upgradeWebSocket: UpgradeWebSocket<WebSocketLike, UpgradeWebSocketOptions>;
|
| 85 |
+
//#endregion
|
| 86 |
+
//#region src/listener.d.ts
|
| 87 |
+
declare const getRequestListener: (fetchCallback: FetchCallback, options?: {
|
| 88 |
+
hostname?: string;
|
| 89 |
+
errorHandler?: CustomErrorHandler;
|
| 90 |
+
overrideGlobalObjects?: boolean;
|
| 91 |
+
autoCleanupIncoming?: boolean;
|
| 92 |
+
}) => (incoming: IncomingMessage | Http2ServerRequest, outgoing: ServerResponse | Http2ServerResponse) => Promise<void>;
|
| 93 |
+
//#endregion
|
| 94 |
+
//#region src/error.d.ts
|
| 95 |
+
declare class RequestError extends Error {
|
| 96 |
+
constructor(message: string, options?: {
|
| 97 |
+
cause?: unknown;
|
| 98 |
+
});
|
| 99 |
+
}
|
| 100 |
+
//#endregion
|
| 101 |
+
export { type Http2Bindings, type HttpBindings, RequestError, type ServerType, type WebSocketData, type WebSocketLike, type WebSocketServerLike, createAdaptorServer, getRequestListener, serve, upgradeWebSocket };
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/index.mjs
ADDED
|
@@ -0,0 +1,1335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { t as X_ALREADY_SENT } from "./constants-BLSFu_RU.mjs";
|
| 2 |
+
import { STATUS_CODES, ServerResponse, createServer } from "node:http";
|
| 3 |
+
import { Http2ServerRequest, constants } from "node:http2";
|
| 4 |
+
import { Readable } from "node:stream";
|
| 5 |
+
import { defineWebSocketHelper } from "hono/ws";
|
| 6 |
+
|
| 7 |
+
//#region src/error.ts
|
| 8 |
+
var RequestError = class extends Error {
|
| 9 |
+
constructor(message, options) {
|
| 10 |
+
super(message, options);
|
| 11 |
+
this.name = "RequestError";
|
| 12 |
+
}
|
| 13 |
+
};
|
| 14 |
+
|
| 15 |
+
//#endregion
|
| 16 |
+
//#region src/headers.ts
|
| 17 |
+
const nonJoinedHeaders = new Set([
|
| 18 |
+
"age",
|
| 19 |
+
"authorization",
|
| 20 |
+
"content-length",
|
| 21 |
+
"content-type",
|
| 22 |
+
"etag",
|
| 23 |
+
"expires",
|
| 24 |
+
"from",
|
| 25 |
+
"host",
|
| 26 |
+
"if-modified-since",
|
| 27 |
+
"if-unmodified-since",
|
| 28 |
+
"last-modified",
|
| 29 |
+
"location",
|
| 30 |
+
"max-forwards",
|
| 31 |
+
"proxy-authorization",
|
| 32 |
+
"referer",
|
| 33 |
+
"retry-after",
|
| 34 |
+
"server",
|
| 35 |
+
"user-agent"
|
| 36 |
+
]);
|
| 37 |
+
const validHeaderName = /^[!#$%&'*+\-.^_`|~\dA-Za-z]+$/;
|
| 38 |
+
const isHttpWhitespace = (code) => code === 9 || code === 10 || code === 13 || code === 32;
|
| 39 |
+
const normalizeHeaderValue = (value) => {
|
| 40 |
+
if (!isHttpWhitespace(value.charCodeAt(0)) && !isHttpWhitespace(value.charCodeAt(value.length - 1))) return value;
|
| 41 |
+
let start = 0;
|
| 42 |
+
let end = value.length;
|
| 43 |
+
while (start < end && isHttpWhitespace(value.charCodeAt(start))) start++;
|
| 44 |
+
while (end > start && isHttpWhitespace(value.charCodeAt(end - 1))) end--;
|
| 45 |
+
return value.slice(start, end);
|
| 46 |
+
};
|
| 47 |
+
const forbiddenHeaderValue = /[\0\r\n]/;
|
| 48 |
+
const GlobalHeaders = globalThis.Headers;
|
| 49 |
+
const materializeHeaders = (rawHeaders, HeadersCtor = GlobalHeaders) => {
|
| 50 |
+
const headers = new HeadersCtor();
|
| 51 |
+
for (let i = 0; i < rawHeaders.length; i += 2) {
|
| 52 |
+
const name = rawHeaders[i];
|
| 53 |
+
if (!name.startsWith(":")) headers.append(name, rawHeaders[i + 1]);
|
| 54 |
+
}
|
| 55 |
+
return headers;
|
| 56 |
+
};
|
| 57 |
+
var RequestHeaders = class {
|
| 58 |
+
#incoming;
|
| 59 |
+
#rawHeaders;
|
| 60 |
+
#headers;
|
| 61 |
+
#invalidValue;
|
| 62 |
+
constructor(incoming) {
|
| 63 |
+
this.#incoming = incoming;
|
| 64 |
+
if (incoming instanceof Http2ServerRequest) this.#rawHeaders = incoming.rawHeaders.slice();
|
| 65 |
+
}
|
| 66 |
+
get #lazyRawHeaders() {
|
| 67 |
+
return this.#rawHeaders ??= this.#incoming.rawHeaders.slice();
|
| 68 |
+
}
|
| 69 |
+
get #native() {
|
| 70 |
+
if (!this.#headers) {
|
| 71 |
+
this.#headers = materializeHeaders(this.#lazyRawHeaders);
|
| 72 |
+
this.#rawHeaders = void 0;
|
| 73 |
+
}
|
| 74 |
+
return this.#headers;
|
| 75 |
+
}
|
| 76 |
+
#normalizedName(name) {
|
| 77 |
+
if (typeof name !== "string") return;
|
| 78 |
+
if (!validHeaderName.test(name)) throw new TypeError(`Invalid header name: ${name}`);
|
| 79 |
+
return name.toLowerCase();
|
| 80 |
+
}
|
| 81 |
+
#lookupHttp1(lowerName) {
|
| 82 |
+
const headers = this.#incoming instanceof Http2ServerRequest ? void 0 : this.#incoming.headers;
|
| 83 |
+
if (!headers || nonJoinedHeaders.has(lowerName) || lowerName === "set-cookie" || lowerName === "__proto__") return;
|
| 84 |
+
if (!Object.hasOwn(headers, lowerName)) return null;
|
| 85 |
+
const rawValue = headers[lowerName];
|
| 86 |
+
if (typeof rawValue === "string") {
|
| 87 |
+
const value = normalizeHeaderValue(rawValue);
|
| 88 |
+
return forbiddenHeaderValue.test(value) ? void 0 : value;
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
#lookup(rawHeaders, lowerName) {
|
| 92 |
+
const separator = lowerName === "cookie" ? "; " : ", ";
|
| 93 |
+
let value = null;
|
| 94 |
+
for (let i = 0; i < rawHeaders.length; i += 2) {
|
| 95 |
+
const rawName = rawHeaders[i];
|
| 96 |
+
if (rawName.length === lowerName.length && rawName.toLowerCase() === lowerName) {
|
| 97 |
+
const rawValue = normalizeHeaderValue(rawHeaders[i + 1]);
|
| 98 |
+
if (forbiddenHeaderValue.test(rawValue)) {
|
| 99 |
+
this.#invalidValue = true;
|
| 100 |
+
return;
|
| 101 |
+
}
|
| 102 |
+
value = value === null ? rawValue : value + separator + rawValue;
|
| 103 |
+
}
|
| 104 |
+
}
|
| 105 |
+
return value;
|
| 106 |
+
}
|
| 107 |
+
append(name, value) {
|
| 108 |
+
this.#native.append(name, value);
|
| 109 |
+
}
|
| 110 |
+
delete(name) {
|
| 111 |
+
this.#native.delete(name);
|
| 112 |
+
}
|
| 113 |
+
get(name) {
|
| 114 |
+
const lowerName = this.#normalizedName(name);
|
| 115 |
+
if (lowerName && !this.#headers && !this.#invalidValue) {
|
| 116 |
+
const http1Value = this.#lookupHttp1(lowerName);
|
| 117 |
+
if (http1Value !== void 0) return http1Value;
|
| 118 |
+
const value = this.#lookup(this.#lazyRawHeaders, lowerName);
|
| 119 |
+
if (value !== void 0) return value;
|
| 120 |
+
}
|
| 121 |
+
return this.#native.get(name);
|
| 122 |
+
}
|
| 123 |
+
has(name) {
|
| 124 |
+
const lowerName = this.#normalizedName(name);
|
| 125 |
+
if (lowerName && !this.#headers && !this.#invalidValue) {
|
| 126 |
+
const http1Value = this.#lookupHttp1(lowerName);
|
| 127 |
+
if (http1Value !== void 0) return http1Value !== null;
|
| 128 |
+
const value = this.#lookup(this.#lazyRawHeaders, lowerName);
|
| 129 |
+
if (value !== void 0) return value !== null;
|
| 130 |
+
}
|
| 131 |
+
return this.#native.has(name);
|
| 132 |
+
}
|
| 133 |
+
set(name, value) {
|
| 134 |
+
this.#native.set(name, value);
|
| 135 |
+
}
|
| 136 |
+
getSetCookie() {
|
| 137 |
+
return this.#native.getSetCookie();
|
| 138 |
+
}
|
| 139 |
+
keys() {
|
| 140 |
+
return this.#native.keys();
|
| 141 |
+
}
|
| 142 |
+
values() {
|
| 143 |
+
return this.#native.values();
|
| 144 |
+
}
|
| 145 |
+
entries() {
|
| 146 |
+
return this.#native.entries();
|
| 147 |
+
}
|
| 148 |
+
forEach(callback, thisArg) {
|
| 149 |
+
this.#native.forEach((value, key) => {
|
| 150 |
+
callback.call(thisArg, value, key, this);
|
| 151 |
+
});
|
| 152 |
+
}
|
| 153 |
+
[Symbol.iterator]() {
|
| 154 |
+
return this.entries();
|
| 155 |
+
}
|
| 156 |
+
};
|
| 157 |
+
Object.defineProperty(RequestHeaders.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
|
| 158 |
+
return `Headers (lightweight) ${inspectFn(Object.fromEntries(this), {
|
| 159 |
+
...options,
|
| 160 |
+
depth: depth == null ? null : depth - 1
|
| 161 |
+
})}`;
|
| 162 |
+
} });
|
| 163 |
+
Object.setPrototypeOf(RequestHeaders.prototype, GlobalHeaders.prototype);
|
| 164 |
+
const newHeadersFromIncoming = (incoming) => globalThis.Headers === GlobalHeaders ? new RequestHeaders(incoming) : materializeHeaders(incoming.rawHeaders, globalThis.Headers);
|
| 165 |
+
|
| 166 |
+
//#endregion
|
| 167 |
+
//#region src/url.ts
|
| 168 |
+
const reValidRequestUrl = /^\/[!#$&-;=?-\[\]_a-z~]*$/;
|
| 169 |
+
const reDotSegment = /\/\.\.?(?:[/?#]|$)/;
|
| 170 |
+
const reValidHost = /^[a-z0-9._-]+(?::(?:[1-5]\d{3,4}|[6-9]\d{3}))?$/;
|
| 171 |
+
const buildUrl = (scheme, host, incomingUrl) => {
|
| 172 |
+
const url = `${scheme}://${host}${incomingUrl}`;
|
| 173 |
+
if (!reValidHost.test(host)) {
|
| 174 |
+
const urlObj = new URL(url);
|
| 175 |
+
if (urlObj.hostname.length !== host.length && urlObj.hostname !== (host.includes(":") ? host.replace(/:\d+$/, "") : host).toLowerCase()) throw new RequestError("Invalid host header");
|
| 176 |
+
return urlObj.href;
|
| 177 |
+
} else if (incomingUrl.length === 0) return url + "/";
|
| 178 |
+
else {
|
| 179 |
+
if (incomingUrl.charCodeAt(0) !== 47) throw new RequestError("Invalid URL");
|
| 180 |
+
if (!reValidRequestUrl.test(incomingUrl) || reDotSegment.test(incomingUrl)) return new URL(url).href;
|
| 181 |
+
return url;
|
| 182 |
+
}
|
| 183 |
+
};
|
| 184 |
+
|
| 185 |
+
//#endregion
|
| 186 |
+
//#region src/request.ts
|
| 187 |
+
const toRequestError = (e) => {
|
| 188 |
+
if (e instanceof RequestError) return e;
|
| 189 |
+
return new RequestError(e.message, { cause: e });
|
| 190 |
+
};
|
| 191 |
+
const GlobalRequest = global.Request;
|
| 192 |
+
var Request$1 = class extends GlobalRequest {
|
| 193 |
+
constructor(input, options) {
|
| 194 |
+
if (typeof input === "object" && getRequestCache in input) {
|
| 195 |
+
const hasReplacementBody = options !== void 0 && "body" in options && options.body != null;
|
| 196 |
+
if (input[bodyConsumedDirectlyKey] && !hasReplacementBody) throw new TypeError("Cannot construct a Request with a Request object that has already been used.");
|
| 197 |
+
input = input[getRequestCache]();
|
| 198 |
+
}
|
| 199 |
+
if (typeof (options?.body)?.getReader !== "undefined") options.duplex ??= "half";
|
| 200 |
+
super(input, options);
|
| 201 |
+
}
|
| 202 |
+
};
|
| 203 |
+
const wrapBodyStream = Symbol("wrapBodyStream");
|
| 204 |
+
const byteExactEncodings = new Set([
|
| 205 |
+
"latin1",
|
| 206 |
+
"binary",
|
| 207 |
+
"hex",
|
| 208 |
+
"base64",
|
| 209 |
+
"base64url"
|
| 210 |
+
]);
|
| 211 |
+
const isByteExactEncoding = (encoding) => encoding === null || byteExactEncodings.has(encoding);
|
| 212 |
+
const bodyBufferedBeforeDisconnectKey = Symbol("bodyBufferedBeforeDisconnect");
|
| 213 |
+
const bodyBufferedLengthBeforeDisconnectKey = Symbol("bodyBufferedLengthBeforeDisconnect");
|
| 214 |
+
const toBufferChunk = (chunk, encoding) => Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, encoding ?? "utf8");
|
| 215 |
+
const isRecoverableDisconnectedIncoming = (incoming) => !(incoming instanceof Http2ServerRequest) && !!incoming.complete && !!incoming.readableAborted && typeof incoming.read === "function" && isByteExactEncoding(incoming.readableEncoding);
|
| 216 |
+
const recordBodyBufferedBeforeDisconnect = (incoming) => {
|
| 217 |
+
if (incoming.readableDidRead || !isRecoverableDisconnectedIncoming(incoming)) return;
|
| 218 |
+
const incomingWithRecovery = incoming;
|
| 219 |
+
incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] ??= incoming.readableLength;
|
| 220 |
+
};
|
| 221 |
+
const readBodyBufferedBeforeDisconnect = (incoming, chunks) => {
|
| 222 |
+
if (incoming.readableDidRead && !chunks || !isRecoverableDisconnectedIncoming(incoming)) return;
|
| 223 |
+
const incomingWithRecovery = incoming;
|
| 224 |
+
if (incomingWithRecovery[bodyBufferedBeforeDisconnectKey] !== void 0) return incomingWithRecovery[bodyBufferedBeforeDisconnectKey];
|
| 225 |
+
let result;
|
| 226 |
+
const errored = incoming.errored;
|
| 227 |
+
if (errored && errored.code !== "ECONNRESET") result = errored;
|
| 228 |
+
else if (incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey] !== void 0 && incoming.readableLength !== incomingWithRecovery[bodyBufferedLengthBeforeDisconnectKey]) result = newBodyUnusableError();
|
| 229 |
+
else {
|
| 230 |
+
const bodyChunks = chunks ?? [];
|
| 231 |
+
const chunk = incoming.read();
|
| 232 |
+
if (chunk !== null) bodyChunks.push(toBufferChunk(chunk, incoming.readableEncoding));
|
| 233 |
+
const buffer = bodyChunks.length === 1 ? bodyChunks[0] : Buffer.concat(bodyChunks);
|
| 234 |
+
result = buffer;
|
| 235 |
+
const contentLength = incoming.headers["content-length"];
|
| 236 |
+
if (typeof contentLength === "string" && /^\d+$/.test(contentLength)) {
|
| 237 |
+
const expectedLength = Number(contentLength);
|
| 238 |
+
if (Number.isSafeInteger(expectedLength) && buffer.length !== expectedLength) result = newBodyUnusableError();
|
| 239 |
+
}
|
| 240 |
+
}
|
| 241 |
+
incomingWithRecovery[bodyBufferedBeforeDisconnectKey] = result;
|
| 242 |
+
return result;
|
| 243 |
+
};
|
| 244 |
+
const enqueueBufferedBody = (controller, buffered) => {
|
| 245 |
+
if (buffered instanceof Error) {
|
| 246 |
+
controller.error(buffered);
|
| 247 |
+
return;
|
| 248 |
+
}
|
| 249 |
+
if (buffered.length > 0) controller.enqueue(buffered);
|
| 250 |
+
controller.close();
|
| 251 |
+
};
|
| 252 |
+
const newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
|
| 253 |
+
const init = {
|
| 254 |
+
method,
|
| 255 |
+
headers,
|
| 256 |
+
signal: abortController.signal
|
| 257 |
+
};
|
| 258 |
+
if (method === "TRACE") {
|
| 259 |
+
init.method = "GET";
|
| 260 |
+
const req = new Request$1(url, init);
|
| 261 |
+
Object.defineProperty(req, "method", { get() {
|
| 262 |
+
return "TRACE";
|
| 263 |
+
} });
|
| 264 |
+
return req;
|
| 265 |
+
}
|
| 266 |
+
if (!(method === "GET" || method === "HEAD")) if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) init.body = new ReadableStream({ start(controller) {
|
| 267 |
+
controller.enqueue(incoming.rawBody);
|
| 268 |
+
controller.close();
|
| 269 |
+
} });
|
| 270 |
+
else if (incoming[wrapBodyStream]) {
|
| 271 |
+
let reader;
|
| 272 |
+
init.body = new ReadableStream({ async pull(controller) {
|
| 273 |
+
try {
|
| 274 |
+
if (!reader) {
|
| 275 |
+
const buffered = readBodyBufferedBeforeDisconnect(incoming);
|
| 276 |
+
if (buffered !== void 0) {
|
| 277 |
+
enqueueBufferedBody(controller, buffered);
|
| 278 |
+
return;
|
| 279 |
+
}
|
| 280 |
+
}
|
| 281 |
+
reader ||= Readable.toWeb(incoming).getReader();
|
| 282 |
+
const { done, value } = await reader.read();
|
| 283 |
+
if (done) controller.close();
|
| 284 |
+
else controller.enqueue(value);
|
| 285 |
+
} catch (error) {
|
| 286 |
+
controller.error(error);
|
| 287 |
+
}
|
| 288 |
+
} });
|
| 289 |
+
} else {
|
| 290 |
+
const buffered = readBodyBufferedBeforeDisconnect(incoming);
|
| 291 |
+
if (buffered !== void 0) init.body = new ReadableStream({ start(controller) {
|
| 292 |
+
enqueueBufferedBody(controller, buffered);
|
| 293 |
+
} });
|
| 294 |
+
else init.body = Readable.toWeb(incoming);
|
| 295 |
+
}
|
| 296 |
+
return new Request$1(url, init);
|
| 297 |
+
};
|
| 298 |
+
const getRequestCache = Symbol("getRequestCache");
|
| 299 |
+
const requestCache = Symbol("requestCache");
|
| 300 |
+
const incomingKey = Symbol("incomingKey");
|
| 301 |
+
const urlKey = Symbol("urlKey");
|
| 302 |
+
const methodKey = Symbol("methodKey");
|
| 303 |
+
const headersKey = Symbol("headersKey");
|
| 304 |
+
const abortControllerKey = Symbol("abortControllerKey");
|
| 305 |
+
const getAbortController = Symbol("getAbortController");
|
| 306 |
+
const abortRequest = Symbol("abortRequest");
|
| 307 |
+
const bodyBufferKey = Symbol("bodyBuffer");
|
| 308 |
+
const bodyReadPromiseKey = Symbol("bodyReadPromise");
|
| 309 |
+
const bodyConsumedDirectlyKey = Symbol("bodyConsumedDirectly");
|
| 310 |
+
const bodyLockReaderKey = Symbol("bodyLockReader");
|
| 311 |
+
const abortReasonKey = Symbol("abortReason");
|
| 312 |
+
const newBodyUnusableError = () => {
|
| 313 |
+
return /* @__PURE__ */ new TypeError("Body is unusable");
|
| 314 |
+
};
|
| 315 |
+
const rejectBodyUnusable = () => {
|
| 316 |
+
return Promise.reject(newBodyUnusableError());
|
| 317 |
+
};
|
| 318 |
+
const textDecoder = new TextDecoder();
|
| 319 |
+
const consumeBodyDirectOnce = (request) => {
|
| 320 |
+
if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
|
| 321 |
+
request[bodyConsumedDirectlyKey] = true;
|
| 322 |
+
};
|
| 323 |
+
const toArrayBuffer = (buf) => {
|
| 324 |
+
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
|
| 325 |
+
};
|
| 326 |
+
const contentType = (request) => {
|
| 327 |
+
return (request[headersKey] ||= newHeadersFromIncoming(request[incomingKey])).get("content-type") || "";
|
| 328 |
+
};
|
| 329 |
+
const methodTokenRegExp = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
| 330 |
+
const normalizeIncomingMethod = (method) => {
|
| 331 |
+
if (typeof method !== "string" || method.length === 0) return "GET";
|
| 332 |
+
switch (method) {
|
| 333 |
+
case "DELETE":
|
| 334 |
+
case "GET":
|
| 335 |
+
case "HEAD":
|
| 336 |
+
case "OPTIONS":
|
| 337 |
+
case "PATCH":
|
| 338 |
+
case "POST":
|
| 339 |
+
case "PUT":
|
| 340 |
+
case "QUERY": return method;
|
| 341 |
+
}
|
| 342 |
+
const upper = method.toUpperCase();
|
| 343 |
+
switch (upper) {
|
| 344 |
+
case "DELETE":
|
| 345 |
+
case "GET":
|
| 346 |
+
case "HEAD":
|
| 347 |
+
case "OPTIONS":
|
| 348 |
+
case "POST":
|
| 349 |
+
case "PUT": return upper;
|
| 350 |
+
default: return method;
|
| 351 |
+
}
|
| 352 |
+
};
|
| 353 |
+
const validateDirectReadMethod = (method) => {
|
| 354 |
+
if (!methodTokenRegExp.test(method)) return /* @__PURE__ */ new TypeError(`'${method}' is not a valid HTTP method.`);
|
| 355 |
+
const normalized = method.toUpperCase();
|
| 356 |
+
if (normalized === "CONNECT" || normalized === "TRACK" || normalized === "TRACE" && method !== "TRACE") return /* @__PURE__ */ new TypeError(`'${method}' HTTP method is unsupported.`);
|
| 357 |
+
};
|
| 358 |
+
const readBodyWithFastPath = (request, method, fromBuffer) => {
|
| 359 |
+
if (request[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
|
| 360 |
+
const methodName = request.method;
|
| 361 |
+
if (methodName === "GET" || methodName === "HEAD") return request[getRequestCache]()[method]();
|
| 362 |
+
const methodValidationError = validateDirectReadMethod(methodName);
|
| 363 |
+
if (methodValidationError) return Promise.reject(methodValidationError);
|
| 364 |
+
if (request[requestCache]) {
|
| 365 |
+
if (methodName !== "TRACE") return request[requestCache][method]();
|
| 366 |
+
}
|
| 367 |
+
const alreadyUsedError = consumeBodyDirectOnce(request);
|
| 368 |
+
if (alreadyUsedError) return alreadyUsedError;
|
| 369 |
+
const raw = readRawBodyIfAvailable(request);
|
| 370 |
+
if (raw) {
|
| 371 |
+
const result = Promise.resolve(fromBuffer(raw, request));
|
| 372 |
+
request[bodyBufferKey] = void 0;
|
| 373 |
+
return result;
|
| 374 |
+
}
|
| 375 |
+
return readBodyDirect(request).then((buf) => {
|
| 376 |
+
const result = fromBuffer(buf, request);
|
| 377 |
+
request[bodyBufferKey] = void 0;
|
| 378 |
+
return result;
|
| 379 |
+
});
|
| 380 |
+
};
|
| 381 |
+
const readRawBodyIfAvailable = (request) => {
|
| 382 |
+
const incoming = request[incomingKey];
|
| 383 |
+
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) return incoming.rawBody;
|
| 384 |
+
};
|
| 385 |
+
const normalizeAbortError = (request, incoming) => {
|
| 386 |
+
if (incoming.errored) return incoming.errored;
|
| 387 |
+
const reason = request[abortReasonKey];
|
| 388 |
+
if (reason !== void 0) return reason instanceof Error ? reason : new Error(String(reason));
|
| 389 |
+
return /* @__PURE__ */ new Error("Client connection prematurely closed.");
|
| 390 |
+
};
|
| 391 |
+
const readBodyDirect = (request) => {
|
| 392 |
+
if (request[bodyBufferKey]) return Promise.resolve(request[bodyBufferKey]);
|
| 393 |
+
if (request[bodyReadPromiseKey]) return request[bodyReadPromiseKey];
|
| 394 |
+
const incoming = request[incomingKey];
|
| 395 |
+
if (incoming.readableDidRead) return rejectBodyUnusable();
|
| 396 |
+
const buffered = readBodyBufferedBeforeDisconnect(incoming);
|
| 397 |
+
if (buffered !== void 0) {
|
| 398 |
+
if (buffered instanceof Error) return Promise.reject(buffered);
|
| 399 |
+
request[bodyBufferKey] = buffered;
|
| 400 |
+
return Promise.resolve(buffered);
|
| 401 |
+
}
|
| 402 |
+
const promise = new Promise((resolve, reject) => {
|
| 403 |
+
const chunks = [];
|
| 404 |
+
let settled = false;
|
| 405 |
+
const finish = (callback) => {
|
| 406 |
+
if (settled) return;
|
| 407 |
+
settled = true;
|
| 408 |
+
cleanup();
|
| 409 |
+
callback();
|
| 410 |
+
};
|
| 411 |
+
const recoverCompleteBodyAfterDisconnect = (error) => {
|
| 412 |
+
const streamError = incoming.errored ?? error;
|
| 413 |
+
if (!isRecoverableDisconnectedIncoming(incoming) || streamError && streamError.code !== "ECONNRESET") return false;
|
| 414 |
+
finish(() => {
|
| 415 |
+
const recovered = readBodyBufferedBeforeDisconnect(incoming, chunks);
|
| 416 |
+
if (recovered instanceof Error) reject(recovered);
|
| 417 |
+
else if (recovered === void 0) reject(error ?? normalizeAbortError(request, incoming));
|
| 418 |
+
else {
|
| 419 |
+
request[bodyBufferKey] = recovered;
|
| 420 |
+
resolve(recovered);
|
| 421 |
+
}
|
| 422 |
+
});
|
| 423 |
+
return true;
|
| 424 |
+
};
|
| 425 |
+
const onData = (chunk) => {
|
| 426 |
+
chunks.push(toBufferChunk(chunk, incoming.readableEncoding));
|
| 427 |
+
};
|
| 428 |
+
const onEnd = () => {
|
| 429 |
+
finish(() => {
|
| 430 |
+
const buffer = chunks.length === 1 ? chunks[0] : Buffer.concat(chunks);
|
| 431 |
+
request[bodyBufferKey] = buffer;
|
| 432 |
+
resolve(buffer);
|
| 433 |
+
});
|
| 434 |
+
};
|
| 435 |
+
const onError = (error) => {
|
| 436 |
+
if (recoverCompleteBodyAfterDisconnect(error)) return;
|
| 437 |
+
finish(() => {
|
| 438 |
+
reject(error);
|
| 439 |
+
});
|
| 440 |
+
};
|
| 441 |
+
const onClose = () => {
|
| 442 |
+
if (incoming.readableEnded) {
|
| 443 |
+
onEnd();
|
| 444 |
+
return;
|
| 445 |
+
}
|
| 446 |
+
if (recoverCompleteBodyAfterDisconnect()) return;
|
| 447 |
+
finish(() => {
|
| 448 |
+
reject(normalizeAbortError(request, incoming));
|
| 449 |
+
});
|
| 450 |
+
};
|
| 451 |
+
const cleanup = () => {
|
| 452 |
+
incoming.off("data", onData);
|
| 453 |
+
incoming.off("end", onEnd);
|
| 454 |
+
incoming.off("error", onError);
|
| 455 |
+
incoming.off("close", onClose);
|
| 456 |
+
request[bodyReadPromiseKey] = void 0;
|
| 457 |
+
};
|
| 458 |
+
incoming.on("data", onData);
|
| 459 |
+
incoming.on("end", onEnd);
|
| 460 |
+
incoming.on("error", onError);
|
| 461 |
+
incoming.on("close", onClose);
|
| 462 |
+
queueMicrotask(() => {
|
| 463 |
+
if (settled) return;
|
| 464 |
+
if (incoming.readableEnded) onEnd();
|
| 465 |
+
else if (incoming.errored) onError(incoming.errored);
|
| 466 |
+
else if (incoming.destroyed) onClose();
|
| 467 |
+
});
|
| 468 |
+
});
|
| 469 |
+
request[bodyReadPromiseKey] = promise;
|
| 470 |
+
return promise;
|
| 471 |
+
};
|
| 472 |
+
const requestPrototype = {
|
| 473 |
+
get method() {
|
| 474 |
+
return this[methodKey];
|
| 475 |
+
},
|
| 476 |
+
get url() {
|
| 477 |
+
return this[urlKey];
|
| 478 |
+
},
|
| 479 |
+
get headers() {
|
| 480 |
+
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
|
| 481 |
+
},
|
| 482 |
+
[abortRequest](reason) {
|
| 483 |
+
if (this[abortReasonKey] === void 0) this[abortReasonKey] = reason;
|
| 484 |
+
const abortController = this[abortControllerKey];
|
| 485 |
+
if (abortController && !abortController.signal.aborted) abortController.abort(reason);
|
| 486 |
+
},
|
| 487 |
+
[getAbortController]() {
|
| 488 |
+
this[abortControllerKey] ||= new AbortController();
|
| 489 |
+
if (this[abortReasonKey] !== void 0 && !this[abortControllerKey].signal.aborted) this[abortControllerKey].abort(this[abortReasonKey]);
|
| 490 |
+
return this[abortControllerKey];
|
| 491 |
+
},
|
| 492 |
+
[getRequestCache]() {
|
| 493 |
+
const abortController = this[getAbortController]();
|
| 494 |
+
if (this[requestCache]) return this[requestCache];
|
| 495 |
+
const method = this.method;
|
| 496 |
+
if (this[bodyConsumedDirectlyKey] && !(method === "GET" || method === "HEAD")) {
|
| 497 |
+
this[bodyBufferKey] = void 0;
|
| 498 |
+
const init = {
|
| 499 |
+
method: method === "TRACE" ? "GET" : method,
|
| 500 |
+
headers: this.headers,
|
| 501 |
+
signal: abortController.signal
|
| 502 |
+
};
|
| 503 |
+
if (method !== "TRACE") {
|
| 504 |
+
init.body = new ReadableStream({ start(c) {
|
| 505 |
+
c.close();
|
| 506 |
+
} });
|
| 507 |
+
init.duplex = "half";
|
| 508 |
+
}
|
| 509 |
+
const req = new Request$1(this[urlKey], init);
|
| 510 |
+
if (method === "TRACE") Object.defineProperty(req, "method", { get() {
|
| 511 |
+
return "TRACE";
|
| 512 |
+
} });
|
| 513 |
+
return this[requestCache] = req;
|
| 514 |
+
}
|
| 515 |
+
return this[requestCache] = newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], abortController);
|
| 516 |
+
},
|
| 517 |
+
get body() {
|
| 518 |
+
if (!this[bodyConsumedDirectlyKey]) return this[getRequestCache]().body;
|
| 519 |
+
const request = this[getRequestCache]();
|
| 520 |
+
if (!this[bodyLockReaderKey] && request.body) this[bodyLockReaderKey] = request.body.getReader();
|
| 521 |
+
return request.body;
|
| 522 |
+
},
|
| 523 |
+
get bodyUsed() {
|
| 524 |
+
if (this[bodyConsumedDirectlyKey]) return true;
|
| 525 |
+
if (this[requestCache]) return this[requestCache].bodyUsed;
|
| 526 |
+
return false;
|
| 527 |
+
}
|
| 528 |
+
};
|
| 529 |
+
Object.defineProperty(requestPrototype, "signal", { get() {
|
| 530 |
+
return this[getAbortController]().signal;
|
| 531 |
+
} });
|
| 532 |
+
[
|
| 533 |
+
"cache",
|
| 534 |
+
"credentials",
|
| 535 |
+
"destination",
|
| 536 |
+
"integrity",
|
| 537 |
+
"mode",
|
| 538 |
+
"redirect",
|
| 539 |
+
"referrer",
|
| 540 |
+
"referrerPolicy",
|
| 541 |
+
"keepalive"
|
| 542 |
+
].forEach((k) => {
|
| 543 |
+
Object.defineProperty(requestPrototype, k, { get() {
|
| 544 |
+
return this[getRequestCache]()[k];
|
| 545 |
+
} });
|
| 546 |
+
});
|
| 547 |
+
["clone", "formData"].forEach((k) => {
|
| 548 |
+
Object.defineProperty(requestPrototype, k, { value: function() {
|
| 549 |
+
if (this[bodyConsumedDirectlyKey]) {
|
| 550 |
+
if (k === "clone") throw newBodyUnusableError();
|
| 551 |
+
return rejectBodyUnusable();
|
| 552 |
+
}
|
| 553 |
+
return this[getRequestCache]()[k]();
|
| 554 |
+
} });
|
| 555 |
+
});
|
| 556 |
+
Object.defineProperty(requestPrototype, "text", { value: function() {
|
| 557 |
+
return readBodyWithFastPath(this, "text", (buf) => textDecoder.decode(buf));
|
| 558 |
+
} });
|
| 559 |
+
Object.defineProperty(requestPrototype, "arrayBuffer", { value: function() {
|
| 560 |
+
return readBodyWithFastPath(this, "arrayBuffer", (buf) => toArrayBuffer(buf));
|
| 561 |
+
} });
|
| 562 |
+
Object.defineProperty(requestPrototype, "blob", { value: function() {
|
| 563 |
+
return readBodyWithFastPath(this, "blob", (buf, request) => {
|
| 564 |
+
const type = contentType(request);
|
| 565 |
+
const init = type ? { headers: { "content-type": type } } : void 0;
|
| 566 |
+
return new Response(buf, init).blob();
|
| 567 |
+
});
|
| 568 |
+
} });
|
| 569 |
+
Object.defineProperty(requestPrototype, "json", { value: function() {
|
| 570 |
+
if (this[bodyConsumedDirectlyKey]) return rejectBodyUnusable();
|
| 571 |
+
return this.text().then(JSON.parse);
|
| 572 |
+
} });
|
| 573 |
+
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
|
| 574 |
+
return `Request (lightweight) ${inspectFn({
|
| 575 |
+
method: this.method,
|
| 576 |
+
url: this.url,
|
| 577 |
+
headers: this.headers,
|
| 578 |
+
nativeRequest: this[requestCache]
|
| 579 |
+
}, {
|
| 580 |
+
...options,
|
| 581 |
+
depth: depth == null ? null : depth - 1
|
| 582 |
+
})}`;
|
| 583 |
+
} });
|
| 584 |
+
Object.setPrototypeOf(requestPrototype, Request$1.prototype);
|
| 585 |
+
const newRequest = (incoming, defaultHostname) => {
|
| 586 |
+
const req = Object.create(requestPrototype);
|
| 587 |
+
req[incomingKey] = incoming;
|
| 588 |
+
req[methodKey] = normalizeIncomingMethod(incoming.method);
|
| 589 |
+
const incomingUrl = incoming.url || "";
|
| 590 |
+
if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
|
| 591 |
+
if (incoming instanceof Http2ServerRequest) throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
| 592 |
+
try {
|
| 593 |
+
req[urlKey] = new URL(incomingUrl).href;
|
| 594 |
+
} catch (e) {
|
| 595 |
+
throw new RequestError("Invalid absolute URL", { cause: e });
|
| 596 |
+
}
|
| 597 |
+
return req;
|
| 598 |
+
}
|
| 599 |
+
const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
|
| 600 |
+
if (!host) throw new RequestError("Missing host header");
|
| 601 |
+
let scheme;
|
| 602 |
+
if (incoming instanceof Http2ServerRequest) {
|
| 603 |
+
scheme = incoming.scheme;
|
| 604 |
+
if (!(scheme === "http" || scheme === "https")) throw new RequestError("Unsupported scheme");
|
| 605 |
+
} else scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
|
| 606 |
+
try {
|
| 607 |
+
req[urlKey] = buildUrl(scheme, host, incomingUrl);
|
| 608 |
+
} catch (e) {
|
| 609 |
+
if (e instanceof RequestError) throw e;
|
| 610 |
+
else throw new RequestError("Invalid URL", { cause: e });
|
| 611 |
+
}
|
| 612 |
+
return req;
|
| 613 |
+
};
|
| 614 |
+
|
| 615 |
+
//#endregion
|
| 616 |
+
//#region src/response.ts
|
| 617 |
+
const defaultContentType = "text/plain; charset=UTF-8";
|
| 618 |
+
const responseCache = Symbol("responseCache");
|
| 619 |
+
const getResponseCache = Symbol("getResponseCache");
|
| 620 |
+
const cacheKey = Symbol("cache");
|
| 621 |
+
const GlobalResponse = global.Response;
|
| 622 |
+
var Response$1 = class Response$1 {
|
| 623 |
+
#body;
|
| 624 |
+
#init;
|
| 625 |
+
[getResponseCache]() {
|
| 626 |
+
const cache = this[cacheKey];
|
| 627 |
+
const liveHeaders = cache && cache[2] instanceof Headers ? cache[2] : void 0;
|
| 628 |
+
delete this[cacheKey];
|
| 629 |
+
return this[responseCache] ||= new GlobalResponse(this.#body, liveHeaders ? {
|
| 630 |
+
status: this.#init?.status,
|
| 631 |
+
statusText: this.#init?.statusText,
|
| 632 |
+
headers: liveHeaders
|
| 633 |
+
} : this.#init);
|
| 634 |
+
}
|
| 635 |
+
constructor(body, init) {
|
| 636 |
+
let headers;
|
| 637 |
+
this.#body = body;
|
| 638 |
+
if (init instanceof GlobalResponse) {
|
| 639 |
+
const cachedGlobalResponse = init[responseCache];
|
| 640 |
+
if (cachedGlobalResponse) {
|
| 641 |
+
this.#init = cachedGlobalResponse;
|
| 642 |
+
this[getResponseCache]();
|
| 643 |
+
return;
|
| 644 |
+
}
|
| 645 |
+
this.#init = init instanceof Response$1 ? init.#init : init;
|
| 646 |
+
headers = new Headers(init.headers);
|
| 647 |
+
} else this.#init = init;
|
| 648 |
+
if (body == null || typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) this[cacheKey] = [
|
| 649 |
+
init?.status || 200,
|
| 650 |
+
body ?? null,
|
| 651 |
+
headers || init?.headers
|
| 652 |
+
];
|
| 653 |
+
}
|
| 654 |
+
get headers() {
|
| 655 |
+
const cache = this[cacheKey];
|
| 656 |
+
if (cache) {
|
| 657 |
+
if (!(cache[2] instanceof Headers)) cache[2] = new Headers(cache[2] || (cache[1] === null ? void 0 : { "content-type": defaultContentType }));
|
| 658 |
+
return cache[2];
|
| 659 |
+
}
|
| 660 |
+
return this[getResponseCache]().headers;
|
| 661 |
+
}
|
| 662 |
+
get status() {
|
| 663 |
+
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
|
| 664 |
+
}
|
| 665 |
+
get ok() {
|
| 666 |
+
const status = this.status;
|
| 667 |
+
return status >= 200 && status < 300;
|
| 668 |
+
}
|
| 669 |
+
};
|
| 670 |
+
[
|
| 671 |
+
"body",
|
| 672 |
+
"bodyUsed",
|
| 673 |
+
"redirected",
|
| 674 |
+
"statusText",
|
| 675 |
+
"trailers",
|
| 676 |
+
"type",
|
| 677 |
+
"url"
|
| 678 |
+
].forEach((k) => {
|
| 679 |
+
Object.defineProperty(Response$1.prototype, k, { get() {
|
| 680 |
+
return this[getResponseCache]()[k];
|
| 681 |
+
} });
|
| 682 |
+
});
|
| 683 |
+
[
|
| 684 |
+
"arrayBuffer",
|
| 685 |
+
"blob",
|
| 686 |
+
"clone",
|
| 687 |
+
"formData",
|
| 688 |
+
"json",
|
| 689 |
+
"text"
|
| 690 |
+
].forEach((k) => {
|
| 691 |
+
Object.defineProperty(Response$1.prototype, k, { value: function() {
|
| 692 |
+
return this[getResponseCache]()[k]();
|
| 693 |
+
} });
|
| 694 |
+
});
|
| 695 |
+
Object.defineProperty(Response$1.prototype, Symbol.for("nodejs.util.inspect.custom"), { value: function(depth, options, inspectFn) {
|
| 696 |
+
return `Response (lightweight) ${inspectFn({
|
| 697 |
+
status: this.status,
|
| 698 |
+
headers: this.headers,
|
| 699 |
+
ok: this.ok,
|
| 700 |
+
nativeResponse: this[responseCache]
|
| 701 |
+
}, {
|
| 702 |
+
...options,
|
| 703 |
+
depth: depth == null ? null : depth - 1
|
| 704 |
+
})}`;
|
| 705 |
+
} });
|
| 706 |
+
Object.setPrototypeOf(Response$1, GlobalResponse);
|
| 707 |
+
Object.setPrototypeOf(Response$1.prototype, GlobalResponse.prototype);
|
| 708 |
+
const validRedirectUrl = /^https?:\/\/[!#-;=?-[\]_a-z~A-Z]+$/;
|
| 709 |
+
const parseRedirectUrl = (url) => {
|
| 710 |
+
if (url instanceof URL) return url.href;
|
| 711 |
+
if (validRedirectUrl.test(url)) return url;
|
| 712 |
+
return new URL(url).href;
|
| 713 |
+
};
|
| 714 |
+
const validRedirectStatuses = new Set([
|
| 715 |
+
301,
|
| 716 |
+
302,
|
| 717 |
+
303,
|
| 718 |
+
307,
|
| 719 |
+
308
|
| 720 |
+
]);
|
| 721 |
+
Object.defineProperty(Response$1, "redirect", {
|
| 722 |
+
value: function redirect(url, status = 302) {
|
| 723 |
+
if (!validRedirectStatuses.has(status)) throw new RangeError("Invalid status code");
|
| 724 |
+
return new Response$1(null, {
|
| 725 |
+
status,
|
| 726 |
+
headers: { location: parseRedirectUrl(url) }
|
| 727 |
+
});
|
| 728 |
+
},
|
| 729 |
+
writable: true,
|
| 730 |
+
configurable: true
|
| 731 |
+
});
|
| 732 |
+
Object.defineProperty(Response$1, "json", {
|
| 733 |
+
value: function json(data, init) {
|
| 734 |
+
const body = JSON.stringify(data);
|
| 735 |
+
if (body === void 0) throw new TypeError("The data is not JSON serializable");
|
| 736 |
+
const initHeaders = init?.headers;
|
| 737 |
+
let headers;
|
| 738 |
+
if (initHeaders) {
|
| 739 |
+
headers = new Headers(initHeaders);
|
| 740 |
+
if (!headers.has("content-type")) headers.set("content-type", "application/json");
|
| 741 |
+
} else headers = { "content-type": "application/json" };
|
| 742 |
+
return new Response$1(body, {
|
| 743 |
+
status: init?.status ?? 200,
|
| 744 |
+
statusText: init?.statusText,
|
| 745 |
+
headers
|
| 746 |
+
});
|
| 747 |
+
},
|
| 748 |
+
writable: true,
|
| 749 |
+
configurable: true
|
| 750 |
+
});
|
| 751 |
+
|
| 752 |
+
//#endregion
|
| 753 |
+
//#region src/utils.ts
|
| 754 |
+
async function readWithoutBlocking(readPromise) {
|
| 755 |
+
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
|
| 756 |
+
}
|
| 757 |
+
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
|
| 758 |
+
const cancel = (error) => {
|
| 759 |
+
reader.cancel(error).catch(() => {});
|
| 760 |
+
};
|
| 761 |
+
writable.on("close", cancel);
|
| 762 |
+
writable.on("error", cancel);
|
| 763 |
+
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
|
| 764 |
+
return reader.closed.finally(() => {
|
| 765 |
+
writable.off("close", cancel);
|
| 766 |
+
writable.off("error", cancel);
|
| 767 |
+
});
|
| 768 |
+
function handleStreamError(error) {
|
| 769 |
+
if (error) writable.destroy(error);
|
| 770 |
+
}
|
| 771 |
+
function onDrain() {
|
| 772 |
+
reader.read().then(flow, handleStreamError);
|
| 773 |
+
}
|
| 774 |
+
function flow({ done, value }) {
|
| 775 |
+
try {
|
| 776 |
+
if (done) writable.end();
|
| 777 |
+
else if (!writable.write(value)) writable.once("drain", onDrain);
|
| 778 |
+
else return reader.read().then(flow, handleStreamError);
|
| 779 |
+
} catch (e) {
|
| 780 |
+
handleStreamError(e);
|
| 781 |
+
}
|
| 782 |
+
}
|
| 783 |
+
}
|
| 784 |
+
function writeFromReadableStream(stream, writable) {
|
| 785 |
+
if (stream.locked) throw new TypeError("ReadableStream is locked.");
|
| 786 |
+
else if (writable.destroyed) return;
|
| 787 |
+
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
|
| 788 |
+
}
|
| 789 |
+
const buildOutgoingHttpHeaders = (headers, defaultContentType) => {
|
| 790 |
+
const res = {};
|
| 791 |
+
if (!(headers instanceof Headers)) headers = new Headers(headers ?? void 0);
|
| 792 |
+
if (headers.has("set-cookie")) {
|
| 793 |
+
const cookies = [];
|
| 794 |
+
for (const [k, v] of headers) if (k === "set-cookie") cookies.push(v);
|
| 795 |
+
else res[k] = v;
|
| 796 |
+
if (cookies.length > 0) res["set-cookie"] = cookies;
|
| 797 |
+
} else for (const [k, v] of headers) res[k] = v;
|
| 798 |
+
if (defaultContentType) res["content-type"] ??= defaultContentType;
|
| 799 |
+
return res;
|
| 800 |
+
};
|
| 801 |
+
|
| 802 |
+
//#endregion
|
| 803 |
+
//#region src/listener.ts
|
| 804 |
+
const outgoingEnded = Symbol("outgoingEnded");
|
| 805 |
+
const incomingDraining = Symbol("incomingDraining");
|
| 806 |
+
const DRAIN_TIMEOUT_MS = 500;
|
| 807 |
+
const MAX_DRAIN_BYTES = 64 * 1024 * 1024;
|
| 808 |
+
const drainIncoming = (incoming) => {
|
| 809 |
+
const incomingWithDrainState = incoming;
|
| 810 |
+
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) return;
|
| 811 |
+
incomingWithDrainState[incomingDraining] = true;
|
| 812 |
+
if (incoming instanceof Http2ServerRequest) {
|
| 813 |
+
try {
|
| 814 |
+
incoming.stream?.close?.(constants.NGHTTP2_NO_ERROR);
|
| 815 |
+
} catch {}
|
| 816 |
+
return;
|
| 817 |
+
}
|
| 818 |
+
let bytesRead = 0;
|
| 819 |
+
const cleanup = () => {
|
| 820 |
+
clearTimeout(timer);
|
| 821 |
+
incoming.off("data", onData);
|
| 822 |
+
incoming.off("end", cleanup);
|
| 823 |
+
incoming.off("error", cleanup);
|
| 824 |
+
};
|
| 825 |
+
const forceClose = () => {
|
| 826 |
+
cleanup();
|
| 827 |
+
const socket = incoming.socket;
|
| 828 |
+
if (socket && !socket.destroyed) {
|
| 829 |
+
if (typeof socket.destroySoon === "function") socket.destroySoon();
|
| 830 |
+
else if (typeof socket.destroy === "function") socket.destroy();
|
| 831 |
+
}
|
| 832 |
+
};
|
| 833 |
+
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
|
| 834 |
+
timer.unref?.();
|
| 835 |
+
const onData = (chunk) => {
|
| 836 |
+
bytesRead += chunk.length;
|
| 837 |
+
if (bytesRead > MAX_DRAIN_BYTES) forceClose();
|
| 838 |
+
};
|
| 839 |
+
incoming.on("data", onData);
|
| 840 |
+
incoming.on("end", cleanup);
|
| 841 |
+
incoming.on("error", cleanup);
|
| 842 |
+
incoming.resume();
|
| 843 |
+
};
|
| 844 |
+
const makeCloseHandler = (req, incoming, outgoing, needsBodyCleanup) => () => {
|
| 845 |
+
if (incoming.errored) {
|
| 846 |
+
recordBodyBufferedBeforeDisconnect(incoming);
|
| 847 |
+
req[abortRequest](incoming.errored.toString());
|
| 848 |
+
} else if (!outgoing.writableFinished) {
|
| 849 |
+
recordBodyBufferedBeforeDisconnect(incoming);
|
| 850 |
+
req[abortRequest]("Client connection prematurely closed.");
|
| 851 |
+
}
|
| 852 |
+
if (needsBodyCleanup && !incoming.readableEnded) setTimeout(() => {
|
| 853 |
+
if (!incoming.readableEnded) setTimeout(() => {
|
| 854 |
+
drainIncoming(incoming);
|
| 855 |
+
});
|
| 856 |
+
});
|
| 857 |
+
};
|
| 858 |
+
const isImmediateCacheableResponse = (res) => {
|
| 859 |
+
if (!(cacheKey in res)) return false;
|
| 860 |
+
const body = res[cacheKey][1];
|
| 861 |
+
return body === null || typeof body === "string" || body instanceof Uint8Array;
|
| 862 |
+
};
|
| 863 |
+
const handleRequestError = () => new Response(null, { status: 400 });
|
| 864 |
+
const handleFetchError = (e) => new Response(null, { status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500 });
|
| 865 |
+
const handleResponseError = (e, outgoing) => {
|
| 866 |
+
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
|
| 867 |
+
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") console.info("The user aborted a request.");
|
| 868 |
+
else {
|
| 869 |
+
console.error(e);
|
| 870 |
+
if (!outgoing.headersSent) {
|
| 871 |
+
if (outgoing instanceof ServerResponse) outgoing._contentLength = null;
|
| 872 |
+
outgoing.writeHead(500, { "Content-Type": "text/plain" });
|
| 873 |
+
}
|
| 874 |
+
outgoing.end(`Error: ${err.message}`);
|
| 875 |
+
outgoing.destroy(err);
|
| 876 |
+
}
|
| 877 |
+
};
|
| 878 |
+
const flushHeaders = (outgoing) => {
|
| 879 |
+
if ("flushHeaders" in outgoing && outgoing.writable) outgoing.flushHeaders();
|
| 880 |
+
};
|
| 881 |
+
const trySetContentLength = (outgoing, status, length) => {
|
| 882 |
+
const http1 = outgoing;
|
| 883 |
+
if (http1._contentLength === null && http1._hasBody && http1.useChunkedEncodingByDefault && !http1._removedContLen && status >= 200 && status !== 204 && status !== 304 && !outgoing.hasHeader("content-length") && !outgoing.hasHeader("transfer-encoding") && !outgoing.hasHeader("trailer")) {
|
| 884 |
+
http1._contentLength = length;
|
| 885 |
+
return true;
|
| 886 |
+
}
|
| 887 |
+
return false;
|
| 888 |
+
};
|
| 889 |
+
const writeDefaultHeaders = (outgoing, status, length) => {
|
| 890 |
+
if (trySetContentLength(outgoing, status, length)) outgoing.writeHead(status, { "Content-Type": defaultContentType });
|
| 891 |
+
else outgoing.writeHead(status, {
|
| 892 |
+
"Content-Type": defaultContentType,
|
| 893 |
+
"Content-Length": length
|
| 894 |
+
});
|
| 895 |
+
};
|
| 896 |
+
const responseViaCache = async (res, outgoing) => {
|
| 897 |
+
let [status, body, header] = res[cacheKey];
|
| 898 |
+
if (!header) {
|
| 899 |
+
if (body === null) {
|
| 900 |
+
outgoing.writeHead(status);
|
| 901 |
+
outgoing.end();
|
| 902 |
+
} else if (typeof body === "string") {
|
| 903 |
+
writeDefaultHeaders(outgoing, status, Buffer.byteLength(body));
|
| 904 |
+
outgoing.end(body);
|
| 905 |
+
} else if (body instanceof Uint8Array) {
|
| 906 |
+
writeDefaultHeaders(outgoing, status, body.byteLength);
|
| 907 |
+
outgoing.end(body);
|
| 908 |
+
} else if (body instanceof Blob) {
|
| 909 |
+
writeDefaultHeaders(outgoing, status, body.size);
|
| 910 |
+
outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
| 911 |
+
} else {
|
| 912 |
+
outgoing.writeHead(status, { "Content-Type": defaultContentType });
|
| 913 |
+
flushHeaders(outgoing);
|
| 914 |
+
await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
|
| 915 |
+
}
|
| 916 |
+
outgoing[outgoingEnded]?.();
|
| 917 |
+
return;
|
| 918 |
+
}
|
| 919 |
+
let hasContentLength = false;
|
| 920 |
+
let plainHeaders = false;
|
| 921 |
+
let canAutoLength = true;
|
| 922 |
+
if (header instanceof Headers) {
|
| 923 |
+
hasContentLength = header.has("content-length");
|
| 924 |
+
header = buildOutgoingHttpHeaders(header, body === null ? void 0 : defaultContentType);
|
| 925 |
+
} else if (Array.isArray(header)) {
|
| 926 |
+
const headerObj = new Headers(header);
|
| 927 |
+
hasContentLength = headerObj.has("content-length");
|
| 928 |
+
header = buildOutgoingHttpHeaders(headerObj, body === null ? void 0 : defaultContentType);
|
| 929 |
+
} else {
|
| 930 |
+
plainHeaders = true;
|
| 931 |
+
for (const key in header) {
|
| 932 |
+
if (key.length === 14 && key.toLowerCase() === "content-length") {
|
| 933 |
+
hasContentLength = true;
|
| 934 |
+
break;
|
| 935 |
+
}
|
| 936 |
+
if (key.length === 17 && key.toLowerCase() === "transfer-encoding" || key.length === 7 && key.toLowerCase() === "trailer") canAutoLength = false;
|
| 937 |
+
}
|
| 938 |
+
}
|
| 939 |
+
if (!hasContentLength) {
|
| 940 |
+
let length;
|
| 941 |
+
if (typeof body === "string") length = Buffer.byteLength(body);
|
| 942 |
+
else if (body instanceof Uint8Array) length = body.byteLength;
|
| 943 |
+
else if (body instanceof Blob) length = body.size;
|
| 944 |
+
if (length !== void 0 && (!plainHeaders || !canAutoLength || !trySetContentLength(outgoing, status, length))) {
|
| 945 |
+
if (plainHeaders) header = { ...header };
|
| 946 |
+
header["Content-Length"] = length;
|
| 947 |
+
}
|
| 948 |
+
}
|
| 949 |
+
outgoing.writeHead(status, header);
|
| 950 |
+
if (body == null) outgoing.end();
|
| 951 |
+
else if (typeof body === "string" || body instanceof Uint8Array) outgoing.end(body);
|
| 952 |
+
else if (body instanceof Blob) outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
| 953 |
+
else {
|
| 954 |
+
flushHeaders(outgoing);
|
| 955 |
+
await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
|
| 956 |
+
}
|
| 957 |
+
outgoing[outgoingEnded]?.();
|
| 958 |
+
};
|
| 959 |
+
const isPromise = (res) => typeof res.then === "function";
|
| 960 |
+
const responseViaResponseObject = async (res, outgoing, options = {}) => {
|
| 961 |
+
if (isPromise(res)) if (options.errorHandler) try {
|
| 962 |
+
res = await res;
|
| 963 |
+
} catch (err) {
|
| 964 |
+
const errRes = await options.errorHandler(err);
|
| 965 |
+
if (!errRes) return;
|
| 966 |
+
res = errRes;
|
| 967 |
+
}
|
| 968 |
+
else res = await res.catch(handleFetchError);
|
| 969 |
+
if (cacheKey in res) return responseViaCache(res, outgoing);
|
| 970 |
+
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers, res.body === null ? void 0 : defaultContentType);
|
| 971 |
+
if (res.body) {
|
| 972 |
+
const reader = res.body.getReader();
|
| 973 |
+
const values = [];
|
| 974 |
+
let done = false;
|
| 975 |
+
let currentReadPromise = void 0;
|
| 976 |
+
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
|
| 977 |
+
let maxReadCount = 2;
|
| 978 |
+
for (let i = 0; i < maxReadCount; i++) {
|
| 979 |
+
currentReadPromise ||= reader.read();
|
| 980 |
+
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
|
| 981 |
+
console.error(e);
|
| 982 |
+
done = true;
|
| 983 |
+
});
|
| 984 |
+
if (!chunk) {
|
| 985 |
+
if (i === 1) {
|
| 986 |
+
await new Promise((resolve) => setTimeout(resolve));
|
| 987 |
+
maxReadCount = 3;
|
| 988 |
+
continue;
|
| 989 |
+
}
|
| 990 |
+
break;
|
| 991 |
+
}
|
| 992 |
+
currentReadPromise = void 0;
|
| 993 |
+
if (chunk.value) values.push(chunk.value);
|
| 994 |
+
if (chunk.done) {
|
| 995 |
+
done = true;
|
| 996 |
+
break;
|
| 997 |
+
}
|
| 998 |
+
}
|
| 999 |
+
if (done && !("content-length" in resHeaderRecord)) resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
|
| 1000 |
+
}
|
| 1001 |
+
outgoing.writeHead(res.status, resHeaderRecord);
|
| 1002 |
+
values.forEach((value) => {
|
| 1003 |
+
outgoing.write(value);
|
| 1004 |
+
});
|
| 1005 |
+
if (done) outgoing.end();
|
| 1006 |
+
else {
|
| 1007 |
+
if (values.length === 0) flushHeaders(outgoing);
|
| 1008 |
+
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
|
| 1009 |
+
}
|
| 1010 |
+
} else if (resHeaderRecord[X_ALREADY_SENT]) {} else {
|
| 1011 |
+
outgoing.writeHead(res.status, resHeaderRecord);
|
| 1012 |
+
outgoing.end();
|
| 1013 |
+
}
|
| 1014 |
+
outgoing[outgoingEnded]?.();
|
| 1015 |
+
};
|
| 1016 |
+
const getRequestListener = (fetchCallback, options = {}) => {
|
| 1017 |
+
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
|
| 1018 |
+
if (options.overrideGlobalObjects !== false && global.Request !== Request$1) {
|
| 1019 |
+
Object.defineProperty(global, "Request", { value: Request$1 });
|
| 1020 |
+
Object.defineProperty(global, "Response", { value: Response$1 });
|
| 1021 |
+
}
|
| 1022 |
+
return async (incoming, outgoing) => {
|
| 1023 |
+
let res, req;
|
| 1024 |
+
let needsBodyCleanup = false;
|
| 1025 |
+
let closeHandlerAttached = false;
|
| 1026 |
+
const ensureCloseHandler = () => {
|
| 1027 |
+
if (!req || closeHandlerAttached) return;
|
| 1028 |
+
closeHandlerAttached = true;
|
| 1029 |
+
outgoing.on("close", makeCloseHandler(req, incoming, outgoing, needsBodyCleanup));
|
| 1030 |
+
};
|
| 1031 |
+
try {
|
| 1032 |
+
req = newRequest(incoming, options.hostname);
|
| 1033 |
+
needsBodyCleanup = autoCleanupIncoming && !(incoming.method === "GET" || incoming.method === "HEAD");
|
| 1034 |
+
if (needsBodyCleanup) {
|
| 1035 |
+
incoming[wrapBodyStream] = true;
|
| 1036 |
+
if (incoming instanceof Http2ServerRequest) outgoing[outgoingEnded] = () => {
|
| 1037 |
+
if (!incoming.readableEnded) setTimeout(() => {
|
| 1038 |
+
if (!incoming.readableEnded) setTimeout(() => {
|
| 1039 |
+
incoming.destroy();
|
| 1040 |
+
outgoing.destroy();
|
| 1041 |
+
});
|
| 1042 |
+
});
|
| 1043 |
+
};
|
| 1044 |
+
}
|
| 1045 |
+
res = fetchCallback(req, {
|
| 1046 |
+
incoming,
|
| 1047 |
+
outgoing
|
| 1048 |
+
});
|
| 1049 |
+
if (!isPromise(res) && isImmediateCacheableResponse(res)) {
|
| 1050 |
+
if (needsBodyCleanup && !incoming.readableEnded) outgoing.once("finish", () => {
|
| 1051 |
+
if (!incoming.readableEnded) drainIncoming(incoming);
|
| 1052 |
+
});
|
| 1053 |
+
return responseViaCache(res, outgoing);
|
| 1054 |
+
}
|
| 1055 |
+
ensureCloseHandler();
|
| 1056 |
+
} catch (e) {
|
| 1057 |
+
if (!res) if (options.errorHandler) {
|
| 1058 |
+
ensureCloseHandler();
|
| 1059 |
+
res = await options.errorHandler(req ? e : toRequestError(e));
|
| 1060 |
+
if (!res) return;
|
| 1061 |
+
} else if (!req) res = handleRequestError();
|
| 1062 |
+
else res = handleFetchError(e);
|
| 1063 |
+
else return handleResponseError(e, outgoing);
|
| 1064 |
+
}
|
| 1065 |
+
try {
|
| 1066 |
+
return await responseViaResponseObject(res, outgoing, options);
|
| 1067 |
+
} catch (e) {
|
| 1068 |
+
return handleResponseError(e, outgoing);
|
| 1069 |
+
}
|
| 1070 |
+
};
|
| 1071 |
+
};
|
| 1072 |
+
|
| 1073 |
+
//#endregion
|
| 1074 |
+
//#region src/websocket.ts
|
| 1075 |
+
/**
|
| 1076 |
+
* @link https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
|
| 1077 |
+
*/
|
| 1078 |
+
const CloseEvent = globalThis.CloseEvent ?? class extends Event {
|
| 1079 |
+
#eventInitDict;
|
| 1080 |
+
constructor(type, eventInitDict = {}) {
|
| 1081 |
+
super(type, eventInitDict);
|
| 1082 |
+
this.#eventInitDict = eventInitDict;
|
| 1083 |
+
}
|
| 1084 |
+
get wasClean() {
|
| 1085 |
+
return this.#eventInitDict.wasClean ?? false;
|
| 1086 |
+
}
|
| 1087 |
+
get code() {
|
| 1088 |
+
return this.#eventInitDict.code ?? 0;
|
| 1089 |
+
}
|
| 1090 |
+
get reason() {
|
| 1091 |
+
return this.#eventInitDict.reason ?? "";
|
| 1092 |
+
}
|
| 1093 |
+
};
|
| 1094 |
+
/**
|
| 1095 |
+
* Node.js has no global `ErrorEvent`, unlike `Event`/`MessageEvent`/`CloseEvent`.
|
| 1096 |
+
* @link https://developer.mozilla.org/en-US/docs/Web/API/ErrorEvent
|
| 1097 |
+
*/
|
| 1098 |
+
const ErrorEvent = globalThis.ErrorEvent ?? class extends Event {
|
| 1099 |
+
#eventInitDict;
|
| 1100 |
+
constructor(type, eventInitDict = {}) {
|
| 1101 |
+
super(type, eventInitDict);
|
| 1102 |
+
this.#eventInitDict = eventInitDict;
|
| 1103 |
+
}
|
| 1104 |
+
get message() {
|
| 1105 |
+
return this.#eventInitDict.message ?? "";
|
| 1106 |
+
}
|
| 1107 |
+
get filename() {
|
| 1108 |
+
return this.#eventInitDict.filename ?? "";
|
| 1109 |
+
}
|
| 1110 |
+
get lineno() {
|
| 1111 |
+
return this.#eventInitDict.lineno ?? 0;
|
| 1112 |
+
}
|
| 1113 |
+
get colno() {
|
| 1114 |
+
return this.#eventInitDict.colno ?? 0;
|
| 1115 |
+
}
|
| 1116 |
+
get error() {
|
| 1117 |
+
return this.#eventInitDict.error ?? null;
|
| 1118 |
+
}
|
| 1119 |
+
};
|
| 1120 |
+
const generateConnectionSymbol = () => Symbol("connection");
|
| 1121 |
+
const CONNECTION_SYMBOL_KEY = Symbol("CONNECTION_SYMBOL_KEY");
|
| 1122 |
+
const WAIT_FOR_WEBSOCKET_SYMBOL = Symbol("WAIT_FOR_WEBSOCKET_SYMBOL");
|
| 1123 |
+
const responseHeadersToSkip = new Set([
|
| 1124 |
+
"connection",
|
| 1125 |
+
"content-length",
|
| 1126 |
+
"keep-alive",
|
| 1127 |
+
"proxy-authenticate",
|
| 1128 |
+
"proxy-authorization",
|
| 1129 |
+
"te",
|
| 1130 |
+
"trailer",
|
| 1131 |
+
"transfer-encoding",
|
| 1132 |
+
"upgrade",
|
| 1133 |
+
"sec-websocket-accept",
|
| 1134 |
+
"sec-websocket-extensions",
|
| 1135 |
+
"sec-websocket-protocol"
|
| 1136 |
+
]);
|
| 1137 |
+
const appendResponseHeaders = (headers, responseHeaders) => {
|
| 1138 |
+
if (!responseHeaders) return;
|
| 1139 |
+
responseHeaders.forEach((value, key) => {
|
| 1140 |
+
if (responseHeadersToSkip.has(key.toLowerCase())) return;
|
| 1141 |
+
headers.push(`${key}: ${value}`);
|
| 1142 |
+
});
|
| 1143 |
+
};
|
| 1144 |
+
const rejectUpgradeRequest = (socket, status, responseHeaders) => {
|
| 1145 |
+
const responseLines = ["Connection: close", "Content-Length: 0"];
|
| 1146 |
+
appendResponseHeaders(responseLines, responseHeaders);
|
| 1147 |
+
socket.end(`HTTP/1.1 ${status.toString()} ${STATUS_CODES[status] ?? ""}\r\n${responseLines.join("\r\n")}\r\n\r
|
| 1148 |
+
`);
|
| 1149 |
+
};
|
| 1150 |
+
const createUpgradeRequest = (request) => {
|
| 1151 |
+
const protocol = request.socket.encrypted ? "https" : "http";
|
| 1152 |
+
const url = new URL(request.url ?? "/", `${protocol}://${request.headers.host ?? "localhost"}`);
|
| 1153 |
+
const headers = new Headers();
|
| 1154 |
+
for (const key in request.headers) {
|
| 1155 |
+
const value = request.headers[key];
|
| 1156 |
+
if (!value) continue;
|
| 1157 |
+
headers.append(key, Array.isArray(value) ? value[0] : value);
|
| 1158 |
+
}
|
| 1159 |
+
return new Request(url, { headers });
|
| 1160 |
+
};
|
| 1161 |
+
const setupWebSocket = (options) => {
|
| 1162 |
+
const { server, fetchCallback, wss } = options;
|
| 1163 |
+
const waiterMap = /* @__PURE__ */ new Map();
|
| 1164 |
+
wss.on("connection", (ws, request) => {
|
| 1165 |
+
const waiter = waiterMap.get(request);
|
| 1166 |
+
if (waiter) {
|
| 1167 |
+
waiter.resolve(ws);
|
| 1168 |
+
waiterMap.delete(request);
|
| 1169 |
+
}
|
| 1170 |
+
});
|
| 1171 |
+
const rejectWaiter = (request) => {
|
| 1172 |
+
const waiter = waiterMap.get(request);
|
| 1173 |
+
if (waiter) {
|
| 1174 |
+
waiterMap.delete(request);
|
| 1175 |
+
waiter.reject(/* @__PURE__ */ new Error("WebSocket handshake aborted"));
|
| 1176 |
+
}
|
| 1177 |
+
};
|
| 1178 |
+
const waitForWebSocket = (request, connectionSymbol) => {
|
| 1179 |
+
return new Promise((resolve, reject) => {
|
| 1180 |
+
waiterMap.set(request, {
|
| 1181 |
+
resolve,
|
| 1182 |
+
reject,
|
| 1183 |
+
connectionSymbol
|
| 1184 |
+
});
|
| 1185 |
+
});
|
| 1186 |
+
};
|
| 1187 |
+
server.on("upgrade", async (request, socket, head) => {
|
| 1188 |
+
if (request.headers.upgrade?.toLowerCase() !== "websocket") return;
|
| 1189 |
+
const env = {
|
| 1190 |
+
incoming: request,
|
| 1191 |
+
outgoing: void 0,
|
| 1192 |
+
wss,
|
| 1193 |
+
[WAIT_FOR_WEBSOCKET_SYMBOL]: waitForWebSocket
|
| 1194 |
+
};
|
| 1195 |
+
let status = 400;
|
| 1196 |
+
let responseHeaders;
|
| 1197 |
+
try {
|
| 1198 |
+
const response = await fetchCallback(createUpgradeRequest(request), env);
|
| 1199 |
+
if (response instanceof Response) {
|
| 1200 |
+
status = response.status;
|
| 1201 |
+
responseHeaders = response.headers;
|
| 1202 |
+
}
|
| 1203 |
+
} catch {
|
| 1204 |
+
if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, 500);
|
| 1205 |
+
return;
|
| 1206 |
+
}
|
| 1207 |
+
const waiter = waiterMap.get(request);
|
| 1208 |
+
if (!waiter || waiter.connectionSymbol !== env[CONNECTION_SYMBOL_KEY]) {
|
| 1209 |
+
rejectWaiter(request);
|
| 1210 |
+
if (server.listenerCount("upgrade") === 1) rejectUpgradeRequest(socket, status, responseHeaders);
|
| 1211 |
+
return;
|
| 1212 |
+
}
|
| 1213 |
+
const addResponseHeaders = (headers) => {
|
| 1214 |
+
appendResponseHeaders(headers, responseHeaders);
|
| 1215 |
+
};
|
| 1216 |
+
const reclaimWaiterOnClose = () => rejectWaiter(request);
|
| 1217 |
+
socket.once("close", reclaimWaiterOnClose);
|
| 1218 |
+
wss.on("headers", addResponseHeaders);
|
| 1219 |
+
try {
|
| 1220 |
+
wss.handleUpgrade(request, socket, head, (ws) => {
|
| 1221 |
+
socket.off("close", reclaimWaiterOnClose);
|
| 1222 |
+
wss.emit("connection", ws, request);
|
| 1223 |
+
});
|
| 1224 |
+
} finally {
|
| 1225 |
+
wss.off("headers", addResponseHeaders);
|
| 1226 |
+
}
|
| 1227 |
+
});
|
| 1228 |
+
server.on("close", () => {
|
| 1229 |
+
wss.close();
|
| 1230 |
+
});
|
| 1231 |
+
};
|
| 1232 |
+
const upgradeWebSocket = defineWebSocketHelper(async (c, events, options) => {
|
| 1233 |
+
if (c.req.header("upgrade")?.toLowerCase() !== "websocket") return;
|
| 1234 |
+
const env = c.env;
|
| 1235 |
+
const waitForWebSocket = env[WAIT_FOR_WEBSOCKET_SYMBOL];
|
| 1236 |
+
if (!waitForWebSocket || !env.incoming) return new Response(null, { status: 500 });
|
| 1237 |
+
const connectionSymbol = generateConnectionSymbol();
|
| 1238 |
+
env[CONNECTION_SYMBOL_KEY] = connectionSymbol;
|
| 1239 |
+
(async () => {
|
| 1240 |
+
let ws;
|
| 1241 |
+
try {
|
| 1242 |
+
ws = await waitForWebSocket(env.incoming, connectionSymbol);
|
| 1243 |
+
} catch {
|
| 1244 |
+
return;
|
| 1245 |
+
}
|
| 1246 |
+
const messagesReceivedInStarting = [];
|
| 1247 |
+
const bufferMessage = (data, isBinary) => {
|
| 1248 |
+
messagesReceivedInStarting.push([data, isBinary]);
|
| 1249 |
+
};
|
| 1250 |
+
ws.on("message", bufferMessage);
|
| 1251 |
+
const ctx = {
|
| 1252 |
+
binaryType: "arraybuffer",
|
| 1253 |
+
close(code, reason) {
|
| 1254 |
+
ws.close(code, reason);
|
| 1255 |
+
},
|
| 1256 |
+
protocol: ws.protocol,
|
| 1257 |
+
raw: ws,
|
| 1258 |
+
get readyState() {
|
| 1259 |
+
return ws.readyState;
|
| 1260 |
+
},
|
| 1261 |
+
send(source, opts) {
|
| 1262 |
+
ws.send(source, { compress: opts?.compress });
|
| 1263 |
+
},
|
| 1264 |
+
url: new URL(c.req.url)
|
| 1265 |
+
};
|
| 1266 |
+
try {
|
| 1267 |
+
events?.onOpen?.(new Event("open"), ctx);
|
| 1268 |
+
} catch (e) {
|
| 1269 |
+
(options?.onError ?? console.error)(e);
|
| 1270 |
+
}
|
| 1271 |
+
const handleMessage = (data, isBinary) => {
|
| 1272 |
+
const datas = Array.isArray(data) ? data : [data];
|
| 1273 |
+
for (const data of datas) try {
|
| 1274 |
+
events?.onMessage?.(new MessageEvent("message", { data: isBinary ? data instanceof ArrayBuffer ? data : data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength) : typeof data === "string" ? data : Buffer.from(data).toString("utf-8") }), ctx);
|
| 1275 |
+
} catch (e) {
|
| 1276 |
+
(options?.onError ?? console.error)(e);
|
| 1277 |
+
}
|
| 1278 |
+
};
|
| 1279 |
+
ws.off("message", bufferMessage);
|
| 1280 |
+
for (const message of messagesReceivedInStarting) handleMessage(...message);
|
| 1281 |
+
ws.on("message", (data, isBinary) => {
|
| 1282 |
+
handleMessage(data, isBinary);
|
| 1283 |
+
});
|
| 1284 |
+
ws.on("close", (code, reason) => {
|
| 1285 |
+
try {
|
| 1286 |
+
events?.onClose?.(new CloseEvent("close", {
|
| 1287 |
+
code,
|
| 1288 |
+
reason: reason.toString()
|
| 1289 |
+
}), ctx);
|
| 1290 |
+
} catch (e) {
|
| 1291 |
+
(options?.onError ?? console.error)(e);
|
| 1292 |
+
}
|
| 1293 |
+
});
|
| 1294 |
+
ws.on("error", (error) => {
|
| 1295 |
+
try {
|
| 1296 |
+
events?.onError?.(new ErrorEvent("error", { error }), ctx);
|
| 1297 |
+
} catch (e) {
|
| 1298 |
+
(options?.onError ?? console.error)(e);
|
| 1299 |
+
}
|
| 1300 |
+
});
|
| 1301 |
+
})();
|
| 1302 |
+
return new Response();
|
| 1303 |
+
});
|
| 1304 |
+
|
| 1305 |
+
//#endregion
|
| 1306 |
+
//#region src/server.ts
|
| 1307 |
+
const createAdaptorServer = (options) => {
|
| 1308 |
+
const fetchCallback = options.fetch;
|
| 1309 |
+
const requestListener = getRequestListener(fetchCallback, {
|
| 1310 |
+
hostname: options.hostname,
|
| 1311 |
+
overrideGlobalObjects: options.overrideGlobalObjects,
|
| 1312 |
+
autoCleanupIncoming: options.autoCleanupIncoming
|
| 1313 |
+
});
|
| 1314 |
+
const server = (options.createServer || createServer)(options.serverOptions || {}, requestListener);
|
| 1315 |
+
if (options.websocket && options.websocket.server) {
|
| 1316 |
+
if (options.websocket.server.options.noServer !== true) throw new Error("WebSocket server must be created with { noServer: true } option");
|
| 1317 |
+
setupWebSocket({
|
| 1318 |
+
server,
|
| 1319 |
+
fetchCallback,
|
| 1320 |
+
wss: options.websocket.server
|
| 1321 |
+
});
|
| 1322 |
+
}
|
| 1323 |
+
return server;
|
| 1324 |
+
};
|
| 1325 |
+
const serve = (options, listeningListener) => {
|
| 1326 |
+
const server = createAdaptorServer(options);
|
| 1327 |
+
server.listen(options?.port ?? 3e3, options.hostname, () => {
|
| 1328 |
+
const serverInfo = server.address();
|
| 1329 |
+
listeningListener && listeningListener(serverInfo);
|
| 1330 |
+
});
|
| 1331 |
+
return server;
|
| 1332 |
+
};
|
| 1333 |
+
|
| 1334 |
+
//#endregion
|
| 1335 |
+
export { RequestError, createAdaptorServer, getRequestListener, serve, upgradeWebSocket };
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/serve-static.cjs
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
| 2 |
+
const require_utils_stream = require('./utils/stream.cjs');
|
| 3 |
+
let hono_utils_mime = require("hono/utils/mime");
|
| 4 |
+
let node_fs = require("node:fs");
|
| 5 |
+
let node_path = require("node:path");
|
| 6 |
+
|
| 7 |
+
//#region src/serve-static.ts
|
| 8 |
+
const COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
|
| 9 |
+
const ENCODINGS = {
|
| 10 |
+
br: ".br",
|
| 11 |
+
zstd: ".zst",
|
| 12 |
+
gzip: ".gz"
|
| 13 |
+
};
|
| 14 |
+
const ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);
|
| 15 |
+
const getStats = (path) => {
|
| 16 |
+
let stats;
|
| 17 |
+
try {
|
| 18 |
+
stats = (0, node_fs.statSync)(path);
|
| 19 |
+
} catch {}
|
| 20 |
+
return stats;
|
| 21 |
+
};
|
| 22 |
+
const BYTE_RANGE_PATTERN = /^(?:bytes=)?(?!-$)(\d*)-(\d*)$/;
|
| 23 |
+
const parseByteRange = (range) => {
|
| 24 |
+
const match = range.match(BYTE_RANGE_PATTERN);
|
| 25 |
+
if (!match) return;
|
| 26 |
+
const [, start, end] = match;
|
| 27 |
+
if (start === "") return {
|
| 28 |
+
type: "suffix",
|
| 29 |
+
length: Number(end)
|
| 30 |
+
};
|
| 31 |
+
if (end === "") return {
|
| 32 |
+
type: "open-ended",
|
| 33 |
+
start: Number(start)
|
| 34 |
+
};
|
| 35 |
+
return {
|
| 36 |
+
type: "bounded",
|
| 37 |
+
start: Number(start),
|
| 38 |
+
end: Number(end)
|
| 39 |
+
};
|
| 40 |
+
};
|
| 41 |
+
const resolveByteRange = (spec, size) => {
|
| 42 |
+
if (size === 0) return;
|
| 43 |
+
if (spec.type === "suffix") {
|
| 44 |
+
if (spec.length === 0) return;
|
| 45 |
+
return {
|
| 46 |
+
start: Math.max(size - spec.length, 0),
|
| 47 |
+
end: size - 1
|
| 48 |
+
};
|
| 49 |
+
}
|
| 50 |
+
const end = spec.type === "bounded" ? Math.min(spec.end, size - 1) : size - 1;
|
| 51 |
+
if (spec.start >= size || spec.start > end) return;
|
| 52 |
+
return {
|
| 53 |
+
start: spec.start,
|
| 54 |
+
end
|
| 55 |
+
};
|
| 56 |
+
};
|
| 57 |
+
const tryDecode = (str, decoder) => {
|
| 58 |
+
try {
|
| 59 |
+
return decoder(str);
|
| 60 |
+
} catch {
|
| 61 |
+
return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
|
| 62 |
+
try {
|
| 63 |
+
return decoder(match);
|
| 64 |
+
} catch {
|
| 65 |
+
return match;
|
| 66 |
+
}
|
| 67 |
+
});
|
| 68 |
+
}
|
| 69 |
+
};
|
| 70 |
+
const tryDecodeURI = (str) => tryDecode(str, decodeURI);
|
| 71 |
+
const serveStatic = (options = { root: "" }) => {
|
| 72 |
+
const root = options.root || "";
|
| 73 |
+
const optionPath = options.path;
|
| 74 |
+
if (root !== "" && !(0, node_fs.existsSync)(root)) console.error(`serveStatic: root path '${root}' is not found, are you sure it's correct?`);
|
| 75 |
+
return async (c, next) => {
|
| 76 |
+
if (c.finalized) return next();
|
| 77 |
+
let filename;
|
| 78 |
+
if (optionPath) filename = optionPath;
|
| 79 |
+
else try {
|
| 80 |
+
if (!options.allowPercentInPath && c.req.path.includes("%")) throw new Error();
|
| 81 |
+
filename = tryDecodeURI(c.req.path);
|
| 82 |
+
if (/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(filename)) throw new Error();
|
| 83 |
+
} catch {
|
| 84 |
+
await options.onNotFound?.(c.req.path, c);
|
| 85 |
+
return next();
|
| 86 |
+
}
|
| 87 |
+
let path = (0, node_path.join)(root, !optionPath && options.rewriteRequestPath ? options.rewriteRequestPath(filename, c) : filename);
|
| 88 |
+
let stats = getStats(path);
|
| 89 |
+
if (stats && stats.isDirectory()) {
|
| 90 |
+
const indexFile = options.index ?? "index.html";
|
| 91 |
+
path = (0, node_path.join)(path, indexFile);
|
| 92 |
+
stats = getStats(path);
|
| 93 |
+
}
|
| 94 |
+
if (!stats) {
|
| 95 |
+
await options.onNotFound?.(path, c);
|
| 96 |
+
return next();
|
| 97 |
+
}
|
| 98 |
+
const mimeType = (0, hono_utils_mime.getMimeType)(path);
|
| 99 |
+
c.header("Content-Type", mimeType || "application/octet-stream");
|
| 100 |
+
if (options.precompressed && (!mimeType || mimeType === "application/octet-stream" || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {
|
| 101 |
+
const acceptEncodingSet = new Set(c.req.header("Accept-Encoding")?.split(",").map((encoding) => encoding.trim()));
|
| 102 |
+
for (const encoding of ENCODINGS_ORDERED_KEYS) {
|
| 103 |
+
if (!acceptEncodingSet.has(encoding)) continue;
|
| 104 |
+
const precompressedStats = getStats(path + ENCODINGS[encoding]);
|
| 105 |
+
if (precompressedStats) {
|
| 106 |
+
c.header("Content-Encoding", encoding);
|
| 107 |
+
c.header("Vary", "Accept-Encoding", { append: true });
|
| 108 |
+
stats = precompressedStats;
|
| 109 |
+
path = path + ENCODINGS[encoding];
|
| 110 |
+
break;
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
}
|
| 114 |
+
let result;
|
| 115 |
+
const size = stats.size;
|
| 116 |
+
const range = c.req.header("range") || "";
|
| 117 |
+
c.header("Last-Modified", stats.mtime.toUTCString());
|
| 118 |
+
if (c.req.method == "HEAD" || c.req.method == "OPTIONS") {
|
| 119 |
+
c.header("Content-Length", size.toString());
|
| 120 |
+
c.status(200);
|
| 121 |
+
result = c.body(null);
|
| 122 |
+
} else if (!range) {
|
| 123 |
+
c.header("Content-Length", size.toString());
|
| 124 |
+
result = c.body(require_utils_stream.createStreamBody((0, node_fs.createReadStream)(path)), 200);
|
| 125 |
+
} else {
|
| 126 |
+
c.header("Accept-Ranges", "bytes");
|
| 127 |
+
const resolvedRange = resolveByteRange(parseByteRange(range) ?? {
|
| 128 |
+
type: "open-ended",
|
| 129 |
+
start: 0
|
| 130 |
+
}, size);
|
| 131 |
+
if (!resolvedRange) {
|
| 132 |
+
c.header("Content-Range", `bytes */${size}`);
|
| 133 |
+
result = c.body(null, 416);
|
| 134 |
+
} else {
|
| 135 |
+
const { start, end } = resolvedRange;
|
| 136 |
+
const chunkSize = end - start + 1;
|
| 137 |
+
const stream = (0, node_fs.createReadStream)(path, {
|
| 138 |
+
start,
|
| 139 |
+
end
|
| 140 |
+
});
|
| 141 |
+
c.header("Content-Length", chunkSize.toString());
|
| 142 |
+
c.header("Content-Range", `bytes ${start}-${end}/${size}`);
|
| 143 |
+
result = c.body(require_utils_stream.createStreamBody(stream), 206);
|
| 144 |
+
}
|
| 145 |
+
}
|
| 146 |
+
await options.onFound?.(path, c);
|
| 147 |
+
return result;
|
| 148 |
+
};
|
| 149 |
+
};
|
| 150 |
+
|
| 151 |
+
//#endregion
|
| 152 |
+
exports.serveStatic = serveStatic;
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/serve-static.d.cts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { Context, Env, MiddlewareHandler } from "hono";
|
| 2 |
+
|
| 3 |
+
//#region src/serve-static.d.ts
|
| 4 |
+
type ServeStaticOptions<E extends Env = Env> = {
|
| 5 |
+
/**
|
| 6 |
+
* Root path. Relative path is based on current working directory from which the app was started.
|
| 7 |
+
*/
|
| 8 |
+
root?: string;
|
| 9 |
+
path?: string;
|
| 10 |
+
index?: string;
|
| 11 |
+
precompressed?: boolean; /** Allow percent signs in the routed request path. Defaults to false. */
|
| 12 |
+
allowPercentInPath?: boolean;
|
| 13 |
+
rewriteRequestPath?: (path: string, c: Context<E>) => string;
|
| 14 |
+
onFound?: (path: string, c: Context<E>) => void | Promise<void>;
|
| 15 |
+
onNotFound?: (path: string, c: Context<E>) => void | Promise<void>;
|
| 16 |
+
};
|
| 17 |
+
declare const serveStatic: <E extends Env = any>(options?: ServeStaticOptions<E>) => MiddlewareHandler<E>;
|
| 18 |
+
//#endregion
|
| 19 |
+
export { ServeStaticOptions, serveStatic };
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/serve-static.d.mts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { Context, Env, MiddlewareHandler } from "hono";
|
| 2 |
+
|
| 3 |
+
//#region src/serve-static.d.ts
|
| 4 |
+
type ServeStaticOptions<E extends Env = Env> = {
|
| 5 |
+
/**
|
| 6 |
+
* Root path. Relative path is based on current working directory from which the app was started.
|
| 7 |
+
*/
|
| 8 |
+
root?: string;
|
| 9 |
+
path?: string;
|
| 10 |
+
index?: string;
|
| 11 |
+
precompressed?: boolean; /** Allow percent signs in the routed request path. Defaults to false. */
|
| 12 |
+
allowPercentInPath?: boolean;
|
| 13 |
+
rewriteRequestPath?: (path: string, c: Context<E>) => string;
|
| 14 |
+
onFound?: (path: string, c: Context<E>) => void | Promise<void>;
|
| 15 |
+
onNotFound?: (path: string, c: Context<E>) => void | Promise<void>;
|
| 16 |
+
};
|
| 17 |
+
declare const serveStatic: <E extends Env = any>(options?: ServeStaticOptions<E>) => MiddlewareHandler<E>;
|
| 18 |
+
//#endregion
|
| 19 |
+
export { ServeStaticOptions, serveStatic };
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/serve-static.mjs
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { createStreamBody } from "./utils/stream.mjs";
|
| 2 |
+
import { getMimeType } from "hono/utils/mime";
|
| 3 |
+
import { createReadStream, existsSync, statSync } from "node:fs";
|
| 4 |
+
import { join } from "node:path";
|
| 5 |
+
|
| 6 |
+
//#region src/serve-static.ts
|
| 7 |
+
const COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
|
| 8 |
+
const ENCODINGS = {
|
| 9 |
+
br: ".br",
|
| 10 |
+
zstd: ".zst",
|
| 11 |
+
gzip: ".gz"
|
| 12 |
+
};
|
| 13 |
+
const ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);
|
| 14 |
+
const getStats = (path) => {
|
| 15 |
+
let stats;
|
| 16 |
+
try {
|
| 17 |
+
stats = statSync(path);
|
| 18 |
+
} catch {}
|
| 19 |
+
return stats;
|
| 20 |
+
};
|
| 21 |
+
const BYTE_RANGE_PATTERN = /^(?:bytes=)?(?!-$)(\d*)-(\d*)$/;
|
| 22 |
+
const parseByteRange = (range) => {
|
| 23 |
+
const match = range.match(BYTE_RANGE_PATTERN);
|
| 24 |
+
if (!match) return;
|
| 25 |
+
const [, start, end] = match;
|
| 26 |
+
if (start === "") return {
|
| 27 |
+
type: "suffix",
|
| 28 |
+
length: Number(end)
|
| 29 |
+
};
|
| 30 |
+
if (end === "") return {
|
| 31 |
+
type: "open-ended",
|
| 32 |
+
start: Number(start)
|
| 33 |
+
};
|
| 34 |
+
return {
|
| 35 |
+
type: "bounded",
|
| 36 |
+
start: Number(start),
|
| 37 |
+
end: Number(end)
|
| 38 |
+
};
|
| 39 |
+
};
|
| 40 |
+
const resolveByteRange = (spec, size) => {
|
| 41 |
+
if (size === 0) return;
|
| 42 |
+
if (spec.type === "suffix") {
|
| 43 |
+
if (spec.length === 0) return;
|
| 44 |
+
return {
|
| 45 |
+
start: Math.max(size - spec.length, 0),
|
| 46 |
+
end: size - 1
|
| 47 |
+
};
|
| 48 |
+
}
|
| 49 |
+
const end = spec.type === "bounded" ? Math.min(spec.end, size - 1) : size - 1;
|
| 50 |
+
if (spec.start >= size || spec.start > end) return;
|
| 51 |
+
return {
|
| 52 |
+
start: spec.start,
|
| 53 |
+
end
|
| 54 |
+
};
|
| 55 |
+
};
|
| 56 |
+
const tryDecode = (str, decoder) => {
|
| 57 |
+
try {
|
| 58 |
+
return decoder(str);
|
| 59 |
+
} catch {
|
| 60 |
+
return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
|
| 61 |
+
try {
|
| 62 |
+
return decoder(match);
|
| 63 |
+
} catch {
|
| 64 |
+
return match;
|
| 65 |
+
}
|
| 66 |
+
});
|
| 67 |
+
}
|
| 68 |
+
};
|
| 69 |
+
const tryDecodeURI = (str) => tryDecode(str, decodeURI);
|
| 70 |
+
const serveStatic = (options = { root: "" }) => {
|
| 71 |
+
const root = options.root || "";
|
| 72 |
+
const optionPath = options.path;
|
| 73 |
+
if (root !== "" && !existsSync(root)) console.error(`serveStatic: root path '${root}' is not found, are you sure it's correct?`);
|
| 74 |
+
return async (c, next) => {
|
| 75 |
+
if (c.finalized) return next();
|
| 76 |
+
let filename;
|
| 77 |
+
if (optionPath) filename = optionPath;
|
| 78 |
+
else try {
|
| 79 |
+
if (!options.allowPercentInPath && c.req.path.includes("%")) throw new Error();
|
| 80 |
+
filename = tryDecodeURI(c.req.path);
|
| 81 |
+
if (/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(filename)) throw new Error();
|
| 82 |
+
} catch {
|
| 83 |
+
await options.onNotFound?.(c.req.path, c);
|
| 84 |
+
return next();
|
| 85 |
+
}
|
| 86 |
+
let path = join(root, !optionPath && options.rewriteRequestPath ? options.rewriteRequestPath(filename, c) : filename);
|
| 87 |
+
let stats = getStats(path);
|
| 88 |
+
if (stats && stats.isDirectory()) {
|
| 89 |
+
const indexFile = options.index ?? "index.html";
|
| 90 |
+
path = join(path, indexFile);
|
| 91 |
+
stats = getStats(path);
|
| 92 |
+
}
|
| 93 |
+
if (!stats) {
|
| 94 |
+
await options.onNotFound?.(path, c);
|
| 95 |
+
return next();
|
| 96 |
+
}
|
| 97 |
+
const mimeType = getMimeType(path);
|
| 98 |
+
c.header("Content-Type", mimeType || "application/octet-stream");
|
| 99 |
+
if (options.precompressed && (!mimeType || mimeType === "application/octet-stream" || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {
|
| 100 |
+
const acceptEncodingSet = new Set(c.req.header("Accept-Encoding")?.split(",").map((encoding) => encoding.trim()));
|
| 101 |
+
for (const encoding of ENCODINGS_ORDERED_KEYS) {
|
| 102 |
+
if (!acceptEncodingSet.has(encoding)) continue;
|
| 103 |
+
const precompressedStats = getStats(path + ENCODINGS[encoding]);
|
| 104 |
+
if (precompressedStats) {
|
| 105 |
+
c.header("Content-Encoding", encoding);
|
| 106 |
+
c.header("Vary", "Accept-Encoding", { append: true });
|
| 107 |
+
stats = precompressedStats;
|
| 108 |
+
path = path + ENCODINGS[encoding];
|
| 109 |
+
break;
|
| 110 |
+
}
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
let result;
|
| 114 |
+
const size = stats.size;
|
| 115 |
+
const range = c.req.header("range") || "";
|
| 116 |
+
c.header("Last-Modified", stats.mtime.toUTCString());
|
| 117 |
+
if (c.req.method == "HEAD" || c.req.method == "OPTIONS") {
|
| 118 |
+
c.header("Content-Length", size.toString());
|
| 119 |
+
c.status(200);
|
| 120 |
+
result = c.body(null);
|
| 121 |
+
} else if (!range) {
|
| 122 |
+
c.header("Content-Length", size.toString());
|
| 123 |
+
result = c.body(createStreamBody(createReadStream(path)), 200);
|
| 124 |
+
} else {
|
| 125 |
+
c.header("Accept-Ranges", "bytes");
|
| 126 |
+
const resolvedRange = resolveByteRange(parseByteRange(range) ?? {
|
| 127 |
+
type: "open-ended",
|
| 128 |
+
start: 0
|
| 129 |
+
}, size);
|
| 130 |
+
if (!resolvedRange) {
|
| 131 |
+
c.header("Content-Range", `bytes */${size}`);
|
| 132 |
+
result = c.body(null, 416);
|
| 133 |
+
} else {
|
| 134 |
+
const { start, end } = resolvedRange;
|
| 135 |
+
const chunkSize = end - start + 1;
|
| 136 |
+
const stream = createReadStream(path, {
|
| 137 |
+
start,
|
| 138 |
+
end
|
| 139 |
+
});
|
| 140 |
+
c.header("Content-Length", chunkSize.toString());
|
| 141 |
+
c.header("Content-Range", `bytes ${start}-${end}/${size}`);
|
| 142 |
+
result = c.body(createStreamBody(stream), 206);
|
| 143 |
+
}
|
| 144 |
+
}
|
| 145 |
+
await options.onFound?.(path, c);
|
| 146 |
+
return result;
|
| 147 |
+
};
|
| 148 |
+
};
|
| 149 |
+
|
| 150 |
+
//#endregion
|
| 151 |
+
export { serveStatic };
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/utils/response.cjs
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
| 2 |
+
const require_constants = require('../constants-BXAKTxRC.cjs');
|
| 3 |
+
|
| 4 |
+
//#region src/utils/response.ts
|
| 5 |
+
const RESPONSE_ALREADY_SENT = new Response(null, { headers: { [require_constants.X_ALREADY_SENT]: "true" } });
|
| 6 |
+
|
| 7 |
+
//#endregion
|
| 8 |
+
exports.RESPONSE_ALREADY_SENT = RESPONSE_ALREADY_SENT;
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/utils/response.d.cts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//#region src/utils/response.d.ts
|
| 2 |
+
declare const RESPONSE_ALREADY_SENT: Response;
|
| 3 |
+
//#endregion
|
| 4 |
+
export { RESPONSE_ALREADY_SENT };
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/utils/response.d.mts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
//#region src/utils/response.d.ts
|
| 2 |
+
declare const RESPONSE_ALREADY_SENT: Response;
|
| 3 |
+
//#endregion
|
| 4 |
+
export { RESPONSE_ALREADY_SENT };
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/utils/response.mjs
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { t as X_ALREADY_SENT } from "../constants-BLSFu_RU.mjs";
|
| 2 |
+
|
| 3 |
+
//#region src/utils/response.ts
|
| 4 |
+
const RESPONSE_ALREADY_SENT = new Response(null, { headers: { [X_ALREADY_SENT]: "true" } });
|
| 5 |
+
|
| 6 |
+
//#endregion
|
| 7 |
+
export { RESPONSE_ALREADY_SENT };
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/utils/stream.cjs
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
| 2 |
+
let node_stream = require("node:stream");
|
| 3 |
+
let node_process = require("node:process");
|
| 4 |
+
|
| 5 |
+
//#region src/utils/stream.ts
|
| 6 |
+
const pr54206Applied = () => {
|
| 7 |
+
const [major, minor] = node_process.versions.node.split(".").map((component) => parseInt(component));
|
| 8 |
+
return major >= 23 || major === 22 && minor >= 7 || major === 20 && minor >= 18;
|
| 9 |
+
};
|
| 10 |
+
const useReadableToWeb = pr54206Applied();
|
| 11 |
+
const createStreamBody = (stream, useNativeReadableToWeb = useReadableToWeb) => {
|
| 12 |
+
if (useNativeReadableToWeb) return node_stream.Readable.toWeb(stream);
|
| 13 |
+
let controller;
|
| 14 |
+
let settled = false;
|
| 15 |
+
const cleanup = () => {
|
| 16 |
+
stream.off("data", onData);
|
| 17 |
+
stream.off("error", onError);
|
| 18 |
+
stream.off("end", onTerminate);
|
| 19 |
+
stream.off("close", onTerminate);
|
| 20 |
+
};
|
| 21 |
+
const settle = (callback) => {
|
| 22 |
+
if (settled) return;
|
| 23 |
+
settled = true;
|
| 24 |
+
cleanup();
|
| 25 |
+
callback?.();
|
| 26 |
+
};
|
| 27 |
+
const onData = (chunk) => {
|
| 28 |
+
if (settled || !controller) return;
|
| 29 |
+
controller.enqueue(chunk);
|
| 30 |
+
if ((controller.desiredSize ?? 0) <= 0) stream.pause();
|
| 31 |
+
};
|
| 32 |
+
const onError = (error) => {
|
| 33 |
+
settle(() => {
|
| 34 |
+
controller?.error(error);
|
| 35 |
+
});
|
| 36 |
+
};
|
| 37 |
+
const onTerminate = () => {
|
| 38 |
+
settle(() => {
|
| 39 |
+
controller?.close();
|
| 40 |
+
});
|
| 41 |
+
};
|
| 42 |
+
return new ReadableStream({
|
| 43 |
+
start(streamController) {
|
| 44 |
+
controller = streamController;
|
| 45 |
+
stream.on("data", onData);
|
| 46 |
+
stream.on("error", onError);
|
| 47 |
+
stream.on("end", onTerminate);
|
| 48 |
+
stream.on("close", onTerminate);
|
| 49 |
+
stream.pause();
|
| 50 |
+
},
|
| 51 |
+
pull() {
|
| 52 |
+
if (!settled) stream.resume();
|
| 53 |
+
},
|
| 54 |
+
cancel() {
|
| 55 |
+
settle();
|
| 56 |
+
const ignoreError = () => {};
|
| 57 |
+
stream.on("error", ignoreError);
|
| 58 |
+
stream.once("close", () => stream.off("error", ignoreError));
|
| 59 |
+
stream.destroy();
|
| 60 |
+
}
|
| 61 |
+
});
|
| 62 |
+
};
|
| 63 |
+
|
| 64 |
+
//#endregion
|
| 65 |
+
exports.createStreamBody = createStreamBody;
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/utils/stream.d.cts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { ReadStream } from "node:fs";
|
| 2 |
+
|
| 3 |
+
//#region src/utils/stream.d.ts
|
| 4 |
+
declare const createStreamBody: (stream: ReadStream, useNativeReadableToWeb?: boolean) => ReadableStream<Uint8Array>;
|
| 5 |
+
//#endregion
|
| 6 |
+
export { createStreamBody };
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/utils/stream.d.mts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { ReadStream } from "node:fs";
|
| 2 |
+
|
| 3 |
+
//#region src/utils/stream.d.ts
|
| 4 |
+
declare const createStreamBody: (stream: ReadStream, useNativeReadableToWeb?: boolean) => ReadableStream<Uint8Array>;
|
| 5 |
+
//#endregion
|
| 6 |
+
export { createStreamBody };
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/dist/utils/stream.mjs
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { Readable } from "node:stream";
|
| 2 |
+
import { versions } from "node:process";
|
| 3 |
+
|
| 4 |
+
//#region src/utils/stream.ts
|
| 5 |
+
const pr54206Applied = () => {
|
| 6 |
+
const [major, minor] = versions.node.split(".").map((component) => parseInt(component));
|
| 7 |
+
return major >= 23 || major === 22 && minor >= 7 || major === 20 && minor >= 18;
|
| 8 |
+
};
|
| 9 |
+
const useReadableToWeb = pr54206Applied();
|
| 10 |
+
const createStreamBody = (stream, useNativeReadableToWeb = useReadableToWeb) => {
|
| 11 |
+
if (useNativeReadableToWeb) return Readable.toWeb(stream);
|
| 12 |
+
let controller;
|
| 13 |
+
let settled = false;
|
| 14 |
+
const cleanup = () => {
|
| 15 |
+
stream.off("data", onData);
|
| 16 |
+
stream.off("error", onError);
|
| 17 |
+
stream.off("end", onTerminate);
|
| 18 |
+
stream.off("close", onTerminate);
|
| 19 |
+
};
|
| 20 |
+
const settle = (callback) => {
|
| 21 |
+
if (settled) return;
|
| 22 |
+
settled = true;
|
| 23 |
+
cleanup();
|
| 24 |
+
callback?.();
|
| 25 |
+
};
|
| 26 |
+
const onData = (chunk) => {
|
| 27 |
+
if (settled || !controller) return;
|
| 28 |
+
controller.enqueue(chunk);
|
| 29 |
+
if ((controller.desiredSize ?? 0) <= 0) stream.pause();
|
| 30 |
+
};
|
| 31 |
+
const onError = (error) => {
|
| 32 |
+
settle(() => {
|
| 33 |
+
controller?.error(error);
|
| 34 |
+
});
|
| 35 |
+
};
|
| 36 |
+
const onTerminate = () => {
|
| 37 |
+
settle(() => {
|
| 38 |
+
controller?.close();
|
| 39 |
+
});
|
| 40 |
+
};
|
| 41 |
+
return new ReadableStream({
|
| 42 |
+
start(streamController) {
|
| 43 |
+
controller = streamController;
|
| 44 |
+
stream.on("data", onData);
|
| 45 |
+
stream.on("error", onError);
|
| 46 |
+
stream.on("end", onTerminate);
|
| 47 |
+
stream.on("close", onTerminate);
|
| 48 |
+
stream.pause();
|
| 49 |
+
},
|
| 50 |
+
pull() {
|
| 51 |
+
if (!settled) stream.resume();
|
| 52 |
+
},
|
| 53 |
+
cancel() {
|
| 54 |
+
settle();
|
| 55 |
+
const ignoreError = () => {};
|
| 56 |
+
stream.on("error", ignoreError);
|
| 57 |
+
stream.once("close", () => stream.off("error", ignoreError));
|
| 58 |
+
stream.destroy();
|
| 59 |
+
}
|
| 60 |
+
});
|
| 61 |
+
};
|
| 62 |
+
|
| 63 |
+
//#endregion
|
| 64 |
+
export { createStreamBody };
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@hono/node-server/package.json
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"name": "@hono/node-server",
|
| 3 |
+
"version": "2.1.3",
|
| 4 |
+
"description": "Node.js Adapter for Hono",
|
| 5 |
+
"main": "dist/index.mjs",
|
| 6 |
+
"type": "module",
|
| 7 |
+
"types": "dist/index.d.mts",
|
| 8 |
+
"files": [
|
| 9 |
+
"dist"
|
| 10 |
+
],
|
| 11 |
+
"exports": {
|
| 12 |
+
".": {
|
| 13 |
+
"import": {
|
| 14 |
+
"types": "./dist/index.d.mts",
|
| 15 |
+
"default": "./dist/index.mjs"
|
| 16 |
+
},
|
| 17 |
+
"require": {
|
| 18 |
+
"types": "./dist/index.d.cts",
|
| 19 |
+
"default": "./dist/index.cjs"
|
| 20 |
+
}
|
| 21 |
+
},
|
| 22 |
+
"./serve-static": {
|
| 23 |
+
"import": {
|
| 24 |
+
"types": "./dist/serve-static.d.mts",
|
| 25 |
+
"default": "./dist/serve-static.mjs"
|
| 26 |
+
},
|
| 27 |
+
"require": {
|
| 28 |
+
"types": "./dist/serve-static.d.cts",
|
| 29 |
+
"default": "./dist/serve-static.cjs"
|
| 30 |
+
}
|
| 31 |
+
},
|
| 32 |
+
"./utils/*": {
|
| 33 |
+
"import": {
|
| 34 |
+
"types": "./dist/utils/*.d.mts",
|
| 35 |
+
"default": "./dist/utils/*.mjs"
|
| 36 |
+
},
|
| 37 |
+
"require": {
|
| 38 |
+
"types": "./dist/utils/*.d.cts",
|
| 39 |
+
"default": "./dist/utils/*.cjs"
|
| 40 |
+
}
|
| 41 |
+
},
|
| 42 |
+
"./conninfo": {
|
| 43 |
+
"import": {
|
| 44 |
+
"types": "./dist/conninfo.d.mts",
|
| 45 |
+
"default": "./dist/conninfo.mjs"
|
| 46 |
+
},
|
| 47 |
+
"require": {
|
| 48 |
+
"types": "./dist/conninfo.d.cts",
|
| 49 |
+
"default": "./dist/conninfo.cjs"
|
| 50 |
+
}
|
| 51 |
+
},
|
| 52 |
+
"./early-hints": {
|
| 53 |
+
"import": {
|
| 54 |
+
"types": "./dist/early-hints.d.mts",
|
| 55 |
+
"default": "./dist/early-hints.mjs"
|
| 56 |
+
},
|
| 57 |
+
"require": {
|
| 58 |
+
"types": "./dist/early-hints.d.cts",
|
| 59 |
+
"default": "./dist/early-hints.cjs"
|
| 60 |
+
}
|
| 61 |
+
}
|
| 62 |
+
},
|
| 63 |
+
"typesVersions": {
|
| 64 |
+
"*": {
|
| 65 |
+
".": [
|
| 66 |
+
"./dist/index.d.mts"
|
| 67 |
+
],
|
| 68 |
+
"serve-static": [
|
| 69 |
+
"./dist/serve-static.d.mts"
|
| 70 |
+
],
|
| 71 |
+
"utils/*": [
|
| 72 |
+
"./dist/utils/*.d.mts"
|
| 73 |
+
],
|
| 74 |
+
"conninfo": [
|
| 75 |
+
"./dist/conninfo.d.mts"
|
| 76 |
+
],
|
| 77 |
+
"early-hints": [
|
| 78 |
+
"./dist/early-hints.d.mts"
|
| 79 |
+
]
|
| 80 |
+
}
|
| 81 |
+
},
|
| 82 |
+
"license": "MIT",
|
| 83 |
+
"repository": {
|
| 84 |
+
"type": "git",
|
| 85 |
+
"url": "git+https://github.com/honojs/node-server.git"
|
| 86 |
+
},
|
| 87 |
+
"homepage": "https://github.com/honojs/node-server",
|
| 88 |
+
"author": "Yusuke Wada <yusuke@kamawada.com> (https://github.com/yusukebe)",
|
| 89 |
+
"publishConfig": {
|
| 90 |
+
"registry": "https://registry.npmjs.org",
|
| 91 |
+
"access": "public",
|
| 92 |
+
"provenance": true
|
| 93 |
+
},
|
| 94 |
+
"engines": {
|
| 95 |
+
"node": ">=20"
|
| 96 |
+
},
|
| 97 |
+
"devDependencies": {
|
| 98 |
+
"@hono/eslint-config": "^1.0.1",
|
| 99 |
+
"@types/node": "^20.10.0",
|
| 100 |
+
"@types/ws": "^8.18.1",
|
| 101 |
+
"@whatwg-node/fetch": "^0.9.14",
|
| 102 |
+
"eslint": "^9.10.0",
|
| 103 |
+
"hono": "^4.13.9",
|
| 104 |
+
"np": "^11.2.1",
|
| 105 |
+
"prettier": "^3.2.4",
|
| 106 |
+
"publint": "^0.3.18",
|
| 107 |
+
"tsdown": "^0.20.3",
|
| 108 |
+
"typescript": "^5.3.2",
|
| 109 |
+
"vitest": "^4.0.18",
|
| 110 |
+
"ws": "^8.19.0"
|
| 111 |
+
},
|
| 112 |
+
"peerDependencies": {
|
| 113 |
+
"hono": "^4"
|
| 114 |
+
},
|
| 115 |
+
"scripts": {
|
| 116 |
+
"test": "vitest",
|
| 117 |
+
"build": "tsdown --external hono",
|
| 118 |
+
"watch": "tsdown --watch",
|
| 119 |
+
"postbuild": "publint",
|
| 120 |
+
"prerelease": "pnpm run build && pnpm run test --run",
|
| 121 |
+
"release": "np --no-publish",
|
| 122 |
+
"typecheck": "tsc --noEmit",
|
| 123 |
+
"lint": "eslint src test",
|
| 124 |
+
"lint:fix": "eslint src test --fix",
|
| 125 |
+
"format": "prettier --check \"src/**/*.{js,ts}\" \"test/**/*.{js,ts}\"",
|
| 126 |
+
"format:fix": "prettier --write \"src/**/*.{js,ts}\" \"test/**/*.{js,ts}\""
|
| 127 |
+
}
|
| 128 |
+
}
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@modelcontextprotocol/sdk/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2024 Anthropic, PBC
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@modelcontextprotocol/sdk/README.md
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# MCP TypeScript SDK [](https://www.npmjs.com/package/@modelcontextprotocol/sdk) [](https://github.com/modelcontextprotocol/typescript-sdk/blob/main/LICENSE)
|
| 2 |
+
|
| 3 |
+
<details>
|
| 4 |
+
<summary>Table of Contents</summary>
|
| 5 |
+
|
| 6 |
+
- [Overview](#overview)
|
| 7 |
+
- [Installation](#installation)
|
| 8 |
+
- [Quick Start](#quick-start)
|
| 9 |
+
- [Core Concepts](#core-concepts)
|
| 10 |
+
- [Examples](#examples)
|
| 11 |
+
- [Documentation](#documentation)
|
| 12 |
+
- [Contributing](#contributing)
|
| 13 |
+
- [License](#license)
|
| 14 |
+
|
| 15 |
+
</details>
|
| 16 |
+
|
| 17 |
+
## Overview
|
| 18 |
+
|
| 19 |
+
The Model Context Protocol allows applications to provide context for LLMs in a standardized way, separating the concerns of providing context from the actual LLM interaction. This TypeScript SDK implements
|
| 20 |
+
[the full MCP specification](https://modelcontextprotocol.io/specification/draft), making it easy to:
|
| 21 |
+
|
| 22 |
+
- Create MCP servers that expose resources, prompts and tools
|
| 23 |
+
- Build MCP clients that can connect to any MCP server
|
| 24 |
+
- Use standard transports like stdio and Streamable HTTP
|
| 25 |
+
|
| 26 |
+
## Installation
|
| 27 |
+
|
| 28 |
+
```bash
|
| 29 |
+
npm install @modelcontextprotocol/sdk zod
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
This SDK has a **required peer dependency** on `zod` for schema validation. The SDK internally imports from `zod/v4`, but maintains backwards compatibility with projects using Zod v3.25 or later. You can use either API in your code by importing from `zod/v3` or `zod/v4`:
|
| 33 |
+
|
| 34 |
+
## Quick Start
|
| 35 |
+
|
| 36 |
+
To see the SDK in action end-to-end, start from the runnable examples in `src/examples`:
|
| 37 |
+
|
| 38 |
+
1. **Install dependencies** (from the SDK repo root):
|
| 39 |
+
|
| 40 |
+
```bash
|
| 41 |
+
npm install
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
2. **Run the example Streamable HTTP server**:
|
| 45 |
+
|
| 46 |
+
```bash
|
| 47 |
+
npx tsx src/examples/server/simpleStreamableHttp.ts
|
| 48 |
+
```
|
| 49 |
+
|
| 50 |
+
3. **Run the interactive client in another terminal**:
|
| 51 |
+
|
| 52 |
+
```bash
|
| 53 |
+
npx tsx src/examples/client/simpleStreamableHttp.ts
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
This pair of examples demonstrates tools, resources, prompts, sampling, elicitation, tasks and logging. For a guided walkthrough and variations (stateless servers, JSON-only responses, SSE compatibility, OAuth, etc.), see [docs/server.md](docs/server.md) and
|
| 57 |
+
[docs/client.md](docs/client.md).
|
| 58 |
+
|
| 59 |
+
## Core Concepts
|
| 60 |
+
|
| 61 |
+
### Servers and transports
|
| 62 |
+
|
| 63 |
+
An MCP server is typically created with `McpServer` and connected to a transport such as Streamable HTTP or stdio. The SDK supports:
|
| 64 |
+
|
| 65 |
+
- **Streamable HTTP** for remote servers (recommended).
|
| 66 |
+
- **HTTP + SSE** for backwards compatibility only.
|
| 67 |
+
- **stdio** for local, process-spawned integrations.
|
| 68 |
+
|
| 69 |
+
Runnable server examples live under `src/examples/server` and are documented in [docs/server.md](docs/server.md).
|
| 70 |
+
|
| 71 |
+
### Tools, resources, prompts
|
| 72 |
+
|
| 73 |
+
- **Tools** let LLMs ask your server to take actions (computation, side effects, network calls).
|
| 74 |
+
- **Resources** expose read-only data that clients can surface to users or models.
|
| 75 |
+
- **Prompts** are reusable templates that help users talk to models in a consistent way.
|
| 76 |
+
|
| 77 |
+
The detailed APIs, including `ResourceTemplate`, completions, and display-name metadata, are covered in [docs/server.md](docs/server.md#tools-resources-and-prompts), with runnable implementations in [`simpleStreamableHttp.ts`](src/examples/server/simpleStreamableHttp.ts).
|
| 78 |
+
|
| 79 |
+
### Capabilities: sampling, elicitation, and tasks
|
| 80 |
+
|
| 81 |
+
The SDK includes higher-level capabilities for richer workflows:
|
| 82 |
+
|
| 83 |
+
- **Sampling**: server-side tools can ask connected clients to run LLM completions.
|
| 84 |
+
- **Form elicitation**: tools can request non-sensitive input via structured forms.
|
| 85 |
+
- **URL elicitation**: servers can ask users to complete secure flows in a browser (e.g., API key entry, payments, OAuth).
|
| 86 |
+
- **Tasks (experimental)**: long-running tool calls can be turned into tasks that you poll or resume later.
|
| 87 |
+
|
| 88 |
+
Conceptual overviews and links to runnable examples are in:
|
| 89 |
+
|
| 90 |
+
- [docs/capabilities.md](docs/capabilities.md)
|
| 91 |
+
|
| 92 |
+
Key example servers include:
|
| 93 |
+
|
| 94 |
+
- [`toolWithSampleServer.ts`](src/examples/server/toolWithSampleServer.ts)
|
| 95 |
+
- [`elicitationFormExample.ts`](src/examples/server/elicitationFormExample.ts)
|
| 96 |
+
- [`elicitationUrlExample.ts`](src/examples/server/elicitationUrlExample.ts)
|
| 97 |
+
|
| 98 |
+
### Clients
|
| 99 |
+
|
| 100 |
+
The high-level `Client` class connects to MCP servers over different transports and exposes helpers like `listTools`, `callTool`, `listResources`, `readResource`, `listPrompts`, and `getPrompt`.
|
| 101 |
+
|
| 102 |
+
Runnable clients live under `src/examples/client` and are described in [docs/client.md](docs/client.md), including:
|
| 103 |
+
|
| 104 |
+
- Interactive Streamable HTTP client ([`simpleStreamableHttp.ts`](src/examples/client/simpleStreamableHttp.ts))
|
| 105 |
+
- Streamable HTTP client with SSE fallback ([`streamableHttpWithSseFallbackClient.ts`](src/examples/client/streamableHttpWithSseFallbackClient.ts))
|
| 106 |
+
- OAuth-enabled clients and polling/parallel examples
|
| 107 |
+
|
| 108 |
+
### Node.js Web Crypto (globalThis.crypto) compatibility
|
| 109 |
+
|
| 110 |
+
Some parts of the SDK (for example, JWT-based client authentication in `auth-extensions.ts` via `jose`) rely on the Web Crypto API exposed as `globalThis.crypto`.
|
| 111 |
+
|
| 112 |
+
See [docs/faq.md](docs/faq.md) for details on supported Node.js versions and how to polyfill `globalThis.crypto` when running on older Node.js runtimes.
|
| 113 |
+
|
| 114 |
+
## Examples
|
| 115 |
+
|
| 116 |
+
The SDK ships runnable examples under `src/examples`. Use these tables to find the scenario you care about and jump straight to the corresponding code and docs.
|
| 117 |
+
|
| 118 |
+
### Server examples
|
| 119 |
+
|
| 120 |
+
| Scenario | Description | Example file(s) | Related docs |
|
| 121 |
+
| --------------------------------------------------- | ------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
|
| 122 |
+
| Streamable HTTP server (stateful) | Feature-rich server with tools, resources, prompts, logging, tasks, sampling, and optional OAuth. | [`simpleStreamableHttp.ts`](src/examples/server/simpleStreamableHttp.ts) | [`server.md`](docs/server.md), [`capabilities.md`](docs/capabilities.md) |
|
| 123 |
+
| Streamable HTTP server (stateless) | No session tracking; good for simple API-style servers. | [`simpleStatelessStreamableHttp.ts`](src/examples/server/simpleStatelessStreamableHttp.ts) | [`server.md`](docs/server.md) |
|
| 124 |
+
| JSON response mode (no SSE) | Streamable HTTP with JSON responses only and limited notifications. | [`jsonResponseStreamableHttp.ts`](src/examples/server/jsonResponseStreamableHttp.ts) | [`server.md`](docs/server.md) |
|
| 125 |
+
| Server notifications over Streamable HTTP | Demonstrates server-initiated notifications using SSE with Streamable HTTP. | [`standaloneSseWithGetStreamableHttp.ts`](src/examples/server/standaloneSseWithGetStreamableHttp.ts) | [`server.md`](docs/server.md) |
|
| 126 |
+
| Deprecated HTTP+SSE server | Legacy HTTP+SSE transport for backwards-compatibility testing. | [`simpleSseServer.ts`](src/examples/server/simpleSseServer.ts) | [`server.md`](docs/server.md) |
|
| 127 |
+
| Backwards-compatible server (Streamable HTTP + SSE) | Single server that supports both Streamable HTTP and legacy SSE clients. | [`sseAndStreamableHttpCompatibleServer.ts`](src/examples/server/sseAndStreamableHttpCompatibleServer.ts) | [`server.md`](docs/server.md) |
|
| 128 |
+
| Form elicitation server | Uses form elicitation to collect non-sensitive user input. | [`elicitationFormExample.ts`](src/examples/server/elicitationFormExample.ts) | [`capabilities.md`](docs/capabilities.md#elicitation) |
|
| 129 |
+
| URL elicitation server | Demonstrates URL-mode elicitation in an OAuth-protected server. | [`elicitationUrlExample.ts`](src/examples/server/elicitationUrlExample.ts) | [`capabilities.md`](docs/capabilities.md#elicitation) |
|
| 130 |
+
| Sampling and tasks server | Combines tools, logging, sampling, and experimental task-based execution. | [`toolWithSampleServer.ts`](src/examples/server/toolWithSampleServer.ts) | [`capabilities.md`](docs/capabilities.md) |
|
| 131 |
+
| OAuth demo authorization server | In-memory OAuth provider used with the example servers. | [`demoInMemoryOAuthProvider.ts`](src/examples/server/demoInMemoryOAuthProvider.ts) | [`server.md`](docs/server.md) |
|
| 132 |
+
|
| 133 |
+
### Client examples
|
| 134 |
+
|
| 135 |
+
| Scenario | Description | Example file(s) | Related docs |
|
| 136 |
+
| --------------------------------------------------- | ---------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
|
| 137 |
+
| Interactive Streamable HTTP client | CLI client that exercises tools, resources, prompts, elicitation, and tasks. | [`simpleStreamableHttp.ts`](src/examples/client/simpleStreamableHttp.ts) | [`client.md`](docs/client.md) |
|
| 138 |
+
| Backwards-compatible client (Streamable HTTP → SSE) | Tries Streamable HTTP first, then falls back to SSE on 4xx responses. | [`streamableHttpWithSseFallbackClient.ts`](src/examples/client/streamableHttpWithSseFallbackClient.ts) | [`client.md`](docs/client.md), [`server.md`](docs/server.md) |
|
| 139 |
+
| SSE polling client | Polls a legacy SSE server and demonstrates notification handling. | [`ssePollingClient.ts`](src/examples/client/ssePollingClient.ts) | [`client.md`](docs/client.md) |
|
| 140 |
+
| Parallel tool calls client | Shows how to run multiple tool calls in parallel. | [`parallelToolCallsClient.ts`](src/examples/client/parallelToolCallsClient.ts) | [`client.md`](docs/client.md) |
|
| 141 |
+
| Multiple clients in parallel | Demonstrates connecting multiple clients concurrently to the same server. | [`multipleClientsParallel.ts`](src/examples/client/multipleClientsParallel.ts) | [`client.md`](docs/client.md) |
|
| 142 |
+
| OAuth clients | Examples of client_credentials (basic and private_key_jwt) and reusable providers. | [`simpleOAuthClient.ts`](src/examples/client/simpleOAuthClient.ts), [`simpleOAuthClientProvider.ts`](src/examples/client/simpleOAuthClientProvider.ts), [`simpleClientCredentials.ts`](src/examples/client/simpleClientCredentials.ts) | [`client.md`](docs/client.md) |
|
| 143 |
+
| URL elicitation client | Works with the URL elicitation server to drive secure browser flows. | [`elicitationUrlExample.ts`](src/examples/client/elicitationUrlExample.ts) | [`capabilities.md`](docs/capabilities.md#elicitation) |
|
| 144 |
+
|
| 145 |
+
Shared utilities:
|
| 146 |
+
|
| 147 |
+
- In-memory event store for resumability: [`inMemoryEventStore.ts`](src/examples/shared/inMemoryEventStore.ts) (see [`server.md`](docs/server.md)).
|
| 148 |
+
|
| 149 |
+
For more details on how to run these examples (including recommended commands and deployment diagrams), see `src/examples/README.md`.
|
| 150 |
+
|
| 151 |
+
## Documentation
|
| 152 |
+
|
| 153 |
+
- Local SDK docs:
|
| 154 |
+
- [docs/server.md](docs/server.md) – building and running MCP servers, transports, tools/resources/prompts, CORS, DNS rebinding, and multi-node deployment.
|
| 155 |
+
- [docs/client.md](docs/client.md) – using the high-level client, transports, backwards compatibility, and OAuth helpers.
|
| 156 |
+
- [docs/capabilities.md](docs/capabilities.md) – sampling, elicitation (form and URL), and experimental task-based execution.
|
| 157 |
+
- [docs/protocol.md](docs/protocol.md) – protocol features: ping, progress, cancellation, pagination, capability negotiation, and JSON Schema.
|
| 158 |
+
- [docs/faq.md](docs/faq.md) – environment and troubleshooting FAQs (including Node.js Web Crypto support).
|
| 159 |
+
- External references:
|
| 160 |
+
- [V1 API reference](https://modelcontextprotocol.github.io/typescript-sdk/)
|
| 161 |
+
- [V2 API reference](https://modelcontextprotocol.github.io/typescript-sdk/v2/)
|
| 162 |
+
- [Model Context Protocol documentation](https://modelcontextprotocol.io)
|
| 163 |
+
- [MCP Specification](https://spec.modelcontextprotocol.io)
|
| 164 |
+
- [Example Servers](https://github.com/modelcontextprotocol/servers)
|
| 165 |
+
|
| 166 |
+
## Contributing
|
| 167 |
+
|
| 168 |
+
Issues and pull requests are welcome on GitHub at <https://github.com/modelcontextprotocol/typescript-sdk>.
|
| 169 |
+
|
| 170 |
+
## License
|
| 171 |
+
|
| 172 |
+
This project is licensed under the MIT License—see the [LICENSE](LICENSE) file for details.
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.d.ts
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* OAuth provider extensions for specialized authentication flows.
|
| 3 |
+
*
|
| 4 |
+
* This module provides ready-to-use OAuthClientProvider implementations
|
| 5 |
+
* for common machine-to-machine authentication scenarios.
|
| 6 |
+
*/
|
| 7 |
+
import { OAuthClientInformation, OAuthClientMetadata, OAuthTokens } from '../shared/auth.js';
|
| 8 |
+
import { AddClientAuthentication, OAuthClientProvider } from './auth.js';
|
| 9 |
+
/**
|
| 10 |
+
* Helper to produce a private_key_jwt client authentication function.
|
| 11 |
+
*
|
| 12 |
+
* Usage:
|
| 13 |
+
* const addClientAuth = createPrivateKeyJwtAuth({ issuer, subject, privateKey, alg, audience? });
|
| 14 |
+
* // pass addClientAuth as provider.addClientAuthentication implementation
|
| 15 |
+
*/
|
| 16 |
+
export declare function createPrivateKeyJwtAuth(options: {
|
| 17 |
+
issuer: string;
|
| 18 |
+
subject: string;
|
| 19 |
+
privateKey: string | Uint8Array | Record<string, unknown>;
|
| 20 |
+
alg: string;
|
| 21 |
+
audience?: string | URL;
|
| 22 |
+
lifetimeSeconds?: number;
|
| 23 |
+
claims?: Record<string, unknown>;
|
| 24 |
+
}): AddClientAuthentication;
|
| 25 |
+
/**
|
| 26 |
+
* Options for creating a ClientCredentialsProvider.
|
| 27 |
+
*/
|
| 28 |
+
export interface ClientCredentialsProviderOptions {
|
| 29 |
+
/**
|
| 30 |
+
* The client_id for this OAuth client.
|
| 31 |
+
*/
|
| 32 |
+
clientId: string;
|
| 33 |
+
/**
|
| 34 |
+
* The client_secret for client_secret_basic authentication.
|
| 35 |
+
*/
|
| 36 |
+
clientSecret: string;
|
| 37 |
+
/**
|
| 38 |
+
* Optional client name for metadata.
|
| 39 |
+
*/
|
| 40 |
+
clientName?: string;
|
| 41 |
+
/**
|
| 42 |
+
* Space-separated scopes values requested by the client.
|
| 43 |
+
*/
|
| 44 |
+
scope?: string;
|
| 45 |
+
/**
|
| 46 |
+
* The issuer URL of the authorization server these credentials were registered with.
|
| 47 |
+
* When set, `auth()` only presents them to that authorization server and throws if the
|
| 48 |
+
* MCP server advertises a different URL (one trailing slash aside).
|
| 49 |
+
*
|
| 50 |
+
* Omitting it is deprecated: the credentials then go to whichever authorization server
|
| 51 |
+
* the MCP server advertises first.
|
| 52 |
+
*/
|
| 53 |
+
expectedIssuer?: string;
|
| 54 |
+
}
|
| 55 |
+
/**
|
| 56 |
+
* OAuth provider for client_credentials grant with client_secret_basic authentication.
|
| 57 |
+
*
|
| 58 |
+
* This provider is designed for machine-to-machine authentication where
|
| 59 |
+
* the client authenticates using a client_id and client_secret.
|
| 60 |
+
*
|
| 61 |
+
* @example
|
| 62 |
+
* const provider = new ClientCredentialsProvider({
|
| 63 |
+
* clientId: 'my-client',
|
| 64 |
+
* clientSecret: 'my-secret',
|
| 65 |
+
* expectedIssuer: 'https://auth.example.com'
|
| 66 |
+
* });
|
| 67 |
+
*
|
| 68 |
+
* const transport = new StreamableHTTPClientTransport(serverUrl, {
|
| 69 |
+
* authProvider: provider
|
| 70 |
+
* });
|
| 71 |
+
*/
|
| 72 |
+
export declare class ClientCredentialsProvider implements OAuthClientProvider {
|
| 73 |
+
private _tokens?;
|
| 74 |
+
private _clientInfo;
|
| 75 |
+
private _clientMetadata;
|
| 76 |
+
constructor(options: ClientCredentialsProviderOptions & {
|
| 77 |
+
expectedIssuer: string;
|
| 78 |
+
});
|
| 79 |
+
/** @deprecated Pass `expectedIssuer` so the credentials are only sent to that authorization server. */
|
| 80 |
+
constructor(options: ClientCredentialsProviderOptions);
|
| 81 |
+
get redirectUrl(): undefined;
|
| 82 |
+
get clientMetadata(): OAuthClientMetadata;
|
| 83 |
+
clientInformation(): OAuthClientInformation;
|
| 84 |
+
saveClientInformation(info: OAuthClientInformation): void;
|
| 85 |
+
tokens(): OAuthTokens | undefined;
|
| 86 |
+
saveTokens(tokens: OAuthTokens): void;
|
| 87 |
+
redirectToAuthorization(): void;
|
| 88 |
+
saveCodeVerifier(): void;
|
| 89 |
+
codeVerifier(): string;
|
| 90 |
+
prepareTokenRequest(scope?: string): URLSearchParams;
|
| 91 |
+
}
|
| 92 |
+
/**
|
| 93 |
+
* Options for creating a PrivateKeyJwtProvider.
|
| 94 |
+
*/
|
| 95 |
+
export interface PrivateKeyJwtProviderOptions {
|
| 96 |
+
/**
|
| 97 |
+
* The client_id for this OAuth client.
|
| 98 |
+
*/
|
| 99 |
+
clientId: string;
|
| 100 |
+
/**
|
| 101 |
+
* The private key for signing JWT assertions.
|
| 102 |
+
* Can be a PEM string, Uint8Array, or JWK object.
|
| 103 |
+
*/
|
| 104 |
+
privateKey: string | Uint8Array | Record<string, unknown>;
|
| 105 |
+
/**
|
| 106 |
+
* The algorithm to use for signing (e.g., 'RS256', 'ES256').
|
| 107 |
+
*/
|
| 108 |
+
algorithm: string;
|
| 109 |
+
/**
|
| 110 |
+
* Optional client name for metadata.
|
| 111 |
+
*/
|
| 112 |
+
clientName?: string;
|
| 113 |
+
/**
|
| 114 |
+
* Optional JWT lifetime in seconds (default: 300).
|
| 115 |
+
*/
|
| 116 |
+
jwtLifetimeSeconds?: number;
|
| 117 |
+
/**
|
| 118 |
+
* Space-separated scopes values requested by the client.
|
| 119 |
+
*/
|
| 120 |
+
scope?: string;
|
| 121 |
+
/**
|
| 122 |
+
* The issuer URL of the authorization server these credentials were registered with.
|
| 123 |
+
* When set, `auth()` only presents them to that authorization server and throws if the
|
| 124 |
+
* MCP server advertises a different URL (one trailing slash aside).
|
| 125 |
+
*
|
| 126 |
+
* Omitting it is deprecated: the credentials then go to whichever authorization server
|
| 127 |
+
* the MCP server advertises first.
|
| 128 |
+
*/
|
| 129 |
+
expectedIssuer?: string;
|
| 130 |
+
}
|
| 131 |
+
/**
|
| 132 |
+
* OAuth provider for client_credentials grant with private_key_jwt authentication.
|
| 133 |
+
*
|
| 134 |
+
* This provider is designed for machine-to-machine authentication where
|
| 135 |
+
* the client authenticates using a signed JWT assertion (RFC 7523 Section 2.2).
|
| 136 |
+
*
|
| 137 |
+
* @example
|
| 138 |
+
* const provider = new PrivateKeyJwtProvider({
|
| 139 |
+
* clientId: 'my-client',
|
| 140 |
+
* privateKey: pemEncodedPrivateKey,
|
| 141 |
+
* algorithm: 'RS256',
|
| 142 |
+
* expectedIssuer: 'https://auth.example.com'
|
| 143 |
+
* });
|
| 144 |
+
*
|
| 145 |
+
* const transport = new StreamableHTTPClientTransport(serverUrl, {
|
| 146 |
+
* authProvider: provider
|
| 147 |
+
* });
|
| 148 |
+
*/
|
| 149 |
+
export declare class PrivateKeyJwtProvider implements OAuthClientProvider {
|
| 150 |
+
private _tokens?;
|
| 151 |
+
private _clientInfo;
|
| 152 |
+
private _clientMetadata;
|
| 153 |
+
addClientAuthentication: AddClientAuthentication;
|
| 154 |
+
constructor(options: PrivateKeyJwtProviderOptions & {
|
| 155 |
+
expectedIssuer: string;
|
| 156 |
+
});
|
| 157 |
+
/** @deprecated Pass `expectedIssuer` so the credentials are only sent to that authorization server. */
|
| 158 |
+
constructor(options: PrivateKeyJwtProviderOptions);
|
| 159 |
+
get redirectUrl(): undefined;
|
| 160 |
+
get clientMetadata(): OAuthClientMetadata;
|
| 161 |
+
clientInformation(): OAuthClientInformation;
|
| 162 |
+
saveClientInformation(info: OAuthClientInformation): void;
|
| 163 |
+
tokens(): OAuthTokens | undefined;
|
| 164 |
+
saveTokens(tokens: OAuthTokens): void;
|
| 165 |
+
redirectToAuthorization(): void;
|
| 166 |
+
saveCodeVerifier(): void;
|
| 167 |
+
codeVerifier(): string;
|
| 168 |
+
prepareTokenRequest(scope?: string): URLSearchParams;
|
| 169 |
+
}
|
| 170 |
+
/**
|
| 171 |
+
* Options for creating a StaticPrivateKeyJwtProvider.
|
| 172 |
+
*/
|
| 173 |
+
export interface StaticPrivateKeyJwtProviderOptions {
|
| 174 |
+
/**
|
| 175 |
+
* The client_id for this OAuth client.
|
| 176 |
+
*/
|
| 177 |
+
clientId: string;
|
| 178 |
+
/**
|
| 179 |
+
* A pre-built JWT client assertion to use for authentication.
|
| 180 |
+
*
|
| 181 |
+
* This token should already contain the appropriate claims
|
| 182 |
+
* (iss, sub, aud, exp, etc.) and be signed by the client's key.
|
| 183 |
+
*/
|
| 184 |
+
jwtBearerAssertion: string;
|
| 185 |
+
/**
|
| 186 |
+
* Optional client name for metadata.
|
| 187 |
+
*/
|
| 188 |
+
clientName?: string;
|
| 189 |
+
/**
|
| 190 |
+
* Space-separated scopes values requested by the client.
|
| 191 |
+
*/
|
| 192 |
+
scope?: string;
|
| 193 |
+
/**
|
| 194 |
+
* The issuer URL of the authorization server these credentials were registered with.
|
| 195 |
+
* When set, `auth()` only presents them to that authorization server and throws if the
|
| 196 |
+
* MCP server advertises a different URL (one trailing slash aside).
|
| 197 |
+
*
|
| 198 |
+
* Omitting it is deprecated: the credentials then go to whichever authorization server
|
| 199 |
+
* the MCP server advertises first.
|
| 200 |
+
*/
|
| 201 |
+
expectedIssuer?: string;
|
| 202 |
+
}
|
| 203 |
+
/**
|
| 204 |
+
* OAuth provider for client_credentials grant with a static private_key_jwt assertion.
|
| 205 |
+
*
|
| 206 |
+
* This provider mirrors {@link PrivateKeyJwtProvider} but instead of constructing and
|
| 207 |
+
* signing a JWT on each request, it accepts a pre-built JWT assertion string and
|
| 208 |
+
* uses it directly for authentication.
|
| 209 |
+
*/
|
| 210 |
+
export declare class StaticPrivateKeyJwtProvider implements OAuthClientProvider {
|
| 211 |
+
private _tokens?;
|
| 212 |
+
private _clientInfo;
|
| 213 |
+
private _clientMetadata;
|
| 214 |
+
addClientAuthentication: AddClientAuthentication;
|
| 215 |
+
constructor(options: StaticPrivateKeyJwtProviderOptions & {
|
| 216 |
+
expectedIssuer: string;
|
| 217 |
+
});
|
| 218 |
+
/** @deprecated Pass `expectedIssuer` so the credentials are only sent to that authorization server. */
|
| 219 |
+
constructor(options: StaticPrivateKeyJwtProviderOptions);
|
| 220 |
+
get redirectUrl(): undefined;
|
| 221 |
+
get clientMetadata(): OAuthClientMetadata;
|
| 222 |
+
clientInformation(): OAuthClientInformation;
|
| 223 |
+
saveClientInformation(info: OAuthClientInformation): void;
|
| 224 |
+
tokens(): OAuthTokens | undefined;
|
| 225 |
+
saveTokens(tokens: OAuthTokens): void;
|
| 226 |
+
redirectToAuthorization(): void;
|
| 227 |
+
saveCodeVerifier(): void;
|
| 228 |
+
codeVerifier(): string;
|
| 229 |
+
prepareTokenRequest(scope?: string): URLSearchParams;
|
| 230 |
+
}
|
| 231 |
+
//# sourceMappingURL=auth-extensions.d.ts.map
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.d.ts.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"version":3,"file":"auth-extensions.d.ts","sourceRoot":"","sources":["../../../src/client/auth-extensions.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAE,sBAAsB,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAC7F,OAAO,EAAE,uBAAuB,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAEzE;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,EAAE;IAC7C,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,GAAG,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC1D,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,CAAC,EAAE,MAAM,GAAG,GAAG,CAAC;IACxB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACpC,GAAG,uBAAuB,CAgE1B;AAoBD;;GAEG;AACH,MAAM,WAAW,gCAAgC;IAC7C;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;IAEjB;;OAEG;IACH,YAAY,EAAE,MAAM,CAAC;IAErB;;OAEG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;OAEG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf;;;;;;;OAOG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;CAC3B;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,qBAAa,yBAA0B,YAAW,mBAA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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"use strict";
|
| 2 |
+
/**
|
| 3 |
+
* OAuth provider extensions for specialized authentication flows.
|
| 4 |
+
*
|
| 5 |
+
* This module provides ready-to-use OAuthClientProvider implementations
|
| 6 |
+
* for common machine-to-machine authentication scenarios.
|
| 7 |
+
*/
|
| 8 |
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
| 9 |
+
if (k2 === undefined) k2 = k;
|
| 10 |
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
| 11 |
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
| 12 |
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
| 13 |
+
}
|
| 14 |
+
Object.defineProperty(o, k2, desc);
|
| 15 |
+
}) : (function(o, m, k, k2) {
|
| 16 |
+
if (k2 === undefined) k2 = k;
|
| 17 |
+
o[k2] = m[k];
|
| 18 |
+
}));
|
| 19 |
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
| 20 |
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
| 21 |
+
}) : function(o, v) {
|
| 22 |
+
o["default"] = v;
|
| 23 |
+
});
|
| 24 |
+
var __importStar = (this && this.__importStar) || function (mod) {
|
| 25 |
+
if (mod && mod.__esModule) return mod;
|
| 26 |
+
var result = {};
|
| 27 |
+
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
| 28 |
+
__setModuleDefault(result, mod);
|
| 29 |
+
return result;
|
| 30 |
+
};
|
| 31 |
+
Object.defineProperty(exports, "__esModule", { value: true });
|
| 32 |
+
exports.StaticPrivateKeyJwtProvider = exports.PrivateKeyJwtProvider = exports.ClientCredentialsProvider = void 0;
|
| 33 |
+
exports.createPrivateKeyJwtAuth = createPrivateKeyJwtAuth;
|
| 34 |
+
/**
|
| 35 |
+
* Helper to produce a private_key_jwt client authentication function.
|
| 36 |
+
*
|
| 37 |
+
* Usage:
|
| 38 |
+
* const addClientAuth = createPrivateKeyJwtAuth({ issuer, subject, privateKey, alg, audience? });
|
| 39 |
+
* // pass addClientAuth as provider.addClientAuthentication implementation
|
| 40 |
+
*/
|
| 41 |
+
function createPrivateKeyJwtAuth(options) {
|
| 42 |
+
return async (_headers, params, url, metadata) => {
|
| 43 |
+
// Lazy import to avoid heavy dependency unless used
|
| 44 |
+
if (typeof globalThis.crypto === 'undefined') {
|
| 45 |
+
throw new TypeError('crypto is not available, please ensure you add have Web Crypto API support for older Node.js versions (see https://github.com/modelcontextprotocol/typescript-sdk#nodejs-web-crypto-globalthiscrypto-compatibility)');
|
| 46 |
+
}
|
| 47 |
+
const jose = await Promise.resolve().then(() => __importStar(require('jose')));
|
| 48 |
+
const audience = String(options.audience ?? metadata?.issuer ?? url);
|
| 49 |
+
const lifetimeSeconds = options.lifetimeSeconds ?? 300;
|
| 50 |
+
const now = Math.floor(Date.now() / 1000);
|
| 51 |
+
const jti = `${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
| 52 |
+
const baseClaims = {
|
| 53 |
+
iss: options.issuer,
|
| 54 |
+
sub: options.subject,
|
| 55 |
+
aud: audience,
|
| 56 |
+
exp: now + lifetimeSeconds,
|
| 57 |
+
iat: now,
|
| 58 |
+
jti
|
| 59 |
+
};
|
| 60 |
+
const claims = options.claims ? { ...baseClaims, ...options.claims } : baseClaims;
|
| 61 |
+
// Import key for the requested algorithm
|
| 62 |
+
const alg = options.alg;
|
| 63 |
+
let key;
|
| 64 |
+
if (typeof options.privateKey === 'string') {
|
| 65 |
+
if (alg.startsWith('RS') || alg.startsWith('ES') || alg.startsWith('PS')) {
|
| 66 |
+
key = await jose.importPKCS8(options.privateKey, alg);
|
| 67 |
+
}
|
| 68 |
+
else if (alg.startsWith('HS')) {
|
| 69 |
+
key = new TextEncoder().encode(options.privateKey);
|
| 70 |
+
}
|
| 71 |
+
else {
|
| 72 |
+
throw new Error(`Unsupported algorithm ${alg}`);
|
| 73 |
+
}
|
| 74 |
+
}
|
| 75 |
+
else if (options.privateKey instanceof Uint8Array) {
|
| 76 |
+
if (alg.startsWith('HS')) {
|
| 77 |
+
key = options.privateKey;
|
| 78 |
+
}
|
| 79 |
+
else {
|
| 80 |
+
// Assume PKCS#8 DER in Uint8Array for asymmetric algorithms
|
| 81 |
+
key = await jose.importPKCS8(new TextDecoder().decode(options.privateKey), alg);
|
| 82 |
+
}
|
| 83 |
+
}
|
| 84 |
+
else {
|
| 85 |
+
// Treat as JWK
|
| 86 |
+
key = await jose.importJWK(options.privateKey, alg);
|
| 87 |
+
}
|
| 88 |
+
// Sign JWT
|
| 89 |
+
const assertion = await new jose.SignJWT(claims)
|
| 90 |
+
.setProtectedHeader({ alg, typ: 'JWT' })
|
| 91 |
+
.setIssuer(options.issuer)
|
| 92 |
+
.setSubject(options.subject)
|
| 93 |
+
.setAudience(audience)
|
| 94 |
+
.setIssuedAt(now)
|
| 95 |
+
.setExpirationTime(now + lifetimeSeconds)
|
| 96 |
+
.setJti(jti)
|
| 97 |
+
.sign(key);
|
| 98 |
+
params.set('client_assertion', assertion);
|
| 99 |
+
params.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer');
|
| 100 |
+
};
|
| 101 |
+
}
|
| 102 |
+
/**
|
| 103 |
+
* The `issuer` stamp for constructor-supplied client information. Omitting `expectedIssuer` is
|
| 104 |
+
* deprecated: nothing else says which authorization server such credentials belong to.
|
| 105 |
+
*/
|
| 106 |
+
function checkedExpectedIssuer(expectedIssuer) {
|
| 107 |
+
if (expectedIssuer === undefined) {
|
| 108 |
+
// eslint-disable-next-line no-console
|
| 109 |
+
console.warn('[mcp-sdk] Omitting `expectedIssuer` is deprecated. Without it, the MCP server decides which authorization ' +
|
| 110 |
+
"server receives this client's credentials; pass your authorization server's issuer URL as " +
|
| 111 |
+
'`expectedIssuer` so they are only sent there.');
|
| 112 |
+
}
|
| 113 |
+
else if (typeof expectedIssuer !== 'string' || !expectedIssuer) {
|
| 114 |
+
throw new Error("expectedIssuer must be the authorization server's issuer URL");
|
| 115 |
+
}
|
| 116 |
+
return expectedIssuer;
|
| 117 |
+
}
|
| 118 |
+
/**
|
| 119 |
+
* OAuth provider for client_credentials grant with client_secret_basic authentication.
|
| 120 |
+
*
|
| 121 |
+
* This provider is designed for machine-to-machine authentication where
|
| 122 |
+
* the client authenticates using a client_id and client_secret.
|
| 123 |
+
*
|
| 124 |
+
* @example
|
| 125 |
+
* const provider = new ClientCredentialsProvider({
|
| 126 |
+
* clientId: 'my-client',
|
| 127 |
+
* clientSecret: 'my-secret',
|
| 128 |
+
* expectedIssuer: 'https://auth.example.com'
|
| 129 |
+
* });
|
| 130 |
+
*
|
| 131 |
+
* const transport = new StreamableHTTPClientTransport(serverUrl, {
|
| 132 |
+
* authProvider: provider
|
| 133 |
+
* });
|
| 134 |
+
*/
|
| 135 |
+
class ClientCredentialsProvider {
|
| 136 |
+
constructor(options) {
|
| 137 |
+
this._clientInfo = {
|
| 138 |
+
client_id: options.clientId,
|
| 139 |
+
client_secret: options.clientSecret,
|
| 140 |
+
issuer: checkedExpectedIssuer(options.expectedIssuer)
|
| 141 |
+
};
|
| 142 |
+
this._clientMetadata = {
|
| 143 |
+
client_name: options.clientName ?? 'client-credentials-client',
|
| 144 |
+
redirect_uris: [],
|
| 145 |
+
grant_types: ['client_credentials'],
|
| 146 |
+
token_endpoint_auth_method: 'client_secret_basic',
|
| 147 |
+
scope: options.scope
|
| 148 |
+
};
|
| 149 |
+
}
|
| 150 |
+
get redirectUrl() {
|
| 151 |
+
return undefined;
|
| 152 |
+
}
|
| 153 |
+
get clientMetadata() {
|
| 154 |
+
return this._clientMetadata;
|
| 155 |
+
}
|
| 156 |
+
clientInformation() {
|
| 157 |
+
return this._clientInfo;
|
| 158 |
+
}
|
| 159 |
+
saveClientInformation(info) {
|
| 160 |
+
this._clientInfo = info;
|
| 161 |
+
}
|
| 162 |
+
tokens() {
|
| 163 |
+
return this._tokens;
|
| 164 |
+
}
|
| 165 |
+
saveTokens(tokens) {
|
| 166 |
+
this._tokens = tokens;
|
| 167 |
+
}
|
| 168 |
+
redirectToAuthorization() {
|
| 169 |
+
throw new Error('redirectToAuthorization is not used for client_credentials flow');
|
| 170 |
+
}
|
| 171 |
+
saveCodeVerifier() {
|
| 172 |
+
// Not used for client_credentials
|
| 173 |
+
}
|
| 174 |
+
codeVerifier() {
|
| 175 |
+
throw new Error('codeVerifier is not used for client_credentials flow');
|
| 176 |
+
}
|
| 177 |
+
prepareTokenRequest(scope) {
|
| 178 |
+
const params = new URLSearchParams({ grant_type: 'client_credentials' });
|
| 179 |
+
if (scope)
|
| 180 |
+
params.set('scope', scope);
|
| 181 |
+
return params;
|
| 182 |
+
}
|
| 183 |
+
}
|
| 184 |
+
exports.ClientCredentialsProvider = ClientCredentialsProvider;
|
| 185 |
+
/**
|
| 186 |
+
* OAuth provider for client_credentials grant with private_key_jwt authentication.
|
| 187 |
+
*
|
| 188 |
+
* This provider is designed for machine-to-machine authentication where
|
| 189 |
+
* the client authenticates using a signed JWT assertion (RFC 7523 Section 2.2).
|
| 190 |
+
*
|
| 191 |
+
* @example
|
| 192 |
+
* const provider = new PrivateKeyJwtProvider({
|
| 193 |
+
* clientId: 'my-client',
|
| 194 |
+
* privateKey: pemEncodedPrivateKey,
|
| 195 |
+
* algorithm: 'RS256',
|
| 196 |
+
* expectedIssuer: 'https://auth.example.com'
|
| 197 |
+
* });
|
| 198 |
+
*
|
| 199 |
+
* const transport = new StreamableHTTPClientTransport(serverUrl, {
|
| 200 |
+
* authProvider: provider
|
| 201 |
+
* });
|
| 202 |
+
*/
|
| 203 |
+
class PrivateKeyJwtProvider {
|
| 204 |
+
constructor(options) {
|
| 205 |
+
this._clientInfo = {
|
| 206 |
+
client_id: options.clientId,
|
| 207 |
+
issuer: checkedExpectedIssuer(options.expectedIssuer)
|
| 208 |
+
};
|
| 209 |
+
this._clientMetadata = {
|
| 210 |
+
client_name: options.clientName ?? 'private-key-jwt-client',
|
| 211 |
+
redirect_uris: [],
|
| 212 |
+
grant_types: ['client_credentials'],
|
| 213 |
+
token_endpoint_auth_method: 'private_key_jwt',
|
| 214 |
+
scope: options.scope
|
| 215 |
+
};
|
| 216 |
+
this.addClientAuthentication = createPrivateKeyJwtAuth({
|
| 217 |
+
issuer: options.clientId,
|
| 218 |
+
subject: options.clientId,
|
| 219 |
+
privateKey: options.privateKey,
|
| 220 |
+
alg: options.algorithm,
|
| 221 |
+
lifetimeSeconds: options.jwtLifetimeSeconds
|
| 222 |
+
});
|
| 223 |
+
}
|
| 224 |
+
get redirectUrl() {
|
| 225 |
+
return undefined;
|
| 226 |
+
}
|
| 227 |
+
get clientMetadata() {
|
| 228 |
+
return this._clientMetadata;
|
| 229 |
+
}
|
| 230 |
+
clientInformation() {
|
| 231 |
+
return this._clientInfo;
|
| 232 |
+
}
|
| 233 |
+
saveClientInformation(info) {
|
| 234 |
+
this._clientInfo = info;
|
| 235 |
+
}
|
| 236 |
+
tokens() {
|
| 237 |
+
return this._tokens;
|
| 238 |
+
}
|
| 239 |
+
saveTokens(tokens) {
|
| 240 |
+
this._tokens = tokens;
|
| 241 |
+
}
|
| 242 |
+
redirectToAuthorization() {
|
| 243 |
+
throw new Error('redirectToAuthorization is not used for client_credentials flow');
|
| 244 |
+
}
|
| 245 |
+
saveCodeVerifier() {
|
| 246 |
+
// Not used for client_credentials
|
| 247 |
+
}
|
| 248 |
+
codeVerifier() {
|
| 249 |
+
throw new Error('codeVerifier is not used for client_credentials flow');
|
| 250 |
+
}
|
| 251 |
+
prepareTokenRequest(scope) {
|
| 252 |
+
const params = new URLSearchParams({ grant_type: 'client_credentials' });
|
| 253 |
+
if (scope)
|
| 254 |
+
params.set('scope', scope);
|
| 255 |
+
return params;
|
| 256 |
+
}
|
| 257 |
+
}
|
| 258 |
+
exports.PrivateKeyJwtProvider = PrivateKeyJwtProvider;
|
| 259 |
+
/**
|
| 260 |
+
* OAuth provider for client_credentials grant with a static private_key_jwt assertion.
|
| 261 |
+
*
|
| 262 |
+
* This provider mirrors {@link PrivateKeyJwtProvider} but instead of constructing and
|
| 263 |
+
* signing a JWT on each request, it accepts a pre-built JWT assertion string and
|
| 264 |
+
* uses it directly for authentication.
|
| 265 |
+
*/
|
| 266 |
+
class StaticPrivateKeyJwtProvider {
|
| 267 |
+
constructor(options) {
|
| 268 |
+
this._clientInfo = {
|
| 269 |
+
client_id: options.clientId,
|
| 270 |
+
issuer: checkedExpectedIssuer(options.expectedIssuer)
|
| 271 |
+
};
|
| 272 |
+
this._clientMetadata = {
|
| 273 |
+
client_name: options.clientName ?? 'static-private-key-jwt-client',
|
| 274 |
+
redirect_uris: [],
|
| 275 |
+
grant_types: ['client_credentials'],
|
| 276 |
+
token_endpoint_auth_method: 'private_key_jwt',
|
| 277 |
+
scope: options.scope
|
| 278 |
+
};
|
| 279 |
+
const assertion = options.jwtBearerAssertion;
|
| 280 |
+
this.addClientAuthentication = async (_headers, params) => {
|
| 281 |
+
params.set('client_assertion', assertion);
|
| 282 |
+
params.set('client_assertion_type', 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer');
|
| 283 |
+
};
|
| 284 |
+
}
|
| 285 |
+
get redirectUrl() {
|
| 286 |
+
return undefined;
|
| 287 |
+
}
|
| 288 |
+
get clientMetadata() {
|
| 289 |
+
return this._clientMetadata;
|
| 290 |
+
}
|
| 291 |
+
clientInformation() {
|
| 292 |
+
return this._clientInfo;
|
| 293 |
+
}
|
| 294 |
+
saveClientInformation(info) {
|
| 295 |
+
this._clientInfo = info;
|
| 296 |
+
}
|
| 297 |
+
tokens() {
|
| 298 |
+
return this._tokens;
|
| 299 |
+
}
|
| 300 |
+
saveTokens(tokens) {
|
| 301 |
+
this._tokens = tokens;
|
| 302 |
+
}
|
| 303 |
+
redirectToAuthorization() {
|
| 304 |
+
throw new Error('redirectToAuthorization is not used for client_credentials flow');
|
| 305 |
+
}
|
| 306 |
+
saveCodeVerifier() {
|
| 307 |
+
// Not used for client_credentials
|
| 308 |
+
}
|
| 309 |
+
codeVerifier() {
|
| 310 |
+
throw new Error('codeVerifier is not used for client_credentials flow');
|
| 311 |
+
}
|
| 312 |
+
prepareTokenRequest(scope) {
|
| 313 |
+
const params = new URLSearchParams({ grant_type: 'client_credentials' });
|
| 314 |
+
if (scope)
|
| 315 |
+
params.set('scope', scope);
|
| 316 |
+
return params;
|
| 317 |
+
}
|
| 318 |
+
}
|
| 319 |
+
exports.StaticPrivateKeyJwtProvider = StaticPrivateKeyJwtProvider;
|
| 320 |
+
//# sourceMappingURL=auth-extensions.js.map
|
.nvm/versions/node/v20.20.2/lib/node_modules/@modelcontextprotocol/server-filesystem/node_modules/@modelcontextprotocol/sdk/dist/cjs/client/auth-extensions.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"version":3,"file":"auth-extensions.js","sourceRoot":"","sources":["../../../src/client/auth-extensions.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;;;;;;;;;;;;;;;;;;;;;;;;AAaH,0DAwEC;AA/ED;;;;;;GAMG;AACH,SAAgB,uBAAuB,CAAC,OAQvC;IACG,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,QAAQ,EAAE,EAAE;QAC7C,oDAAoD;QACpD,IAAI,OAAO,UAAU,CAAC,MAAM,KAAK,WAAW,EAAE,CAAC;YAC3C,MAAM,IAAI,SAAS,CACf,qNAAqN,CACxN,CAAC;QACN,CAAC;QAED,MAAM,IAAI,GAAG,wDAAa,MAAM,GAAC,CAAC;QAElC,MAAM,QAAQ,GAAG,MA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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { OAuthClientMetadata, OAuthClientInformationMixed, OAuthTokens, OAuthMetadata, OAuthClientInformationFull, OAuthProtectedResourceMetadata, AuthorizationServerMetadata } from '../shared/auth.js';
|
| 2 |
+
import { OAuthError } from '../server/auth/errors.js';
|
| 3 |
+
import { FetchLike } from '../shared/transport.js';
|
| 4 |
+
/**
|
| 5 |
+
* Function type for adding client authentication to token requests.
|
| 6 |
+
*/
|
| 7 |
+
export type AddClientAuthentication = (headers: Headers, params: URLSearchParams, url: string | URL, metadata?: AuthorizationServerMetadata) => void | Promise<void>;
|
| 8 |
+
/**
|
| 9 |
+
* Implements an end-to-end OAuth client to be used with one MCP server.
|
| 10 |
+
*
|
| 11 |
+
* This client relies upon a concept of an authorized "session," the exact
|
| 12 |
+
* meaning of which is application-defined. Tokens, authorization codes, and
|
| 13 |
+
* code verifiers should not cross different sessions.
|
| 14 |
+
*/
|
| 15 |
+
export interface OAuthClientProvider {
|
| 16 |
+
/**
|
| 17 |
+
* The URL to redirect the user agent to after authorization.
|
| 18 |
+
* Return undefined for non-interactive flows that don't require user interaction
|
| 19 |
+
* (e.g., client_credentials, jwt-bearer).
|
| 20 |
+
*/
|
| 21 |
+
get redirectUrl(): string | URL | undefined;
|
| 22 |
+
/**
|
| 23 |
+
* External URL the server should use to fetch client metadata document
|
| 24 |
+
*/
|
| 25 |
+
clientMetadataUrl?: string;
|
| 26 |
+
/**
|
| 27 |
+
* Metadata about this OAuth client.
|
| 28 |
+
*/
|
| 29 |
+
get clientMetadata(): OAuthClientMetadata;
|
| 30 |
+
/**
|
| 31 |
+
* Returns a OAuth2 state parameter.
|
| 32 |
+
*/
|
| 33 |
+
state?(): string | Promise<string>;
|
| 34 |
+
/**
|
| 35 |
+
* Loads information about this OAuth client, as registered already with the
|
| 36 |
+
* server, or returns `undefined` if the client is not registered with the
|
| 37 |
+
* server.
|
| 38 |
+
*
|
| 39 |
+
* A provider that returns pre-registered credentials should include `issuer`, the URL of
|
| 40 |
+
* the authorization server they were registered with; {@linkcode auth} then does not
|
| 41 |
+
* present them to any other.
|
| 42 |
+
*/
|
| 43 |
+
clientInformation(): OAuthClientInformationMixed | undefined | Promise<OAuthClientInformationMixed | undefined>;
|
| 44 |
+
/**
|
| 45 |
+
* If implemented, this permits the OAuth client to dynamically register with
|
| 46 |
+
* the server. Client information saved this way should later be read via
|
| 47 |
+
* `clientInformation()`.
|
| 48 |
+
*
|
| 49 |
+
* This method is not required to be implemented if client information is
|
| 50 |
+
* statically known (e.g., pre-registered).
|
| 51 |
+
*
|
| 52 |
+
* The object carries `issuer`, the authorization server it was obtained from. Store it
|
| 53 |
+
* unchanged so that {@linkcode auth} does not reuse the registration with a different one.
|
| 54 |
+
* Client information stored without `issuer` is passed here, with it, after its first successful use.
|
| 55 |
+
*/
|
| 56 |
+
saveClientInformation?(clientInformation: OAuthClientInformationMixed): void | Promise<void>;
|
| 57 |
+
/**
|
| 58 |
+
* Loads any existing OAuth tokens for the current session, or returns
|
| 59 |
+
* `undefined` if there are no saved tokens.
|
| 60 |
+
*/
|
| 61 |
+
tokens(): OAuthTokens | undefined | Promise<OAuthTokens | undefined>;
|
| 62 |
+
/**
|
| 63 |
+
* Stores new OAuth tokens for the current session, after a successful
|
| 64 |
+
* authorization.
|
| 65 |
+
*
|
| 66 |
+
* The object carries `issuer`, the authorization server that issued the tokens. Store it
|
| 67 |
+
* unchanged so that {@linkcode auth} does not present the refresh token to a different one.
|
| 68 |
+
*/
|
| 69 |
+
saveTokens(tokens: OAuthTokens): void | Promise<void>;
|
| 70 |
+
/**
|
| 71 |
+
* Invoked to redirect the user agent to the given URL to begin the authorization flow.
|
| 72 |
+
*/
|
| 73 |
+
redirectToAuthorization(authorizationUrl: URL): void | Promise<void>;
|
| 74 |
+
/**
|
| 75 |
+
* Saves a PKCE code verifier for the current session, before redirecting to
|
| 76 |
+
* the authorization flow.
|
| 77 |
+
*/
|
| 78 |
+
saveCodeVerifier(codeVerifier: string): void | Promise<void>;
|
| 79 |
+
/**
|
| 80 |
+
* Loads the PKCE code verifier for the current session, necessary to validate
|
| 81 |
+
* the authorization result.
|
| 82 |
+
*/
|
| 83 |
+
codeVerifier(): string | Promise<string>;
|
| 84 |
+
/**
|
| 85 |
+
* Adds custom client authentication to OAuth token requests.
|
| 86 |
+
*
|
| 87 |
+
* This optional method allows implementations to customize how client credentials
|
| 88 |
+
* are included in token exchange and refresh requests. When provided, this method
|
| 89 |
+
* is called instead of the default authentication logic, giving full control over
|
| 90 |
+
* the authentication mechanism.
|
| 91 |
+
*
|
| 92 |
+
* Common use cases include:
|
| 93 |
+
* - Supporting authentication methods beyond the standard OAuth 2.0 methods
|
| 94 |
+
* - Adding custom headers for proprietary authentication schemes
|
| 95 |
+
* - Implementing client assertion-based authentication (e.g., JWT bearer tokens)
|
| 96 |
+
*
|
| 97 |
+
* @param headers - The request headers (can be modified to add authentication)
|
| 98 |
+
* @param params - The request body parameters (can be modified to add credentials)
|
| 99 |
+
* @param url - The token endpoint URL being called
|
| 100 |
+
* @param metadata - Optional OAuth metadata for the server, which may include supported authentication methods
|
| 101 |
+
*/
|
| 102 |
+
addClientAuthentication?: AddClientAuthentication;
|
| 103 |
+
/**
|
| 104 |
+
* If defined, overrides the selection and validation of the
|
| 105 |
+
* RFC 8707 Resource Indicator. If left undefined, default
|
| 106 |
+
* validation behavior will be used.
|
| 107 |
+
*
|
| 108 |
+
* Implementations must verify the returned resource matches the MCP server.
|
| 109 |
+
*/
|
| 110 |
+
validateResourceURL?(serverUrl: string | URL, resource?: string): Promise<URL | undefined>;
|
| 111 |
+
/**
|
| 112 |
+
* If implemented, provides a way for the client to invalidate (e.g. delete) the specified
|
| 113 |
+
* credentials, in the case where the server has indicated that they are no longer valid.
|
| 114 |
+
* This avoids requiring the user to intervene manually.
|
| 115 |
+
*/
|
| 116 |
+
invalidateCredentials?(scope: 'all' | 'client' | 'tokens' | 'verifier' | 'discovery'): void | Promise<void>;
|
| 117 |
+
/**
|
| 118 |
+
* Prepares grant-specific parameters for a token request.
|
| 119 |
+
*
|
| 120 |
+
* This optional method allows providers to customize the token request based on
|
| 121 |
+
* the grant type they support. When implemented, it returns the grant type and
|
| 122 |
+
* any grant-specific parameters needed for the token exchange.
|
| 123 |
+
*
|
| 124 |
+
* If not implemented, the default behavior depends on the flow:
|
| 125 |
+
* - For authorization code flow: uses code, code_verifier, and redirect_uri
|
| 126 |
+
* - For client_credentials: detected via grant_types in clientMetadata
|
| 127 |
+
*
|
| 128 |
+
* @param scope - Optional scope to request
|
| 129 |
+
* @returns Grant type and parameters, or undefined to use default behavior
|
| 130 |
+
*
|
| 131 |
+
* @example
|
| 132 |
+
* // For client_credentials grant:
|
| 133 |
+
* prepareTokenRequest(scope) {
|
| 134 |
+
* return {
|
| 135 |
+
* grantType: 'client_credentials',
|
| 136 |
+
* params: scope ? { scope } : {}
|
| 137 |
+
* };
|
| 138 |
+
* }
|
| 139 |
+
*
|
| 140 |
+
* @example
|
| 141 |
+
* // For authorization_code grant (default behavior):
|
| 142 |
+
* async prepareTokenRequest() {
|
| 143 |
+
* return {
|
| 144 |
+
* grantType: 'authorization_code',
|
| 145 |
+
* params: {
|
| 146 |
+
* code: this.authorizationCode,
|
| 147 |
+
* code_verifier: await this.codeVerifier(),
|
| 148 |
+
* redirect_uri: String(this.redirectUrl)
|
| 149 |
+
* }
|
| 150 |
+
* };
|
| 151 |
+
* }
|
| 152 |
+
*/
|
| 153 |
+
prepareTokenRequest?(scope?: string): URLSearchParams | Promise<URLSearchParams | undefined> | undefined;
|
| 154 |
+
/**
|
| 155 |
+
* Saves the OAuth discovery state after RFC 9728 and authorization server metadata
|
| 156 |
+
* discovery. Providers can persist this state to avoid redundant discovery requests
|
| 157 |
+
* on subsequent {@linkcode auth} calls.
|
| 158 |
+
*
|
| 159 |
+
* This state can also be provided out-of-band (e.g., from a previous session or
|
| 160 |
+
* external configuration) to bootstrap the OAuth flow without discovery.
|
| 161 |
+
*
|
| 162 |
+
* Called by {@linkcode auth} after successful discovery.
|
| 163 |
+
*/
|
| 164 |
+
saveDiscoveryState?(state: OAuthDiscoveryState): void | Promise<void>;
|
| 165 |
+
/**
|
| 166 |
+
* Returns previously saved discovery state, or `undefined` if none is cached.
|
| 167 |
+
*
|
| 168 |
+
* When available, {@linkcode auth} restores the discovery state (authorization server
|
| 169 |
+
* URL, resource metadata, etc.) instead of performing RFC 9728 discovery, reducing
|
| 170 |
+
* latency on subsequent calls.
|
| 171 |
+
*
|
| 172 |
+
* Providers should clear cached discovery state on repeated authentication failures
|
| 173 |
+
* (via {@linkcode invalidateCredentials} with scope `'discovery'` or `'all'`) to allow
|
| 174 |
+
* re-discovery in case the authorization server has changed.
|
| 175 |
+
*/
|
| 176 |
+
discoveryState?(): OAuthDiscoveryState | undefined | Promise<OAuthDiscoveryState | undefined>;
|
| 177 |
+
}
|
| 178 |
+
/**
|
| 179 |
+
* Discovery state that can be persisted across sessions by an {@linkcode OAuthClientProvider}.
|
| 180 |
+
*
|
| 181 |
+
* Contains the results of RFC 9728 protected resource metadata discovery and
|
| 182 |
+
* authorization server metadata discovery. Persisting this state avoids
|
| 183 |
+
* redundant discovery HTTP requests on subsequent {@linkcode auth} calls.
|
| 184 |
+
*/
|
| 185 |
+
export interface OAuthDiscoveryState extends OAuthServerInfo {
|
| 186 |
+
/** The URL at which the protected resource metadata was found, if available. */
|
| 187 |
+
resourceMetadataUrl?: string;
|
| 188 |
+
}
|
| 189 |
+
export type AuthResult = 'AUTHORIZED' | 'REDIRECT';
|
| 190 |
+
export declare class UnauthorizedError extends Error {
|
| 191 |
+
constructor(message?: string);
|
| 192 |
+
}
|
| 193 |
+
type ClientAuthMethod = 'client_secret_basic' | 'client_secret_post' | 'none';
|
| 194 |
+
/**
|
| 195 |
+
* Determines the best client authentication method to use based on server support and client configuration.
|
| 196 |
+
*
|
| 197 |
+
* Priority order (highest to lowest):
|
| 198 |
+
* 1. client_secret_basic (if client secret is available)
|
| 199 |
+
* 2. client_secret_post (if client secret is available)
|
| 200 |
+
* 3. none (for public clients)
|
| 201 |
+
*
|
| 202 |
+
* @param clientInformation - OAuth client information containing credentials
|
| 203 |
+
* @param supportedMethods - Authentication methods supported by the authorization server
|
| 204 |
+
* @returns The selected authentication method
|
| 205 |
+
*/
|
| 206 |
+
export declare function selectClientAuthMethod(clientInformation: OAuthClientInformationMixed, supportedMethods: string[]): ClientAuthMethod;
|
| 207 |
+
/**
|
| 208 |
+
* Parses an OAuth error response from a string or Response object.
|
| 209 |
+
*
|
| 210 |
+
* If the input is a standard OAuth2.0 error response, it will be parsed according to the spec
|
| 211 |
+
* and an instance of the appropriate OAuthError subclass will be returned.
|
| 212 |
+
* If parsing fails, it falls back to a generic ServerError that includes
|
| 213 |
+
* the response status (if available) and original content.
|
| 214 |
+
*
|
| 215 |
+
* @param input - A Response object or string containing the error response
|
| 216 |
+
* @returns A Promise that resolves to an OAuthError instance
|
| 217 |
+
*/
|
| 218 |
+
export declare function parseErrorResponse(input: Response | string): Promise<OAuthError>;
|
| 219 |
+
/**
|
| 220 |
+
* Orchestrates the full auth flow with a server.
|
| 221 |
+
*
|
| 222 |
+
* This can be used as a single entry point for all authorization functionality,
|
| 223 |
+
* instead of linking together the other lower-level functions in this module.
|
| 224 |
+
*/
|
| 225 |
+
export declare function auth(provider: OAuthClientProvider, options: {
|
| 226 |
+
serverUrl: string | URL;
|
| 227 |
+
authorizationCode?: string;
|
| 228 |
+
scope?: string;
|
| 229 |
+
resourceMetadataUrl?: URL;
|
| 230 |
+
fetchFn?: FetchLike;
|
| 231 |
+
}): Promise<AuthResult>;
|
| 232 |
+
/**
|
| 233 |
+
* SEP-991: URL-based Client IDs
|
| 234 |
+
* Validate that the client_id is a valid URL with https scheme
|
| 235 |
+
*/
|
| 236 |
+
export declare function isHttpsUrl(value?: string): boolean;
|
| 237 |
+
/**
|
| 238 |
+
* Selects the RFC 8707 resource indicator for an MCP server: the provider's
|
| 239 |
+
* {@linkcode OAuthClientProvider.validateResourceURL | validateResourceURL} result when
|
| 240 |
+
* implemented, otherwise the protected resource metadata's `resource` (checked against the
|
| 241 |
+
* server URL with `checkResourceAllowed`), or `undefined` when there is no metadata.
|
| 242 |
+
*
|
| 243 |
+
* The result is a parsed `URL`, so a pathless indicator such as `https://example.com` has
|
| 244 |
+
* the `href` `https://example.com/`. {@linkcode auth} therefore sends the metadata string
|
| 245 |
+
* verbatim instead of this URL's `href` (#1968); callers that emit the `resource`
|
| 246 |
+
* parameter themselves should do the same.
|
| 247 |
+
*/
|
| 248 |
+
export declare function selectResourceURL(serverUrl: string | URL, provider: OAuthClientProvider, resourceMetadata?: OAuthProtectedResourceMetadata): Promise<URL | undefined>;
|
| 249 |
+
/**
|
| 250 |
+
* Extract resource_metadata, scope, and error from WWW-Authenticate header.
|
| 251 |
+
*/
|
| 252 |
+
export declare function extractWWWAuthenticateParams(res: Response): {
|
| 253 |
+
resourceMetadataUrl?: URL;
|
| 254 |
+
scope?: string;
|
| 255 |
+
error?: string;
|
| 256 |
+
};
|
| 257 |
+
/**
|
| 258 |
+
* Extract resource_metadata from response header.
|
| 259 |
+
* @deprecated Use `extractWWWAuthenticateParams` instead.
|
| 260 |
+
*/
|
| 261 |
+
export declare function extractResourceMetadataUrl(res: Response): URL | undefined;
|
| 262 |
+
/**
|
| 263 |
+
* Looks up RFC 9728 OAuth 2.0 Protected Resource Metadata.
|
| 264 |
+
*
|
| 265 |
+
* If the server returns a 404 for the well-known endpoint, this function will
|
| 266 |
+
* return `undefined`. Any other errors will be thrown as exceptions.
|
| 267 |
+
*/
|
| 268 |
+
export declare function discoverOAuthProtectedResourceMetadata(serverUrl: string | URL, opts?: {
|
| 269 |
+
protocolVersion?: string;
|
| 270 |
+
resourceMetadataUrl?: string | URL;
|
| 271 |
+
}, fetchFn?: FetchLike): Promise<OAuthProtectedResourceMetadata>;
|
| 272 |
+
/**
|
| 273 |
+
* Looks up RFC 8414 OAuth 2.0 Authorization Server Metadata.
|
| 274 |
+
*
|
| 275 |
+
* If the server returns a 404 for the well-known endpoint, this function will
|
| 276 |
+
* return `undefined`. Any other errors will be thrown as exceptions.
|
| 277 |
+
*
|
| 278 |
+
* @deprecated This function is deprecated in favor of `discoverAuthorizationServerMetadata`.
|
| 279 |
+
*/
|
| 280 |
+
export declare function discoverOAuthMetadata(issuer: string | URL, { authorizationServerUrl, protocolVersion }?: {
|
| 281 |
+
authorizationServerUrl?: string | URL;
|
| 282 |
+
protocolVersion?: string;
|
| 283 |
+
}, fetchFn?: FetchLike): Promise<OAuthMetadata | undefined>;
|
| 284 |
+
/**
|
| 285 |
+
* Builds a list of discovery URLs to try for authorization server metadata.
|
| 286 |
+
* URLs are returned in priority order:
|
| 287 |
+
* 1. OAuth metadata at the given URL
|
| 288 |
+
* 2. OIDC metadata endpoints at the given URL
|
| 289 |
+
*/
|
| 290 |
+
export declare function buildDiscoveryUrls(authorizationServerUrl: string | URL): {
|
| 291 |
+
url: URL;
|
| 292 |
+
type: 'oauth' | 'oidc';
|
| 293 |
+
}[];
|
| 294 |
+
/**
|
| 295 |
+
* Discovers authorization server metadata with support for RFC 8414 OAuth 2.0 Authorization Server Metadata
|
| 296 |
+
* and OpenID Connect Discovery 1.0 specifications.
|
| 297 |
+
*
|
| 298 |
+
* This function implements a fallback strategy for authorization server discovery:
|
| 299 |
+
* 1. Attempts RFC 8414 OAuth metadata discovery first
|
| 300 |
+
* 2. If OAuth discovery fails, falls back to OpenID Connect Discovery
|
| 301 |
+
*
|
| 302 |
+
* @param authorizationServerUrl - The authorization server URL obtained from the MCP Server's
|
| 303 |
+
* protected resource metadata, or the MCP server's URL if the
|
| 304 |
+
* metadata was not found.
|
| 305 |
+
* @param options - Configuration options
|
| 306 |
+
* @param options.fetchFn - Optional fetch function for making HTTP requests, defaults to global fetch
|
| 307 |
+
* @param options.protocolVersion - MCP protocol version to use, defaults to LATEST_PROTOCOL_VERSION
|
| 308 |
+
* @returns Promise resolving to authorization server metadata, or undefined if discovery fails
|
| 309 |
+
*/
|
| 310 |
+
export declare function discoverAuthorizationServerMetadata(authorizationServerUrl: string | URL, { fetchFn, protocolVersion }?: {
|
| 311 |
+
fetchFn?: FetchLike;
|
| 312 |
+
protocolVersion?: string;
|
| 313 |
+
}): Promise<AuthorizationServerMetadata | undefined>;
|
| 314 |
+
/**
|
| 315 |
+
* Result of {@linkcode discoverOAuthServerInfo}.
|
| 316 |
+
*/
|
| 317 |
+
export interface OAuthServerInfo {
|
| 318 |
+
/**
|
| 319 |
+
* The authorization server URL, either discovered via RFC 9728
|
| 320 |
+
* or derived from the MCP server URL as a fallback.
|
| 321 |
+
*/
|
| 322 |
+
authorizationServerUrl: string;
|
| 323 |
+
/**
|
| 324 |
+
* The authorization server metadata (endpoints, capabilities),
|
| 325 |
+
* or `undefined` if metadata discovery failed.
|
| 326 |
+
*/
|
| 327 |
+
authorizationServerMetadata?: AuthorizationServerMetadata;
|
| 328 |
+
/**
|
| 329 |
+
* The OAuth 2.0 Protected Resource Metadata from RFC 9728,
|
| 330 |
+
* or `undefined` if the server does not support it.
|
| 331 |
+
*/
|
| 332 |
+
resourceMetadata?: OAuthProtectedResourceMetadata;
|
| 333 |
+
}
|
| 334 |
+
/**
|
| 335 |
+
* Discovers the authorization server for an MCP server following
|
| 336 |
+
* {@link https://datatracker.ietf.org/doc/html/rfc9728 | RFC 9728} (OAuth 2.0 Protected
|
| 337 |
+
* Resource Metadata), with fallback to treating the server URL as the
|
| 338 |
+
* authorization server.
|
| 339 |
+
*
|
| 340 |
+
* This function combines two discovery steps into one call:
|
| 341 |
+
* 1. Probes `/.well-known/oauth-protected-resource` on the MCP server to find the
|
| 342 |
+
* authorization server URL (RFC 9728).
|
| 343 |
+
* 2. Fetches authorization server metadata from that URL (RFC 8414 / OpenID Connect Discovery).
|
| 344 |
+
*
|
| 345 |
+
* Use this when you need the authorization server metadata for operations outside the
|
| 346 |
+
* {@linkcode auth} orchestrator, such as token refresh or token revocation.
|
| 347 |
+
*
|
| 348 |
+
* @param serverUrl - The MCP resource server URL
|
| 349 |
+
* @param opts - Optional configuration
|
| 350 |
+
* @param opts.resourceMetadataUrl - Override URL for the protected resource metadata endpoint
|
| 351 |
+
* @param opts.fetchFn - Custom fetch function for HTTP requests
|
| 352 |
+
* @returns Authorization server URL, metadata, and resource metadata (if available)
|
| 353 |
+
*/
|
| 354 |
+
export declare function discoverOAuthServerInfo(serverUrl: string | URL, opts?: {
|
| 355 |
+
resourceMetadataUrl?: URL;
|
| 356 |
+
fetchFn?: FetchLike;
|
| 357 |
+
}): Promise<OAuthServerInfo>;
|
| 358 |
+
/**
|
| 359 |
+
* Begins the authorization flow with the given server, by generating a PKCE challenge and constructing the authorization URL.
|
| 360 |
+
*/
|
| 361 |
+
export declare function startAuthorization(authorizationServerUrl: string | URL, { metadata, clientInformation, redirectUrl, scope, state, resource }: {
|
| 362 |
+
metadata?: AuthorizationServerMetadata;
|
| 363 |
+
clientInformation: OAuthClientInformationMixed;
|
| 364 |
+
redirectUrl: string | URL;
|
| 365 |
+
scope?: string;
|
| 366 |
+
state?: string;
|
| 367 |
+
resource?: string | URL;
|
| 368 |
+
}): Promise<{
|
| 369 |
+
authorizationUrl: URL;
|
| 370 |
+
codeVerifier: string;
|
| 371 |
+
}>;
|
| 372 |
+
/**
|
| 373 |
+
* Prepares token request parameters for an authorization code exchange.
|
| 374 |
+
*
|
| 375 |
+
* This is the default implementation used by fetchToken when the provider
|
| 376 |
+
* doesn't implement prepareTokenRequest.
|
| 377 |
+
*
|
| 378 |
+
* @param authorizationCode - The authorization code received from the authorization endpoint
|
| 379 |
+
* @param codeVerifier - The PKCE code verifier
|
| 380 |
+
* @param redirectUri - The redirect URI used in the authorization request
|
| 381 |
+
* @returns URLSearchParams for the authorization_code grant
|
| 382 |
+
*/
|
| 383 |
+
export declare function prepareAuthorizationCodeRequest(authorizationCode: string, codeVerifier: string, redirectUri: string | URL): URLSearchParams;
|
| 384 |
+
/**
|
| 385 |
+
* Exchanges an authorization code for an access token with the given server.
|
| 386 |
+
*
|
| 387 |
+
* Supports multiple client authentication methods as specified in OAuth 2.1:
|
| 388 |
+
* - Automatically selects the best authentication method based on server support
|
| 389 |
+
* - Falls back to appropriate defaults when server metadata is unavailable
|
| 390 |
+
*
|
| 391 |
+
* @param authorizationServerUrl - The authorization server's base URL
|
| 392 |
+
* @param options - Configuration object containing client info, auth code, etc.
|
| 393 |
+
* @returns Promise resolving to OAuth tokens
|
| 394 |
+
* @throws {Error} When token exchange fails or authentication is invalid
|
| 395 |
+
*/
|
| 396 |
+
export declare function exchangeAuthorization(authorizationServerUrl: string | URL, { metadata, clientInformation, authorizationCode, codeVerifier, redirectUri, resource, addClientAuthentication, fetchFn }: {
|
| 397 |
+
metadata?: AuthorizationServerMetadata;
|
| 398 |
+
clientInformation: OAuthClientInformationMixed;
|
| 399 |
+
authorizationCode: string;
|
| 400 |
+
codeVerifier: string;
|
| 401 |
+
redirectUri: string | URL;
|
| 402 |
+
resource?: string | URL;
|
| 403 |
+
addClientAuthentication?: OAuthClientProvider['addClientAuthentication'];
|
| 404 |
+
fetchFn?: FetchLike;
|
| 405 |
+
}): Promise<OAuthTokens>;
|
| 406 |
+
/**
|
| 407 |
+
* Exchange a refresh token for an updated access token.
|
| 408 |
+
*
|
| 409 |
+
* Supports multiple client authentication methods as specified in OAuth 2.1:
|
| 410 |
+
* - Automatically selects the best authentication method based on server support
|
| 411 |
+
* - Preserves the original refresh token if a new one is not returned
|
| 412 |
+
*
|
| 413 |
+
* @param authorizationServerUrl - The authorization server's base URL
|
| 414 |
+
* @param options - Configuration object containing client info, refresh token, etc.
|
| 415 |
+
* @returns Promise resolving to OAuth tokens (preserves original refresh_token if not replaced)
|
| 416 |
+
* @throws {Error} When token refresh fails or authentication is invalid
|
| 417 |
+
*/
|
| 418 |
+
export declare function refreshAuthorization(authorizationServerUrl: string | URL, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }: {
|
| 419 |
+
metadata?: AuthorizationServerMetadata;
|
| 420 |
+
clientInformation: OAuthClientInformationMixed;
|
| 421 |
+
refreshToken: string;
|
| 422 |
+
resource?: string | URL;
|
| 423 |
+
addClientAuthentication?: OAuthClientProvider['addClientAuthentication'];
|
| 424 |
+
fetchFn?: FetchLike;
|
| 425 |
+
}): Promise<OAuthTokens>;
|
| 426 |
+
/**
|
| 427 |
+
* Unified token fetching that works with any grant type via provider.prepareTokenRequest().
|
| 428 |
+
*
|
| 429 |
+
* This function provides a single entry point for obtaining tokens regardless of the
|
| 430 |
+
* OAuth grant type. The provider's prepareTokenRequest() method determines which grant
|
| 431 |
+
* to use and supplies the grant-specific parameters.
|
| 432 |
+
*
|
| 433 |
+
* @param provider - OAuth client provider that implements prepareTokenRequest()
|
| 434 |
+
* @param authorizationServerUrl - The authorization server's base URL
|
| 435 |
+
* @param options - Configuration for the token request
|
| 436 |
+
* @returns Promise resolving to OAuth tokens
|
| 437 |
+
* @throws {Error} When provider doesn't implement prepareTokenRequest or token fetch fails
|
| 438 |
+
*
|
| 439 |
+
* @example
|
| 440 |
+
* // Provider for client_credentials:
|
| 441 |
+
* class MyProvider implements OAuthClientProvider {
|
| 442 |
+
* prepareTokenRequest(scope) {
|
| 443 |
+
* const params = new URLSearchParams({ grant_type: 'client_credentials' });
|
| 444 |
+
* if (scope) params.set('scope', scope);
|
| 445 |
+
* return params;
|
| 446 |
+
* }
|
| 447 |
+
* // ... other methods
|
| 448 |
+
* }
|
| 449 |
+
*
|
| 450 |
+
* const tokens = await fetchToken(provider, authServerUrl, { metadata });
|
| 451 |
+
*/
|
| 452 |
+
export declare function fetchToken(provider: OAuthClientProvider, authorizationServerUrl: string | URL, { metadata, resource, authorizationCode, fetchFn }?: {
|
| 453 |
+
metadata?: AuthorizationServerMetadata;
|
| 454 |
+
resource?: string | URL;
|
| 455 |
+
/** Authorization code for the default authorization_code grant flow */
|
| 456 |
+
authorizationCode?: string;
|
| 457 |
+
fetchFn?: FetchLike;
|
| 458 |
+
}): Promise<OAuthTokens>;
|
| 459 |
+
/**
|
| 460 |
+
* Performs OAuth 2.0 Dynamic Client Registration according to RFC 7591.
|
| 461 |
+
*
|
| 462 |
+
* If `scope` is provided, it overrides `clientMetadata.scope` in the registration
|
| 463 |
+
* request body. This allows callers to apply the Scope Selection Strategy (SEP-835)
|
| 464 |
+
* consistently across both DCR and the subsequent authorization request.
|
| 465 |
+
*/
|
| 466 |
+
export declare function registerClient(authorizationServerUrl: string | URL, { metadata, clientMetadata, scope, fetchFn }: {
|
| 467 |
+
metadata?: AuthorizationServerMetadata;
|
| 468 |
+
clientMetadata: OAuthClientMetadata;
|
| 469 |
+
scope?: string;
|
| 470 |
+
fetchFn?: FetchLike;
|
| 471 |
+
}): Promise<OAuthClientInformationFull>;
|
| 472 |
+
export {};
|
| 473 |
+
//# sourceMappingURL=auth.d.ts.map
|