@amritk/helpers 0.13.2 → 0.13.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/dist/has-ref.js CHANGED
@@ -1,8 +1,6 @@
1
- /** Type guard to check if a value is a non-null, non-array object with a string $ref property */
2
- export const hasRef = (value) => {
3
- return (typeof value === 'object' &&
4
- value !== null &&
5
- !Array.isArray(value) &&
6
- '$ref' in value &&
7
- typeof value.$ref === 'string');
1
+ const hasRef = (value) => {
2
+ return typeof value === "object" && value !== null && !Array.isArray(value) && "$ref" in value && typeof value.$ref === "string";
3
+ };
4
+ export {
5
+ hasRef
8
6
  };
package/dist/is-object.js CHANGED
@@ -1,14 +1,4 @@
1
- /**
2
- * Returns true if the provided value is a plain object.
3
- * Optimized for JSON data validation: checks that value is truthy, typeof object,
4
- * and not an array. This correctly handles all JSON value types.
5
- *
6
- * Examples:
7
- * isObject({}) // true
8
- * isObject({ a: 1 }) // true
9
- * isObject([]) // false (Array)
10
- * isObject(null) // false
11
- * isObject(123) // false
12
- * isObject('string') // false
13
- */
14
- export const isObject = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
1
+ const isObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
2
+ export {
3
+ isObject
4
+ };
@@ -1,51 +1,32 @@
1
- import { isSchemaObject } from './schema-guards.js';
2
- /**
3
- * Vendor extension keyword carrying mjst-specific runtime hints that plain JSON
4
- * Schema cannot express on its own. Adapters (TypeBox, Zod, ...) emit it when a
5
- * source construct has no native JSON Schema equivalent, and the generators read
6
- * it to produce the right TypeScript type and runtime checks.
7
- */
8
- export const MJST_EXTENSION_KEY = 'x-mjst';
9
- // Only identifier-safe class names are honoured, so a malicious or malformed
10
- // schema cannot inject arbitrary code into the generated output.
1
+ import { isSchemaObject } from "./schema-guards.js";
2
+ const MJST_EXTENSION_KEY = "x-mjst";
11
3
  const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
12
- // The non-JSON primitives we know how to generate type/runtime handling for.
13
- // Anything outside this set is ignored so unknown hints degrade gracefully.
14
- const SUPPORTED_PRIMITIVES = new Set(['bigint']);
15
- // Brand names are embedded inside a single-quoted string literal in generated
16
- // output, so we only allow characters that cannot break out of the literal.
4
+ const SUPPORTED_PRIMITIVES = /* @__PURE__ */ new Set(["bigint"]);
17
5
  const SAFE_BRAND = /^[\w$ -]+$/;
18
6
  const readExtensionString = (schema, field) => {
19
- if (!isSchemaObject(schema))
20
- return undefined;
21
- const extension = schema[MJST_EXTENSION_KEY];
22
- if (typeof extension !== 'object' || extension === null)
23
- return undefined;
24
- const value = extension[field];
25
- return typeof value === 'string' ? value : undefined;
7
+ if (!isSchemaObject(schema))
8
+ return void 0;
9
+ const extension = schema[MJST_EXTENSION_KEY];
10
+ if (typeof extension !== "object" || extension === null)
11
+ return void 0;
12
+ const value = extension[field];
13
+ return typeof value === "string" ? value : void 0;
26
14
  };
27
- /**
28
- * Reads the `instanceOf` class name from a schema's `x-mjst` extension, when it
29
- * is present and a safe identifier. Returns undefined otherwise so callers fall
30
- * back to ordinary type handling.
31
- */
32
- export const getMjstInstanceOf = (schema) => {
33
- const instanceOf = readExtensionString(schema, 'instanceOf');
34
- return instanceOf !== undefined && IDENTIFIER.test(instanceOf) ? instanceOf : undefined;
15
+ const getMjstInstanceOf = (schema) => {
16
+ const instanceOf = readExtensionString(schema, "instanceOf");
17
+ return instanceOf !== void 0 && IDENTIFIER.test(instanceOf) ? instanceOf : void 0;
35
18
  };
36
- /**
37
- * Reads the `primitive` type name from a schema's `x-mjst` extension, when it is
38
- * one we support (e.g. `'bigint'`). Returns undefined otherwise.
39
- */
40
- export const getMjstPrimitive = (schema) => {
41
- const primitive = readExtensionString(schema, 'primitive');
42
- return primitive !== undefined && SUPPORTED_PRIMITIVES.has(primitive) ? primitive : undefined;
19
+ const getMjstPrimitive = (schema) => {
20
+ const primitive = readExtensionString(schema, "primitive");
21
+ return primitive !== void 0 && SUPPORTED_PRIMITIVES.has(primitive) ? primitive : void 0;
43
22
  };
44
- /**
45
- * Reads the nominal `brand` name from a schema's `x-mjst` extension, when it is
46
- * present and safe to embed in generated output. Returns undefined otherwise.
47
- */
48
- export const getMjstBrand = (schema) => {
49
- const brand = readExtensionString(schema, 'brand');
50
- return brand !== undefined && SAFE_BRAND.test(brand) ? brand : undefined;
23
+ const getMjstBrand = (schema) => {
24
+ const brand = readExtensionString(schema, "brand");
25
+ return brand !== void 0 && SAFE_BRAND.test(brand) ? brand : void 0;
26
+ };
27
+ export {
28
+ MJST_EXTENSION_KEY,
29
+ getMjstBrand,
30
+ getMjstInstanceOf,
31
+ getMjstPrimitive
51
32
  };
@@ -1,30 +1,16 @@
1
- /**
2
- * Emits code for a JSON Schema `multipleOf` check that agrees with the runtime
3
- * interpreter (`packages/runtime-validators/src/interpreter/interpret.ts`).
4
- *
5
- * The naive `x % m === 0` is float-wrong: IEEE-754 makes `0.3 % 0.1` evaluate to
6
- * `0.0999…`, so `0.3` would spuriously fail `multipleOf: 0.1`. The interpreter
7
- * instead divides and compares the quotient to its nearest integer within a
8
- * tolerance that *scales with the quotient's magnitude* — a fixed epsilon falsely
9
- * rejects large values (e.g. `1234567.89` against `multipleOf: 0.01`) whose
10
- * representation error in the quotient already exceeds it. Keeping the emitted
11
- * check identical to the interpreter's keeps generated validators/parsers and the
12
- * interpreter from disagreeing on the same document.
13
- *
14
- * `valueExpr` is inlined three times, so it must be a side-effect-free expression
15
- * (a property read or a cached variable — which is all the generators ever pass).
16
- */
17
1
  const quotientTolerance = (valueExpr, divisor) => {
18
- const q = `${valueExpr} / ${divisor}`;
19
- return { q, tol: `1e-8 * Math.max(1, Math.abs(${q}))` };
2
+ const q = `${valueExpr} / ${divisor}`;
3
+ return { q, tol: `1e-8 * Math.max(1, Math.abs(${q}))` };
20
4
  };
21
- /** Boolean expression that is TRUE when `valueExpr` is a valid multiple of `divisor`. */
22
- export const multipleOfPassExpr = (valueExpr, divisor) => {
23
- const { q, tol } = quotientTolerance(valueExpr, divisor);
24
- return `Math.abs(${q} - Math.round(${q})) <= ${tol}`;
5
+ const multipleOfPassExpr = (valueExpr, divisor) => {
6
+ const { q, tol } = quotientTolerance(valueExpr, divisor);
7
+ return `Math.abs(${q} - Math.round(${q})) <= ${tol}`;
25
8
  };
26
- /** Boolean expression that is TRUE when `valueExpr` is NOT a multiple of `divisor` (the error condition). */
27
- export const multipleOfFailExpr = (valueExpr, divisor) => {
28
- const { q, tol } = quotientTolerance(valueExpr, divisor);
29
- return `Math.abs(${q} - Math.round(${q})) > ${tol}`;
9
+ const multipleOfFailExpr = (valueExpr, divisor) => {
10
+ const { q, tol } = quotientTolerance(valueExpr, divisor);
11
+ return `Math.abs(${q} - Math.round(${q})) > ${tol}`;
12
+ };
13
+ export {
14
+ multipleOfFailExpr,
15
+ multipleOfPassExpr
30
16
  };
@@ -1,136 +1,94 @@
1
- /**
2
- * Fetches and parses OpenAPI specification documentation from the markdown source.
3
- *
4
- * When a section has no Fixed Fields table (e.g. Header Object delegates to Parameter Object),
5
- * pass `fallbackCommentUrl` to inherit property documentation from another section.
6
- */
7
- export const parseDocumentation = (markdownDocumentation, commentUrl, fallbackCommentUrl) => {
8
- try {
9
- const markdown = markdownDocumentation;
10
- // Extract the fragment ID from the URL (e.g., #info-object)
11
- const fragmentId = commentUrl.split('#')[1];
12
- if (!fragmentId) {
13
- return null;
14
- }
15
- // Extract the base URL (everything before the #)
16
- const baseUrl = commentUrl.split('#')[0];
17
- // Convert fragment ID to title case (e.g., "info-object" -> "Info Object")
18
- const titleWords = fragmentId.split('-');
19
- let sectionTitle = '';
20
- for (let i = 0; i < titleWords.length; i++) {
21
- if (i > 0)
22
- sectionTitle += ' ';
23
- const word = titleWords[i] ?? '';
24
- sectionTitle += word.charAt(0).toUpperCase() + word.slice(1);
25
- }
26
- // Detect the heading level used for object sections in this markdown file.
27
- // OAS 3.1 uses #### while OAS 3.2 uses ###, so we probe for both.
28
- const headingLevelMatch = markdown.match(/^(#{2,5})\s+\S.*Object\s*$/m);
29
- const headingHashes = headingLevelMatch?.[1] ?? '####';
30
- const subHeadingHashes = headingHashes + '#';
31
- // Find the section in the markdown
32
- // Match the section heading and capture everything until the next same-level heading or end of file.
33
- // `sectionTitle` comes from the URL fragment, so escape any regex metacharacters
34
- // before interpolating — otherwise a fragment containing `+`, `(`, etc. throws a
35
- // SyntaxError that the outer catch then mislabels as a fetch failure.
36
- const escapedHashes = headingHashes.replace(/#/g, '\\#');
37
- const escapedTitle = sectionTitle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
38
- const sectionRegex = new RegExp(`${escapedHashes}\\s+${escapedTitle}\\s*\\n([\\s\\S]*?)(?=\\n${escapedHashes}\\s|$)`, 'i');
39
- const sectionMatch = markdown.match(sectionRegex);
40
- if (!sectionMatch) {
41
- return null;
1
+ const parseDocumentation = (markdownDocumentation, commentUrl, fallbackCommentUrl) => {
2
+ try {
3
+ const markdown = markdownDocumentation;
4
+ const fragmentId = commentUrl.split("#")[1];
5
+ if (!fragmentId) {
6
+ return null;
7
+ }
8
+ const baseUrl = commentUrl.split("#")[0];
9
+ const titleWords = fragmentId.split("-");
10
+ let sectionTitle = "";
11
+ for (let i = 0; i < titleWords.length; i++) {
12
+ if (i > 0)
13
+ sectionTitle += " ";
14
+ const word = titleWords[i] ?? "";
15
+ sectionTitle += word.charAt(0).toUpperCase() + word.slice(1);
16
+ }
17
+ const headingLevelMatch = markdown.match(/^(#{2,5})\s+\S.*Object\s*$/m);
18
+ const headingHashes = headingLevelMatch?.[1] ?? "####";
19
+ const subHeadingHashes = headingHashes + "#";
20
+ const escapedHashes = headingHashes.replace(/#/g, "\\#");
21
+ const escapedTitle = sectionTitle.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
22
+ const sectionRegex = new RegExp(`${escapedHashes}\\s+${escapedTitle}\\s*\\n([\\s\\S]*?)(?=\\n${escapedHashes}\\s|$)`, "i");
23
+ const sectionMatch = markdown.match(sectionRegex);
24
+ if (!sectionMatch) {
25
+ return null;
26
+ }
27
+ const sectionContent = sectionMatch?.[1];
28
+ if (!sectionContent) {
29
+ return null;
30
+ }
31
+ const escapedSubHashes = subHeadingHashes.replace(/#/g, "\\#");
32
+ const descriptionMatch = sectionContent.match(new RegExp(`^([\\s\\S]*?)(?=\\n?${escapedSubHashes}|$)`));
33
+ const description = descriptionMatch?.[1]?.trim().replace(/\n/g, " ") || "";
34
+ const fixedFieldsRegex = new RegExp(`${escapedSubHashes} Fixed Fields\\s*\\n([\\s\\S]*)`);
35
+ const fixedFieldsMatch = sectionContent.match(fixedFieldsRegex);
36
+ const properties = {};
37
+ if (fixedFieldsMatch?.[1]) {
38
+ const fixedFieldsContent = fixedFieldsMatch[1];
39
+ const lines = fixedFieldsContent.split("\n");
40
+ let inTable = false;
41
+ for (const line of lines) {
42
+ if (line.includes("Field Name") || line.includes("---|")) {
43
+ inTable = true;
44
+ continue;
42
45
  }
43
- const sectionContent = sectionMatch?.[1];
44
- if (!sectionContent) {
45
- return null;
46
+ if (line.startsWith("#")) {
47
+ inTable = false;
48
+ continue;
46
49
  }
47
- // Extract the description (paragraphs before the "Fixed Fields" sub-heading)
48
- // \n? handles the case where sectionContent starts directly with the sub-heading (no leading newline),
49
- // which happens when the section heading is followed by a blank line consumed by \s* in sectionRegex.
50
- const escapedSubHashes = subHeadingHashes.replace(/#/g, '\\#');
51
- const descriptionMatch = sectionContent.match(new RegExp(`^([\\s\\S]*?)(?=\\n?${escapedSubHashes}|$)`));
52
- const description = descriptionMatch?.[1]?.trim().replace(/\n/g, ' ') || '';
53
- // Extract all Fixed Fields tables within the section (some objects like Encoding Object
54
- // split their fields across multiple sub-tables under different sub-sub-headings).
55
- // Capture everything from the first "Fixed Fields" sub-heading to the end of the section —
56
- // the section content is already bounded by the outer section regex so we don't need
57
- // a stop condition here.
58
- const fixedFieldsRegex = new RegExp(`${escapedSubHashes} Fixed Fields\\s*\\n([\\s\\S]*)`);
59
- const fixedFieldsMatch = sectionContent.match(fixedFieldsRegex);
60
- const properties = {};
61
- if (fixedFieldsMatch?.[1]) {
62
- const fixedFieldsContent = fixedFieldsMatch[1];
63
- // Parse all markdown table rows across all sub-tables within the Fixed Fields section
64
- const lines = fixedFieldsContent.split('\n');
65
- let inTable = false;
66
- for (const line of lines) {
67
- // Skip the header row and separator row
68
- if (line.includes('Field Name') || line.includes('---|')) {
69
- inTable = true;
70
- continue;
71
- }
72
- // A ###### sub-heading resets inTable so we re-enter on the next header row
73
- if (line.startsWith('#')) {
74
- inTable = false;
75
- continue;
76
- }
77
- if (!inTable || !line.trim() || !line.includes('|')) {
78
- continue;
79
- }
80
- // Parse table row: | fieldName | type | description |
81
- // First, replace escaped pipes (\|) with a placeholder to avoid splitting on them
82
- const lineWithPlaceholder = line.replace(/\\\|/g, '___PIPE___');
83
- const cells = lineWithPlaceholder
84
- .split('|')
85
- .map((cell) => cell.replace(/___PIPE___/g, '|').trim())
86
- .filter((cell) => cell);
87
- if (cells.length >= 3) {
88
- const fieldName = cells[0]?.replace(/<[^>]*>/g, '').trim(); // Remove HTML tags
89
- // Some OpenAPI tables include an "Applies To" column before Description.
90
- // We always want the right-most column as the property description.
91
- const descriptionCellIndex = cells.length >= 4 ? 3 : 2;
92
- let fieldDescription = cells[descriptionCellIndex]?.trim() || '';
93
- const isRequired = fieldDescription.includes('REQUIRED');
94
- // Replace relative anchor links with full URLs using the base URL
95
- fieldDescription = fieldDescription.replace(/\(#([^)]+)\)/g, `(${baseUrl}#$1)`);
96
- // Only accept field names that look like valid identifiers (camelCase or plain words).
97
- // This filters out rows from non-field tables (e.g. type/contentType default tables)
98
- // where the "field name" column contains type annotations like `string` or [_absent_].
99
- const isValidFieldName = fieldName &&
100
- !fieldName.includes('Field Name') &&
101
- !fieldName.startsWith('`') &&
102
- !fieldName.startsWith('[') &&
103
- /^[a-zA-Z]/.test(fieldName);
104
- if (isValidFieldName) {
105
- properties[fieldName] = {
106
- description: fieldDescription,
107
- isRequired,
108
- };
109
- }
110
- }
111
- }
50
+ if (!inTable || !line.trim() || !line.includes("|")) {
51
+ continue;
112
52
  }
113
- // Format title as "Info object" instead of "Info Object"
114
- const title = sectionTitle.replace(/\sObject$/, ' object');
115
- // If no properties were found and a fallback URL is provided, inherit properties from it
116
- if (Object.keys(properties).length === 0 && fallbackCommentUrl) {
117
- const fallback = parseDocumentation(markdownDocumentation, fallbackCommentUrl);
118
- if (fallback && Object.keys(fallback.properties).length > 0) {
119
- return {
120
- title,
121
- description,
122
- properties: fallback.properties,
123
- };
124
- }
53
+ const lineWithPlaceholder = line.replace(/\\\|/g, "___PIPE___");
54
+ const cells = lineWithPlaceholder.split("|").map((cell) => cell.replace(/___PIPE___/g, "|").trim()).filter((cell) => cell);
55
+ if (cells.length >= 3) {
56
+ const fieldName = cells[0]?.replace(/<[^>]*>/g, "").trim();
57
+ const descriptionCellIndex = cells.length >= 4 ? 3 : 2;
58
+ let fieldDescription = cells[descriptionCellIndex]?.trim() || "";
59
+ const isRequired = fieldDescription.includes("REQUIRED");
60
+ fieldDescription = fieldDescription.replace(/\(#([^)]+)\)/g, `(${baseUrl}#$1)`);
61
+ const isValidFieldName = fieldName && !fieldName.includes("Field Name") && !fieldName.startsWith("`") && !fieldName.startsWith("[") && /^[a-zA-Z]/.test(fieldName);
62
+ if (isValidFieldName) {
63
+ properties[fieldName] = {
64
+ description: fieldDescription,
65
+ isRequired
66
+ };
67
+ }
125
68
  }
69
+ }
70
+ }
71
+ const title = sectionTitle.replace(/\sObject$/, " object");
72
+ if (Object.keys(properties).length === 0 && fallbackCommentUrl) {
73
+ const fallback = parseDocumentation(markdownDocumentation, fallbackCommentUrl);
74
+ if (fallback && Object.keys(fallback.properties).length > 0) {
126
75
  return {
127
- title,
128
- description,
129
- properties,
76
+ title,
77
+ description,
78
+ properties: fallback.properties
130
79
  };
80
+ }
131
81
  }
132
- catch (error) {
133
- console.error('Failed to fetch OpenAPI documentation:', error);
134
- return null;
135
- }
82
+ return {
83
+ title,
84
+ description,
85
+ properties
86
+ };
87
+ } catch (error) {
88
+ console.error("Failed to fetch OpenAPI documentation:", error);
89
+ return null;
90
+ }
91
+ };
92
+ export {
93
+ parseDocumentation
136
94
  };
@@ -1,19 +1,5 @@
1
- // Characters that force the JSON.stringify escaping path below: quote,
2
- // backslash, C0 controls, and the JS line separators. Anything else sits
3
- // verbatim inside a double-quoted literal.
4
- // biome-ignore lint/suspicious/noControlCharactersInRegex: the C0 range is exactly the set that must never appear raw in a generated string literal
5
1
  const NEEDS_ESCAPING = /["\\\u0000-\u001f\u2028\u2029]/;
6
- /**
7
- * Emits `text` as a double-quoted JS string literal for generated code.
8
- *
9
- * This is the one escape-or-quote decision for schema-controlled text
10
- * (property names, patterns, enum values) embedded in generated source — a key
11
- * like `it's` or a pattern with a quote or newline must never break out of the
12
- * literal or inject code, so anything carrying such a character goes through
13
- * `JSON.stringify`. The common all-plain string skips the full escaper: code
14
- * generators emit one literal per assertion/message, and the stringify calls
15
- * were a measurable slice of generation time. Centralized so the next
16
- * generator wanting the fast path cannot get the security-sensitive regex
17
- * subtly wrong.
18
- */
19
- export const quoteJsString = (text) => (NEEDS_ESCAPING.test(text) ? JSON.stringify(text) : `"${text}"`);
2
+ const quoteJsString = (text) => NEEDS_ESCAPING.test(text) ? JSON.stringify(text) : `"${text}"`;
3
+ export {
4
+ quoteJsString
5
+ };
@@ -1,108 +1,43 @@
1
- /**
2
- * Converts a PascalCase or camelCase string to kebab-case.
3
- * Handles consecutive uppercase sequences (e.g. "APIKey" → "api-key") and
4
- * known mixed-case acronyms like "OAuth" that would otherwise split incorrectly.
5
- *
6
- * @example
7
- * ```ts
8
- * toKebabCase('ServerVariable') // 'server-variable'
9
- * toKebabCase('APIKeySecurityScheme') // 'api-key-security-scheme'
10
- * toKebabCase('OAuthFlows') // 'oauth-flows'
11
- * toKebabCase('already-kebab') // 'already-kebab'
12
- * ```
13
- */
14
- export const toKebabCase = (value) => value
15
- // Collapse known mixed-case acronyms before splitting so they stay together
16
- .replace(/OAuth/g, 'Oauth')
17
- .replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
18
- .replace(/([a-z\d])([A-Z])/g, '$1-$2')
19
- .toLowerCase();
20
- /**
21
- * Derives a unique kebab-case filename from a URI ref.
22
- *
23
- * For a plain URI (no fragment), uses the path segments after the host,
24
- * stripping version numbers, `.json` extension, and joining with `-`.
25
- * For a URI with a fragment, appends the fragment's last path segment.
26
- *
27
- * @example
28
- * ```ts
29
- * uriRefToFilename('http://asyncapi.com/definitions/3.1.0/channel.json')
30
- * // 'channel'
31
- * uriRefToFilename('http://asyncapi.com/bindings/kafka/0.5.0/channel.json')
32
- * // 'kafka-channel-binding'
33
- * uriRefToFilename('http://asyncapi.com/bindings/sns/0.1.0/channel.json#/definitions/queue')
34
- * // 'sns-channel-queue'
35
- * ```
36
- */
1
+ const toKebabCase = (value) => value.replace(/OAuth/g, "Oauth").replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2").replace(/([a-z\d])([A-Z])/g, "$1-$2").toLowerCase();
37
2
  const uriRefToFilename = (uri) => {
38
- const hashIndex = uri.indexOf('#');
39
- const baseUri = hashIndex === -1 ? uri : uri.slice(0, hashIndex);
40
- const fragment = hashIndex === -1 ? '' : uri.slice(hashIndex + 1);
41
- // Strip protocol + host, remove .json extension
42
- const withoutProtocol = baseUri.replace(/^https?:\/\/[^/]+\//, '');
43
- const withoutExt = withoutProtocol.replace(/\.json$/, '');
44
- // Drop structural/noise segments:
45
- // - "definitions" and "$defs" container keys
46
- // - Version numbers that immediately follow "definitions" (e.g. "3.1.0" in "definitions/3.1.0/channel")
47
- // but NOT version numbers in other positions (e.g. "0.5.0" in "bindings/kafka/0.5.0/channel")
48
- // since those are needed to disambiguate multiple versions of the same binding
49
- const rawSegments = withoutExt.split('/');
50
- const SKIP_KEYS = new Set(['definitions', '$defs']);
51
- const segments = [];
52
- for (let i = 0; i < rawSegments.length; i++) {
53
- const s = rawSegments[i];
54
- if (SKIP_KEYS.has(s))
55
- continue;
56
- // Skip a version segment only if the previous (non-skipped) segment was "definitions"
57
- const prevRaw = rawSegments[i - 1];
58
- if (/^\d+\.\d+/.test(s) && prevRaw !== undefined && SKIP_KEYS.has(prevRaw))
59
- continue;
60
- segments.push(s);
61
- }
62
- // Join remaining segments, converting to kebab-case and replacing dots with dashes
63
- const baseName = segments.map((s) => toKebabCase(s).replace(/\./g, '-')).join('-');
64
- if (!fragment)
65
- return baseName;
66
- // Append the last meaningful segment of the fragment, skipping structural keys
67
- const fragSegments = fragment.split('/').filter((s) => s && !SKIP_KEYS.has(s) && s !== 'properties');
68
- const fragLast = fragSegments[fragSegments.length - 1];
69
- if (!fragLast)
70
- return baseName;
71
- return `${baseName}-${toKebabCase(fragLast)}`;
3
+ const hashIndex = uri.indexOf("#");
4
+ const baseUri = hashIndex === -1 ? uri : uri.slice(0, hashIndex);
5
+ const fragment = hashIndex === -1 ? "" : uri.slice(hashIndex + 1);
6
+ const withoutProtocol = baseUri.replace(/^https?:\/\/[^/]+\//, "");
7
+ const withoutExt = withoutProtocol.replace(/\.json$/, "");
8
+ const rawSegments = withoutExt.split("/");
9
+ const SKIP_KEYS = /* @__PURE__ */ new Set(["definitions", "$defs"]);
10
+ const segments = [];
11
+ for (let i = 0; i < rawSegments.length; i++) {
12
+ const s = rawSegments[i];
13
+ if (SKIP_KEYS.has(s))
14
+ continue;
15
+ const prevRaw = rawSegments[i - 1];
16
+ if (/^\d+\.\d+/.test(s) && prevRaw !== void 0 && SKIP_KEYS.has(prevRaw))
17
+ continue;
18
+ segments.push(s);
19
+ }
20
+ const baseName = segments.map((s) => toKebabCase(s).replace(/\./g, "-")).join("-");
21
+ if (!fragment)
22
+ return baseName;
23
+ const fragSegments = fragment.split("/").filter((s) => s && !SKIP_KEYS.has(s) && s !== "properties");
24
+ const fragLast = fragSegments[fragSegments.length - 1];
25
+ if (!fragLast)
26
+ return baseName;
27
+ return `${baseName}-${toKebabCase(fragLast)}`;
72
28
  };
73
- /**
74
- * Converts a JSON Schema $ref to a filename.
75
- *
76
- * Handles three ref forms:
77
- * - Internal `#/$defs/contact` → `contact`
78
- * - Internal `#/definitions/ServerVariable` → `server-variable`
79
- * - URI `http://example.com/definitions/3.1.0/channel.json` → `channel`
80
- * - URI with fragment `http://example.com/channel.json#/definitions/queue` → `channel-queue`
81
- *
82
- * @param ref - The $ref string
83
- * @returns The filename without extension
84
- *
85
- * @example
86
- * ```ts
87
- * refToFilename('#/$defs/contact') // 'contact'
88
- * refToFilename('#/$defs/server-variable') // 'server-variable'
89
- * refToFilename('#/definitions/ServerVariable') // 'server-variable'
90
- * refToFilename('#/definitions/APIKeySecurityScheme') // 'api-key-security-scheme'
91
- * refToFilename('http://asyncapi.com/definitions/3.1.0/channel.json') // 'channel'
92
- * ```
93
- */
94
- export const refToFilename = (ref) => {
95
- // URI ref — derive name from URI path
96
- if (ref.startsWith('http://') || ref.startsWith('https://')) {
97
- return uriRefToFilename(ref);
98
- }
99
- // Internal ref — extract the last segment after the last /
100
- const segments = ref.split('/');
101
- // Non-null assertion is safe here: split always returns at least one element
102
- let filename = segments[segments.length - 1];
103
- // Normalise PascalCase/camelCase keys (e.g. from draft-07 "definitions") to kebab-case
104
- if (/[A-Z]/.test(filename)) {
105
- filename = toKebabCase(filename);
106
- }
107
- return filename;
29
+ const refToFilename = (ref) => {
30
+ if (ref.startsWith("http://") || ref.startsWith("https://")) {
31
+ return uriRefToFilename(ref);
32
+ }
33
+ const segments = ref.split("/");
34
+ let filename = segments[segments.length - 1];
35
+ if (/[A-Z]/.test(filename)) {
36
+ filename = toKebabCase(filename);
37
+ }
38
+ return filename;
39
+ };
40
+ export {
41
+ refToFilename,
42
+ toKebabCase
108
43
  };
@@ -1,55 +1,19 @@
1
- import { refToFilename } from './ref-to-filename.js';
2
- /**
3
- * Converts a filename-like string to a PascalCase TypeScript identifier,
4
- * appending an optional suffix.
5
- *
6
- * Word boundaries are *any* run of characters that cannot appear in a JS
7
- * identifier — not just `-` — so a dotted key like `io.k8s.api.core.v1.Pod`
8
- * becomes `IoK8sApiCoreV1Pod` instead of the invalid `Io.k8s.api.core.v1.pod`.
9
- * A leading digit is prefixed with `_`, and an otherwise-empty result falls back
10
- * to `_`, so the output is always a usable identifier.
11
- *
12
- * @example
13
- * ```ts
14
- * kebabToPascal('server-variable') // 'ServerVariable'
15
- * kebabToPascal('channel') // 'Channel'
16
- * kebabToPascal('channel', 'Object') // 'ChannelObject'
17
- * kebabToPascal('io.k8s.api.core.v1.pod') // 'IoK8sApiCoreV1Pod'
18
- * kebabToPascal('123abc') // '_123abc'
19
- * ```
20
- */
1
+ import { refToFilename } from "./ref-to-filename.js";
21
2
  const kebabToPascal = (kebab, suffix) => {
22
- const words = kebab.split(/[^A-Za-z0-9]+/);
23
- let pascalCase = '';
24
- for (const word of words) {
25
- if (word === '')
26
- continue;
27
- pascalCase += word.charAt(0).toUpperCase() + word.slice(1);
28
- }
29
- if (pascalCase === '')
30
- pascalCase = '_';
31
- else if (/^[0-9]/.test(pascalCase))
32
- pascalCase = `_${pascalCase}`;
33
- return pascalCase + suffix;
3
+ const words = kebab.split(/[^A-Za-z0-9]+/);
4
+ let pascalCase = "";
5
+ for (const word of words) {
6
+ if (word === "")
7
+ continue;
8
+ pascalCase += word.charAt(0).toUpperCase() + word.slice(1);
9
+ }
10
+ if (pascalCase === "")
11
+ pascalCase = "_";
12
+ else if (/^[0-9]/.test(pascalCase))
13
+ pascalCase = `_${pascalCase}`;
14
+ return pascalCase + suffix;
15
+ };
16
+ const refToName = (ref, suffix = "") => kebabToPascal(refToFilename(ref), suffix);
17
+ export {
18
+ refToName
34
19
  };
35
- /**
36
- * Converts a JSON Schema $ref to a type name.
37
- * Derives the filename via `refToFilename` then converts to PascalCase,
38
- * appending an optional suffix.
39
- *
40
- * Handles all ref forms: internal `#/$defs/...`, `#/definitions/...`, and URI refs.
41
- *
42
- * @param ref - The $ref string
43
- * @param suffix - Optional suffix appended to the PascalCase name. Defaults to
44
- * `''` (no suffix). Pass e.g. `'Object'` to get `ContactObject`.
45
- * @returns The type name in PascalCase with the suffix applied
46
- *
47
- * @example
48
- * ```ts
49
- * refToName('#/$defs/contact') // 'Contact'
50
- * refToName('#/$defs/server-variable') // 'ServerVariable'
51
- * refToName('#/$defs/contact', 'Object') // 'ContactObject'
52
- * refToName('http://asyncapi.com/definitions/3.1.0/channel.json') // 'Channel'
53
- * ```
54
- */
55
- export const refToName = (ref, suffix = '') => kebabToPascal(refToFilename(ref), suffix);