@sleep/magic (0.1.1)
Installation
@sleep:registry=https://git.teawin.ru/api/packages/moonlight/npm/npm install @sleep/magic@0.1.1"@sleep/magic": "0.1.1"About this package
Magic — experimental native transport
Node.js / Deno transport built on AzureTLS and a shared Go C ABI. Targets: Windows x64 and Linux x64/glibc. Not a conformant drop-in replacement for browser Fetch or WebSocket. Gitea npm publication is configured for version-tag pushes; a successful registry release has not been verified here.
Build and load
Requires Go 1.24+, Node >=22.18.0 with TypeScript stripping, Deno 2, and GCC/G++ (MinGW-w64 and dlltool on Windows). The addon build downloads Node headers from nodejs.org when suitable local headers are unavailable. No runtime npm dependencies.
npm run build
Outputs: build/magic.dll or build/libmagic.so, and native/node/magic.node.
The recorded local environment is Windows x64, Node 26.7, Deno 2.9.6, Go 1.24.
Linux CI is configured; its runtime results have not been observed here.
import { createClient, MagicError } from './src/node.ts';
// Deno: import { createClient, MagicError } from './src/deno.ts';
const client = await createClient({
browser: 'chrome', // Transport profile, not an automatic User-Agent change.
maxConnections: 16, // Exclusive transport leases; integer 1..64.
userAgent: 'Magic example/1.0',
headerOrder: ['user-agent', 'accept'],
});
try {
await client.cookies.set('https://example.com/', {
name: 'session', value: 'example', secure: true, httpOnly: true,
sameSite: 'lax', path: '/',
});
const response = await client.fetch(new Request('https://example.com/', {
headers: { accept: 'text/plain' },
}));
console.log(response.status, await response.text());
const saved = await client.cookies.export(); // Sensitive session data.
console.log(saved.length);
} catch (error) {
if (error instanceof MagicError) console.error(error.code, error.operation);
throw error;
} finally {
await client.close();
}
src/node.ts and src/deno.ts are the stable source entrypoints. Public release
packaging compiles src/ to lib/*.js; Node imports @sleep/magic and
@sleep/magic/node execute compiled JS without TS stripping in node_modules.
Deno also uses compiled JS, with source TypeScript retained for types. The main
package selects exact-version optional native packages for Windows x64 or Linux
x64/glibc (Node-API 8; Node >=22.18.0), with no install scripts or downloads.
Public npm payloads exclude native sources/build scripts, not TypeScript source.
Configure the consumer's .npmrc before npm install @sleep/magic:
@sleep:registry=https://gitea.example.com/api/packages/moonlight/npm/
Replace the example host and owner with your Gitea destination; the registry
owner can differ from the @sleep scope. Public packages can be hosted under a
public owner while the source repository remains private. See
distribution for release setup and prerelease installation.
Earlier local Windows legacy package/smoke checks passed, but do not establish
new npm release or Linux CI success. The earlier full suite failed before fixes;
only targeted reruns passed afterward. See validation.
Implemented
- Immutable per-session browser/TLS/H2/header options and a transport-client pool (default 16 leases, configurable 1..64), with a shared session cookie jar.
- Async HTTP streaming upload/download, Request input, request headers, standard runtime body encoding (including Blob, FormData/multipart, URLSearchParams), AbortSignal through body completion, redirects and lazy decompression.
- Session-isolated PSL-aware cookies shared by HTTP and WS, with get/set/delete/clear/import/export and canonical persistence records.
- Low-level
openWebSocket(url, { protocols?, headers?, signal? }): subprotocols, custom handshake headers, cancellable connects, close metadata and bounded graceful shutdown; an experimental EventTarget class facade supplies states/events, binaryType and bufferedAmount.createWebSocketClassis exported by both stable top-level entrypoints; see usage. - Structured
MagicError; Node environment-owned handles and async Worker teardown, bounded admission and two independent cleanup executors.
The low-level WebSocket API accepts only an optional settings object; old
protocol-string/array overloads and a third argument are removed. Reserved
handshake headers reject before native calls. The standard facade constructor
remains new WebSocket(url, protocols). Matching native components must be
rebuilt for the new {protocols:[],headers:[pairs]} JSON payload; see
WebSocket usage.
Ownership and limits
Read or cancel every response body. Explicitly close sockets and
await client.close(); the class facade's close() returns void and completes
via its close event. Deno requires FFI permission; native network access is not
restricted by --allow-net. Shared libraries remain process-pinned in normal use.
maxConnections bounds exclusive transport-client leases, not physical TCP/TLS
sockets. Each HTTP exchange holds its lease through body EOF/cancel; each WS
holds one until close. Waiting acquisition is abortable. Read/cancel bodies and
close sockets to free capacity. Node's independent 128-data-call admission cap
can reject excess work rather than queue it; Deno has no total pending-queue
bound. See runtime limits.
Profiles are pinned to the native dependency versions, not exact browser-version
impersonation. browser does not automatically set a matching User-Agent;
ja3 takes a full string, and http2 a four-field fingerprint. Proxy options are
unsupported. See profile configuration.
Node admits 128 ordinary data calls plus 128 shutdown calls per environment; 1024 resource reservations (at most 128 sessions), with two cleanup threads. This is not a production event dispatcher. WS messages are limited to 64 KiB. Application queues, stream tee/clone buffers and total RSS are not globally bounded.
Full Fetch/WebSocket conformance, credentials policy, caching and integrity are
unfinished. This is a server context: no browser CORS enforcement; manual
redirects expose the real response, not an opaque redirect. Autobahn is not done.
ABI stays at version 1, but current adapters require additive symbols absent
from original v1 libraries, including required magic_session_create_options:
rebuild matching components rather than mix versions.
Gitea is the only configured CI. Its sequential Linux-host workflow checks Linux
offline npm installation and runtime, and inspects/extracts Windows cross-built
npm archives without installing or executing them, then publishes both platform
packages before the main package to Gitea's npm registry on matching version-tag
pushes. Legacy archive scripts remain manual. See
distribution.
Documentation
- Usage: cookies, Fetch and WebSocket
- Session options and transport profiles
- Implemented vs remaining stages
- Compatibility matrix
- Runtime ownership and limits
- C ABI and additive compatibility
- Distribution and workflows
- Validation record
Sources are separated into src/shared/, src/node/, src/deno/, native/go/
and native/node/. The older native adapter README
contains useful low-level details but some API/compatibility descriptions lag
implementation; the source-checked docs above describe the current behavior.
Dependencies
Optional Dependencies
| ID | Version |
|---|---|
| @sleep/magic-linux-x64-gnu | 0.1.1 |
| @sleep/magic-win32-x64 | 0.1.1 |