@cldmv/wisp 1.0.6 → 1.0.8

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.
@@ -1,148 +0,0 @@
1
- /**
2
- * @function getStack
3
- * @package
4
- * @internal
5
- * @param {Function} [skipFn] - Function to skip in stack trace via Error.captureStackTrace
6
- * @returns {Array<CallSite>} Array of V8 CallSite objects with methods like getFileName(), getLineNumber(), etc.
7
- *
8
- * @description
9
- * Get V8 stack trace as CallSite array for debugging and caller detection.
10
- * Temporarily overrides Error.prepareStackTrace to access raw V8 CallSite objects
11
- * instead of formatted string stack traces. Provides safe restoration of original handler.
12
- *
13
- * @example
14
- * // Get current call stack for debugging
15
- * const stack = getStack();
16
- * console.log(stack[0]?.getFileName?.()); // Current file path
17
- * console.log(stack[0]?.getLineNumber?.()); // Current line number
18
- *
19
- * @example
20
- * // Skip current function from stack trace
21
- * function myFunction() {
22
- * return getStack(myFunction); // Stack starts from caller of myFunction
23
- * }
24
- * const callerStack = myFunction();
25
- *
26
- * @example
27
- * // Stack analysis for caller detection
28
- * function findCaller() {
29
- * const stack = getStack(findCaller);
30
- * for (const frame of stack) {
31
- * const filename = frame?.getFileName?.();
32
- * if (filename && !filename.includes("node_modules")) {
33
- * return filename; // First non-dependency file
34
- * }
35
- * }
36
- * }
37
- */
38
- export function getStack(skipFn?: Function): Array<CallSite>;
39
- /**
40
- * @function resolvePathFromCaller
41
- * @package
42
- * @internal
43
- * @param {string} rel - Relative path to resolve (e.g., "../config.json", "./data/file.txt")
44
- * @returns {string} Absolute filesystem path with platform-specific separators
45
- * @throws {TypeError} When rel parameter is not a string
46
- *
47
- * @description
48
- * Resolve a relative path from the caller's context to an absolute filesystem path.
49
- * Primary public API for filesystem path resolution with intelligent caller detection.
50
- * Uses sophisticated stack trace analysis to determine the appropriate base directory.
51
- *
52
- * Resolution behavior:
53
- * - file:// URLs: Converted to filesystem paths via fileURLToPath()
54
- * - Absolute paths: Returned unchanged (already absolute)
55
- * - Relative paths: Resolved using caller detection algorithm
56
- *
57
- * Caller detection process:
58
- * 1. Primary: Use sophisticated slothlet.mjs-aware stack analysis
59
- * 2. Fallback: Use first non-helper frame if primary fails
60
- * 3. Existence check: Prefer primary if target exists, otherwise use fallback
61
- *
62
- * @example
63
- * // From a file at /project/src/modules/math.mjs
64
- * const configPath = resolvePathFromCaller("../config.json");
65
- * // Returns: /project/config.json (absolute filesystem path)
66
- *
67
- * @example
68
- * // Short-circuit cases
69
- * resolvePathFromCaller("file:///absolute/path.txt");
70
- * // Returns: /absolute/path.txt (converted from URL)
71
- *
72
- * resolvePathFromCaller("/already/absolute/path.txt");
73
- * // Returns: /already/absolute/path.txt (unchanged)
74
- *
75
- * @example
76
- * // Relative resolution from different contexts
77
- * // If called from /project/src/lib/utils.mjs:
78
- * resolvePathFromCaller("./helpers/format.js");
79
- * // Returns: /project/src/lib/helpers/format.js
80
- *
81
- * resolvePathFromCaller("../../config/settings.json");
82
- * // Returns: /project/config/settings.json
83
- */
84
- export function resolvePathFromCaller(rel: string): string;
85
- /**
86
- * @function resolveUrlFromCaller
87
- * @package
88
- * @internal
89
- * @param {string} rel - Relative path to resolve (e.g., "../config.json", "./data/file.txt")
90
- * @returns {string} Absolute file:// URL suitable for dynamic imports and URL operations
91
- * @throws {TypeError} When rel parameter is not a string
92
- *
93
- * @description
94
- * Resolve a relative path from the caller's context to a file:// URL.
95
- * Companion API to resolvePathFromCaller that returns file:// URLs instead of filesystem paths.
96
- * Uses identical caller detection algorithm but outputs URL format for ESM imports.
97
- *
98
- * Resolution behavior:
99
- * - file:// URLs: Returned unchanged (already in URL format)
100
- * - Absolute paths: Converted to file:// URLs via pathToFileURL()
101
- * - Relative paths: Resolved using caller detection, then converted to URL
102
- *
103
- * Caller detection uses the same sophisticated algorithm as resolvePathFromCaller,
104
- * but the final result is converted to a file:// URL for compatibility with
105
- * ESM dynamic imports and other URL-based operations.
106
- *
107
- * @example
108
- * // From a file at /project/src/modules/math.mjs
109
- * const configUrl = resolveUrlFromCaller("../config.json");
110
- * // Returns: file:///project/config.json (absolute file:// URL)
111
- *
112
- * @example
113
- * // Short-circuit cases
114
- * resolveUrlFromCaller("file:///absolute/path.txt");
115
- * // Returns: file:///absolute/path.txt (unchanged)
116
- *
117
- * resolveUrlFromCaller("/already/absolute/path.txt");
118
- * // Returns: file:///already/absolute/path.txt (converted to URL)
119
- *
120
- * @example
121
- * // Dynamic ESM import usage
122
- * const modulePath = resolveUrlFromCaller("./dynamic-module.mjs");
123
- * const dynamicModule = await import(modulePath);
124
- * // Works seamlessly with ESM import() which expects URLs
125
- *
126
- * @example
127
- * // Cross-platform URL handling
128
- * // Unix: resolveUrlFromCaller("../config.json") → file:///project/config.json
129
- * // Windows: resolveUrlFromCaller("../config.json") → file:///C:/project/config.json
130
- */
131
- export function resolveUrlFromCaller(rel: string): string;
132
- export function toFsPath(v: any): string | null;
133
- export type CallSite = {
134
- getFileName: () => string | undefined;
135
- getLineNumber: () => number | undefined;
136
- getFunctionName: () => string | undefined;
137
- getTypeName: () => string | undefined;
138
- getMethodName: () => string | undefined;
139
- getScriptNameOrSourceURL: () => string | undefined;
140
- getColumnNumber: () => number | undefined;
141
- isNative: () => boolean | undefined;
142
- isEval: () => boolean | undefined;
143
- isConstructor: () => boolean | undefined;
144
- isToplevel: () => boolean | undefined;
145
- isAsync: () => boolean | undefined;
146
- isPromiseAll: () => boolean | undefined;
147
- getPromiseIndex: () => number | undefined;
148
- };
@@ -1,54 +0,0 @@
1
- /**
2
- * Asynchronously loads JSON from a file, trying modern import with 'with', then 'assert', then fs.
3
- * @public
4
- * @param {string|URL} input - The path or URL to the JSON file.
5
- * @param {Object} [options] - Options object.
6
- * @param {string|URL} [options.base] - Base URL for relative paths.
7
- * @param {Function} [options.validate] - Validation function for the parsed JSON.
8
- * @param {Function} [options.reviver] - Reviver function for JSON.parse.
9
- * @param {string} [options.type='json'] - The type of the file being imported. Defaults to 'json'.
10
- * @param {string|URL} [options.fallback] - Fallback path or URL if the primary file is missing.
11
- * @returns {Promise<*>} The parsed JSON value.
12
- *
13
- * @description
14
- * Loads JSON asynchronously with version-agnostic support.
15
- * Attempts modern import syntax first, falls back to legacy assert, then fs.readFile.
16
- *
17
- * @example
18
- * import { wisp } from '@cldmv/wisp';
19
- * const data = await wisp('./config.json');
20
- */
21
- export function wisp(input: string | URL, options?: {
22
- base?: string | URL;
23
- validate?: Function;
24
- reviver?: Function;
25
- type?: string;
26
- fallback?: string | URL;
27
- }): Promise<any>;
28
- /**
29
- * Synchronously loads JSON from a file using fs.
30
- * @public
31
- * @param {string|URL} input - The path or URL to the JSON file.
32
- * @param {Object} [options] - Options object.
33
- * @param {string|URL} [options.base] - Base URL for relative paths.
34
- * @param {Function} [options.validate] - Validation function for the parsed JSON.
35
- * @param {Function} [options.reviver] - Reviver function for JSON.parse.
36
- * @param {string} [options.type='json'] - The type of the file being imported. Defaults to 'json'.
37
- * @param {string|URL} [options.fallback] - Fallback path or URL if the primary file is missing.
38
- * @returns {*} The parsed JSON value.
39
- *
40
- * @description
41
- * Loads JSON synchronously using fs.readFileSync.
42
- *
43
- * @example
44
- * import { wispSync } from '@cldmv/wisp';
45
- * const data = wispSync('./config.json');
46
- */
47
- export function wispSync(input: string | URL, options?: {
48
- base?: string | URL;
49
- validate?: Function;
50
- reviver?: Function;
51
- type?: string;
52
- fallback?: string | URL;
53
- }): any;
54
- export default wisp;
package/src/wisp.mjs DELETED
@@ -1,190 +0,0 @@
1
- /**
2
- *
3
- * @Project: @cldmv/wisp
4
- * @Filename: /src/wisp.mjs
5
- * @Date: 2025-10-30T14:12:05-07:00 (1761858725)
6
- * @Author: Nate Corcoran <CLDMV>
7
- * @Email: <Shinrai@users.noreply.github.com>
8
- * -----
9
- * @Last modified by: Nate Corcoran <CLDMV> (Shinrai@users.noreply.github.com)
10
- * @Last modified time: 2026-10-02T15:12:05-07:00 (1790979125)
11
- * -----
12
- * @Copyright: Copyright (c) 2013-2026 Catalyzed Motivation Inc. All rights reserved.
13
- *
14
- */
15
-
16
- /**
17
- * @fileoverview Internal implementation of @cldmv/wisp. Not exported in package.json.
18
- * @module @cldmv/wisp.src.wisp
19
- * @internal
20
- * @private
21
- *
22
- * @description
23
- * This module provides the core implementation for version-agnostic JSON importing in Node.js.
24
- * It includes functions to load JSON asynchronously and synchronously, with fallbacks for different Node versions.
25
- *
26
- * @example
27
- * // Internal usage example
28
- * import { wisp } from './src/wisp.mjs';
29
- * const data = await wisp('./data.json');
30
- */
31
-
32
- import fs from "node:fs";
33
- import { readFile } from "node:fs/promises";
34
- import path from "node:path";
35
- import { pathToFileURL } from "node:url";
36
- import { resolveUrlFromCaller } from "./lib/resolve-from-caller.mjs";
37
-
38
- /**
39
- * Deep clones a value using structuredClone if available, otherwise JSON.parse/stringify.
40
- * @private
41
- * @param {*} v - The value to clone.
42
- * @returns {*} The cloned value.
43
- */
44
- /**
45
- * Deep clones a value using structuredClone if available, otherwise JSON.parse/stringify.
46
- * @private
47
- * @param {*} v - The value to clone.
48
- * @returns {*} The cloned value.
49
- */
50
- function deepClone(v) {
51
- return typeof globalThis.structuredClone === "function" ? globalThis.structuredClone(v) : JSON.parse(JSON.stringify(v));
52
- }
53
-
54
- /**
55
- * Asynchronously loads JSON from a file, trying modern import with 'with', then 'assert', then fs.
56
- * @public
57
- * @param {string|URL} input - The path or URL to the JSON file.
58
- * @param {Object} [options] - Options object.
59
- * @param {string|URL} [options.base] - Base URL for relative paths.
60
- * @param {(val: any) => void} [options.validate] - Validation function for the parsed JSON.
61
- * @param {(this: any, key: string, value: any) => any} [options.reviver] - Reviver function for JSON.parse.
62
- * @param {string} [options.type='json'] - The type of the file being imported. Defaults to 'json'.
63
- * @param {string|URL} [options.fallback] - Fallback path or URL if the primary file is missing.
64
- * @returns {Promise<*>} The parsed JSON value.
65
- *
66
- * @description
67
- * Loads JSON asynchronously with version-agnostic support.
68
- * Attempts modern import syntax first, falls back to legacy assert, then fs.readFile.
69
- *
70
- * @example
71
- * import { wisp } from '@cldmv/wisp';
72
- * const data = await wisp('./config.json');
73
- */
74
- export async function wisp(input, options = {}) {
75
- const { base, validate, reviver, type = "json", fallback } = options;
76
- let url;
77
- if (input instanceof URL) url = input;
78
- else {
79
- const s = String(input);
80
- if (s.startsWith("file://")) url = new URL(s);
81
- else if (path.isAbsolute(s)) url = pathToFileURL(s);
82
- else if (base) url = new URL(s, new URL(base));
83
- else url = new URL(resolveUrlFromCaller(s));
84
- }
85
-
86
- try {
87
- const mod = await import(url.href, { with: { type } });
88
- if (!reviver && !validate) return mod?.default ?? mod;
89
- let val = deepClone(mod?.default ?? mod);
90
- if (reviver) val = JSON.parse(JSON.stringify(val), reviver);
91
- if (validate) {
92
- try {
93
- validate(val);
94
- } catch (e) {
95
- throw new Error(`@cldmv/wisp: ${e?.message ?? e}`, { cause: e });
96
- }
97
- }
98
- return val;
99
- } catch {}
100
-
101
- try {
102
- // Legacy import assertions (`assert`) for Node 16.14-20.9, which predate `with`; the cast keeps the type checker from rejecting the key.
103
- const mod = await import(url.href, /** @type {any} */ ({ assert: { type } }));
104
- if (!reviver && !validate) return mod?.default ?? mod;
105
- let val = deepClone(mod?.default ?? mod);
106
- if (reviver) val = JSON.parse(JSON.stringify(val), reviver);
107
- if (validate) {
108
- try {
109
- validate(val);
110
- } catch (e) {
111
- throw new Error(`@cldmv/wisp: ${e?.message ?? e}`, { cause: e });
112
- }
113
- }
114
- return val;
115
- } catch {}
116
-
117
- if (type === "json") {
118
- try {
119
- const txt = await readFile(url, "utf8");
120
- const val = deepClone(JSON.parse(txt, reviver));
121
- if (validate) {
122
- try {
123
- validate(val);
124
- } catch (e) {
125
- throw new Error(`@cldmv/wisp: ${e?.message ?? e}`, { cause: e });
126
- }
127
- }
128
- return val;
129
- } catch (e) {
130
- if (fallback) {
131
- return wisp(fallback, options);
132
- }
133
- throw new Error(`@cldmv/wisp: Failed to load JSON file at ${url.href}: ${e.message}`, { cause: e });
134
- }
135
- }
136
-
137
- throw new Error(`@cldmv/wisp: Unsupported type '${type}' or failed to load module at ${url.href}`);
138
- }
139
-
140
- /**
141
- * Synchronously loads JSON from a file using fs.
142
- * @public
143
- * @param {string|URL} input - The path or URL to the JSON file.
144
- * @param {Object} [options] - Options object.
145
- * @param {string|URL} [options.base] - Base URL for relative paths.
146
- * @param {(val: any) => void} [options.validate] - Validation function for the parsed JSON.
147
- * @param {(this: any, key: string, value: any) => any} [options.reviver] - Reviver function for JSON.parse.
148
- * @param {string} [options.type='json'] - The type of the file being imported. Defaults to 'json'.
149
- * @param {string|URL} [options.fallback] - Fallback path or URL if the primary file is missing.
150
- * @returns {*} The parsed JSON value.
151
- *
152
- * @description
153
- * Loads JSON synchronously using fs.readFileSync.
154
- *
155
- * @example
156
- * import { wispSync } from '@cldmv/wisp';
157
- * const data = wispSync('./config.json');
158
- */
159
- export function wispSync(input, options = {}) {
160
- const { base, validate, reviver, fallback } = options;
161
- let url;
162
- if (input instanceof URL) url = input;
163
- else {
164
- const s = String(input);
165
- if (s.startsWith("file://")) url = new URL(s);
166
- else if (path.isAbsolute(s)) url = pathToFileURL(s);
167
- else if (base) url = new URL(s, new URL(base));
168
- else url = new URL(resolveUrlFromCaller(s));
169
- }
170
-
171
- try {
172
- const txt = fs.readFileSync(url, "utf8");
173
- const val = deepClone(JSON.parse(txt, reviver));
174
- if (validate) {
175
- try {
176
- validate(val);
177
- } catch (e) {
178
- throw new Error(`@cldmv/wisp: ${e?.message ?? e}`, { cause: e });
179
- }
180
- }
181
- return val;
182
- } catch (e) {
183
- if (fallback) {
184
- return wispSync(fallback, options);
185
- }
186
- throw new Error(`@cldmv/wisp: Failed to load JSON file at ${url.href}: ${e.message}`, { cause: e });
187
- }
188
- }
189
-
190
- export default wisp;