@amritk/helpers 0.19.0 → 0.21.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.
@@ -19,11 +19,18 @@ export declare const MJST_EXTENSION_KEY = "x-mjst";
19
19
  * runtime value still validates as its underlying JSON Schema type, but the
20
20
  * generated TypeScript type is intersected with a unique brand so values are
21
21
  * not interchangeable with the unbranded base type.
22
+ * - `discriminator` names the property that says *which message* a frame is.
23
+ * Unlike the three above it is not read off a schema: it belongs on an
24
+ * AsyncAPI channel, whose messages become one `@amritk/api` message contract
25
+ * and therefore need one tag property between them. A document that spells
26
+ * its tag `event` rather than `type` says so once, on the channel, instead of
27
+ * the generator's caller having to remember per run.
22
28
  */
23
29
  export type MjstExtension = {
24
30
  readonly instanceOf?: string;
25
31
  readonly primitive?: string;
26
32
  readonly brand?: string;
33
+ readonly discriminator?: string;
27
34
  };
28
35
  /**
29
36
  * Reads the `instanceOf` class name from a schema's `x-mjst` extension, when it
@@ -43,3 +50,12 @@ export declare const getMjstPrimitive: (schema: JSONSchema) => string | undefine
43
50
  * present and safe to embed in generated output. Returns undefined otherwise.
44
51
  */
45
52
  export declare const getMjstBrand: (schema: JSONSchema) => string | undefined;
53
+ /**
54
+ * Reads the message `discriminator` property name from a node's `x-mjst`
55
+ * extension — an AsyncAPI channel, in practice, rather than a schema.
56
+ *
57
+ * A name we could not safely emit (see {@link SAFE_DISCRIMINATOR}) is warned
58
+ * about once and ignored, so the caller falls back to its own default rather
59
+ * than writing a broken literal into generated code.
60
+ */
61
+ export declare const getMjstDiscriminator: (node: unknown) => string | undefined;
@@ -5,10 +5,12 @@ const SUPPORTED_INSTANCE_CLASSES = /* @__PURE__ */ new Set(["Date"]);
5
5
  const SUPPORTED_PRIMITIVES = /* @__PURE__ */ new Set(["bigint"]);
6
6
  const warnedInstanceClasses = /* @__PURE__ */ new Set();
7
7
  const SAFE_BRAND = /^[\w$ -]+$/;
8
- const readExtensionString = (schema, field) => {
9
- if (!isSchemaObject(schema))
8
+ const SAFE_DISCRIMINATOR = /^[A-Za-z_$][\w$-]*$/;
9
+ const warnedDiscriminators = /* @__PURE__ */ new Set();
10
+ const readExtensionString = (node, field) => {
11
+ if (!isSchemaObject(node))
10
12
  return void 0;
11
- const extension = readKey(schema, MJST_EXTENSION_KEY);
13
+ const extension = readKey(node, MJST_EXTENSION_KEY);
12
14
  if (typeof extension !== "object" || extension === null)
13
15
  return void 0;
14
16
  const value = readKey(extension, field);
@@ -34,9 +36,22 @@ const getMjstBrand = (schema) => {
34
36
  const brand = readExtensionString(schema, "brand");
35
37
  return brand !== void 0 && SAFE_BRAND.test(brand) ? brand : void 0;
36
38
  };
39
+ const getMjstDiscriminator = (node) => {
40
+ const discriminator = readExtensionString(node, "discriminator");
41
+ if (discriminator === void 0)
42
+ return void 0;
43
+ if (SAFE_DISCRIMINATOR.test(discriminator))
44
+ return discriminator;
45
+ if (!warnedDiscriminators.has(discriminator)) {
46
+ warnedDiscriminators.add(discriminator);
47
+ console.warn(`Warning: ignoring unsupported x-mjst discriminator "${discriminator}". Expected a property name starting with a letter, "_" or "$".`);
48
+ }
49
+ return void 0;
50
+ };
37
51
  export {
38
52
  MJST_EXTENSION_KEY,
39
53
  getMjstBrand,
54
+ getMjstDiscriminator,
40
55
  getMjstInstanceOf,
41
56
  getMjstPrimitive
42
57
  };
@@ -15,9 +15,28 @@ export declare const toKebabCase: (value: string) => string;
15
15
  /**
16
16
  * Converts a JSON Schema $ref to a filename.
17
17
  *
18
- * Handles three ref forms:
18
+ * The name is built from every part of the ref that names something: the base
19
+ * URI a relative ref points at, then the pointer's own definition names. For the
20
+ * refs almost every document writes — `#/$defs/contact`,
21
+ * `#/components/schemas/UserProfile`, `#named` — there is exactly one, and the
22
+ * name is what it has always been.
23
+ *
24
+ * Deriving it from the whole ref is what makes the name a *pure function of the
25
+ * ref*, and that is load-bearing rather than tidy. Two definitions in different
26
+ * parents (`#/$defs/user/$defs/meta` and `#/$defs/order/$defs/meta`) or in
27
+ * different embedded resources (`first#/$defs/stuff` and `second#/$defs/stuff`)
28
+ * are an ordinary shape in a real document, and naming both after their last
29
+ * segment made them one file — so generation refused rather than emit a silently
30
+ * wrong type. Resolving that by *renaming* whichever was reached second would
31
+ * need every emitter to agree on the walk order, since each turns a `$ref` into
32
+ * an import name on its own; deriving a distinct name from the ref itself means
33
+ * they agree without having to coordinate at all.
34
+ *
35
+ * Handles these ref forms:
19
36
  * - Internal `#/$defs/contact` → `contact`
20
37
  * - Internal `#/definitions/ServerVariable` → `server-variable`
38
+ * - Nested `#/$defs/user/$defs/meta` → `user-meta`
39
+ * - Relative-base `second#/$defs/stuff` → `second-stuff`
21
40
  * - URI `http://example.com/definitions/3.1.0/channel.json` → `channel`
22
41
  * - URI with fragment `http://example.com/channel.json#/definitions/queue` → `channel-queue`
23
42
  *
@@ -28,8 +47,10 @@ export declare const toKebabCase: (value: string) => string;
28
47
  * ```ts
29
48
  * refToFilename('#/$defs/contact') // 'contact'
30
49
  * refToFilename('#/$defs/server-variable') // 'server-variable'
31
- * refToFilename('#/definitions/ServerVariable') // 'server-variable'
32
50
  * refToFilename('#/definitions/APIKeySecurityScheme') // 'api-key-security-scheme'
51
+ * refToFilename('#/components/schemas/UserProfile') // 'user-profile'
52
+ * refToFilename('#/$defs/user/$defs/meta') // 'user-meta'
53
+ * refToFilename('second#/$defs/stuff') // 'second-stuff'
33
54
  * refToFilename('http://asyncapi.com/definitions/3.1.0/channel.json') // 'channel'
34
55
  * refToFilename('#named') // 'named' — a plain `$anchor` ref
35
56
  * ```
@@ -42,16 +42,22 @@ const uriRefToFilename = (uri) => {
42
42
  return baseName;
43
43
  return `${baseName}-${toKebabCase(fragLast)}`;
44
44
  };
45
+ const CONTAINER_SEGMENTS = /* @__PURE__ */ new Set(["$defs", "definitions", "properties"]);
46
+ const pointerNameParts = (pointer) => {
47
+ const segments = pointer.split("/").filter((segment) => segment !== "");
48
+ const named = segments.map((segment, index) => ({ segment, nested: index > 0 && CONTAINER_SEGMENTS.has(segments[index - 1]) })).filter(({ segment }) => !CONTAINER_SEGMENTS.has(segment));
49
+ return named.filter((part, index) => part.nested || index === named.length - 1).map(({ segment }) => segment);
50
+ };
45
51
  const refToFilename = (ref) => {
46
52
  if (ref.startsWith("http://") || ref.startsWith("https://")) {
47
53
  return normalizeFilename(uriRefToFilename(ref), ref);
48
54
  }
49
- const segments = ref.split("/");
50
- let filename = segments[segments.length - 1];
51
- if (/[A-Z]/.test(filename)) {
52
- filename = toKebabCase(filename);
53
- }
54
- return normalizeFilename(filename, ref);
55
+ const hashIndex = ref.indexOf("#");
56
+ const base = hashIndex === -1 ? "" : ref.slice(0, hashIndex);
57
+ const pointer = hashIndex === -1 ? ref : ref.slice(hashIndex + 1);
58
+ const baseParts = base.replace(/\.json$/, "").split("/").filter((segment) => segment !== "");
59
+ const parts = [...baseParts, ...pointerNameParts(pointer)];
60
+ return normalizeFilename(parts.map((part) => /[A-Z]/.test(part) ? toKebabCase(part) : part).join("-"), ref);
55
61
  };
56
62
  export {
57
63
  refToFilename,
@@ -231,6 +231,24 @@ const cachedExtractRefs = (cache, schema) => {
231
231
  cache.extractRefsCache.set(schema, refs);
232
232
  return refs;
233
233
  };
234
+ const claimNames = (ref, resolved, typeSuffix, filenameOwners, typeNameOwners) => {
235
+ const filename = refToFilename(ref);
236
+ const typeName = refToName(ref, typeSuffix);
237
+ const fileOwner = filenameOwners.get(filename);
238
+ if (fileOwner !== void 0) {
239
+ if (sameDefinition(fileOwner.resolved, resolved))
240
+ return void 0;
241
+ throw new Error(`"${ref}" and ${fileOwner.label} both generate the file "${filename}.ts", so only one of them can be emitted and every reference to the other would resolve to the wrong type. Rename one definition.`);
242
+ }
243
+ const typeOwner = typeNameOwners.get(typeName);
244
+ if (typeOwner !== void 0) {
245
+ throw new Error(`"${ref}" and ${typeOwner.label} both generate the type name "${typeName}" from different files, so the generated output would import that name twice and fail to parse. Rename one definition.`);
246
+ }
247
+ const owner = { label: `"${ref}"`, resolved };
248
+ filenameOwners.set(filename, owner);
249
+ typeNameOwners.set(typeName, owner);
250
+ return { filename, typeName };
251
+ };
234
252
  const walkRefGraph = (rootSchema, rootTypeName, options, visit) => {
235
253
  const typeSuffix = options.typeSuffix ?? "";
236
254
  const baseCache = getRootCache(rootSchema, options.schemas);
@@ -289,25 +307,12 @@ const walkRefGraph = (rootSchema, rootTypeName, options, visit) => {
289
307
  if (!resolved) {
290
308
  throw new Error(`Could not resolve $ref "${ref}". Nothing in the document defines it, so the generated output would reference a type and a function that are never emitted. Fix the ref, or drop it from the schema.`);
291
309
  }
292
- const filename = refToFilename(ref);
293
- const typeName = refToName(ref, typeSuffix);
294
- const fileOwner = filenameOwners.get(filename);
295
- if (fileOwner) {
296
- if (!sameDefinition(fileOwner.resolved, resolved)) {
297
- throw new Error(`"${ref}" and ${fileOwner.label} both generate the file "${filename}.ts", so only one of them can be emitted and every reference to the other would resolve to the wrong type. Rename one definition.`);
298
- }
299
- } else {
300
- const typeOwner = typeNameOwners.get(typeName);
301
- if (typeOwner) {
302
- throw new Error(`"${ref}" and ${typeOwner.label} both generate the type name "${typeName}" from different files, so the generated output would import that name twice and fail to parse. Rename one definition.`);
303
- }
304
- const owner = { label: `"${ref}"`, resolved };
305
- filenameOwners.set(filename, owner);
306
- typeNameOwners.set(typeName, owner);
310
+ const claimed = claimNames(ref, resolved, typeSuffix, filenameOwners, typeNameOwners);
311
+ if (claimed !== void 0) {
307
312
  visit({
308
313
  ref,
309
- typeName,
310
- filename,
314
+ typeName: claimed.typeName,
315
+ filename: claimed.filename,
311
316
  schema: resolveDynamicRefs(resolved, dynamicRefMap),
312
317
  rootSchema: upgraded,
313
318
  isRoot: false
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amritk/helpers",
3
- "version": "0.19.0",
3
+ "version": "0.21.0",
4
4
  "description": "Shared utilities for the mjst code generation ecosystem.",
5
5
  "type": "module",
6
6
  "sideEffects": false,