@liautaud/typezod 1.0.1 → 2.0.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/README.md CHANGED
@@ -27,7 +27,7 @@ const Rectangle = t.object({
27
27
  height: t.number(),
28
28
  });
29
29
 
30
- const ElectronWindow = t.fromModule("/electron/", "BaseWindow");
30
+ const ElectronWindow = t.fromModule("electron", "BaseWindow");
31
31
 
32
32
  // Inside a typescript-eslint rule's `create()` function, build a context
33
33
  // from the parser services and use `isAssignableTo` to check types.
@@ -51,36 +51,55 @@ by the schema.
51
51
  ### `SchemaContext`
52
52
 
53
53
  The context object passed to `isAssignableTo`. Contains a `checker`
54
- (required) and an optional `program` (only needed for `t.fromModule()`).
54
+ (always required), a `program` (required when using `t.fromModule()`),
55
+ and a `sourceFile` (required when using `t.fromModule()` with a relative
56
+ module specifier such as `"./foo"` or `"../foo"`).
57
+
58
+ Example for relative module specifiers inside an ESLint rule:
59
+
60
+ ```typescript
61
+ const tsNode = parserServices.esTreeNodeToTSNodeMap.get(node);
62
+ const ctx: SchemaContext = {
63
+ checker: parserServices.program.getTypeChecker(),
64
+ program: parserServices.program,
65
+ sourceFile: tsNode.getSourceFile(),
66
+ };
67
+ ```
55
68
 
56
69
  ### Primitives
57
70
 
58
- | Builder | Description |
59
- | ---------------- | ------------------------------ |
60
- | `t.string()` | Represents the `string` type |
61
- | `t.number()` | Represents the `number` type |
62
- | `t.boolean()` | Represents the `boolean` type |
63
- | `t.void()` | Represents the `void` type |
64
- | `t.undefined()` | Represents the `undefined` type|
65
- | `t.null()` | Represents the `null` type |
66
- | `t.any()` | Accepts any type |
67
- | `t.unknown()` | Accepts any type |
71
+ | Builder | Description |
72
+ | --------------- | ------------------------------- |
73
+ | `t.string()` | Represents the `string` type |
74
+ | `t.number()` | Represents the `number` type |
75
+ | `t.boolean()` | Represents the `boolean` type |
76
+ | `t.void()` | Represents the `void` type |
77
+ | `t.undefined()` | Represents the `undefined` type |
78
+ | `t.null()` | Represents the `null` type |
79
+ | `t.any()` | Accepts any type |
80
+ | `t.unknown()` | Accepts any type |
68
81
 
69
82
  ### Combinators
70
83
 
71
- | Builder | Description |
72
- | -------------------------- | ---------------------------------------------------------------- |
73
- | `t.object(shape)` | Represents an object with the given shape (structural subtyping) |
74
- | `t.array(element)` | Represents an array whose element satisfies the given schema |
75
- | `t.union(...schemas)` | Represents a union of the given schemas |
76
- | `t.intersection(...schemas)` | Represents an intersection of the given schemas |
84
+ | Builder | Description |
85
+ | ---------------------------- | ---------------------------------------------------------------- |
86
+ | `t.object(shape)` | Represents an object with the given shape (structural subtyping) |
87
+ | `t.array(element)` | Represents an array whose element satisfies the given schema |
88
+ | `t.union(...schemas)` | Represents a union of the given schemas |
89
+ | `t.intersection(...schemas)` | Represents an intersection of the given schemas |
77
90
 
78
91
  ### Advanced
79
92
 
80
- | Builder | Description |
81
- | --------------------------------------- | ------------------------------------------------------- |
82
- | `t.fromModule(pathPattern, exportName)` | Represents a type exported from a module in the program |
83
- | `t.custom(fn)` | Escape hatch for arbitrary predicates |
93
+ | Builder | Description |
94
+ | -------------------------------------- | ------------------------------------------------------- |
95
+ | `t.fromModule(moduleName, exportName)` | Represents a type exported from a module in the program |
96
+ | `t.custom(fn)` | Escape hatch for arbitrary predicates |
97
+
98
+ `t.fromModule()` accepts the same module specifier you'd write in an `import` statement.
99
+ Installed packages (`"typescript"`, `"electron"`), relative paths (`"./types"`,
100
+ `"../shared/types"`), and ambient module declarations (`declare module '...'`) are
101
+ all supported. Relative specifiers require `sourceFile` in the context. Throws if the
102
+ module or export cannot be found.
84
103
 
85
104
  ### Modifiers
86
105
 
package/dist/index.d.mts CHANGED
@@ -1,14 +1,21 @@
1
- import { Program, Type, TypeChecker } from "typescript";
1
+ import { Program, SourceFile, Type, TypeChecker } from "typescript";
2
2
 
3
3
  //#region src/index.d.ts
4
4
 
5
5
  /**
6
- * Context required by all schema checks. The `program` field is only needed
7
- * for schemas that resolve types from external modules ({@link t.fromModule}).
6
+ * Context required by all schema checks.
7
+ *
8
+ * `program` is required by schemas that resolve module exports
9
+ * ({@link t.fromModule}).
10
+ *
11
+ * `sourceFile` is only required when resolving relative module specifiers
12
+ * (`"./x"`, `"../x"`) with {@link t.fromModule}. It should be the source file
13
+ * currently being analyzed.
8
14
  */
9
15
  type SchemaContext = {
10
16
  checker: TypeChecker;
11
17
  program?: Program;
18
+ sourceFile?: SourceFile;
12
19
  };
13
20
  type AcceptsFn = (type: Type, ctx: SchemaContext) => boolean;
14
21
  /**
@@ -56,6 +63,12 @@ declare class TypeSchema {
56
63
  */
57
64
  nullish(): TypeSchema;
58
65
  }
66
+ /**
67
+ * Returns `true` if the given TypeScript type is assignable to the schema–in
68
+ * other words, if `type extends T` with `T` the TypeScript type represented
69
+ * by the schema.
70
+ */
71
+ declare function isAssignableTo(ctx: SchemaContext, type: Type, schema: TypeSchema): boolean;
59
72
  /**
60
73
  * Schema builder namespace.
61
74
  */
@@ -134,25 +147,27 @@ declare const t: {
134
147
  */
135
148
  intersection: (...members: TypeSchema[]) => TypeSchema;
136
149
  /**
137
- * Represents a type exported from a module in the program. Resolves a genuine
138
- * `ts.Type` and delegates to `checker.isTypeAssignableTo()`, so it handles
139
- * nominal class hierarchies correctly.
150
+ * Represents a type exported from a module. Resolves the module using
151
+ * TypeScript's module resolution algorithm, with a fallback to ambient
152
+ * module declarations. Resolved types are cached per `TypeChecker` instance.
140
153
  *
141
- * Resolved types are cached per `TypeChecker` instance (via a `WeakMap`) so
142
- * repeated calls across files do not re-scan source files.
154
+ * Requires `program` in the {@link SchemaContext}. Relative specifiers
155
+ * (`"./x"`, `"../x"`) also require `sourceFile`.
143
156
  *
144
- * Requires `program` in the {@link SchemaContext}.
145
- *
146
- * @param modulePathPattern Substring matched against source-file paths.
157
+ * @param moduleName The module specifier, as in an `import` statement.
147
158
  * @param exportName The exported type, class or interface name.
148
159
  *
149
160
  * @example
150
161
  * ```typescript
151
- * const BaseWindow = t.fromModule("/electron/", "BaseWindow");
152
- * const Buffer = t.fromModule("@types/node", "Buffer");
162
+ * const BaseWindow = t.fromModule("electron", "BaseWindow");
163
+ * const Buffer = t.fromModule("node:buffer", "Buffer");
153
164
  * ```
165
+ *
166
+ * @throws When `program` is missing from the context.
167
+ * @throws When `moduleName` is relative and `sourceFile` is missing.
168
+ * @throws When no export named `exportName` can be resolved from `moduleName`.
154
169
  */
155
- fromModule: (modulePathPattern: string, exportName: string) => TypeSchema;
170
+ fromModule: (moduleName: string, exportName: string) => TypeSchema;
156
171
  /**
157
172
  * Escape hatch for arbitrary predicates that the DSL cannot express directly.
158
173
  *
@@ -165,11 +180,5 @@ declare const t: {
165
180
  */
166
181
  custom: (predicate: AcceptsFn) => TypeSchema;
167
182
  };
168
- /**
169
- * Returns `true` if the given TypeScript type is assignable to the schema–in
170
- * other words, if `type extends T` with `T` the TypeScript type represented
171
- * by the schema.
172
- */
173
- declare function isAssignableTo(ctx: SchemaContext, type: Type, schema: TypeSchema): boolean;
174
183
  //#endregion
175
184
  export { SchemaContext, TypeSchema, isAssignableTo, t };
package/dist/index.mjs CHANGED
@@ -1,3 +1,5 @@
1
+ import ts from "typescript";
2
+
1
3
  //#region src/index.ts
2
4
  const TS_SYMBOL_FLAGS_OPTIONAL = 16777216;
3
5
  /**
@@ -55,7 +57,14 @@ var TypeSchema = class TypeSchema {
55
57
  }
56
58
  };
57
59
  const schema = (check) => new TypeSchema(check);
58
- const moduleTypeCache = /* @__PURE__ */ new WeakMap();
60
+ /**
61
+ * Returns `true` if the given TypeScript type is assignable to the schema–in
62
+ * other words, if `type extends T` with `T` the TypeScript type represented
63
+ * by the schema.
64
+ */
65
+ function isAssignableTo(ctx, type, schema$1) {
66
+ return schema$1._accepts(type, ctx);
67
+ }
59
68
  /**
60
69
  * Schema builder namespace.
61
70
  */
@@ -85,42 +94,56 @@ const t = {
85
94
  return members.some((m) => m._accepts(type, ctx));
86
95
  }),
87
96
  intersection: (...members) => schema((type, ctx) => members.every((m) => m._accepts(type, ctx))),
88
- fromModule: (modulePathPattern, exportName) => schema((type, { checker, program }) => {
97
+ fromModule: (moduleName, exportName) => schema((type, { checker, program, sourceFile }) => {
89
98
  if (!program) throw new Error("t.fromModule() requires `program` in the SchemaContext.");
99
+ const isRelative = moduleName.startsWith("./") || moduleName.startsWith("../");
100
+ if (isRelative && !sourceFile) throw new Error("t.fromModule() requires `sourceFile` in the SchemaContext for relative module specifiers.");
90
101
  let cache = moduleTypeCache.get(checker);
91
102
  if (!cache) {
92
103
  cache = /* @__PURE__ */ new Map();
93
104
  moduleTypeCache.set(checker, cache);
94
105
  }
95
- const cacheKey = JSON.stringify([modulePathPattern, exportName]);
96
- if (!cache.has(cacheKey)) {
97
- let resolved = null;
98
- for (const sourceFile of program.getSourceFiles()) {
99
- if (!sourceFile.fileName.includes(modulePathPattern)) continue;
100
- const moduleSymbol = checker.getSymbolAtLocation(sourceFile);
101
- if (!moduleSymbol) continue;
102
- const exportSymbol = checker.getExportsOfModule(moduleSymbol).find((s) => s.getName() === exportName);
103
- if (exportSymbol) {
104
- resolved = checker.getDeclaredTypeOfSymbol(exportSymbol);
105
- break;
106
- }
107
- }
108
- cache.set(cacheKey, resolved);
109
- }
106
+ const cacheKey = JSON.stringify([
107
+ moduleName,
108
+ exportName,
109
+ isRelative ? sourceFile.fileName : null
110
+ ]);
111
+ if (!cache.has(cacheKey)) cache.set(cacheKey, resolveModuleType(checker, program, moduleName, exportName, sourceFile));
110
112
  const targetType = cache.get(cacheKey);
111
- if (targetType == null) throw new Error(`t.fromModule(): could not resolve export "${exportName}" from any module matching "${modulePathPattern}".`);
113
+ if (targetType == null) throw new Error(`t.fromModule(): could not resolve export "${exportName}" from module "${moduleName}".`);
112
114
  return checker.isTypeAssignableTo(type, targetType);
113
115
  }),
114
116
  custom: (predicate) => schema(predicate)
115
117
  };
118
+ /** Per-checker cache for `t.fromModule()` resolved types. */
119
+ const moduleTypeCache = /* @__PURE__ */ new WeakMap();
116
120
  /**
117
- * Returns `true` if the given TypeScript type is assignable to the schema–in
118
- * other words, if `type extends T` with `T` the TypeScript type represented
119
- * by the schema.
121
+ * Resolves a module's exported type using TypeScript's module resolution
122
+ * algorithm, with a fallback to ambient module declarations.
123
+ *
124
+ * Returns the resolved `ts.Type`, or `null` if the export cannot be found.
125
+ *
126
+ * @throws When multiple ambient/resolved symbols yield different types for the
127
+ * same export name (ambiguity).
120
128
  */
121
- function isAssignableTo(ctx, type, schema$1) {
122
- return schema$1._accepts(type, ctx);
123
- }
129
+ const resolveModuleType = (checker, program, moduleName, exportName, sourceFile) => {
130
+ const compilerOptions = program.getCompilerOptions();
131
+ const containingFile = sourceFile ? sourceFile.fileName : program.getCurrentDirectory() + "/__typezod__.ts";
132
+ let moduleSymbol;
133
+ const resolved = ts.resolveModuleName(moduleName, containingFile, compilerOptions, ts.sys);
134
+ if (resolved.resolvedModule) {
135
+ const resolvedSf = program.getSourceFile(resolved.resolvedModule.resolvedFileName);
136
+ if (resolvedSf) moduleSymbol = checker.getSymbolAtLocation(resolvedSf);
137
+ }
138
+ if (!moduleSymbol) {
139
+ const quotedName = `"${moduleName}"`;
140
+ moduleSymbol = checker.getAmbientModules().find((s) => s.getName() === quotedName);
141
+ }
142
+ if (!moduleSymbol) return null;
143
+ const exportSymbol = checker.getExportsOfModule(moduleSymbol).find((s) => s.getName() === exportName);
144
+ if (!exportSymbol) return null;
145
+ return checker.getDeclaredTypeOfSymbol(exportSymbol);
146
+ };
124
147
 
125
148
  //#endregion
126
149
  export { TypeSchema, isAssignableTo, t };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@liautaud/typezod",
3
3
  "type": "module",
4
- "version": "1.0.1",
4
+ "version": "2.0.0",
5
5
  "description": "Zod-like DSL for comparing TypeScript compiler types against user-defined schemas",
6
6
  "author": "Romain Liautaud",
7
7
  "license": "MIT",