@amritk/helpers 0.15.4 → 0.17.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.
@@ -3,7 +3,7 @@ import { assertSchemaDepth } from "./max-schema-depth.js";
3
3
  import { readKey } from "./read-key.js";
4
4
  import { isSchemaObject } from "./schema-guards.js";
5
5
  const buildDynamicRefMap = (rootSchema) => {
6
- const map = {};
6
+ const map = /* @__PURE__ */ Object.create(null);
7
7
  if (!isSchemaObject(rootSchema))
8
8
  return map;
9
9
  const walk = (node, pointer, depth, inSchemaMap) => {
@@ -17,7 +17,7 @@ const buildDynamicRefMap = (rootSchema) => {
17
17
  }
18
18
  const record = node;
19
19
  const anchor = readKey(record, "$dynamicAnchor");
20
- if (typeof anchor === "string" && !(`#${anchor}` in map)) {
20
+ if (typeof anchor === "string" && !Object.hasOwn(map, `#${anchor}`)) {
21
21
  map[`#${anchor}`] = `#${pointer}`;
22
22
  }
23
23
  for (const key of Object.keys(record)) {
@@ -45,9 +45,8 @@ const registries = /* @__PURE__ */ new WeakMap();
45
45
  const buildResourceRegistry = (root) => {
46
46
  if (root === null || typeof root !== "object")
47
47
  return null;
48
- const memoized = registries.get(root);
49
- if (memoized !== void 0 || registries.has(root))
50
- return memoized ?? null;
48
+ if (registries.has(root))
49
+ return registries.get(root) ?? null;
51
50
  const resources = /* @__PURE__ */ new Map();
52
51
  const anchors = /* @__PURE__ */ new Map();
53
52
  const dynamicAnchors = /* @__PURE__ */ new Map();
@@ -1,12 +1,16 @@
1
1
  import { isObject } from "./is-object.js";
2
+ import { readKey } from "./read-key.js";
3
+ import { isIdentifierStart, toPascalWords } from "./ref-to-name.js";
2
4
  const titleToPascalCase = (title) => {
3
- const words = title.split(/[^a-zA-Z0-9]+/).filter(Boolean);
4
- const pascal = words.map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
5
- return pascal.replace(/^\d+/, "");
5
+ const pascal = toPascalWords(title).replace(/^\d+/, "");
6
+ if (pascal === "" || isIdentifierStart(pascal))
7
+ return pascal;
8
+ return `_${pascal}`;
6
9
  };
7
10
  const deriveRootTypeName = (schema, fallbackName) => {
8
- if (isObject(schema) && typeof schema["title"] === "string") {
9
- const fromTitle = titleToPascalCase(schema["title"]);
11
+ const title = isObject(schema) ? readKey(schema, "title") : void 0;
12
+ if (typeof title === "string") {
13
+ const fromTitle = titleToPascalCase(title);
10
14
  if (fromTitle)
11
15
  return fromTitle;
12
16
  }
@@ -5,7 +5,7 @@ export declare const escapeRegexPattern: (pattern: string) => string;
5
5
  *
6
6
  * A 2020-12 `pattern` is meant to be read as Unicode — Ajv compiles with `u` by
7
7
  * default, and so does `@amritk/runtime-validators` (`compilePattern` in
8
- * `interpreter/interpret.ts`) — and without the flag `\p{L}` is misread as a
8
+ * `interpreter/compile.ts`) — and without the flag `\p{L}` is misread as a
9
9
  * literal `p` and `^.$` rejects a single astral character. The flag is not
10
10
  * unconditional because `u` also outlaws escapes that are legal without it
11
11
  * (`\-`, a bare `\p`), and a pattern using one would turn into a syntax error in
@@ -8,52 +8,59 @@ const lineTerminatorEscapes = {
8
8
  8233: "\\u2029"
9
9
  // PARAGRAPH SEPARATOR
10
10
  };
11
+ const unicodeEscape = (code) => `\\u${code.toString(16).padStart(4, "0")}`;
11
12
  const escapeCache = /* @__PURE__ */ new Map();
12
- const flagCache = /* @__PURE__ */ new Map();
13
+ const modeCache = /* @__PURE__ */ new Map();
13
14
  const ESCAPE_CACHE_LIMIT = 1e3;
14
- const escapeRegexPattern = (pattern) => {
15
- const cached = escapeCache.get(pattern);
15
+ const evictIfFull = (cache) => {
16
+ if (cache.size >= ESCAPE_CACHE_LIMIT)
17
+ cache.delete(cache.keys().next().value);
18
+ };
19
+ const compileMode = (pattern) => {
20
+ const cached = modeCache.get(pattern);
16
21
  if (cached !== void 0)
17
22
  return cached;
23
+ let mode;
18
24
  try {
19
- new RegExp(pattern);
20
- } catch (error) {
21
- throw new Error(`Invalid regex pattern ${JSON.stringify(pattern)}: ${error instanceof Error ? error.message : String(error)}`);
22
- }
23
- const escaped = pattern.replace(/\\[\s\S]|[/\n\r\u2028\u2029]/g, (match) => {
24
- if (match === "/")
25
- return "\\/";
26
- const terminatorEscape = lineTerminatorEscapes[match.charCodeAt(0)];
27
- if (terminatorEscape !== void 0 && match.length === 1)
28
- return terminatorEscape;
29
- return match;
30
- });
31
- if (escaped === "") {
32
- escapeCache.set(pattern, "(?:)");
33
- return "(?:)";
34
- }
35
- if (escapeCache.size >= ESCAPE_CACHE_LIMIT) {
36
- escapeCache.delete(escapeCache.keys().next().value);
25
+ new RegExp(pattern, "u");
26
+ mode = "u";
27
+ } catch {
28
+ try {
29
+ new RegExp(pattern);
30
+ mode = "";
31
+ } catch {
32
+ mode = null;
33
+ }
37
34
  }
38
- escapeCache.set(pattern, escaped);
39
- return escaped;
35
+ evictIfFull(modeCache);
36
+ modeCache.set(pattern, mode);
37
+ return mode;
40
38
  };
41
- const regexFlagsFor = (pattern) => {
42
- const cached = flagCache.get(pattern);
39
+ const escapeRegexPattern = (pattern) => {
40
+ const cached = escapeCache.get(pattern);
43
41
  if (cached !== void 0)
44
42
  return cached;
45
- let flags = "";
46
- try {
47
- new RegExp(pattern, "u");
48
- flags = "u";
49
- } catch {
50
- flags = "";
43
+ if (compileMode(pattern) === null) {
44
+ try {
45
+ new RegExp(pattern, "u");
46
+ } catch (error) {
47
+ throw new Error(`Invalid regex pattern ${JSON.stringify(pattern)}: ${error instanceof Error ? error.message : String(error)}`);
48
+ }
51
49
  }
52
- if (flagCache.size >= ESCAPE_CACHE_LIMIT)
53
- flagCache.delete(flagCache.keys().next().value);
54
- flagCache.set(pattern, flags);
55
- return flags;
50
+ const escaped = pattern.replace(/\\[\s\S]|[/\n\r\u2028\u2029]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, (match) => {
51
+ if (match.length !== 1)
52
+ return match;
53
+ if (match === "/")
54
+ return "\\/";
55
+ const code = match.charCodeAt(0);
56
+ return lineTerminatorEscapes[code] ?? unicodeEscape(code);
57
+ });
58
+ const result = escaped === "" ? "(?:)" : escaped;
59
+ evictIfFull(escapeCache);
60
+ escapeCache.set(pattern, result);
61
+ return result;
56
62
  };
63
+ const regexFlagsFor = (pattern) => compileMode(pattern) ?? "";
57
64
  const regexLiteral = (pattern) => `/${escapeRegexPattern(pattern)}/${regexFlagsFor(pattern)}`;
58
65
  export {
59
66
  escapeRegexPattern,
@@ -24,8 +24,9 @@ const extractRefs = (schema) => {
24
24
  return;
25
25
  }
26
26
  const record = obj;
27
- if (!inSchemaMap && typeof readKey(record, "$ref") === "string" && isResolvableRef(record["$ref"])) {
28
- refs.add(record["$ref"]);
27
+ const ref = inSchemaMap ? void 0 : readKey(record, "$ref");
28
+ if (typeof ref === "string" && isResolvableRef(ref)) {
29
+ refs.add(ref);
29
30
  }
30
31
  for (const key of Object.keys(record)) {
31
32
  if (isDataPosition(key, inSchemaMap))
@@ -1,14 +1,16 @@
1
1
  import { assignKey } from "./assign-key.js";
2
2
  import { entersSchemaMap, isDataPosition } from "./build-resource-registry.js";
3
+ import { assertSchemaDepth } from "./max-schema-depth.js";
3
4
  const foldNullable = (schema) => {
4
- const folded = fold(schema);
5
+ const folded = fold(schema, 0);
5
6
  return folded;
6
7
  };
7
- const fold = (node, inSchemaMap = false) => {
8
+ const fold = (node, depth, inSchemaMap = false) => {
9
+ assertSchemaDepth(depth, "foldNullable");
8
10
  if (Array.isArray(node)) {
9
11
  let changed2 = false;
10
12
  const next2 = node.map((item) => {
11
- const folded = fold(item, inSchemaMap);
13
+ const folded = fold(item, depth + 1, inSchemaMap);
12
14
  if (folded !== item)
13
15
  changed2 = true;
14
16
  return folded;
@@ -25,7 +27,7 @@ const fold = (node, inSchemaMap = false) => {
25
27
  for (const key of Object.keys(record)) {
26
28
  if (isDataPosition(key, inSchemaMap))
27
29
  continue;
28
- const folded = fold(record[key], entersSchemaMap(key, inSchemaMap));
30
+ const folded = fold(record[key], depth + 1, entersSchemaMap(key, inSchemaMap));
29
31
  if (folded !== record[key])
30
32
  changed = true;
31
33
  assignKey(next, key, folded);
@@ -23,7 +23,19 @@ export type GenerateIndexBarrelOptions = {
23
23
  * Builds the `index.ts` barrel that re-exports every generated module. This is
24
24
  * the shared version of the near-identical barrel each generator used to build
25
25
  * inline: it scans each file's source for `export type` / `export const`
26
- * declarations and emits one re-export line per module, sorted by filename.
26
+ * declarations and emits re-exports per module, sorted by filename.
27
+ *
28
+ * Values are re-exported as `const` aliases (`import { parseFoo as parseFoo$0 }
29
+ * … export const parseFoo = parseFoo$0`) rather than through `export { parseFoo }
30
+ * from './foo.js'`. Under ESM the two are equivalent, but TypeScript lowers a
31
+ * re-export to CommonJS as an **accessor**
32
+ * (`Object.defineProperty(exports, 'parseFoo', { get() { … } })`), so every call
33
+ * reached through the barrel pays a getter — and a consumer importing from a
34
+ * barrel that itself barrels a subdirectory pays one per hop. The alias form
35
+ * lowers to a plain data property (`exports.parseFoo = foo_1.parseFoo`), which
36
+ * costs nothing, and stays statically analysable for tree-shaking in esbuild and
37
+ * rollup. Types keep the `export type { … } from` form: a type cannot be aliased
38
+ * through a `const`, and a type re-export emits no runtime code either way.
27
39
  *
28
40
  * Files under `_helpers/` are internal runtime helpers (embedded-mode output)
29
41
  * and are never re-exported. Modules that expose nothing are skipped.
@@ -19,32 +19,29 @@ const exportNameAt = (content, at, prefix) => {
19
19
  return end > at + prefix.length ? content.slice(at + prefix.length, end) : null;
20
20
  };
21
21
  const isLineTerminator = (code) => code === 10 || code === 13 || code === 8232 || code === 8233;
22
+ const EXPORT_KEYWORD = "export ";
22
23
  const collectExportNames = (content, typeNames, constNames) => {
23
- let lineStart = 0;
24
- while (lineStart < content.length) {
25
- if (content.charCodeAt(lineStart) === 101 && content.startsWith("export ", lineStart)) {
26
- const typeName = exportNameAt(content, lineStart, "export type ");
24
+ let at = content.indexOf(EXPORT_KEYWORD);
25
+ while (at !== -1) {
26
+ if (at === 0 || isLineTerminator(content.charCodeAt(at - 1))) {
27
+ const typeName = exportNameAt(content, at, "export type ");
27
28
  if (typeName !== null) {
28
29
  typeNames.push(typeName);
29
30
  } else {
30
- const constName = exportNameAt(content, lineStart, "export const ");
31
+ const constName = exportNameAt(content, at, "export const ");
31
32
  if (constName !== null)
32
33
  constNames.push(constName);
33
34
  }
34
35
  }
35
- let next = lineStart;
36
- while (next < content.length && !isLineTerminator(content.charCodeAt(next)))
37
- next++;
38
- if (next >= content.length)
39
- break;
40
- lineStart = content.charCodeAt(next) === 13 && content.charCodeAt(next + 1) === 10 ? next + 2 : next + 1;
36
+ at = content.indexOf(EXPORT_KEYWORD, at + EXPORT_KEYWORD.length);
41
37
  }
42
38
  };
43
39
  const generateIndexBarrel = (files, options = {}) => {
44
40
  const typesOnly = options.typesOnly ?? false;
45
41
  const importExt = options.importExt ?? "js";
46
42
  const sortedFiles = files.filter((file) => !file.filename.startsWith("_helpers/")).sort((a, b) => a.filename.localeCompare(b.filename));
47
- let indexContent = "";
43
+ const modules = [];
44
+ const declaredNames = /* @__PURE__ */ new Set();
48
45
  for (const file of sortedFiles) {
49
46
  const moduleName = file.filename.replace(/\.ts$/, "");
50
47
  const typeNames = [];
@@ -52,16 +49,41 @@ const generateIndexBarrel = (files, options = {}) => {
52
49
  collectExportNames(file.content, typeNames, constNames);
53
50
  if (typeNames.length === 0 && constNames.length === 0)
54
51
  continue;
55
- if (typesOnly) {
56
- indexContent += `export type { ${typeNames.join(", ")} } from './${moduleName}.${importExt}';
57
- `;
58
- } else {
59
- const typeExports = typeNames.map((name) => `type ${name}`);
60
- indexContent += `export { ${[...typeExports, ...constNames].join(", ")} } from './${moduleName}.${importExt}';
52
+ modules.push({ specifier: `./${moduleName}.${importExt}`, typeNames, constNames });
53
+ for (const name of constNames)
54
+ declaredNames.add(name);
55
+ }
56
+ if (typesOnly) {
57
+ let indexContent = "";
58
+ for (const { specifier, typeNames } of modules) {
59
+ indexContent += `export type { ${typeNames.join(", ")} } from '${specifier}';
61
60
  `;
62
61
  }
62
+ return indexContent;
63
63
  }
64
- return indexContent;
64
+ const importLines = [];
65
+ const typeLines = [];
66
+ const valueLines = [];
67
+ modules.forEach(({ specifier, typeNames, constNames }, index) => {
68
+ if (typeNames.length > 0) {
69
+ typeLines.push(`export type { ${typeNames.join(", ")} } from '${specifier}';`);
70
+ }
71
+ if (constNames.length === 0)
72
+ return;
73
+ const aliases = constNames.map((name) => {
74
+ let alias = `${name}$${index}`;
75
+ while (declaredNames.has(alias))
76
+ alias += "$";
77
+ declaredNames.add(alias);
78
+ return alias;
79
+ });
80
+ importLines.push(`import { ${constNames.map((name, i) => `${name} as ${aliases[i]}`).join(", ")} } from '${specifier}';`);
81
+ for (const [i, name] of constNames.entries())
82
+ valueLines.push(`export const ${name} = ${aliases[i]};`);
83
+ });
84
+ const sections = [importLines, typeLines, valueLines].filter((section) => section.length > 0);
85
+ return sections.map((section) => `${section.join("\n")}
86
+ `).join("\n");
65
87
  };
66
88
  export {
67
89
  generateIndexBarrel