@socketsecurity/lib 3.0.2 → 3.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/dist/abort.js +60 -1
- package/dist/abort.js.map +2 -2
- package/dist/agent.js +289 -1
- package/dist/agent.js.map +2 -2
- package/dist/ansi.js +60 -1
- package/dist/ansi.js.map +2 -2
- package/dist/argv/flags.js +282 -1
- package/dist/argv/flags.js.map +2 -2
- package/dist/argv/parse.js +171 -1
- package/dist/argv/parse.js.map +2 -2
- package/dist/arrays.js +85 -1
- package/dist/arrays.js.map +2 -2
- package/dist/bin.js +419 -5
- package/dist/bin.js.map +2 -2
- package/dist/cacache.js +139 -1
- package/dist/cacache.js.map +2 -2
- package/dist/cache-with-ttl.js +223 -1
- package/dist/cache-with-ttl.js.map +2 -2
- package/dist/constants/agents.js +126 -1
- package/dist/constants/agents.js.map +2 -2
- package/dist/constants/core.js +57 -2
- package/dist/constants/core.js.map +2 -2
- package/dist/constants/encoding.js +48 -1
- package/dist/constants/encoding.js.map +2 -2
- package/dist/constants/github.js +30 -1
- package/dist/constants/github.js.map +2 -2
- package/dist/constants/licenses.js +66 -1
- package/dist/constants/licenses.js.map +2 -2
- package/dist/constants/node.js +185 -1
- package/dist/constants/node.js.map +2 -2
- package/dist/constants/packages.js +128 -1
- package/dist/constants/packages.js.map +2 -2
- package/dist/constants/paths.js +150 -1
- package/dist/constants/paths.js.map +2 -2
- package/dist/constants/platform.js +41 -1
- package/dist/constants/platform.js.map +2 -2
- package/dist/constants/process.js +52 -1
- package/dist/constants/process.js.map +2 -2
- package/dist/constants/socket.js +102 -1
- package/dist/constants/socket.js.map +2 -2
- package/dist/constants/testing.js +36 -1
- package/dist/constants/testing.js.map +2 -2
- package/dist/constants/time.js +39 -1
- package/dist/constants/time.js.map +2 -2
- package/dist/constants/typescript.js +54 -1
- package/dist/constants/typescript.js.map +2 -2
- package/dist/cover/code.js +135 -1
- package/dist/cover/code.js.map +2 -2
- package/dist/cover/formatters.js +101 -11
- package/dist/cover/formatters.js.map +2 -2
- package/dist/cover/type.js +63 -1
- package/dist/cover/type.js.map +2 -2
- package/dist/cover/types.js +15 -1
- package/dist/cover/types.js.map +2 -2
- package/dist/debug.js +337 -2
- package/dist/debug.js.map +2 -2
- package/dist/dlx-binary.js +408 -7
- package/dist/dlx-binary.js.map +2 -2
- package/dist/dlx-package.js +278 -7
- package/dist/dlx-package.js.map +2 -2
- package/dist/dlx.js +214 -7
- package/dist/dlx.js.map +2 -2
- package/dist/effects/pulse-frames.js +64 -1
- package/dist/effects/pulse-frames.js.map +2 -2
- package/dist/effects/text-shimmer.js +174 -1
- package/dist/effects/text-shimmer.js.map +2 -2
- package/dist/effects/types.js +15 -1
- package/dist/effects/types.js.map +2 -2
- package/dist/effects/ultra.js +61 -1
- package/dist/effects/ultra.js.map +2 -2
- package/dist/env/ci.js +31 -1
- package/dist/env/ci.js.map +2 -2
- package/dist/env/debug.js +30 -1
- package/dist/env/debug.js.map +2 -2
- package/dist/env/github.js +65 -1
- package/dist/env/github.js.map +2 -2
- package/dist/env/helpers.js +47 -1
- package/dist/env/helpers.js.map +2 -2
- package/dist/env/home.js +30 -1
- package/dist/env/home.js.map +2 -2
- package/dist/env/locale.js +40 -1
- package/dist/env/locale.js.map +2 -2
- package/dist/env/node-auth-token.js +30 -1
- package/dist/env/node-auth-token.js.map +2 -2
- package/dist/env/node-env.js +30 -1
- package/dist/env/node-env.js.map +2 -2
- package/dist/env/npm.js +50 -1
- package/dist/env/npm.js.map +2 -2
- package/dist/env/package-manager.js +73 -1
- package/dist/env/package-manager.js.map +2 -2
- package/dist/env/path.js +30 -1
- package/dist/env/path.js.map +2 -2
- package/dist/env/pre-commit.js +31 -1
- package/dist/env/pre-commit.js.map +2 -2
- package/dist/env/rewire.js +72 -1
- package/dist/env/rewire.js.map +2 -2
- package/dist/env/shell.js +30 -1
- package/dist/env/shell.js.map +2 -2
- package/dist/env/socket-cli-shadow.js +51 -1
- package/dist/env/socket-cli-shadow.js.map +2 -2
- package/dist/env/socket-cli.js +86 -1
- package/dist/env/socket-cli.js.map +2 -2
- package/dist/env/socket.js +101 -1
- package/dist/env/socket.js.map +2 -2
- package/dist/env/temp-dir.js +40 -1
- package/dist/env/temp-dir.js.map +2 -2
- package/dist/env/term.js +30 -1
- package/dist/env/term.js.map +2 -2
- package/dist/env/test.js +43 -1
- package/dist/env/test.js.map +2 -2
- package/dist/env/windows.js +45 -1
- package/dist/env/windows.js.map +2 -2
- package/dist/env/xdg.js +40 -1
- package/dist/env/xdg.js.map +2 -2
- package/dist/env.js +170 -1
- package/dist/env.js.map +2 -2
- package/dist/fs.js +670 -7
- package/dist/fs.js.map +2 -2
- package/dist/functions.js +68 -1
- package/dist/functions.js.map +2 -2
- package/dist/git.js +329 -2
- package/dist/git.js.map +2 -2
- package/dist/github.js +202 -1
- package/dist/github.js.map +2 -2
- package/dist/globs.js +149 -1
- package/dist/globs.js.map +2 -2
- package/dist/http-request.js +335 -3
- package/dist/http-request.js.map +2 -2
- package/dist/index.js +69 -1
- package/dist/index.js.map +2 -2
- package/dist/ipc.js +244 -1
- package/dist/ipc.js.map +2 -2
- package/dist/json.js +73 -1
- package/dist/json.js.map +2 -2
- package/dist/links/index.js +60 -1
- package/dist/links/index.js.map +2 -2
- package/dist/logger.js +1383 -6
- package/dist/logger.js.map +2 -2
- package/dist/maintained-node-versions.js +35 -1
- package/dist/maintained-node-versions.js.map +2 -2
- package/dist/memoization.js +210 -1
- package/dist/memoization.js.map +2 -2
- package/dist/objects.js +311 -1
- package/dist/objects.js.map +2 -2
- package/dist/packages/editable.js +356 -9
- package/dist/packages/editable.js.map +2 -2
- package/dist/packages/exports.js +162 -1
- package/dist/packages/exports.js.map +2 -2
- package/dist/packages/isolation.js +187 -1
- package/dist/packages/isolation.js.map +2 -2
- package/dist/packages/licenses.js +214 -1
- package/dist/packages/licenses.js.map +2 -2
- package/dist/packages/manifest.js +190 -1
- package/dist/packages/manifest.js.map +2 -2
- package/dist/packages/normalize.js +132 -1
- package/dist/packages/normalize.js.map +2 -2
- package/dist/packages/operations.js +320 -1
- package/dist/packages/operations.js.map +2 -2
- package/dist/packages/paths.js +53 -1
- package/dist/packages/paths.js.map +2 -2
- package/dist/packages/provenance.js +178 -1
- package/dist/packages/provenance.js.map +2 -2
- package/dist/packages/specs.js +83 -1
- package/dist/packages/specs.js.map +2 -2
- package/dist/packages/validation.js +51 -1
- package/dist/packages/validation.js.map +2 -2
- package/dist/packages.js +129 -1
- package/dist/packages.js.map +2 -2
- package/dist/path.js +446 -1
- package/dist/path.js.map +2 -2
- package/dist/paths/rewire.js +79 -1
- package/dist/paths/rewire.js.map +2 -2
- package/dist/paths.js +190 -1
- package/dist/paths.js.map +2 -2
- package/dist/performance.js +216 -15
- package/dist/performance.js.map +2 -2
- package/dist/process-lock.js +287 -8
- package/dist/process-lock.js.map +2 -2
- package/dist/promise-queue.js +109 -1
- package/dist/promise-queue.js.map +2 -2
- package/dist/promises.js +267 -1
- package/dist/promises.js.map +2 -2
- package/dist/prompts/index.js +45 -1
- package/dist/prompts/index.js.map +2 -2
- package/dist/prompts.js +58 -1
- package/dist/prompts.js.map +2 -2
- package/dist/regexps.js +30 -1
- package/dist/regexps.js.map +2 -2
- package/dist/sea.js +44 -1
- package/dist/sea.js.map +2 -2
- package/dist/shadow.js +58 -1
- package/dist/shadow.js.map +2 -2
- package/dist/signal-exit.js +248 -1
- package/dist/signal-exit.js.map +2 -2
- package/dist/sorts.js +94 -1
- package/dist/sorts.js.map +2 -2
- package/dist/spawn.js +200 -1
- package/dist/spawn.js.map +2 -2
- package/dist/spinner.js +961 -1
- package/dist/spinner.js.map +2 -2
- package/dist/ssri.js +71 -1
- package/dist/ssri.js.map +2 -2
- package/dist/stdio/clear.js +82 -1
- package/dist/stdio/clear.js.map +2 -2
- package/dist/stdio/divider.js +89 -3
- package/dist/stdio/divider.js.map +2 -2
- package/dist/stdio/footer.js +94 -2
- package/dist/stdio/footer.js.map +2 -2
- package/dist/stdio/header.js +100 -2
- package/dist/stdio/header.js.map +2 -2
- package/dist/stdio/mask.js +207 -5
- package/dist/stdio/mask.js.map +2 -2
- package/dist/stdio/progress.js +209 -2
- package/dist/stdio/progress.js.map +2 -2
- package/dist/stdio/prompts.js +88 -1
- package/dist/stdio/prompts.js.map +2 -2
- package/dist/stdio/stderr.js +89 -2
- package/dist/stdio/stderr.js.map +2 -2
- package/dist/stdio/stdout.js +103 -2
- package/dist/stdio/stdout.js.map +2 -2
- package/dist/streams.js +78 -1
- package/dist/streams.js.map +2 -2
- package/dist/strings.js +251 -3
- package/dist/strings.js.map +2 -2
- package/dist/suppress-warnings.js +98 -1
- package/dist/suppress-warnings.js.map +2 -2
- package/dist/tables.js +128 -3
- package/dist/tables.js.map +2 -2
- package/dist/temporary-executor.js +53 -1
- package/dist/temporary-executor.js.map +2 -2
- package/dist/themes/context.js +71 -1
- package/dist/themes/context.js.map +2 -2
- package/dist/themes/index.js +57 -1
- package/dist/themes/index.js.map +2 -2
- package/dist/themes/themes.js +195 -1
- package/dist/themes/themes.js.map +2 -2
- package/dist/themes/types.js +15 -1
- package/dist/themes/types.js.map +2 -2
- package/dist/themes/utils.js +116 -1
- package/dist/themes/utils.js.map +2 -2
- package/dist/types.js +59 -1
- package/dist/types.js.map +2 -2
- package/dist/url.js +142 -1
- package/dist/url.js.map +2 -2
- package/dist/utils/get-ipc.js +58 -1
- package/dist/utils/get-ipc.js.map +2 -2
- package/dist/validation/json-parser.js +127 -1
- package/dist/validation/json-parser.js.map +2 -2
- package/dist/validation/types.js +15 -1
- package/dist/validation/types.js.map +2 -2
- package/dist/versions.js +154 -1
- package/dist/versions.js.map +2 -2
- package/dist/words.js +50 -1
- package/dist/words.js.map +2 -2
- package/dist/zod.js +27 -1
- package/dist/zod.js.map +2 -2
- package/package.json +1 -1
package/dist/ipc.js
CHANGED
|
@@ -1,3 +1,246 @@
|
|
|
1
1
|
/* Socket Lib - Built with esbuild */
|
|
2
|
-
var
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
var ipc_exports = {};
|
|
30
|
+
__export(ipc_exports, {
|
|
31
|
+
IpcHandshakeSchema: () => IpcHandshakeSchema,
|
|
32
|
+
cleanupIpcStubs: () => cleanupIpcStubs,
|
|
33
|
+
createIpcChannelId: () => createIpcChannelId,
|
|
34
|
+
createIpcMessage: () => createIpcMessage,
|
|
35
|
+
getIpcStubPath: () => getIpcStubPath,
|
|
36
|
+
hasIpcChannel: () => hasIpcChannel,
|
|
37
|
+
onIpc: () => onIpc,
|
|
38
|
+
parseIpcMessage: () => parseIpcMessage,
|
|
39
|
+
readIpcStub: () => readIpcStub,
|
|
40
|
+
sendIpc: () => sendIpc,
|
|
41
|
+
waitForIpc: () => waitForIpc,
|
|
42
|
+
writeIpcStub: () => writeIpcStub
|
|
43
|
+
});
|
|
44
|
+
module.exports = __toCommonJS(ipc_exports);
|
|
45
|
+
var import_crypto = __toESM(require("crypto"));
|
|
46
|
+
var import_fs = require("fs");
|
|
47
|
+
var import_path = __toESM(require("path"));
|
|
48
|
+
var import_fs2 = require("./fs");
|
|
49
|
+
var import_paths = require("./paths");
|
|
50
|
+
var import_zod = require("./zod");
|
|
51
|
+
const IpcMessageSchema = import_zod.z.object({
|
|
52
|
+
/** Unique identifier for message tracking and response correlation. */
|
|
53
|
+
id: import_zod.z.string().min(1),
|
|
54
|
+
/** Unix timestamp for freshness validation and replay prevention. */
|
|
55
|
+
timestamp: import_zod.z.number().positive(),
|
|
56
|
+
/** Message type identifier for routing and handling. */
|
|
57
|
+
type: import_zod.z.string().min(1),
|
|
58
|
+
/** Payload data - can be any JSON-serializable value. */
|
|
59
|
+
data: import_zod.z.unknown()
|
|
60
|
+
});
|
|
61
|
+
const IpcHandshakeSchema = IpcMessageSchema.extend({
|
|
62
|
+
type: import_zod.z.literal("handshake"),
|
|
63
|
+
data: import_zod.z.object({
|
|
64
|
+
/** Protocol version for compatibility checking. */
|
|
65
|
+
version: import_zod.z.string(),
|
|
66
|
+
/** Process ID for identification. */
|
|
67
|
+
pid: import_zod.z.number().int().positive(),
|
|
68
|
+
/** Optional API token for authentication. */
|
|
69
|
+
apiToken: import_zod.z.string().optional(),
|
|
70
|
+
/** Application name for multi-app support. */
|
|
71
|
+
appName: import_zod.z.string()
|
|
72
|
+
})
|
|
73
|
+
});
|
|
74
|
+
const IpcStubSchema = import_zod.z.object({
|
|
75
|
+
/** Process ID that created the stub. */
|
|
76
|
+
pid: import_zod.z.number().int().positive(),
|
|
77
|
+
/** Creation timestamp for age validation. */
|
|
78
|
+
timestamp: import_zod.z.number().positive(),
|
|
79
|
+
/** The actual data payload. */
|
|
80
|
+
data: import_zod.z.unknown()
|
|
81
|
+
});
|
|
82
|
+
function createIpcChannelId(prefix = "socket") {
|
|
83
|
+
return `${prefix}-${process.pid}-${import_crypto.default.randomBytes(8).toString("hex")}`;
|
|
84
|
+
}
|
|
85
|
+
function getIpcStubPath(appName) {
|
|
86
|
+
const tempDir = (0, import_paths.getOsTmpDir)();
|
|
87
|
+
const stubDir = import_path.default.join(tempDir, ".socket-ipc", appName);
|
|
88
|
+
return import_path.default.join(stubDir, `stub-${process.pid}.json`);
|
|
89
|
+
}
|
|
90
|
+
async function ensureIpcDirectory(filePath) {
|
|
91
|
+
const dir = import_path.default.dirname(filePath);
|
|
92
|
+
await import_fs.promises.mkdir(dir, { recursive: true });
|
|
93
|
+
}
|
|
94
|
+
async function writeIpcStub(appName, data) {
|
|
95
|
+
const stubPath = getIpcStubPath(appName);
|
|
96
|
+
await ensureIpcDirectory(stubPath);
|
|
97
|
+
const ipcData = {
|
|
98
|
+
data,
|
|
99
|
+
pid: process.pid,
|
|
100
|
+
timestamp: Date.now()
|
|
101
|
+
};
|
|
102
|
+
const validated = IpcStubSchema.parse(ipcData);
|
|
103
|
+
await import_fs.promises.writeFile(stubPath, JSON.stringify(validated, null, 2), "utf8");
|
|
104
|
+
return stubPath;
|
|
105
|
+
}
|
|
106
|
+
async function readIpcStub(stubPath) {
|
|
107
|
+
try {
|
|
108
|
+
const content = await import_fs.promises.readFile(stubPath, "utf8");
|
|
109
|
+
const parsed = JSON.parse(content);
|
|
110
|
+
const validated = IpcStubSchema.parse(parsed);
|
|
111
|
+
const ageMs = Date.now() - validated.timestamp;
|
|
112
|
+
const maxAgeMs = 5 * 60 * 1e3;
|
|
113
|
+
if (ageMs > maxAgeMs) {
|
|
114
|
+
try {
|
|
115
|
+
(0, import_fs2.safeDeleteSync)(stubPath, { force: true });
|
|
116
|
+
} catch {
|
|
117
|
+
}
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
return validated.data;
|
|
121
|
+
} catch {
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
async function cleanupIpcStubs(appName) {
|
|
126
|
+
const tempDir = (0, import_paths.getOsTmpDir)();
|
|
127
|
+
const stubDir = import_path.default.join(tempDir, ".socket-ipc", appName);
|
|
128
|
+
try {
|
|
129
|
+
const files = await import_fs.promises.readdir(stubDir);
|
|
130
|
+
const now = Date.now();
|
|
131
|
+
const maxAgeMs = 5 * 60 * 1e3;
|
|
132
|
+
await Promise.all(
|
|
133
|
+
files.map(async (file) => {
|
|
134
|
+
if (file.startsWith("stub-") && file.endsWith(".json")) {
|
|
135
|
+
const filePath = import_path.default.join(stubDir, file);
|
|
136
|
+
try {
|
|
137
|
+
const stats = await import_fs.promises.stat(filePath);
|
|
138
|
+
const mtimeAge = now - stats.mtimeMs;
|
|
139
|
+
let isStale = mtimeAge > maxAgeMs;
|
|
140
|
+
try {
|
|
141
|
+
const content = await import_fs.promises.readFile(filePath, "utf8");
|
|
142
|
+
const parsed = JSON.parse(content);
|
|
143
|
+
const validated = IpcStubSchema.parse(parsed);
|
|
144
|
+
const contentAge = now - validated.timestamp;
|
|
145
|
+
isStale = isStale || contentAge > maxAgeMs;
|
|
146
|
+
} catch {
|
|
147
|
+
}
|
|
148
|
+
if (isStale) {
|
|
149
|
+
(0, import_fs2.safeDeleteSync)(filePath, { force: true });
|
|
150
|
+
}
|
|
151
|
+
} catch {
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
})
|
|
155
|
+
);
|
|
156
|
+
} catch {
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
function sendIpc(process2, message) {
|
|
160
|
+
if (process2 && typeof process2 === "object" && "send" in process2 && typeof process2.send === "function") {
|
|
161
|
+
try {
|
|
162
|
+
const validated = IpcMessageSchema.parse(message);
|
|
163
|
+
return process2.send(validated);
|
|
164
|
+
} catch {
|
|
165
|
+
return false;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return false;
|
|
169
|
+
}
|
|
170
|
+
function onIpc(handler) {
|
|
171
|
+
const listener = (message) => {
|
|
172
|
+
const parsed = parseIpcMessage(message);
|
|
173
|
+
if (parsed) {
|
|
174
|
+
handler(parsed);
|
|
175
|
+
}
|
|
176
|
+
};
|
|
177
|
+
process.on("message", listener);
|
|
178
|
+
return () => {
|
|
179
|
+
process.off("message", listener);
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
function waitForIpc(messageType, options = {}) {
|
|
183
|
+
const { timeout = 3e4 } = options;
|
|
184
|
+
return new Promise((resolve, reject) => {
|
|
185
|
+
let cleanup = null;
|
|
186
|
+
let timeoutId = null;
|
|
187
|
+
const handleTimeout = () => {
|
|
188
|
+
if (cleanup) {
|
|
189
|
+
cleanup();
|
|
190
|
+
}
|
|
191
|
+
reject(new Error(`IPC timeout waiting for message type: ${messageType}`));
|
|
192
|
+
};
|
|
193
|
+
const handleMessage = (message) => {
|
|
194
|
+
if (message.type === messageType) {
|
|
195
|
+
if (timeoutId) {
|
|
196
|
+
clearTimeout(timeoutId);
|
|
197
|
+
}
|
|
198
|
+
if (cleanup) {
|
|
199
|
+
cleanup();
|
|
200
|
+
}
|
|
201
|
+
resolve(message.data);
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
cleanup = onIpc(handleMessage);
|
|
205
|
+
if (timeout > 0) {
|
|
206
|
+
timeoutId = setTimeout(handleTimeout, timeout);
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
function createIpcMessage(type, data) {
|
|
211
|
+
return {
|
|
212
|
+
id: import_crypto.default.randomBytes(16).toString("hex"),
|
|
213
|
+
timestamp: Date.now(),
|
|
214
|
+
type,
|
|
215
|
+
data
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
function hasIpcChannel(process2) {
|
|
219
|
+
return Boolean(
|
|
220
|
+
process2 && typeof process2 === "object" && "send" in process2 && typeof process2.send === "function" && "channel" in process2 && process2.channel !== void 0
|
|
221
|
+
);
|
|
222
|
+
}
|
|
223
|
+
function parseIpcMessage(message) {
|
|
224
|
+
try {
|
|
225
|
+
const validated = IpcMessageSchema.parse(message);
|
|
226
|
+
return validated;
|
|
227
|
+
} catch {
|
|
228
|
+
return null;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
232
|
+
0 && (module.exports = {
|
|
233
|
+
IpcHandshakeSchema,
|
|
234
|
+
cleanupIpcStubs,
|
|
235
|
+
createIpcChannelId,
|
|
236
|
+
createIpcMessage,
|
|
237
|
+
getIpcStubPath,
|
|
238
|
+
hasIpcChannel,
|
|
239
|
+
onIpc,
|
|
240
|
+
parseIpcMessage,
|
|
241
|
+
readIpcStub,
|
|
242
|
+
sendIpc,
|
|
243
|
+
waitForIpc,
|
|
244
|
+
writeIpcStub
|
|
245
|
+
});
|
|
3
246
|
//# sourceMappingURL=ipc.js.map
|
package/dist/ipc.js.map
CHANGED
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/ipc.ts"],
|
|
4
4
|
"sourcesContent": ["/**\n * IPC (Inter-Process Communication) Module\n * ==========================================\n *\n * This module provides secure inter-process communication utilities for Socket CLI\n * and related tools. It replaces environment variable passing with more secure and\n * scalable alternatives.\n *\n * ## Key Features:\n * - File-based stub communication for initial data handoff\n * - Node.js IPC channel support for real-time bidirectional messaging\n * - Automatic cleanup of temporary files\n * - Type-safe message validation with Zod schemas\n * - Timeout handling for reliability\n *\n * ## Use Cases:\n * 1. Passing API tokens between processes without exposing them in env vars\n * 2. Transferring large configuration objects that exceed env var size limits\n * 3. Bidirectional communication between parent and child processes\n * 4. Secure handshake protocols between Socket CLI components\n *\n * ## Security Considerations:\n * - Stub files are created with restricted permissions in OS temp directory\n * - Messages include timestamps for freshness validation\n * - Automatic cleanup prevents sensitive data persistence\n * - Unique IDs prevent message replay attacks\n *\n * @module ipc\n */\n\nimport crypto from 'crypto'\n\nimport { promises as fs } from 'fs'\n\nimport path from 'path'\n\nimport { safeDeleteSync } from './fs'\nimport { getOsTmpDir } from './paths'\nimport { z } from './zod'\n\n// Define BufferEncoding type for TypeScript compatibility.\ntype BufferEncoding = globalThis.BufferEncoding\n\n/**\n * Zod Schemas for Runtime Validation\n * ====================================\n * These schemas provide runtime type safety for IPC messages,\n * ensuring data integrity across process boundaries.\n */\n\n/**\n * Base IPC message schema - validates the core message structure.\n * All IPC messages must conform to this schema.\n */\nconst IpcMessageSchema = z.object({\n /** Unique identifier for message tracking and response correlation. */\n id: z.string().min(1),\n /** Unix timestamp for freshness validation and replay prevention. */\n timestamp: z.number().positive(),\n /** Message type identifier for routing and handling. */\n type: z.string().min(1),\n /** Payload data - can be any JSON-serializable value. */\n data: z.unknown(),\n})\n\n/**\n * IPC handshake schema - used for initial connection establishment.\n * The handshake includes version info and authentication tokens.\n * @internal Exported for testing purposes.\n */\nexport const IpcHandshakeSchema = IpcMessageSchema.extend({\n type: z.literal('handshake'),\n data: z.object({\n /** Protocol version for compatibility checking. */\n version: z.string(),\n /** Process ID for identification. */\n pid: z.number().int().positive(),\n /** Optional API token for authentication. */\n apiToken: z.string().optional(),\n /** Application name for multi-app support. */\n appName: z.string(),\n }),\n})\n\n/**\n * IPC stub file schema - validates the structure of stub files.\n * Stub files are used for passing data between processes via filesystem.\n */\nconst IpcStubSchema = z.object({\n /** Process ID that created the stub. */\n pid: z.number().int().positive(),\n /** Creation timestamp for age validation. */\n timestamp: z.number().positive(),\n /** The actual data payload. */\n data: z.unknown(),\n})\n\n/**\n * TypeScript interfaces for IPC communication.\n * These types ensure type consistency across the IPC module.\n */\n\n/**\n * Base IPC message interface.\n * All IPC messages must conform to this structure.\n */\nexport interface IpcMessage<T = unknown> {\n /** Unique identifier for message tracking and response correlation. */\n id: string\n /** Unix timestamp for freshness validation and replay prevention. */\n timestamp: number\n /** Message type identifier for routing and handling. */\n type: string\n /** Payload data - can be any JSON-serializable value. */\n data: T\n}\n\n/**\n * IPC handshake message interface.\n * Used for initial connection establishment.\n */\nexport interface IpcHandshake\n extends IpcMessage<{\n /** Protocol version for compatibility checking. */\n version: string\n /** Process ID for identification. */\n pid: number\n /** Optional API token for authentication. */\n apiToken?: string\n /** Application name for multi-app support. */\n appName: string\n }> {\n type: 'handshake'\n}\n\n/**\n * IPC stub file interface.\n * Represents the structure of stub files used for filesystem-based IPC.\n */\nexport interface IpcStub {\n /** Process ID that created the stub. */\n pid: number\n /** Creation timestamp for age validation. */\n timestamp: number\n /** The actual data payload. */\n data: unknown\n}\n\n/**\n * Options for IPC communication\n */\nexport interface IpcOptions {\n /** Timeout in milliseconds for async operations. */\n timeout?: number\n /** Text encoding for message serialization. */\n encoding?: BufferEncoding\n}\n\n/**\n * Create a unique IPC channel identifier for message correlation.\n *\n * Generates a unique identifier that combines:\n * - A prefix for namespacing (defaults to 'socket')\n * - The current process ID for process identification\n * - A random hex string for uniqueness\n *\n * @param prefix - Optional prefix to namespace the channel ID\n * @returns A unique channel identifier string\n *\n * @example\n * ```typescript\n * const channelId = createIpcChannelId('socket-cli')\n * // Returns: 'socket-cli-12345-a1b2c3d4e5f6g7h8'\n * ```\n */\nexport function createIpcChannelId(prefix = 'socket'): string {\n return `${prefix}-${process.pid}-${crypto.randomBytes(8).toString('hex')}`\n}\n\n/**\n * Get the IPC stub path for a given application.\n *\n * This function generates a unique file path for IPC stub files that are used\n * to pass data between processes. The stub files are stored in a hidden directory\n * within the system's temporary folder.\n *\n * ## Path Structure:\n * - Base: System temp directory (e.g., /tmp on Unix, %TEMP% on Windows)\n * - Directory: `.socket-ipc/{appName}/`\n * - Filename: `stub-{pid}.json`\n *\n * ## Security Features:\n * - Files are isolated per application via appName parameter\n * - Process ID in filename prevents collisions between concurrent processes\n * - Temporary directory location ensures automatic cleanup on system restart\n *\n * @param appName - The application identifier (e.g., 'socket-cli', 'socket-dlx')\n * @returns Full path to the IPC stub file\n *\n * @example\n * ```typescript\n * const stubPath = getIpcStubPath('socket-cli')\n * // Returns: '/tmp/.socket-ipc/socket-cli/stub-12345.json' (Unix)\n * // Returns: 'C:\\\\Users\\\\Name\\\\AppData\\\\Local\\\\Temp\\\\.socket-ipc\\\\socket-cli\\\\stub-12345.json' (Windows)\n * ```\n *\n * @used Currently used by socket-cli for self-update and inter-process communication\n */\nexport function getIpcStubPath(appName: string): string {\n // Get the system's temporary directory - this is platform-specific.\n const tempDir = getOsTmpDir()\n\n // Create a hidden directory structure for Socket IPC files.\n // The dot prefix makes it hidden on Unix-like systems.\n const stubDir = path.join(tempDir, '.socket-ipc', appName)\n\n // Generate filename with process ID to ensure uniqueness.\n // The PID prevents conflicts when multiple processes run simultaneously.\n return path.join(stubDir, `stub-${process.pid}.json`)\n}\n\n/**\n * Ensure IPC directory exists for stub file creation.\n *\n * This helper function creates the directory structure needed for IPC stub files.\n * It's called before writing stub files to ensure the parent directories exist.\n *\n * @param filePath - Full path to the file that needs its directory created\n * @returns Promise that resolves when directory is created\n *\n * @internal Helper function used by writeIpcStub\n */\nasync function ensureIpcDirectory(filePath: string): Promise<void> {\n const dir = path.dirname(filePath)\n // Create directory recursively if it doesn't exist.\n await fs.mkdir(dir, { recursive: true })\n}\n\n/**\n * Write IPC data to a stub file for inter-process data transfer.\n *\n * This function creates a stub file containing data that needs to be passed\n * between processes. The stub file includes metadata like process ID and\n * timestamp for validation.\n *\n * ## File Structure:\n * ```json\n * {\n * \"pid\": 12345,\n * \"timestamp\": 1699564234567,\n * \"data\": { ... }\n * }\n * ```\n *\n * ## Use Cases:\n * - Passing API tokens to child processes\n * - Transferring configuration between Socket CLI components\n * - Sharing large data that exceeds environment variable limits\n *\n * @param appName - The application identifier\n * @param data - The data to write to the stub file\n * @returns Promise resolving to the stub file path\n *\n * @example\n * ```typescript\n * const stubPath = await writeIpcStub('socket-cli', {\n * apiToken: 'secret-token',\n * config: { ... }\n * })\n * // Pass stubPath to child process for reading\n * ```\n */\nexport async function writeIpcStub(\n appName: string,\n data: unknown,\n): Promise<string> {\n const stubPath = getIpcStubPath(appName)\n await ensureIpcDirectory(stubPath)\n\n // Create stub data with validation metadata.\n const ipcData: IpcStub = {\n data,\n pid: process.pid,\n timestamp: Date.now(),\n }\n\n // Validate data structure with Zod schema.\n const validated = IpcStubSchema.parse(ipcData)\n\n // Write with pretty printing for debugging.\n await fs.writeFile(stubPath, JSON.stringify(validated, null, 2), 'utf8')\n return stubPath\n}\n\n/**\n * Read IPC data from a stub file with automatic cleanup.\n *\n * This function reads data from an IPC stub file and validates its freshness.\n * Stale files (older than 5 minutes) are automatically cleaned up to prevent\n * accumulation of temporary files.\n *\n * ## Validation Steps:\n * 1. Read and parse JSON file\n * 2. Validate structure with Zod schema\n * 3. Check timestamp freshness\n * 4. Clean up if stale\n * 5. Return data if valid\n *\n * @param stubPath - Path to the stub file to read\n * @returns Promise resolving to the data or null if invalid/stale\n *\n * @example\n * ```typescript\n * const data = await readIpcStub('/tmp/.socket-ipc/socket-cli/stub-12345.json')\n * if (data) {\n * console.log('Received:', data)\n * }\n * ```\n *\n * @unused Reserved for future implementation\n */\nexport async function readIpcStub(stubPath: string): Promise<unknown> {\n try {\n const content = await fs.readFile(stubPath, 'utf8')\n const parsed = JSON.parse(content)\n // Validate structure with Zod schema.\n const validated = IpcStubSchema.parse(parsed)\n // Check age for freshness validation.\n const ageMs = Date.now() - validated.timestamp\n // 5 minutes.\n const maxAgeMs = 5 * 60 * 1000\n if (ageMs > maxAgeMs) {\n // Clean up stale file. IPC stubs are always in tmpdir, so use force: true.\n try {\n safeDeleteSync(stubPath, { force: true })\n } catch {\n // Ignore deletion errors\n }\n return null\n }\n return validated.data\n } catch {\n // Return null for any errors (file not found, invalid JSON, validation failure).\n return null\n }\n}\n\n/**\n * Clean up IPC stub files for an application.\n *\n * This maintenance function removes stale IPC stub files to prevent\n * accumulation in the temporary directory. It's designed to be called\n * periodically or on application startup.\n *\n * ## Cleanup Rules:\n * - Files older than 5 minutes are removed (checked via both filesystem mtime and JSON timestamp)\n * - Only stub files (stub-*.json) are processed\n * - Errors are silently ignored (best-effort cleanup)\n *\n * @param appName - The application identifier\n * @returns Promise that resolves when cleanup is complete\n *\n * @example\n * ```typescript\n * // Clean up on application startup\n * await cleanupIpcStubs('socket-cli')\n * ```\n *\n * @unused Reserved for future implementation\n */\nexport async function cleanupIpcStubs(appName: string): Promise<void> {\n const tempDir = getOsTmpDir()\n const stubDir = path.join(tempDir, '.socket-ipc', appName)\n try {\n const files = await fs.readdir(stubDir)\n const now = Date.now()\n // 5 minutes.\n const maxAgeMs = 5 * 60 * 1000\n // Process each file in parallel for efficiency.\n await Promise.all(\n files.map(async file => {\n if (file.startsWith('stub-') && file.endsWith('.json')) {\n const filePath = path.join(stubDir, file)\n try {\n // Check both filesystem mtime and JSON timestamp for more reliable detection\n const stats = await fs.stat(filePath)\n const mtimeAge = now - stats.mtimeMs\n let isStale = mtimeAge > maxAgeMs\n\n // Always check the timestamp inside the JSON file for accuracy\n // This is more reliable than filesystem mtime in some environments\n try {\n const content = await fs.readFile(filePath, 'utf8')\n const parsed = JSON.parse(content)\n const validated = IpcStubSchema.parse(parsed)\n const contentAge = now - validated.timestamp\n // File is stale if EITHER check indicates staleness\n isStale = isStale || contentAge > maxAgeMs\n } catch {\n // If we can't read/parse the file, rely on mtime check\n }\n\n if (isStale) {\n // IPC stubs are always in tmpdir, so we can use force: true to skip path checks\n safeDeleteSync(filePath, { force: true })\n }\n } catch {\n // Ignore errors for individual files.\n }\n }\n }),\n )\n } catch {\n // Directory might not exist, that's ok.\n }\n}\n\n/**\n * Send data through Node.js IPC channel.\n *\n * This function sends structured messages through the Node.js IPC channel\n * when available. The IPC channel must be established with stdio: ['pipe', 'pipe', 'pipe', 'ipc'].\n *\n * ## Requirements:\n * - Process must have been spawned with IPC channel enabled\n * - Message must be serializable to JSON\n * - Process.send() must be available\n *\n * @param process - The process object with IPC channel\n * @param message - The IPC message to send\n * @returns true if message was sent, false otherwise\n *\n * @example\n * ```typescript\n * const message = createIpcMessage('handshake', { version: '1.0.0' })\n * const sent = sendIpc(childProcess, message)\n * ```\n *\n * @unused Reserved for bidirectional communication implementation\n */\nexport function sendIpc(\n process: NodeJS.Process | unknown,\n message: IpcMessage,\n): boolean {\n if (\n process &&\n typeof process === 'object' &&\n 'send' in process &&\n typeof process.send === 'function'\n ) {\n try {\n // Validate message structure before sending.\n const validated = IpcMessageSchema.parse(message)\n return process.send(validated)\n } catch {\n return false\n }\n }\n return false\n}\n\n/**\n * Receive data through Node.js IPC channel.\n *\n * Sets up a listener for IPC messages with automatic validation and parsing.\n * Returns a cleanup function to remove the listener when no longer needed.\n *\n * ## Message Flow:\n * 1. Receive raw message from IPC channel\n * 2. Validate with parseIpcMessage\n * 3. Call handler if valid\n * 4. Ignore invalid messages\n *\n * @param handler - Function to call with valid IPC messages\n * @returns Cleanup function to remove the listener\n *\n * @example\n * ```typescript\n * const cleanup = onIpc((message) => {\n * console.log('Received:', message.type, message.data)\n * })\n * // Later...\n * cleanup() // Remove listener\n * ```\n *\n * @unused Reserved for bidirectional communication\n */\nexport function onIpc(handler: (message: IpcMessage) => void): () => void {\n const listener = (message: unknown) => {\n const parsed = parseIpcMessage(message)\n if (parsed) {\n handler(parsed)\n }\n }\n process.on('message', listener)\n // Return cleanup function for proper resource management.\n return () => {\n process.off('message', listener)\n }\n}\n\n/**\n * Create a promise that resolves when a specific IPC message is received.\n *\n * This utility function provides async/await support for IPC communication,\n * allowing you to wait for specific message types with timeout support.\n *\n * ## Features:\n * - Automatic timeout handling\n * - Type-safe message data\n * - Resource cleanup on completion\n * - Promise-based API\n *\n * @param messageType - The message type to wait for\n * @param options - Options including timeout configuration\n * @returns Promise resolving to the message data\n *\n * @example\n * ```typescript\n * try {\n * const response = await waitForIpc<ConfigData>('config-response', {\n * timeout: 5000 // 5 seconds\n * })\n * console.log('Config received:', response)\n * } catch (error) {\n * console.error('Timeout waiting for config')\n * }\n * ```\n *\n * @unused Reserved for request-response pattern implementation\n */\nexport function waitForIpc<T = unknown>(\n messageType: string,\n options: IpcOptions = {},\n): Promise<T> {\n const { timeout = 30_000 } = options\n return new Promise((resolve, reject) => {\n let cleanup: (() => void) | null = null\n let timeoutId: NodeJS.Timeout | null = null\n const handleTimeout = () => {\n if (cleanup) {\n cleanup()\n }\n reject(new Error(`IPC timeout waiting for message type: ${messageType}`))\n }\n const handleMessage = (message: IpcMessage) => {\n if (message.type === messageType) {\n if (timeoutId) {\n clearTimeout(timeoutId)\n }\n if (cleanup) {\n cleanup()\n }\n resolve(message.data as T)\n }\n }\n cleanup = onIpc(handleMessage)\n if (timeout > 0) {\n timeoutId = setTimeout(handleTimeout, timeout)\n }\n })\n}\n\n/**\n * Create an IPC message with proper structure and metadata.\n *\n * This factory function creates properly structured IPC messages with:\n * - Unique ID for tracking\n * - Timestamp for freshness\n * - Type for routing\n * - Data payload\n *\n * @param type - The message type identifier\n * @param data - The message payload\n * @returns A properly structured IPC message\n *\n * @example\n * ```typescript\n * const handshake = createIpcMessage('handshake', {\n * version: '1.0.0',\n * pid: process.pid,\n * appName: 'socket-cli'\n * })\n * ```\n *\n * @unused Reserved for future message creation needs\n */\nexport function createIpcMessage<T = unknown>(\n type: string,\n data: T,\n): IpcMessage<T> {\n return {\n id: crypto.randomBytes(16).toString('hex'),\n timestamp: Date.now(),\n type,\n data,\n }\n}\n\n/**\n * Check if process has IPC channel available.\n *\n * This utility checks whether a process object has the necessary\n * properties for IPC communication. Used to determine if IPC\n * messaging is possible before attempting to send.\n *\n * @param process - The process object to check\n * @returns true if IPC is available, false otherwise\n *\n * @example\n * ```typescript\n * if (hasIpcChannel(childProcess)) {\n * sendIpc(childProcess, message)\n * } else {\n * // Fall back to alternative communication method\n * }\n * ```\n *\n * @unused Reserved for IPC availability detection\n */\nexport function hasIpcChannel(process: unknown): boolean {\n return Boolean(\n process &&\n typeof process === 'object' &&\n 'send' in process &&\n typeof process.send === 'function' &&\n 'channel' in process &&\n process.channel !== undefined,\n )\n}\n\n/**\n * Safely parse and validate IPC messages.\n *\n * This function performs runtime validation of incoming messages\n * to ensure they conform to the IPC message structure. It uses\n * Zod schemas for robust validation.\n *\n * ## Validation Steps:\n * 1. Check if message is an object\n * 2. Validate required fields exist\n * 3. Validate field types\n * 4. Return typed message or null\n *\n * @param message - The raw message to parse\n * @returns Parsed IPC message or null if invalid\n *\n * @example\n * ```typescript\n * const parsed = parseIpcMessage(rawMessage)\n * if (parsed) {\n * handleMessage(parsed)\n * }\n * ```\n *\n * @unused Reserved for message validation needs\n */\nexport function parseIpcMessage(message: unknown): IpcMessage | null {\n try {\n // Use Zod schema for comprehensive validation.\n const validated = IpcMessageSchema.parse(message)\n return validated as IpcMessage\n } catch {\n // Return null for any validation failure.\n return null\n }\n}\n"],
|
|
5
|
-
"mappings": ";
|
|
6
|
-
"names": ["
|
|
5
|
+
"mappings": "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",
|
|
6
|
+
"names": ["import_fs", "crypto", "path", "fs", "process"]
|
|
7
7
|
}
|
package/dist/json.js
CHANGED
|
@@ -1,3 +1,75 @@
|
|
|
1
1
|
/* Socket Lib - Built with esbuild */
|
|
2
|
-
var
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
var json_exports = {};
|
|
20
|
+
__export(json_exports, {
|
|
21
|
+
isJsonPrimitive: () => isJsonPrimitive,
|
|
22
|
+
jsonParse: () => jsonParse
|
|
23
|
+
});
|
|
24
|
+
module.exports = __toCommonJS(json_exports);
|
|
25
|
+
var import_strings = require("./strings");
|
|
26
|
+
const JSONParse = JSON.parse;
|
|
27
|
+
// @__NO_SIDE_EFFECTS__
|
|
28
|
+
function isBuffer(x) {
|
|
29
|
+
if (!x || typeof x !== "object") {
|
|
30
|
+
return false;
|
|
31
|
+
}
|
|
32
|
+
const obj = x;
|
|
33
|
+
if (typeof obj["length"] !== "number") {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
if (typeof obj["copy"] !== "function" || typeof obj["slice"] !== "function") {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
if (typeof obj["length"] === "number" && obj["length"] > 0 && typeof obj[0] !== "number") {
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
const Ctor = x.constructor;
|
|
43
|
+
return !!(typeof Ctor?.isBuffer === "function" && Ctor.isBuffer(x));
|
|
44
|
+
}
|
|
45
|
+
// @__NO_SIDE_EFFECTS__
|
|
46
|
+
function isJsonPrimitive(value) {
|
|
47
|
+
return value === null || typeof value === "boolean" || typeof value === "number" || typeof value === "string";
|
|
48
|
+
}
|
|
49
|
+
// @__NO_SIDE_EFFECTS__
|
|
50
|
+
function jsonParse(content, options) {
|
|
51
|
+
const { filepath, reviver, throws } = {
|
|
52
|
+
__proto__: null,
|
|
53
|
+
...options
|
|
54
|
+
};
|
|
55
|
+
const shouldThrow = throws === void 0 || !!throws;
|
|
56
|
+
const jsonStr = /* @__PURE__ */ isBuffer(content) ? content.toString("utf8") : content;
|
|
57
|
+
try {
|
|
58
|
+
return JSONParse((0, import_strings.stripBom)(jsonStr), reviver);
|
|
59
|
+
} catch (e) {
|
|
60
|
+
if (shouldThrow) {
|
|
61
|
+
const error = e;
|
|
62
|
+
if (error && typeof filepath === "string") {
|
|
63
|
+
error.message = `${filepath}: ${error.message}`;
|
|
64
|
+
}
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return void 0;
|
|
69
|
+
}
|
|
70
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
71
|
+
0 && (module.exports = {
|
|
72
|
+
isJsonPrimitive,
|
|
73
|
+
jsonParse
|
|
74
|
+
});
|
|
3
75
|
//# sourceMappingURL=json.js.map
|
package/dist/json.js.map
CHANGED
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/json.ts"],
|
|
4
4
|
"sourcesContent": ["/**\n * @fileoverview JSON parsing utilities with Buffer detection and BOM stripping.\n * Provides safe JSON parsing with automatic encoding handling.\n */\n\nimport { stripBom } from './strings'\n\n/**\n * JSON primitive types: `null`, `boolean`, `number`, or `string`.\n *\n * @example\n * ```ts\n * const primitives: JsonPrimitive[] = [null, true, 42, 'hello']\n * ```\n */\nexport type JsonPrimitive = null | boolean | number | string\n\n/**\n * Any valid JSON value: primitive, object, or array.\n *\n * @example\n * ```ts\n * const values: JsonValue[] = [\n * null,\n * true,\n * 42,\n * 'hello',\n * { key: 'value' },\n * [1, 2, 3]\n * ]\n * ```\n */\nexport type JsonValue = JsonPrimitive | JsonObject | JsonArray\n\n/**\n * A JSON object with string keys and JSON values.\n *\n * @example\n * ```ts\n * const obj: JsonObject = {\n * name: 'example',\n * count: 42,\n * active: true,\n * nested: { key: 'value' }\n * }\n * ```\n */\nexport interface JsonObject {\n [key: string]: JsonValue\n}\n\n/**\n * A JSON array containing JSON values.\n *\n * @example\n * ```ts\n * const arr: JsonArray = [1, 'two', { three: 3 }, [4, 5]]\n * ```\n */\nexport interface JsonArray extends Array<JsonValue> {}\n\n/**\n * Reviver function for transforming parsed JSON values.\n * Called for each key-value pair during parsing.\n *\n * @param key - The object key or array index being parsed\n * @param value - The parsed value\n * @returns The transformed value (or original if no transform needed)\n *\n * @example\n * ```ts\n * // Convert date strings to Date objects\n * const reviver: JsonReviver = (key, value) => {\n * if (typeof value === 'string' && /^\\d{4}-\\d{2}-\\d{2}/.test(value)) {\n * return new Date(value)\n * }\n * return value\n * }\n * ```\n */\nexport type JsonReviver = (key: string, value: unknown) => unknown\n\n/**\n * Options for JSON parsing operations.\n */\nexport interface JsonParseOptions {\n /**\n * Optional filepath for improved error messages.\n * When provided, errors will be prefixed with the filepath.\n *\n * @example\n * ```ts\n * // Error message will be: \"config.json: Unexpected token } in JSON\"\n * jsonParse('invalid', { filepath: 'config.json' })\n * ```\n */\n filepath?: string | undefined\n /**\n * Optional reviver function to transform parsed values.\n * Called for each key-value pair during parsing.\n *\n * @example\n * ```ts\n * // Convert ISO date strings to Date objects\n * const options = {\n * reviver: (key, value) => {\n * if (typeof value === 'string' && /^\\d{4}-\\d{2}-\\d{2}/.test(value)) {\n * return new Date(value)\n * }\n * return value\n * }\n * }\n * ```\n */\n reviver?: JsonReviver | undefined\n /**\n * Whether to throw on parse errors.\n * When `false`, returns `undefined` instead of throwing.\n *\n * @default true\n *\n * @example\n * ```ts\n * // Throws error\n * jsonParse('invalid', { throws: true })\n *\n * // Returns undefined\n * const result = jsonParse('invalid', { throws: false })\n * ```\n */\n throws?: boolean | undefined\n}\n\n// IMPORTANT: Do not use destructuring here - use direct assignment instead.\n// tsgo has a bug that incorrectly transpiles destructured exports, resulting in\n// `exports.SomeName = void 0;` which causes runtime errors.\n// See: https://github.com/SocketDev/socket-packageurl-js/issues/3\nconst JSONParse = JSON.parse\n\n/**\n * Check if a value is a Buffer instance.\n * Uses duck-typing to detect Buffer without requiring Node.js Buffer in type system.\n *\n * @param x - Value to check\n * @returns `true` if value is a Buffer, `false` otherwise\n *\n * @example\n * ```ts\n * isBuffer(Buffer.from('hello')) // => true\n * isBuffer('hello') // => false\n * isBuffer({ length: 5 }) // => false\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nfunction isBuffer(x: unknown): x is Buffer {\n if (!x || typeof x !== 'object') {\n return false\n }\n const obj = x as Record<string | number, unknown>\n if (typeof obj['length'] !== 'number') {\n return false\n }\n if (typeof obj['copy'] !== 'function' || typeof obj['slice'] !== 'function') {\n return false\n }\n if (\n typeof obj['length'] === 'number' &&\n obj['length'] > 0 &&\n typeof obj[0] !== 'number'\n ) {\n return false\n }\n\n const Ctor = (x as { constructor?: unknown }).constructor as\n | { isBuffer?: unknown }\n | undefined\n return !!(typeof Ctor?.isBuffer === 'function' && Ctor.isBuffer(x))\n}\n\n/**\n * Check if a value is a JSON primitive type.\n * JSON primitives are: `null`, `boolean`, `number`, or `string`.\n *\n * @param value - Value to check\n * @returns `true` if value is a JSON primitive, `false` otherwise\n *\n * @example\n * ```ts\n * isJsonPrimitive(null) // => true\n * isJsonPrimitive(true) // => true\n * isJsonPrimitive(42) // => true\n * isJsonPrimitive('hello') // => true\n * isJsonPrimitive({}) // => false\n * isJsonPrimitive([]) // => false\n * isJsonPrimitive(undefined) // => false\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function isJsonPrimitive(value: unknown): value is JsonPrimitive {\n return (\n value === null ||\n typeof value === 'boolean' ||\n typeof value === 'number' ||\n typeof value === 'string'\n )\n}\n\n/**\n * Parse JSON content with automatic Buffer handling and BOM stripping.\n * Provides safer JSON parsing with helpful error messages and optional error suppression.\n *\n * Features:\n * - Automatic UTF-8 Buffer conversion\n * - BOM (Byte Order Mark) stripping for cross-platform compatibility\n * - Enhanced error messages with filepath context\n * - Optional error suppression (returns `undefined` instead of throwing)\n * - Optional reviver for transforming parsed values\n *\n * @param content - JSON string or Buffer to parse\n * @param options - Optional parsing configuration\n * @returns Parsed JSON value, or `undefined` if parsing fails and `throws` is `false`\n *\n * @throws {SyntaxError} When JSON is invalid and `throws` is `true` (default)\n *\n * @example\n * ```ts\n * // Basic usage\n * const data = jsonParse('{\"name\":\"example\"}')\n * console.log(data.name) // => 'example'\n *\n * // Parse Buffer with UTF-8 BOM\n * const buffer = Buffer.from('\\uFEFF{\"value\":42}')\n * const data = jsonParse(buffer)\n * console.log(data.value) // => 42\n *\n * // Enhanced error messages with filepath\n * try {\n * jsonParse('invalid', { filepath: 'config.json' })\n * } catch (err) {\n * console.error(err.message)\n * // => \"config.json: Unexpected token i in JSON at position 0\"\n * }\n *\n * // Suppress errors\n * const result = jsonParse('invalid', { throws: false })\n * console.log(result) // => undefined\n *\n * // Transform values with reviver\n * const json = '{\"created\":\"2024-01-15T10:30:00Z\"}'\n * const data = jsonParse(json, {\n * reviver: (key, value) => {\n * if (key === 'created' && typeof value === 'string') {\n * return new Date(value)\n * }\n * return value\n * }\n * })\n * console.log(data.created instanceof Date) // => true\n * ```\n */\n/*@__NO_SIDE_EFFECTS__*/\nexport function jsonParse(\n content: string | Buffer,\n options?: JsonParseOptions | undefined,\n): JsonValue | undefined {\n const { filepath, reviver, throws } = {\n __proto__: null,\n ...options,\n } as JsonParseOptions\n const shouldThrow = throws === undefined || !!throws\n const jsonStr = isBuffer(content) ? content.toString('utf8') : content\n try {\n return JSONParse(stripBom(jsonStr), reviver)\n } catch (e) {\n if (shouldThrow) {\n const error = e as Error\n if (error && typeof filepath === 'string') {\n error.message = `${filepath}: ${error.message}`\n }\n throw error\n }\n }\n return undefined\n}\n"],
|
|
5
|
-
"mappings": ";
|
|
6
|
-
"names": [
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,qBAAyB;AAoIzB,MAAM,YAAY,KAAK;AAAA;AAiBvB,SAAS,SAAS,GAAyB;AACzC,MAAI,CAAC,KAAK,OAAO,MAAM,UAAU;AAC/B,WAAO;AAAA,EACT;AACA,QAAM,MAAM;AACZ,MAAI,OAAO,IAAI,QAAQ,MAAM,UAAU;AACrC,WAAO;AAAA,EACT;AACA,MAAI,OAAO,IAAI,MAAM,MAAM,cAAc,OAAO,IAAI,OAAO,MAAM,YAAY;AAC3E,WAAO;AAAA,EACT;AACA,MACE,OAAO,IAAI,QAAQ,MAAM,YACzB,IAAI,QAAQ,IAAI,KAChB,OAAO,IAAI,CAAC,MAAM,UAClB;AACA,WAAO;AAAA,EACT;AAEA,QAAM,OAAQ,EAAgC;AAG9C,SAAO,CAAC,EAAE,OAAO,MAAM,aAAa,cAAc,KAAK,SAAS,CAAC;AACnE;AAAA;AAqBO,SAAS,gBAAgB,OAAwC;AACtE,SACE,UAAU,QACV,OAAO,UAAU,aACjB,OAAO,UAAU,YACjB,OAAO,UAAU;AAErB;AAAA;AAwDO,SAAS,UACd,SACA,SACuB;AACvB,QAAM,EAAE,UAAU,SAAS,OAAO,IAAI;AAAA,IACpC,WAAW;AAAA,IACX,GAAG;AAAA,EACL;AACA,QAAM,cAAc,WAAW,UAAa,CAAC,CAAC;AAC9C,QAAM,UAAU,yBAAS,OAAO,IAAI,QAAQ,SAAS,MAAM,IAAI;AAC/D,MAAI;AACF,WAAO,cAAU,yBAAS,OAAO,GAAG,OAAO;AAAA,EAC7C,SAAS,GAAG;AACV,QAAI,aAAa;AACf,YAAM,QAAQ;AACd,UAAI,SAAS,OAAO,aAAa,UAAU;AACzC,cAAM,UAAU,GAAG,QAAQ,KAAK,MAAM,OAAO;AAAA,MAC/C;AACA,YAAM;AAAA,IACR;AAAA,EACF;AACA,SAAO;AACT;",
|
|
6
|
+
"names": []
|
|
7
7
|
}
|
package/dist/links/index.js
CHANGED
|
@@ -1,3 +1,62 @@
|
|
|
1
1
|
/* Socket Lib - Built with esbuild */
|
|
2
|
-
var
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
var links_exports = {};
|
|
30
|
+
__export(links_exports, {
|
|
31
|
+
link: () => link,
|
|
32
|
+
links: () => links
|
|
33
|
+
});
|
|
34
|
+
module.exports = __toCommonJS(links_exports);
|
|
35
|
+
var import_yoctocolors_cjs = __toESM(require("../external/yoctocolors-cjs"));
|
|
36
|
+
var import_context = require("../themes/context");
|
|
37
|
+
var import_utils = require("../themes/utils");
|
|
38
|
+
function link(text, url, options) {
|
|
39
|
+
const opts = { __proto__: null, fallback: false, ...options };
|
|
40
|
+
const theme = typeof opts.theme === "string" ? require("../themes/themes").THEMES[opts.theme] : opts.theme ?? (0, import_context.getTheme)();
|
|
41
|
+
const linkColor = (0, import_utils.resolveColor)(theme.colors.link, theme.colors);
|
|
42
|
+
const colors = import_yoctocolors_cjs.default;
|
|
43
|
+
let colored;
|
|
44
|
+
if (typeof linkColor === "string" && linkColor !== "inherit") {
|
|
45
|
+
const colorMethod = colors[linkColor];
|
|
46
|
+
colored = colorMethod ? colorMethod(text) : colors.cyan(text);
|
|
47
|
+
} else if (Array.isArray(linkColor)) {
|
|
48
|
+
colored = colors.cyan(text);
|
|
49
|
+
} else {
|
|
50
|
+
colored = colors.cyan(text);
|
|
51
|
+
}
|
|
52
|
+
return opts.fallback ? `${colored} (${url})` : colored;
|
|
53
|
+
}
|
|
54
|
+
function links(linkSpecs, options) {
|
|
55
|
+
return linkSpecs.map(([text, url]) => link(text, url, options));
|
|
56
|
+
}
|
|
57
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
58
|
+
0 && (module.exports = {
|
|
59
|
+
link,
|
|
60
|
+
links
|
|
61
|
+
});
|
|
3
62
|
//# sourceMappingURL=index.js.map
|
package/dist/links/index.js.map
CHANGED
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/links/index.ts"],
|
|
4
4
|
"sourcesContent": ["/**\n * @fileoverview Themed hyperlink utilities for terminal output.\n * Provides colored hyperlinks using theme configuration.\n */\n\nimport yoctocolorsCjs from '../external/yoctocolors-cjs'\nimport type { ColorName } from '../spinner'\nimport { getTheme } from '../themes/context'\nimport { resolveColor } from '../themes/utils'\nimport type { Theme } from '../themes/types'\nimport type { ThemeName } from '../themes/themes'\n\n/**\n * Options for creating themed links.\n */\nexport type LinkOptions = {\n /** Theme to use (overrides global) */\n theme?: Theme | ThemeName | undefined\n /** Show URL as fallback if terminal doesn't support links */\n fallback?: boolean | undefined\n}\n\n/**\n * Create a themed hyperlink for terminal output.\n * The link text is colored using the theme's link color.\n *\n * Note: Most terminals support ANSI color codes but not clickable links.\n * This function colors the text but does not create clickable hyperlinks.\n * For clickable links, use a library like 'terminal-link' separately.\n *\n * @param text - Link text to display\n * @param url - URL (included in fallback mode)\n * @param options - Link configuration options\n * @returns Colored link text\n *\n * @example\n * ```ts\n * import { link } from '@socketsecurity/lib/links'\n *\n * // Use current theme\n * console.log(link('Documentation', 'https://socket.dev'))\n *\n * // Override theme\n * console.log(link('API Docs', 'https://api.socket.dev', {\n * theme: 'coana'\n * }))\n *\n * // Show URL as fallback\n * console.log(link('GitHub', 'https://github.com', {\n * fallback: true\n * }))\n * // Output: \"GitHub (https://github.com)\"\n * ```\n */\nexport function link(text: string, url: string, options?: LinkOptions): string {\n const opts = { __proto__: null, fallback: false, ...options } as LinkOptions\n\n // Resolve theme\n const theme =\n typeof opts.theme === 'string'\n ? require('../themes/themes').THEMES[opts.theme]\n : (opts.theme ?? getTheme())\n\n // Resolve link color\n const linkColor = resolveColor(theme.colors.link, theme.colors)\n\n // Apply color - for now just use cyan as a simple fallback\n // Note: RGB color support to be added in yoctocolors wrapper\n const colors = yoctocolorsCjs\n let colored: string\n if (typeof linkColor === 'string' && linkColor !== 'inherit') {\n // Use named color method if available\n const colorMethod = colors[linkColor as ColorName]\n colored = colorMethod ? colorMethod(text) : colors.cyan(text)\n } else if (Array.isArray(linkColor)) {\n // RGB color - for now fallback to cyan\n // Note: RGB color support to be implemented\n colored = colors.cyan(text)\n } else {\n colored = colors.cyan(text)\n }\n\n // Return with or without URL fallback\n return opts.fallback ? `${colored} (${url})` : colored\n}\n\n/**\n * Create multiple themed links from an array of link specifications.\n *\n * @param links - Array of [text, url] pairs\n * @param options - Link configuration options\n * @returns Array of colored link texts\n *\n * @example\n * ```ts\n * import { links } from '@socketsecurity/lib/links'\n *\n * const formatted = links([\n * ['Documentation', 'https://socket.dev'],\n * ['API Reference', 'https://api.socket.dev'],\n * ['GitHub', 'https://github.com/SocketDev']\n * ])\n *\n * formatted.forEach(link => console.log(link))\n * ```\n */\nexport function links(\n linkSpecs: Array<[text: string, url: string]>,\n options?: LinkOptions,\n): string[] {\n return linkSpecs.map(([text, url]) => link(text, url, options))\n}\n"],
|
|
5
|
-
"mappings": ";
|
|
6
|
-
"names": ["
|
|
5
|
+
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAKA,6BAA2B;AAE3B,qBAAyB;AACzB,mBAA6B;AA8CtB,SAAS,KAAK,MAAc,KAAa,SAA+B;AAC7E,QAAM,OAAO,EAAE,WAAW,MAAM,UAAU,OAAO,GAAG,QAAQ;AAG5D,QAAM,QACJ,OAAO,KAAK,UAAU,WAClB,QAAQ,kBAAkB,EAAE,OAAO,KAAK,KAAK,IAC5C,KAAK,aAAS,yBAAS;AAG9B,QAAM,gBAAY,2BAAa,MAAM,OAAO,MAAM,MAAM,MAAM;AAI9D,QAAM,SAAS,uBAAAA;AACf,MAAI;AACJ,MAAI,OAAO,cAAc,YAAY,cAAc,WAAW;AAE5D,UAAM,cAAc,OAAO,SAAsB;AACjD,cAAU,cAAc,YAAY,IAAI,IAAI,OAAO,KAAK,IAAI;AAAA,EAC9D,WAAW,MAAM,QAAQ,SAAS,GAAG;AAGnC,cAAU,OAAO,KAAK,IAAI;AAAA,EAC5B,OAAO;AACL,cAAU,OAAO,KAAK,IAAI;AAAA,EAC5B;AAGA,SAAO,KAAK,WAAW,GAAG,OAAO,KAAK,GAAG,MAAM;AACjD;AAsBO,SAAS,MACd,WACA,SACU;AACV,SAAO,UAAU,IAAI,CAAC,CAAC,MAAM,GAAG,MAAM,KAAK,MAAM,KAAK,OAAO,CAAC;AAChE;",
|
|
6
|
+
"names": ["yoctocolorsCjs"]
|
|
7
7
|
}
|