@hellaweb3/wiremock-testcontainers-nodejs 0.2.0 → 0.3.0

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/src/sources.ts DELETED
@@ -1,143 +0,0 @@
1
- import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
2
- import { createRequire } from "node:module";
3
- import { dirname, join, relative, resolve, sep } from "node:path";
4
- import { fileURLToPath } from "node:url";
5
-
6
- /** A path (relative to the working directory) or a `file:` URL. */
7
- export type WiremockPath = string | URL;
8
-
9
- /**
10
- * A fixture file: a local path or `file:` URL, `{ file }`, a file inside an installed npm
11
- * package `{ package, file }` (its `exports` are ignored), or a file next to a module
12
- * `{ module: import.meta.url | __filename | __dirname, file }`.
13
- */
14
- export type WiremockFileSource =
15
- | WiremockPath
16
- | { readonly file: WiremockPath }
17
- | { readonly package: string; readonly file: string }
18
- | { readonly module: WiremockPath; readonly file: string };
19
-
20
- /** A WireMock stub; fields besides `request` and `response` are passed through. */
21
- export interface WiremockStubMapping {
22
- readonly request: object;
23
- readonly response: object;
24
- readonly [field: string]: unknown;
25
- }
26
-
27
- /** A file source, or inline JSON: a string, a stub or `{ mappings: [...] }`. */
28
- export type WiremockMappingSource =
29
- | WiremockFileSource
30
- | { readonly json: string | WiremockStubMapping | { readonly mappings: readonly WiremockStubMapping[] } };
31
-
32
- /** A file source; object forms may set `name`, the path below `__files/` (default: the base name). */
33
- export type WiremockStaticFile = WiremockPath | (Exclude<WiremockFileSource, WiremockPath> & { readonly name?: string });
34
-
35
- const PACKAGE_NAME = /^(?:@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/u;
36
-
37
- export function fail(message: string): never {
38
- throw new Error(message);
39
- }
40
-
41
- /** Runs `fn`, prefixing the message of any error it throws with `context`. */
42
- export function within<T>(context: string, fn: () => T): T {
43
- try {
44
- return fn();
45
- } catch (error) {
46
- throw new Error(`${context}: ${(error as Error).message}`, { cause: error });
47
- }
48
- }
49
-
50
- export const isRecord = (value: unknown): value is Record<string, unknown> =>
51
- typeof value === "object" && value !== null && !Array.isArray(value);
52
-
53
- const show = (value: unknown): string => (value instanceof URL ? value.href : (JSON.stringify(value) ?? String(value)));
54
-
55
- const text = (value: unknown, field: string): string =>
56
- typeof value === "string" && value.trim() !== "" ? value : fail(`"${field}" must be a non-empty string, got ${show(value)}`);
57
-
58
- const toPath = (value: unknown, field: string): string => {
59
- if (!(value instanceof URL) && !text(value, field).startsWith("file:")) return resolve(value as string);
60
- try {
61
- return fileURLToPath(value as WiremockPath);
62
- } catch {
63
- return fail(`"${field}" must be a path or a file: URL, got ${show(value)}`);
64
- }
65
- };
66
-
67
- const existingFile = (path: string): string => {
68
- const stats = statSync(path, { throwIfNoEntry: false });
69
- return stats?.isFile() ? path : fail(`"${path}" ${stats ? "is not a file" : "does not exist"}`);
70
- };
71
-
72
- /** Finds an installed package the way `require()` would from the working directory. */
73
- const packageRoot = (name: string): string => {
74
- if (!PACKAGE_NAME.test(name)) fail(`"${name}" is not a valid npm package name`);
75
- const searchPaths = createRequire(join(process.cwd(), "noop.js")).resolve.paths(name) ?? [];
76
- const root = searchPaths.map((dir) => join(dir, name)).find((dir) => existsSync(join(dir, "package.json")));
77
- return root ?? fail(`package "${name}" is not installed (searched from "${process.cwd()}")`);
78
- };
79
-
80
- /** Resolves a {@link WiremockFileSource} to the absolute path of an existing file. */
81
- export function resolveFile(source: unknown): string {
82
- if (typeof source === "string" || source instanceof URL) return existingFile(toPath(source, "source"));
83
- if (!isRecord(source)) return fail(`unsupported source ${show(source)}; expected a path, a file: URL, { file }, { package, file } or { module, file }`);
84
- const { file, package: pkg, module } = source;
85
- if (pkg !== undefined && module !== undefined) fail('a source may set "package" or "module", not both');
86
- if (pkg !== undefined) {
87
- const root = packageRoot(text(pkg, "package"));
88
- const path = resolve(root, text(file, "file"));
89
- return relative(root, path).split(sep)[0] === ".." ? fail(`"${String(file)}" must point to a file inside package "${pkg}"`) : existingFile(path);
90
- }
91
- if (module === undefined) return existingFile(toPath(file, "file"));
92
- const anchor = toPath(module, "module");
93
- return existingFile(resolve(statSync(anchor, { throwIfNoEntry: false })?.isDirectory() ? anchor : dirname(anchor), text(file, "file")));
94
- }
95
-
96
- /** Validates a `/`-separated relative container name (no empty, `.` or `..` segments). */
97
- export const containerName = (name: unknown): string => {
98
- const value = text(name, "name");
99
- const invalid = value.split("/").some((part) => ["", ".", ".."].includes(part) || /[\\\0]/u.test(part));
100
- return invalid ? fail(`name "${value}" must be a relative path using "/" separators, without empty, "." or ".." segments`) : value;
101
- };
102
-
103
- /** Inline mapping JSON: strings verbatim, anything else pretty-printed. */
104
- export const inlineJson = (json: unknown): string =>
105
- typeof json === "string" ? json : (JSON.stringify(json, null, 2) ?? fail('"json" must be a JSON string or an object'));
106
-
107
- const parseJson = (json: string): unknown => {
108
- try {
109
- return JSON.parse(json);
110
- } catch (error) {
111
- return fail(`invalid JSON (${(error as Error).message})`);
112
- }
113
- };
114
-
115
- /** Validates a mapping file – one stub or `{ mappings: [...] }` – and returns its stub ids. */
116
- export function stubIds(json: string): string[] {
117
- const value = parseJson(json);
118
- const many = isRecord(value) && "mappings" in value;
119
- const stubs = many ? value.mappings : [value];
120
- if (!Array.isArray(stubs) || stubs.length === 0) fail('"mappings" must be a non-empty array of stub mappings');
121
- return stubs.flatMap((stub: unknown, index) => {
122
- if (!isRecord(stub) || !isRecord(stub.request) || !isRecord(stub.response)) {
123
- fail(`${many ? `mappings[${index}]` : "the mapping"} is not a WireMock stub mapping ("request" and "response" objects are required)`);
124
- }
125
- const id = stub.id ?? stub.uuid;
126
- return typeof id === "string" ? [id] : [];
127
- });
128
- }
129
-
130
- /** {@link stubIds} of a file in a mounted directory; malformed files are left for WireMock to report. */
131
- export const stubIdsOf = (path: string): string[] => {
132
- try {
133
- return path.endsWith(".json") ? stubIds(readFileSync(path, "utf8")) : [];
134
- } catch {
135
- return [];
136
- }
137
- };
138
-
139
- /** Files below `dir`, as `/`-separated relative paths. */
140
- export const listFiles = (dir: string): string[] =>
141
- readdirSync(dir, { recursive: true, withFileTypes: true })
142
- .filter((entry) => !entry.isDirectory())
143
- .map((entry) => relative(dir, join(entry.parentPath, entry.name)).split(sep).join("/"));