mirascope 2.0.0-alpha.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.
Files changed (46) hide show
  1. package/README.md +397 -0
  2. package/dist/bun.cjs +447 -0
  3. package/dist/bun.cjs.map +1 -0
  4. package/dist/bun.d.cts +53 -0
  5. package/dist/bun.d.ts +53 -0
  6. package/dist/bun.js +94 -0
  7. package/dist/bun.js.map +1 -0
  8. package/dist/chunk-2R5IW35Y.js +116 -0
  9. package/dist/chunk-2R5IW35Y.js.map +1 -0
  10. package/dist/chunk-A6ZCB7BU.js +6826 -0
  11. package/dist/chunk-A6ZCB7BU.js.map +1 -0
  12. package/dist/chunk-NSBPE2FW.js +15 -0
  13. package/dist/chunk-NSBPE2FW.js.map +1 -0
  14. package/dist/chunk-RMNCGJYW.js +49 -0
  15. package/dist/chunk-RMNCGJYW.js.map +1 -0
  16. package/dist/chunk-U4MFJ4DP.js +358 -0
  17. package/dist/chunk-U4MFJ4DP.js.map +1 -0
  18. package/dist/index.cjs +7705 -0
  19. package/dist/index.cjs.map +1 -0
  20. package/dist/index.d.cts +4859 -0
  21. package/dist/index.d.ts +4859 -0
  22. package/dist/index.js +324 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/model-T6IQ7UUA.js +4 -0
  25. package/dist/model-T6IQ7UUA.js.map +1 -0
  26. package/dist/tool-schema-Dh-RLHhC.d.cts +45 -0
  27. package/dist/tool-schema-Dh-RLHhC.d.ts +45 -0
  28. package/dist/transform/index.cjs +525 -0
  29. package/dist/transform/index.cjs.map +1 -0
  30. package/dist/transform/index.d.cts +89 -0
  31. package/dist/transform/index.d.ts +89 -0
  32. package/dist/transform/index.js +6 -0
  33. package/dist/transform/index.js.map +1 -0
  34. package/dist/transform/plugins/esbuild.cjs +472 -0
  35. package/dist/transform/plugins/esbuild.cjs.map +1 -0
  36. package/dist/transform/plugins/esbuild.d.cts +46 -0
  37. package/dist/transform/plugins/esbuild.d.ts +46 -0
  38. package/dist/transform/plugins/esbuild.js +5 -0
  39. package/dist/transform/plugins/esbuild.js.map +1 -0
  40. package/dist/transform/plugins/vite.cjs +405 -0
  41. package/dist/transform/plugins/vite.cjs.map +1 -0
  42. package/dist/transform/plugins/vite.d.cts +50 -0
  43. package/dist/transform/plugins/vite.d.ts +50 -0
  44. package/dist/transform/plugins/vite.js +5 -0
  45. package/dist/transform/plugins/vite.js.map +1 -0
  46. package/package.json +127 -0
package/dist/bun.cjs ADDED
@@ -0,0 +1,447 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var bun = require('bun');
6
+ var fs = require('fs');
7
+ var path = require('path');
8
+ var ts3 = require('typescript');
9
+
10
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
11
+
12
+ var ts3__default = /*#__PURE__*/_interopDefault(ts3);
13
+
14
+ // src/bun.ts
15
+ function isArrayLikeType(type, checker) {
16
+ if (type.getFlags() & ts3__default.default.TypeFlags.Object) {
17
+ const objectType = type;
18
+ const objectFlags = objectType.objectFlags;
19
+ if (objectFlags & ts3__default.default.ObjectFlags.Reference) {
20
+ const typeRef = type;
21
+ const symbol = typeRef.symbol;
22
+ if (symbol && symbol.getName() === "Array") {
23
+ return true;
24
+ }
25
+ const target = typeRef.target;
26
+ if (target && target.symbol && target.symbol.getName() === "Array") {
27
+ return true;
28
+ }
29
+ }
30
+ }
31
+ const typeString = checker.typeToString(type);
32
+ if (typeString.endsWith("[]") || typeString.startsWith("Array<")) {
33
+ return true;
34
+ }
35
+ return false;
36
+ }
37
+ function typeToJsonSchema(type, ctx) {
38
+ const checker = ctx.checker;
39
+ if (type.isUnion()) {
40
+ return handleUnionType(type, ctx);
41
+ }
42
+ if (type.isIntersection()) {
43
+ return handleIntersectionType(type, ctx);
44
+ }
45
+ if (type.isLiteral()) {
46
+ return handleLiteralType(type);
47
+ }
48
+ const flags = type.getFlags();
49
+ if (flags & ts3__default.default.TypeFlags.BooleanLiteral) {
50
+ const intrinsicName = type.intrinsicName;
51
+ const isTrue = intrinsicName === "true";
52
+ return { type: "boolean", enum: [isTrue] };
53
+ }
54
+ if (flags & ts3__default.default.TypeFlags.String) {
55
+ return { type: "string" };
56
+ }
57
+ if (flags & ts3__default.default.TypeFlags.Number) {
58
+ return { type: "number" };
59
+ }
60
+ if (flags & ts3__default.default.TypeFlags.Null) {
61
+ return { type: "null" };
62
+ }
63
+ if (flags & ts3__default.default.TypeFlags.Undefined) {
64
+ return {};
65
+ }
66
+ if (checker.isArrayType(type) || isArrayLikeType(type, checker)) {
67
+ const typeRef = type;
68
+ const typeArgs = checker.getTypeArguments(typeRef);
69
+ if (typeArgs && typeArgs.length > 0) {
70
+ return {
71
+ type: "array",
72
+ items: typeToJsonSchema(typeArgs[0], ctx)
73
+ };
74
+ }
75
+ return { type: "array" };
76
+ }
77
+ if (flags & ts3__default.default.TypeFlags.Object) {
78
+ return handleObjectType(type, ctx);
79
+ }
80
+ return {};
81
+ }
82
+ function handleUnionType(type, ctx) {
83
+ const types = type.types;
84
+ const nonUndefinedTypes = types.filter(
85
+ (t) => !(t.getFlags() & ts3__default.default.TypeFlags.Undefined)
86
+ );
87
+ if (nonUndefinedTypes.length === 2 && nonUndefinedTypes.every((t) => t.getFlags() & ts3__default.default.TypeFlags.BooleanLiteral)) {
88
+ return { type: "boolean" };
89
+ }
90
+ if (nonUndefinedTypes.every(
91
+ (t) => t.isStringLiteral()
92
+ )) {
93
+ return {
94
+ type: "string",
95
+ enum: nonUndefinedTypes.map((t) => t.value)
96
+ };
97
+ }
98
+ if (nonUndefinedTypes.every(
99
+ (t) => t.isNumberLiteral()
100
+ )) {
101
+ return {
102
+ type: "number",
103
+ enum: nonUndefinedTypes.map((t) => t.value)
104
+ };
105
+ }
106
+ if (nonUndefinedTypes.length === 1) {
107
+ return typeToJsonSchema(nonUndefinedTypes[0], ctx);
108
+ }
109
+ return {
110
+ oneOf: nonUndefinedTypes.map((t) => typeToJsonSchema(t, ctx))
111
+ };
112
+ }
113
+ function handleIntersectionType(type, ctx) {
114
+ const allOf = type.types.map((t) => typeToJsonSchema(t, ctx));
115
+ if (allOf.every((s) => s.type === "object")) {
116
+ const merged = {
117
+ type: "object",
118
+ properties: {},
119
+ required: []
120
+ };
121
+ for (const schema of allOf) {
122
+ if (schema.properties) {
123
+ merged.properties = { ...merged.properties, ...schema.properties };
124
+ }
125
+ if (schema.required) {
126
+ merged.required = [
127
+ ...merged.required,
128
+ ...schema.required
129
+ ];
130
+ }
131
+ }
132
+ return merged;
133
+ }
134
+ return { allOf };
135
+ }
136
+ function handleLiteralType(type) {
137
+ if (type.isStringLiteral()) {
138
+ return { type: "string", enum: [type.value] };
139
+ }
140
+ if (type.isNumberLiteral()) {
141
+ return { type: "number", enum: [type.value] };
142
+ }
143
+ return {};
144
+ }
145
+ function handleObjectType(type, ctx) {
146
+ const checker = ctx.checker;
147
+ const properties = {};
148
+ const required = [];
149
+ const props = checker.getPropertiesOfType(type);
150
+ for (const prop of props) {
151
+ const propName = prop.getName();
152
+ const propType = checker.getTypeOfSymbol(prop);
153
+ const isOptional = (prop.getFlags() & ts3__default.default.SymbolFlags.Optional) !== 0;
154
+ const propSchema = typeToJsonSchema(propType, ctx);
155
+ const jsDocComment = prop.getDocumentationComment(checker);
156
+ if (jsDocComment.length > 0) {
157
+ const description = jsDocComment.map((c) => c.text).join("");
158
+ propSchema.description = description;
159
+ }
160
+ properties[propName] = propSchema;
161
+ if (!isOptional) {
162
+ required.push(propName);
163
+ }
164
+ }
165
+ return {
166
+ type: "object",
167
+ properties,
168
+ required: required.length > 0 ? required : void 0
169
+ };
170
+ }
171
+ function typeToToolParameterSchema(type, checker) {
172
+ const ctx = {
173
+ checker,
174
+ definitions: /* @__PURE__ */ new Map()};
175
+ const schema = typeToJsonSchema(type, ctx);
176
+ if (schema.type !== "object") {
177
+ throw new Error(
178
+ "Tool parameter type must be an object type, got: " + JSON.stringify(schema)
179
+ );
180
+ }
181
+ const result = {
182
+ type: "object",
183
+ properties: schema.properties ?? {},
184
+ required: schema.required ?? [],
185
+ additionalProperties: false
186
+ };
187
+ if (ctx.definitions.size > 0) {
188
+ result.$defs = Object.fromEntries(ctx.definitions);
189
+ }
190
+ return result;
191
+ }
192
+
193
+ // src/transform/transformer.ts
194
+ var TOOL_FUNCTION_NAMES = /* @__PURE__ */ new Set(["defineTool", "defineContextTool"]);
195
+ var FORMAT_FUNCTION_NAMES = /* @__PURE__ */ new Set(["defineFormat"]);
196
+ function createToolSchemaTransformer(program) {
197
+ const checker = program.getTypeChecker();
198
+ return (context) => {
199
+ return (sourceFile) => {
200
+ const visitor = (node) => {
201
+ if (ts3__default.default.isCallExpression(node)) {
202
+ const toolTransformed = tryTransformToolCall(node, checker, context);
203
+ if (toolTransformed) {
204
+ return toolTransformed;
205
+ }
206
+ const formatTransformed = tryTransformFormatCall(
207
+ node,
208
+ checker,
209
+ context
210
+ );
211
+ if (formatTransformed) {
212
+ return formatTransformed;
213
+ }
214
+ }
215
+ return ts3__default.default.visitEachChild(node, visitor, context);
216
+ };
217
+ return ts3__default.default.visitNode(sourceFile, visitor);
218
+ };
219
+ };
220
+ }
221
+ function tryTransformToolCall(node, checker, context) {
222
+ const functionName = getFunctionName(node);
223
+ if (!functionName || !TOOL_FUNCTION_NAMES.has(functionName)) {
224
+ return void 0;
225
+ }
226
+ const typeArgs = node.typeArguments;
227
+ if (!typeArgs || typeArgs.length === 0) {
228
+ return void 0;
229
+ }
230
+ const argsTypeNode = typeArgs[0];
231
+ const argsType = checker.getTypeFromTypeNode(argsTypeNode);
232
+ let schema;
233
+ try {
234
+ schema = typeToToolParameterSchema(argsType, checker);
235
+ } catch {
236
+ return void 0;
237
+ }
238
+ const args = node.arguments;
239
+ const firstArg = args[0];
240
+ if (!firstArg || !ts3__default.default.isObjectLiteralExpression(firstArg)) {
241
+ return void 0;
242
+ }
243
+ const optionsObject = firstArg;
244
+ const hasSchema = optionsObject.properties.some(
245
+ (prop) => ts3__default.default.isPropertyAssignment(prop) && ts3__default.default.isIdentifier(prop.name) && prop.name.text === "__schema"
246
+ );
247
+ if (hasSchema) {
248
+ return void 0;
249
+ }
250
+ const schemaProperty = createSchemaProperty(schema, context.factory);
251
+ const newProperties = [...optionsObject.properties, schemaProperty];
252
+ const newOptionsObject = context.factory.updateObjectLiteralExpression(
253
+ optionsObject,
254
+ newProperties
255
+ );
256
+ const newArgs = [newOptionsObject, ...args.slice(1)];
257
+ return context.factory.updateCallExpression(
258
+ node,
259
+ node.expression,
260
+ node.typeArguments,
261
+ newArgs
262
+ );
263
+ }
264
+ function tryTransformFormatCall(node, checker, context) {
265
+ const functionName = getFunctionName(node);
266
+ if (!functionName || !FORMAT_FUNCTION_NAMES.has(functionName)) {
267
+ return void 0;
268
+ }
269
+ const typeArgs = node.typeArguments;
270
+ if (!typeArgs || typeArgs.length === 0) {
271
+ return void 0;
272
+ }
273
+ const outputTypeNode = typeArgs[0];
274
+ const outputType = checker.getTypeFromTypeNode(outputTypeNode);
275
+ const args = node.arguments;
276
+ const firstArg = args[0];
277
+ if (!firstArg) {
278
+ return void 0;
279
+ }
280
+ if (ts3__default.default.isObjectLiteralExpression(firstArg)) {
281
+ const formatSpecObject = firstArg;
282
+ const hasSchema = formatSpecObject.properties.some(
283
+ (prop) => ts3__default.default.isPropertyAssignment(prop) && ts3__default.default.isIdentifier(prop.name) && prop.name.text === "__schema"
284
+ );
285
+ if (hasSchema) {
286
+ return void 0;
287
+ }
288
+ let schema;
289
+ try {
290
+ schema = typeToToolParameterSchema(outputType, checker);
291
+ } catch {
292
+ return void 0;
293
+ }
294
+ const schemaProperty = createSchemaProperty(schema, context.factory);
295
+ const newProperties = [...formatSpecObject.properties, schemaProperty];
296
+ const newFormatSpecObject = context.factory.updateObjectLiteralExpression(
297
+ formatSpecObject,
298
+ newProperties
299
+ );
300
+ const newArgs = [newFormatSpecObject, ...args.slice(1)];
301
+ return context.factory.updateCallExpression(
302
+ node,
303
+ node.expression,
304
+ node.typeArguments,
305
+ newArgs
306
+ );
307
+ }
308
+ return void 0;
309
+ }
310
+ function getFunctionName(node) {
311
+ const expression = node.expression;
312
+ if (ts3__default.default.isIdentifier(expression)) {
313
+ return expression.text;
314
+ }
315
+ if (ts3__default.default.isPropertyAccessExpression(expression)) {
316
+ return expression.name.text;
317
+ }
318
+ return void 0;
319
+ }
320
+ function createSchemaProperty(schema, factory) {
321
+ return factory.createPropertyAssignment(
322
+ factory.createIdentifier("__schema"),
323
+ jsonToAst(schema, factory)
324
+ );
325
+ }
326
+ function jsonToAst(value, factory) {
327
+ if (value === null) {
328
+ return factory.createNull();
329
+ }
330
+ if (value === void 0) {
331
+ return factory.createIdentifier("undefined");
332
+ }
333
+ if (typeof value === "string") {
334
+ return factory.createStringLiteral(value);
335
+ }
336
+ if (typeof value === "number") {
337
+ return factory.createNumericLiteral(value);
338
+ }
339
+ if (typeof value === "boolean") {
340
+ return value ? factory.createTrue() : factory.createFalse();
341
+ }
342
+ if (Array.isArray(value)) {
343
+ return factory.createArrayLiteralExpression(
344
+ value.map((item) => jsonToAst(item, factory))
345
+ );
346
+ }
347
+ if (typeof value === "object") {
348
+ const properties = Object.entries(value).map(
349
+ ([key, val]) => factory.createPropertyAssignment(
350
+ factory.createIdentifier(key),
351
+ jsonToAst(val, factory)
352
+ )
353
+ );
354
+ return factory.createObjectLiteralExpression(properties, true);
355
+ }
356
+ return factory.createIdentifier("undefined");
357
+ }
358
+
359
+ // src/bun.ts
360
+ function needsTransform(contents) {
361
+ return /\bdefineTool\b|\bdefineContextTool\b|\bdefineFormat\b/.test(contents);
362
+ }
363
+ function transformSource(filePath, contents) {
364
+ const configPath = ts3__default.default.findConfigFile(
365
+ path.dirname(filePath),
366
+ ts3__default.default.sys.fileExists,
367
+ "tsconfig.json"
368
+ );
369
+ const compilerOptions = {
370
+ target: ts3__default.default.ScriptTarget.ESNext,
371
+ module: ts3__default.default.ModuleKind.ESNext,
372
+ moduleResolution: ts3__default.default.ModuleResolutionKind.Bundler,
373
+ esModuleInterop: true,
374
+ strict: true
375
+ };
376
+ if (configPath) {
377
+ const configFile = ts3__default.default.readConfigFile(configPath, ts3__default.default.sys.readFile);
378
+ if (!configFile.error) {
379
+ const parsed = ts3__default.default.parseJsonConfigFileContent(
380
+ configFile.config,
381
+ ts3__default.default.sys,
382
+ path.dirname(configPath)
383
+ );
384
+ Object.assign(compilerOptions, parsed.options);
385
+ }
386
+ }
387
+ const host = ts3__default.default.createCompilerHost(compilerOptions);
388
+ const originalGetSourceFile = host.getSourceFile;
389
+ host.getSourceFile = (fileName, languageVersion, onError, shouldCreateNewSourceFile) => {
390
+ if (path.resolve(fileName) === path.resolve(filePath)) {
391
+ return ts3__default.default.createSourceFile(fileName, contents, languageVersion, true);
392
+ }
393
+ return originalGetSourceFile(
394
+ fileName,
395
+ languageVersion,
396
+ onError,
397
+ shouldCreateNewSourceFile
398
+ );
399
+ };
400
+ const program = ts3__default.default.createProgram([filePath], compilerOptions, host);
401
+ const sourceFile = program.getSourceFile(filePath);
402
+ if (!sourceFile) {
403
+ return void 0;
404
+ }
405
+ const transformer = createToolSchemaTransformer(program);
406
+ const result = ts3__default.default.transform(sourceFile, [transformer]);
407
+ const transformedSourceFile = result.transformed[0];
408
+ if (!transformedSourceFile) {
409
+ result.dispose();
410
+ return void 0;
411
+ }
412
+ const printer = ts3__default.default.createPrinter({ newLine: ts3__default.default.NewLineKind.LineFeed });
413
+ const output = printer.printFile(transformedSourceFile);
414
+ result.dispose();
415
+ return output;
416
+ }
417
+ function mirascope(options = {}) {
418
+ const { filter = /\.tsx?$/, exclude = [/node_modules/] } = options;
419
+ bun.plugin({
420
+ name: "mirascope",
421
+ setup(build) {
422
+ build.onLoad({ filter }, (args) => {
423
+ for (const pattern of exclude) {
424
+ if (pattern.test(args.path)) {
425
+ return;
426
+ }
427
+ }
428
+ const contents = fs.readFileSync(args.path, "utf-8");
429
+ const loader = args.path.endsWith(".tsx") ? "tsx" : "ts";
430
+ if (!needsTransform(contents)) {
431
+ return { contents, loader };
432
+ }
433
+ const transformed = transformSource(args.path, contents);
434
+ return {
435
+ contents: transformed ?? contents,
436
+ loader
437
+ };
438
+ });
439
+ }
440
+ });
441
+ }
442
+ var bun_default = mirascope;
443
+
444
+ exports.default = bun_default;
445
+ exports.mirascope = mirascope;
446
+ //# sourceMappingURL=bun.cjs.map
447
+ //# sourceMappingURL=bun.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/transform/type-to-schema.ts","../src/transform/transformer.ts","../src/bun.ts"],"names":["ts","dirname","resolve","plugin","readFileSync"],"mappings":";;;;;;;;;;;;;;AAmCA,SAAS,eAAA,CAAgB,MAAe,OAAA,EAAkC;AAExE,EAAA,IAAI,IAAA,CAAK,QAAA,EAAS,GAAIA,oBAAA,CAAG,UAAU,MAAA,EAAQ;AACzC,IAAA,MAAM,UAAA,GAAa,IAAA;AACnB,IAAA,MAAM,cAAc,UAAA,CAAW,WAAA;AAG/B,IAAA,IAAI,WAAA,GAAcA,oBAAA,CAAG,WAAA,CAAY,SAAA,EAAW;AAC1C,MAAA,MAAM,OAAA,GAAU,IAAA;AAChB,MAAA,MAAM,SAAS,OAAA,CAAQ,MAAA;AACvB,MAAA,IAAI,MAAA,IAAU,MAAA,CAAO,OAAA,EAAQ,KAAM,OAAA,EAAS;AAC1C,QAAA,OAAO,IAAA;AAAA,MACT;AAEA,MAAA,MAAM,SAAS,OAAA,CAAQ,MAAA;AACvB,MAAA,IAAI,UAAU,MAAA,CAAO,MAAA,IAAU,OAAO,MAAA,CAAO,OAAA,OAAc,OAAA,EAAS;AAClE,QAAA,OAAO,IAAA;AAAA,MACT;AAAA,IACF;AAAA,EACF;AAGA,EAAA,MAAM,UAAA,GAAa,OAAA,CAAQ,YAAA,CAAa,IAAI,CAAA;AAC5C,EAAA,IAAI,WAAW,QAAA,CAAS,IAAI,KAAK,UAAA,CAAW,UAAA,CAAW,QAAQ,CAAA,EAAG;AAChE,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,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AAO,EAAG,CAAC,IAAA,KAAS;AAEjC,QAAA,KAAA,MAAW,WAAW,OAAA,EAAS;AAC7B,UAAA,IAAI,OAAA,CAAQ,IAAA,CAAK,IAAA,CAAK,IAAI,CAAA,EAAG;AAE3B,YAAA;AAAA,UACF;AAAA,QACF;AAEA,QAAA,MAAM,QAAA,GAAWC,eAAA,CAAa,IAAA,CAAK,IAAA,EAAM,OAAO,CAAA;AAChD,QAAA,MAAM,SAAS,IAAA,CAAK,IAAA,CAAK,QAAA,CAAS,MAAM,IAAI,KAAA,GAAQ,IAAA;AAGpD,QAAA,IAAI,CAAC,cAAA,CAAe,QAAQ,CAAA,EAAG;AAE7B,UAAA,OAAO,EAAE,UAAU,MAAA,EAAO;AAAA,QAC5B;AAEA,QAAA,MAAM,WAAA,GAAc,eAAA,CAAgB,IAAA,CAAK,IAAA,EAAM,QAAQ,CAAA;AAGvD,QAAA,OAAO;AAAA,UACL,UAAU,WAAA,IAAe,QAAA;AAAA,UACzB;AAAA,SACF;AAAA,MACF,CAAC,CAAA;AAAA,IACH;AAAA,GACD,CAAA;AACH;AAEA,IAAO,WAAA,GAAQ","file":"bun.cjs","sourcesContent":["/**\n * Convert TypeScript types to JSON Schema.\n *\n * Uses the TypeScript Compiler API to introspect types and generate\n * JSON Schema representations suitable for LLM tool definitions.\n */\n\nimport ts from \"typescript\";\n\nimport type { JsonSchemaProperty, ToolParameterSchema } from \"@/llm/tools\";\n\n/**\n * Context for type-to-schema conversion.\n */\ninterface ConversionContext {\n /** The TypeScript type checker. */\n checker: ts.TypeChecker;\n /** Definitions for referenced types ($defs). */\n definitions: Map<string, JsonSchemaProperty>;\n /** Set of type names currently being processed (for cycle detection). */\n processing: Set<string>;\n}\n\n/**\n * Check if a type is an array-like type (handles cases where isArrayType doesn't work).\n *\n * This is needed because TypeScript's isArrayType requires proper lib.d.ts setup.\n * We also check for Array<T> and T[] patterns by looking at the type structure.\n *\n * Coverage ignored: This is defensive fallback code for edge cases where\n * checker.isArrayType() fails due to missing/broken lib.d.ts. In normal\n * usage with proper TypeScript setup, checker.isArrayType() succeeds and\n * this function is never called (short-circuit evaluation on line 120).\n */\n/* v8 ignore start */\nfunction isArrayLikeType(type: ts.Type, checker: ts.TypeChecker): boolean {\n // Check if it's a TypeReference with 'Array' as the symbol name\n if (type.getFlags() & ts.TypeFlags.Object) {\n const objectType = type as ts.ObjectType;\n const objectFlags = objectType.objectFlags;\n\n // Check for array reference (Array<T>)\n if (objectFlags & ts.ObjectFlags.Reference) {\n const typeRef = type as ts.TypeReference;\n const symbol = typeRef.symbol;\n if (symbol && symbol.getName() === \"Array\") {\n return true;\n }\n // Also check the target's symbol for ReadonlyArray, etc.\n const target = typeRef.target;\n if (target && target.symbol && target.symbol.getName() === \"Array\") {\n return true;\n }\n }\n }\n\n // Check the type string as a fallback\n const typeString = checker.typeToString(type);\n if (typeString.endsWith(\"[]\") || typeString.startsWith(\"Array<\")) {\n return true;\n }\n\n return false;\n}\n/* v8 ignore end */\n\n/**\n * Convert a TypeScript type to a JSON Schema property.\n *\n * @param type - The TypeScript type to convert.\n * @param ctx - The conversion context.\n * @returns The JSON Schema property.\n */\nexport function typeToJsonSchema(\n type: ts.Type,\n ctx: ConversionContext,\n): JsonSchemaProperty {\n const checker = ctx.checker;\n\n // Handle union types (including optional which is T | undefined)\n if (type.isUnion()) {\n return handleUnionType(type, ctx);\n }\n\n // Handle intersection types\n if (type.isIntersection()) {\n return handleIntersectionType(type, ctx);\n }\n\n // Handle literal types\n if (type.isLiteral()) {\n return handleLiteralType(type);\n }\n\n // Handle boolean literals (true/false) - these aren't captured by isLiteral()\n // They are intrinsic types with BooleanLiteral flag\n const flags = type.getFlags();\n if (flags & ts.TypeFlags.BooleanLiteral) {\n const intrinsicName = (type as ts.Type & { intrinsicName?: string })\n .intrinsicName;\n const isTrue = intrinsicName === \"true\";\n return { type: \"boolean\", enum: [isTrue] };\n }\n\n // Handle primitive types\n\n if (flags & ts.TypeFlags.String) {\n return { type: \"string\" };\n }\n\n if (flags & ts.TypeFlags.Number) {\n return { type: \"number\" };\n }\n\n if (flags & ts.TypeFlags.Null) {\n return { type: \"null\" };\n }\n\n if (flags & ts.TypeFlags.Undefined) {\n // undefined is typically filtered out from unions\n return {};\n }\n\n // Handle array types\n // Check both checker.isArrayType and TypeReference patterns\n if (checker.isArrayType(type) || isArrayLikeType(type, checker)) {\n const typeRef = type as ts.TypeReference;\n const typeArgs = checker.getTypeArguments(typeRef);\n if (typeArgs && typeArgs.length > 0) {\n return {\n type: \"array\",\n items: typeToJsonSchema(typeArgs[0]!, ctx),\n };\n }\n // Coverage ignored: Fallback for arrays without type arguments (e.g., broken lib.d.ts)\n /* v8 ignore next */\n return { type: \"array\" };\n }\n\n // Handle object types (interfaces, type literals, classes)\n if (flags & ts.TypeFlags.Object) {\n return handleObjectType(type as ts.ObjectType, ctx);\n }\n\n /* v8 ignore start */\n return {};\n}\n/* v8 ignore end */\n\n/**\n * Handle union types, including optional types (T | undefined).\n */\nfunction handleUnionType(\n type: ts.UnionType,\n ctx: ConversionContext,\n): JsonSchemaProperty {\n const types = type.types;\n\n // Filter out undefined (for optional properties)\n const nonUndefinedTypes = types.filter(\n (t) => !(t.getFlags() & ts.TypeFlags.Undefined),\n );\n\n // Check if this is a boolean type (union of true | false)\n if (\n nonUndefinedTypes.length === 2 &&\n nonUndefinedTypes.every((t) => t.getFlags() & ts.TypeFlags.BooleanLiteral)\n ) {\n return { type: \"boolean\" };\n }\n\n // If all non-undefined types are string/number literals, create an enum\n if (\n nonUndefinedTypes.every((t): t is ts.StringLiteralType =>\n t.isStringLiteral(),\n )\n ) {\n return {\n type: \"string\",\n enum: nonUndefinedTypes.map((t) => t.value),\n };\n }\n\n if (\n nonUndefinedTypes.every((t): t is ts.NumberLiteralType =>\n t.isNumberLiteral(),\n )\n ) {\n return {\n type: \"number\",\n enum: nonUndefinedTypes.map((t) => t.value),\n };\n }\n\n // If only one non-undefined type remains, use it directly\n if (nonUndefinedTypes.length === 1) {\n return typeToJsonSchema(nonUndefinedTypes[0]!, ctx);\n }\n\n // Otherwise, create a oneOf schema\n return {\n oneOf: nonUndefinedTypes.map((t) => typeToJsonSchema(t, ctx)),\n };\n}\n\n/**\n * Handle intersection types by merging properties.\n */\nfunction handleIntersectionType(\n type: ts.IntersectionType,\n ctx: ConversionContext,\n): JsonSchemaProperty {\n const allOf = type.types.map((t) => typeToJsonSchema(t, ctx));\n\n // If all parts are objects, try to merge them\n if (allOf.every((s) => s.type === \"object\")) {\n const merged: JsonSchemaProperty = {\n type: \"object\",\n properties: {},\n required: [],\n };\n\n for (const schema of allOf) {\n if (schema.properties) {\n merged.properties = { ...merged.properties, ...schema.properties };\n }\n if (schema.required) {\n merged.required = [\n ...(merged.required as string[]),\n ...(schema.required as string[]),\n ];\n }\n }\n\n return merged;\n }\n\n return { allOf };\n}\n\n/**\n * Handle literal types (string, number literals).\n * Note: Boolean literals (true/false) are handled earlier via BooleanLiteral flag\n * since TypeScript's isLiteral() doesn't return true for them.\n */\nfunction handleLiteralType(type: ts.Type): JsonSchemaProperty {\n if (type.isStringLiteral()) {\n return { type: \"string\", enum: [type.value] };\n }\n\n if (type.isNumberLiteral()) {\n return { type: \"number\", enum: [type.value] };\n }\n\n /* v8 ignore start */\n return {};\n}\n/* v8 ignore end */\n\n/**\n * Handle object types (interfaces, type literals, classes).\n */\nfunction handleObjectType(\n type: ts.ObjectType,\n ctx: ConversionContext,\n): JsonSchemaProperty {\n const checker = ctx.checker;\n const properties: Record<string, JsonSchemaProperty> = {};\n const required: string[] = [];\n\n // Get all properties of the type\n const props = checker.getPropertiesOfType(type);\n\n for (const prop of props) {\n const propName = prop.getName();\n const propType = checker.getTypeOfSymbol(prop);\n\n // Check if the property is optional\n const isOptional = (prop.getFlags() & ts.SymbolFlags.Optional) !== 0;\n\n // Convert the property type to schema\n const propSchema = typeToJsonSchema(propType, ctx);\n\n // Extract JSDoc description from property declaration\n const jsDocComment = prop.getDocumentationComment(checker);\n if (jsDocComment.length > 0) {\n const description = jsDocComment.map((c) => c.text).join(\"\");\n propSchema.description = description;\n }\n\n properties[propName] = propSchema;\n\n // Add to required if not optional\n if (!isOptional) {\n required.push(propName);\n }\n }\n\n return {\n type: \"object\",\n properties,\n required: required.length > 0 ? required : undefined,\n };\n}\n\n/**\n * Convert a TypeScript type to a ToolParameterSchema.\n *\n * This is the main entry point for converting tool argument types\n * to the schema format expected by LLM providers.\n *\n * @param type - The TypeScript type to convert (should be an object type).\n * @param checker - The TypeScript type checker.\n * @returns The tool parameter schema.\n */\nexport function typeToToolParameterSchema(\n type: ts.Type,\n checker: ts.TypeChecker,\n): ToolParameterSchema {\n const ctx: ConversionContext = {\n checker,\n definitions: new Map(),\n processing: new Set(),\n };\n\n const schema = typeToJsonSchema(type, ctx);\n\n // Ensure the result is an object schema\n if (schema.type !== \"object\") {\n throw new Error(\n \"Tool parameter type must be an object type, got: \" +\n JSON.stringify(schema),\n );\n }\n\n // Build a mutable result, then return as readonly\n const result: {\n type: \"object\";\n properties: Record<string, JsonSchemaProperty>;\n required: readonly string[];\n additionalProperties: false;\n $defs?: Record<string, JsonSchemaProperty>;\n } = {\n type: \"object\",\n properties: schema.properties ?? {},\n required: (schema.required as readonly string[]) ?? [],\n additionalProperties: false,\n };\n\n // Coverage ignored: $defs only populated for recursive types (not yet implemented)\n /* v8 ignore start */\n if (ctx.definitions.size > 0) {\n result.$defs = Object.fromEntries(ctx.definitions);\n }\n /* v8 ignore end */\n\n return result;\n}\n\n/**\n * Create a ConversionContext for testing or manual use.\n */\nexport function createConversionContext(\n checker: ts.TypeChecker,\n): ConversionContext {\n return {\n checker,\n definitions: new Map(),\n processing: new Set(),\n };\n}\n","/**\n * TypeScript transformer for injecting schemas into tool and format definitions.\n *\n * This transformer finds calls to `defineTool<T>()`, `defineContextTool<T, DepsT>()`,\n * and `defineFormat<T>()` and injects the `__schema` property with the JSON schema\n * generated from type T.\n */\n\nimport ts from \"typescript\";\n\nimport { typeToToolParameterSchema } from \"./type-to-schema\";\n\n/**\n * Names of functions that should have schemas injected.\n */\nconst TOOL_FUNCTION_NAMES = new Set([\"defineTool\", \"defineContextTool\"]);\n\n/**\n * Names of format functions that should have schemas injected.\n */\nconst FORMAT_FUNCTION_NAMES = new Set([\"defineFormat\"]);\n\n/**\n * Create a TypeScript transformer that injects __schema into tool definitions.\n *\n * @param program - The TypeScript program.\n * @returns A transformer factory.\n */\nexport function createToolSchemaTransformer(\n program: ts.Program,\n): ts.TransformerFactory<ts.SourceFile> {\n const checker = program.getTypeChecker();\n\n return (context: ts.TransformationContext) => {\n return (sourceFile: ts.SourceFile) => {\n const visitor = (node: ts.Node): ts.Node => {\n // Look for call expressions\n if (ts.isCallExpression(node)) {\n // Try tool transform first\n const toolTransformed = tryTransformToolCall(node, checker, context);\n if (toolTransformed) {\n return toolTransformed;\n }\n\n // Try format transform\n const formatTransformed = tryTransformFormatCall(\n node,\n checker,\n context,\n );\n if (formatTransformed) {\n return formatTransformed;\n }\n }\n\n // Continue visiting children\n return ts.visitEachChild(node, visitor, context);\n };\n\n return ts.visitNode(sourceFile, visitor) as ts.SourceFile;\n };\n };\n}\n\n/**\n * Try to transform a call expression if it's a tool definition.\n *\n * @param node - The call expression node.\n * @param checker - The type checker.\n * @param context - The transformation context.\n * @returns The transformed node, or undefined if not a tool definition.\n */\nfunction tryTransformToolCall(\n node: ts.CallExpression,\n checker: ts.TypeChecker,\n context: ts.TransformationContext,\n): ts.CallExpression | undefined {\n // Check if this is a call to defineTool or defineContextTool\n const functionName = getFunctionName(node);\n if (!functionName || !TOOL_FUNCTION_NAMES.has(functionName)) {\n return undefined;\n }\n\n // Get the type arguments (the generic parameter T)\n const typeArgs = node.typeArguments;\n if (!typeArgs || typeArgs.length === 0) {\n // No type arguments - can't generate schema\n return undefined;\n }\n\n // Get the first type argument (T for args type)\n const argsTypeNode = typeArgs[0]!;\n const argsType = checker.getTypeFromTypeNode(argsTypeNode);\n\n // Generate the schema from the type\n let schema;\n try {\n schema = typeToToolParameterSchema(argsType, checker);\n } catch {\n // If schema generation fails, leave the call unchanged\n return undefined;\n }\n\n // Get the first argument (the options object)\n const args = node.arguments;\n const firstArg = args[0];\n if (!firstArg || !ts.isObjectLiteralExpression(firstArg)) {\n return undefined;\n }\n\n const optionsObject = firstArg;\n\n // Check if __schema is already present\n const hasSchema = optionsObject.properties.some(\n (prop) =>\n ts.isPropertyAssignment(prop) &&\n ts.isIdentifier(prop.name) &&\n prop.name.text === \"__schema\",\n );\n\n if (hasSchema) {\n // Already has a schema, don't override\n return undefined;\n }\n\n // Create the __schema property\n const schemaProperty = createSchemaProperty(schema, context.factory);\n\n // Create a new options object with __schema added\n const newProperties = [...optionsObject.properties, schemaProperty];\n const newOptionsObject = context.factory.updateObjectLiteralExpression(\n optionsObject,\n newProperties,\n );\n\n // Create a new call expression with the updated options\n const newArgs = [newOptionsObject, ...args.slice(1)];\n return context.factory.updateCallExpression(\n node,\n node.expression,\n node.typeArguments,\n newArgs,\n );\n}\n\n/**\n * Try to transform a call expression if it's a format definition.\n *\n * For defineFormat<T>(options):\n * - If the options arg is an object literal, inject __schema from type T\n * - If __schema is already present, leave unchanged\n * - If options has a validator, the validator's schema is used at runtime\n *\n * @param node - The call expression node.\n * @param checker - The type checker.\n * @param context - The transformation context.\n * @returns The transformed node, or undefined if not a format definition.\n */\nfunction tryTransformFormatCall(\n node: ts.CallExpression,\n checker: ts.TypeChecker,\n context: ts.TransformationContext,\n): ts.CallExpression | undefined {\n // Check if this is a call to defineFormat\n const functionName = getFunctionName(node);\n if (!functionName || !FORMAT_FUNCTION_NAMES.has(functionName)) {\n return undefined;\n }\n\n // Get the type arguments (the generic parameter T)\n const typeArgs = node.typeArguments;\n if (!typeArgs || typeArgs.length === 0) {\n // No type arguments - can't generate schema\n return undefined;\n }\n\n // Get the first type argument (T for the output type)\n const outputTypeNode = typeArgs[0]!;\n const outputType = checker.getTypeFromTypeNode(outputTypeNode);\n\n // Get the first argument\n const args = node.arguments;\n const firstArg = args[0];\n if (!firstArg) {\n return undefined;\n }\n\n // If first arg is an object literal (FormatSpec), inject __schema\n if (ts.isObjectLiteralExpression(firstArg)) {\n const formatSpecObject = firstArg;\n\n // Check if __schema is already present\n const hasSchema = formatSpecObject.properties.some(\n (prop) =>\n ts.isPropertyAssignment(prop) &&\n ts.isIdentifier(prop.name) &&\n prop.name.text === \"__schema\",\n );\n\n if (hasSchema) {\n // Already has a schema, don't override\n return undefined;\n }\n\n // Generate the schema from the type\n let schema;\n try {\n schema = typeToToolParameterSchema(outputType, checker);\n } catch {\n // If schema generation fails, leave the call unchanged\n return undefined;\n }\n\n // Create the __schema property\n const schemaProperty = createSchemaProperty(schema, context.factory);\n\n // Create a new format spec object with __schema added\n const newProperties = [...formatSpecObject.properties, schemaProperty];\n const newFormatSpecObject = context.factory.updateObjectLiteralExpression(\n formatSpecObject,\n newProperties,\n );\n\n // Create a new call expression with the updated format spec\n const newArgs = [newFormatSpecObject, ...args.slice(1)];\n return context.factory.updateCallExpression(\n node,\n node.expression,\n node.typeArguments,\n newArgs,\n );\n }\n\n // If first arg is not an object literal (e.g., a Zod schema identifier),\n // leave unchanged - Zod schemas handle their own schema generation\n return undefined;\n}\n\n/**\n * Get the function name from a call expression.\n */\n/* v8 ignore start */\nfunction getFunctionName(node: ts.CallExpression): string | undefined {\n const expression = node.expression;\n\n // Direct call: defineTool(...)\n if (ts.isIdentifier(expression)) {\n return expression.text;\n }\n\n // Property access: llm.defineTool(...)\n if (ts.isPropertyAccessExpression(expression)) {\n return expression.name.text;\n }\n\n return undefined;\n}\n/* v8 ignore end */\n\n/**\n * Create a __schema property assignment from a schema object.\n */\nfunction createSchemaProperty(\n schema: object,\n factory: ts.NodeFactory,\n): ts.PropertyAssignment {\n return factory.createPropertyAssignment(\n factory.createIdentifier(\"__schema\"),\n jsonToAst(schema, factory),\n );\n}\n\n/**\n * Convert a JSON value to a TypeScript AST expression.\n *\n * Coverage notes: Some branches are ignored because JSON Schema values\n * are always one of: null, string, number, boolean, array, or object.\n * The ignored branches handle edge cases that can't occur with valid schemas.\n */\nfunction jsonToAst(value: unknown, factory: ts.NodeFactory): ts.Expression {\n // Coverage ignored: JSON schemas from typeToToolParameterSchema never contain\n // top-level null/undefined values, but we handle them defensively\n /* v8 ignore start */\n if (value === null) {\n return factory.createNull();\n }\n if (value === undefined) {\n return factory.createIdentifier(\"undefined\");\n }\n /* v8 ignore end */\n\n if (typeof value === \"string\") {\n return factory.createStringLiteral(value);\n }\n\n if (typeof value === \"number\") {\n return factory.createNumericLiteral(value);\n }\n\n if (typeof value === \"boolean\") {\n /* v8 ignore next */\n return value ? factory.createTrue() : factory.createFalse();\n }\n\n if (Array.isArray(value)) {\n return factory.createArrayLiteralExpression(\n value.map((item) => jsonToAst(item, factory)),\n );\n }\n\n if (typeof value === \"object\") {\n const properties = Object.entries(value).map(([key, val]) =>\n factory.createPropertyAssignment(\n factory.createIdentifier(key),\n jsonToAst(val, factory),\n ),\n );\n return factory.createObjectLiteralExpression(properties, true);\n }\n\n // Coverage ignored: After handling all JSON-valid types (null, undefined,\n // string, number, boolean, array, object), this is unreachable\n /* v8 ignore next */\n return factory.createIdentifier(\"undefined\");\n}\n\n/**\n * Default export for ts-patch and other transformer loaders.\n */\nexport default function transformer(\n program: ts.Program,\n): ts.TransformerFactory<ts.SourceFile> {\n return createToolSchemaTransformer(program);\n}\n","/**\n * Bun preload plugin for Mirascope tool schema transformation.\n *\n * This plugin intercepts TypeScript file loading and applies the Mirascope\n * transformer to inject tool schemas at runtime.\n *\n * ## Usage\n *\n * Create a preload file (e.g., `preload.ts`):\n * ```typescript\n * import { mirascope } from 'mirascope/bun';\n * mirascope();\n * ```\n *\n * Add to your `bunfig.toml`:\n * ```toml\n * preload = [\"./preload.ts\"]\n * ```\n *\n * Then run your files normally:\n * ```bash\n * bun run my-file.ts\n * ```\n */\n\n/* eslint-disable @typescript-eslint/unbound-method */\nimport { plugin } from \"bun\";\nimport { readFileSync } from \"fs\";\nimport { resolve, dirname } from \"path\";\nimport ts from \"typescript\";\n\nimport { createToolSchemaTransformer } from \"./transform/transformer\";\n\n/**\n * Options for the Mirascope Bun plugin.\n */\nexport interface MirascopeBunPluginOptions {\n /**\n * File filter pattern. Defaults to /\\.tsx?$/\n */\n filter?: RegExp;\n\n /**\n * Patterns to exclude. Files matching these won't be transformed.\n * Defaults to [/node_modules/]\n */\n exclude?: RegExp[];\n}\n\n/**\n * Check if a file contains defineTool, defineContextTool, or defineFormat calls.\n * Quick regex check to avoid expensive TypeScript compilation for files that don't need it.\n */\nfunction needsTransform(contents: string): boolean {\n return /\\bdefineTool\\b|\\bdefineContextTool\\b|\\bdefineFormat\\b/.test(contents);\n}\n\n/**\n * Transform TypeScript source code to inject tool schemas.\n */\nfunction transformSource(\n filePath: string,\n contents: string,\n): string | undefined {\n // Find tsconfig.json\n const configPath = ts.findConfigFile(\n dirname(filePath),\n ts.sys.fileExists,\n \"tsconfig.json\",\n );\n\n const compilerOptions: ts.CompilerOptions = {\n target: ts.ScriptTarget.ESNext,\n module: ts.ModuleKind.ESNext,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n esModuleInterop: true,\n strict: true,\n };\n\n // Load tsconfig if found\n if (configPath) {\n const configFile = ts.readConfigFile(configPath, ts.sys.readFile);\n if (!configFile.error) {\n const parsed = ts.parseJsonConfigFileContent(\n configFile.config,\n ts.sys,\n dirname(configPath),\n );\n Object.assign(compilerOptions, parsed.options);\n }\n }\n\n // Create a program with just this file\n const host = ts.createCompilerHost(compilerOptions);\n const originalGetSourceFile = host.getSourceFile;\n\n // Override to provide our in-memory source\n host.getSourceFile = (\n fileName: string,\n languageVersion: ts.ScriptTarget,\n onError?: (message: string) => void,\n shouldCreateNewSourceFile?: boolean,\n ) => {\n if (resolve(fileName) === resolve(filePath)) {\n return ts.createSourceFile(fileName, contents, languageVersion, true);\n }\n return originalGetSourceFile(\n fileName,\n languageVersion,\n onError,\n shouldCreateNewSourceFile,\n );\n };\n\n const program = ts.createProgram([filePath], compilerOptions, host);\n const sourceFile = program.getSourceFile(filePath);\n\n if (!sourceFile) {\n return undefined;\n }\n\n // Apply the transformer\n const transformer = createToolSchemaTransformer(program);\n const result = ts.transform(sourceFile, [transformer]);\n const transformedSourceFile = result.transformed[0];\n\n if (!transformedSourceFile) {\n result.dispose();\n return undefined;\n }\n\n // Print the transformed source back to string\n const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });\n const output = printer.printFile(transformedSourceFile);\n\n result.dispose();\n return output;\n}\n\n/**\n * Register the Mirascope Bun plugin for tool schema transformation.\n *\n * @param options - Plugin options.\n *\n * @example\n * ```typescript\n * // preload.ts\n * import { mirascope } from 'mirascope/bun';\n * mirascope();\n * ```\n */\nexport function mirascope(options: MirascopeBunPluginOptions = {}): void {\n const { filter = /\\.tsx?$/, exclude = [/node_modules/] } = options;\n\n plugin({\n name: \"mirascope\",\n setup(build) {\n build.onLoad({ filter }, (args) => {\n // Check exclusions - let Bun handle these normally\n for (const pattern of exclude) {\n if (pattern.test(args.path)) {\n // Return undefined to let Bun handle it normally\n return;\n }\n }\n\n const contents = readFileSync(args.path, \"utf-8\");\n const loader = args.path.endsWith(\".tsx\") ? \"tsx\" : \"ts\";\n\n // Quick check: skip files without tool definitions\n if (!needsTransform(contents)) {\n // Return original contents to keep Bun happy\n return { contents, loader };\n }\n\n const transformed = transformSource(args.path, contents);\n\n // Return transformed or original contents\n return {\n contents: transformed ?? contents,\n loader,\n };\n });\n },\n });\n}\n\nexport default mirascope;\n"]}
package/dist/bun.d.cts ADDED
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Bun preload plugin for Mirascope tool schema transformation.
3
+ *
4
+ * This plugin intercepts TypeScript file loading and applies the Mirascope
5
+ * transformer to inject tool schemas at runtime.
6
+ *
7
+ * ## Usage
8
+ *
9
+ * Create a preload file (e.g., `preload.ts`):
10
+ * ```typescript
11
+ * import { mirascope } from 'mirascope/bun';
12
+ * mirascope();
13
+ * ```
14
+ *
15
+ * Add to your `bunfig.toml`:
16
+ * ```toml
17
+ * preload = ["./preload.ts"]
18
+ * ```
19
+ *
20
+ * Then run your files normally:
21
+ * ```bash
22
+ * bun run my-file.ts
23
+ * ```
24
+ */
25
+ /**
26
+ * Options for the Mirascope Bun plugin.
27
+ */
28
+ interface MirascopeBunPluginOptions {
29
+ /**
30
+ * File filter pattern. Defaults to /\.tsx?$/
31
+ */
32
+ filter?: RegExp;
33
+ /**
34
+ * Patterns to exclude. Files matching these won't be transformed.
35
+ * Defaults to [/node_modules/]
36
+ */
37
+ exclude?: RegExp[];
38
+ }
39
+ /**
40
+ * Register the Mirascope Bun plugin for tool schema transformation.
41
+ *
42
+ * @param options - Plugin options.
43
+ *
44
+ * @example
45
+ * ```typescript
46
+ * // preload.ts
47
+ * import { mirascope } from 'mirascope/bun';
48
+ * mirascope();
49
+ * ```
50
+ */
51
+ declare function mirascope(options?: MirascopeBunPluginOptions): void;
52
+
53
+ export { type MirascopeBunPluginOptions, mirascope as default, mirascope };
package/dist/bun.d.ts ADDED
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Bun preload plugin for Mirascope tool schema transformation.
3
+ *
4
+ * This plugin intercepts TypeScript file loading and applies the Mirascope
5
+ * transformer to inject tool schemas at runtime.
6
+ *
7
+ * ## Usage
8
+ *
9
+ * Create a preload file (e.g., `preload.ts`):
10
+ * ```typescript
11
+ * import { mirascope } from 'mirascope/bun';
12
+ * mirascope();
13
+ * ```
14
+ *
15
+ * Add to your `bunfig.toml`:
16
+ * ```toml
17
+ * preload = ["./preload.ts"]
18
+ * ```
19
+ *
20
+ * Then run your files normally:
21
+ * ```bash
22
+ * bun run my-file.ts
23
+ * ```
24
+ */
25
+ /**
26
+ * Options for the Mirascope Bun plugin.
27
+ */
28
+ interface MirascopeBunPluginOptions {
29
+ /**
30
+ * File filter pattern. Defaults to /\.tsx?$/
31
+ */
32
+ filter?: RegExp;
33
+ /**
34
+ * Patterns to exclude. Files matching these won't be transformed.
35
+ * Defaults to [/node_modules/]
36
+ */
37
+ exclude?: RegExp[];
38
+ }
39
+ /**
40
+ * Register the Mirascope Bun plugin for tool schema transformation.
41
+ *
42
+ * @param options - Plugin options.
43
+ *
44
+ * @example
45
+ * ```typescript
46
+ * // preload.ts
47
+ * import { mirascope } from 'mirascope/bun';
48
+ * mirascope();
49
+ * ```
50
+ */
51
+ declare function mirascope(options?: MirascopeBunPluginOptions): void;
52
+
53
+ export { type MirascopeBunPluginOptions, mirascope as default, mirascope };