@skmtc/core 0.0.794 → 0.0.796

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,14 +3,183 @@ import { camelCase } from 'lodash-es';
3
3
  import { match, P } from 'ts-pattern';
4
4
  import { List } from './List.js';
5
5
  import { isEmpty } from '../helpers/isEmpty.js';
6
+ /**
7
+ * Generates TypeScript function parameters with advanced handling for different parameter patterns.
8
+ *
9
+ * `FunctionParameter` is a sophisticated utility for generating TypeScript function parameter
10
+ * syntax that handles multiple parameter patterns including named parameters, destructured
11
+ * object parameters, and void parameters. It provides intelligent type handling and can
12
+ * generate both the parameter declaration and the parameter usage patterns.
13
+ *
14
+ * This class is essential for generating type-safe function signatures in API clients,
15
+ * utility functions, and other generated code where parameters need to be handled
16
+ * consistently and safely.
17
+ *
18
+ * ## Supported Parameter Patterns
19
+ *
20
+ * - **Named Parameters**: Traditional `paramName: Type` syntax
21
+ * - **Destructured Parameters**: `{ prop1, prop2 }: ObjectType` syntax
22
+ * - **Void Parameters**: No parameters when dealing with void types
23
+ * - **Optional Parameters**: Automatic handling of optional parameter markers
24
+ * - **Empty Filtering**: Option to skip empty properties in destructured objects
25
+ *
26
+ * @example Named parameter generation
27
+ * ```typescript
28
+ * import { FunctionParameter, Definition, Identifier } from '@skmtc/core';
29
+ *
30
+ * const userIdParam = new FunctionParameter({
31
+ * name: 'userId',
32
+ * typeDefinition: new Definition({
33
+ * context: generateContext,
34
+ * identifier: Identifier.createType('string'),
35
+ * value: { type: 'string' }
36
+ * }),
37
+ * required: true
38
+ * });
39
+ *
40
+ * console.log(userIdParam.toString()); // 'userId: string'
41
+ * console.log(userIdParam.toInbound()); // 'userId'
42
+ * ```
43
+ *
44
+ * @example Destructured parameter generation
45
+ * ```typescript
46
+ * const destructuredParam = new FunctionParameter({
47
+ * typeDefinition: new Definition({
48
+ * context: generateContext,
49
+ * identifier: Identifier.createType('UserParams'),
50
+ * value: {
51
+ * type: 'object',
52
+ * objectProperties: {
53
+ * properties: {
54
+ * name: { type: 'string' },
55
+ * email: { type: 'string' },
56
+ * age: { type: 'number' }
57
+ * }
58
+ * }
59
+ * }
60
+ * }),
61
+ * destructure: true,
62
+ * required: true
63
+ * });
64
+ *
65
+ * console.log(destructuredParam.toString());
66
+ * // '{ name, email, age }: UserParams'
67
+ *
68
+ * console.log(destructuredParam.toInbound());
69
+ * // '{ name, email, age }'
70
+ * ```
71
+ *
72
+ * @example Optional parameter handling
73
+ * ```typescript
74
+ * const optionalParam = new FunctionParameter({
75
+ * name: 'options',
76
+ * typeDefinition: optionsTypeDefinition,
77
+ * required: false
78
+ * });
79
+ *
80
+ * console.log(optionalParam.toString()); // 'options?: OptionsType'
81
+ * ```
82
+ *
83
+ * @example Void parameter handling
84
+ * ```typescript
85
+ * const voidParam = new FunctionParameter({
86
+ * typeDefinition: new Definition({
87
+ * context: generateContext,
88
+ * identifier: Identifier.createType('void'),
89
+ * value: { type: 'void' }
90
+ * })
91
+ * });
92
+ *
93
+ * console.log(voidParam.toString()); // ''
94
+ * console.log(voidParam.toInbound()); // ''
95
+ * ```
96
+ *
97
+ * @example Property checking
98
+ * ```typescript
99
+ * const objectParam = new FunctionParameter({
100
+ * typeDefinition: userTypeDefinition,
101
+ * destructure: true,
102
+ * required: true
103
+ * });
104
+ *
105
+ * if (objectParam.hasProperty('email')) {
106
+ * // Handle email property access
107
+ * console.log('Parameter includes email property');
108
+ * }
109
+ *
110
+ * const propertyList = objectParam.toPropertyList();
111
+ * console.log(propertyList.toString()); // 'name, email, age'
112
+ * ```
113
+ *
114
+ * @example API method generation with parameters
115
+ * ```typescript
116
+ * class ApiMethodGenerator {
117
+ * generateMethod(
118
+ * methodName: string,
119
+ * pathParams?: FunctionParameter,
120
+ * bodyParam?: FunctionParameter
121
+ * ) {
122
+ * const parameters = [pathParams, bodyParam]
123
+ * .filter(p => p && p.toString())
124
+ * .map(p => p!.toString())
125
+ * .join(', ');
126
+ *
127
+ * const pathInbound = pathParams?.toInbound() || '';
128
+ * const bodyInbound = bodyParam?.toInbound() || '';
129
+ *
130
+ * return `
131
+ * async ${methodName}(${parameters}) {
132
+ * const path = this.buildPath(${pathInbound});
133
+ * return this.request('POST', path, ${bodyInbound});
134
+ * }`;
135
+ * }
136
+ * }
137
+ * ```
138
+ *
139
+ * @example Empty property filtering
140
+ * ```typescript
141
+ * const filteredParam = new FunctionParameter({
142
+ * typeDefinition: sparseObjectDefinition,
143
+ * destructure: true,
144
+ * required: true,
145
+ * skipEmpty: true // Skip properties with empty types
146
+ * });
147
+ *
148
+ * // Only non-empty properties will be included in destructuring
149
+ * console.log(filteredParam.toString());
150
+ * // '{ validProp1, validProp2 }: FilteredType' (empty props omitted)
151
+ * ```
152
+ */
6
153
  export class FunctionParameter {
154
+ /**
155
+ * Creates a new FunctionParameter instance with the specified configuration.
156
+ *
157
+ * The constructor analyzes the provided type definition and configuration options
158
+ * to determine the appropriate parameter pattern (void, regular, or destructured).
159
+ * It handles the complex logic of parameter type determination and validation.
160
+ *
161
+ * @param args - Configuration options for the function parameter
162
+ *
163
+ * @throws {Error} When the parameter configuration is invalid
164
+ *
165
+ * @example
166
+ * ```typescript
167
+ * const param = new FunctionParameter({
168
+ * name: 'userData',
169
+ * typeDefinition: userTypeDefinition,
170
+ * required: true
171
+ * });
172
+ * ```
173
+ */
7
174
  constructor(args) {
175
+ /** The internal parameter configuration determining how the parameter is generated */
8
176
  Object.defineProperty(this, "properties", {
9
177
  enumerable: true,
10
178
  configurable: true,
11
179
  writable: true,
12
180
  value: void 0
13
181
  });
182
+ /** Whether to skip empty properties in destructured parameters */
14
183
  Object.defineProperty(this, "skipEmpty", {
15
184
  enumerable: true,
16
185
  configurable: true,
@@ -39,6 +208,34 @@ export class FunctionParameter {
39
208
  this.properties = { type: 'void' };
40
209
  }
41
210
  }
211
+ /**
212
+ * Checks if the parameter has a specific property (for object-based parameters).
213
+ *
214
+ * This method determines whether a given property name exists within the parameter's
215
+ * type structure. It's useful for conditional code generation based on available
216
+ * properties and only returns true for object-based parameters (regular object
217
+ * parameters or destructured parameters).
218
+ *
219
+ * @param name - The property name to check for
220
+ * @returns True if the property exists in the parameter's type structure
221
+ *
222
+ * @example
223
+ * ```typescript
224
+ * const userParam = new FunctionParameter({
225
+ * typeDefinition: userTypeDefinition, // has properties: name, email, age
226
+ * destructure: true,
227
+ * required: true
228
+ * });
229
+ *
230
+ * if (userParam.hasProperty('email')) {
231
+ * console.log('Parameter includes email property');
232
+ * }
233
+ *
234
+ * if (userParam.hasProperty('nonexistent')) {
235
+ * // This won't execute
236
+ * }
237
+ * ```
238
+ */
42
239
  hasProperty(name) {
43
240
  return match(this.properties)
44
241
  .with({ type: 'void' }, () => false)
@@ -51,6 +248,37 @@ export class FunctionParameter {
51
248
  })
52
249
  .exhaustive();
53
250
  }
251
+ /**
252
+ * Generates a List of property names from the parameter.
253
+ *
254
+ * This method extracts property names from object-based parameters and returns
255
+ * them as a List instance. For regular parameters, it returns the parameter name,
256
+ * for destructured parameters it returns all object properties, and for void
257
+ * parameters it returns an empty list.
258
+ *
259
+ * @returns List containing the relevant property or parameter names
260
+ *
261
+ * @example
262
+ * ```typescript
263
+ * const destructuredParam = new FunctionParameter({
264
+ * typeDefinition: userTypeDefinition, // has properties: name, email, age
265
+ * destructure: true,
266
+ * required: true
267
+ * });
268
+ *
269
+ * const propertyList = destructuredParam.toPropertyList();
270
+ * console.log(propertyList.toString()); // 'name, email, age'
271
+ *
272
+ * const regularParam = new FunctionParameter({
273
+ * name: 'userData',
274
+ * typeDefinition: userTypeDefinition,
275
+ * required: true
276
+ * });
277
+ *
278
+ * const regularList = regularParam.toPropertyList();
279
+ * console.log(regularList.toString()); // 'userData'
280
+ * ```
281
+ */
54
282
  toPropertyList() {
55
283
  return match(this.properties)
56
284
  .with({ type: 'void' }, () => List.toEmpty())
@@ -60,6 +288,35 @@ export class FunctionParameter {
60
288
  })
61
289
  .exhaustive();
62
290
  }
291
+ /**
292
+ * Generates the inbound parameter syntax for function calls.
293
+ *
294
+ * This method produces the syntax used when calling a function with this parameter.
295
+ * For regular parameters, it returns the parameter name. For destructured parameters,
296
+ * it returns the destructured object syntax. For void parameters, it returns an
297
+ * empty string.
298
+ *
299
+ * @returns The inbound parameter syntax string
300
+ *
301
+ * @example
302
+ * ```typescript
303
+ * const regularParam = new FunctionParameter({
304
+ * name: 'userId',
305
+ * typeDefinition: stringTypeDefinition,
306
+ * required: true
307
+ * });
308
+ *
309
+ * console.log(regularParam.toInbound()); // 'userId'
310
+ *
311
+ * const destructuredParam = new FunctionParameter({
312
+ * typeDefinition: userTypeDefinition,
313
+ * destructure: true,
314
+ * required: true
315
+ * });
316
+ *
317
+ * console.log(destructuredParam.toInbound()); // '{ name, email, age }'
318
+ * ```
319
+ */
63
320
  toInbound() {
64
321
  return match(this.properties)
65
322
  .with({ type: 'void' }, () => '')
@@ -69,6 +326,42 @@ export class FunctionParameter {
69
326
  })
70
327
  .exhaustive();
71
328
  }
329
+ /**
330
+ * Generates the complete function parameter declaration syntax.
331
+ *
332
+ * This method produces the full parameter declaration that appears in a function
333
+ * signature, including the parameter name, type annotation, and optional markers.
334
+ * It handles all parameter patterns supported by the class.
335
+ *
336
+ * @returns The complete parameter declaration string
337
+ *
338
+ * @example
339
+ * ```typescript
340
+ * const requiredParam = new FunctionParameter({
341
+ * name: 'userId',
342
+ * typeDefinition: stringTypeDefinition,
343
+ * required: true
344
+ * });
345
+ *
346
+ * console.log(requiredParam.toString()); // 'userId: string'
347
+ *
348
+ * const optionalParam = new FunctionParameter({
349
+ * name: 'options',
350
+ * typeDefinition: optionsTypeDefinition,
351
+ * required: false
352
+ * });
353
+ *
354
+ * console.log(optionalParam.toString()); // 'options?: OptionsType'
355
+ *
356
+ * const destructuredParam = new FunctionParameter({
357
+ * typeDefinition: userTypeDefinition,
358
+ * destructure: true,
359
+ * required: true
360
+ * });
361
+ *
362
+ * console.log(destructuredParam.toString()); // '{ name, email, age }: UserType'
363
+ * ```
364
+ */
72
365
  toString() {
73
366
  return match(this.properties)
74
367
  .with({ type: 'void' }, () => '')
@@ -86,6 +379,41 @@ export class FunctionParameter {
86
379
  .exhaustive();
87
380
  }
88
381
  }
382
+ /**
383
+ * Generates destructured object parameter syntax from a type definition.
384
+ *
385
+ * This helper function creates the destructured parameter syntax for object types,
386
+ * handling property name validation and optional camelCase conversion for invalid
387
+ * JavaScript identifiers. It integrates with the List system to produce properly
388
+ * formatted destructured parameter lists.
389
+ *
390
+ * @param typeDefinition - The object type definition to destructure
391
+ * @param options - Options for controlling the destructuring behavior
392
+ * @param options.skipEmpty - Whether to skip empty properties
393
+ * @returns List instance representing the destructured parameter structure
394
+ *
395
+ * @example
396
+ * ```typescript
397
+ * const objectDef = new Definition({
398
+ * context: generateContext,
399
+ * identifier: Identifier.createType('ApiParams'),
400
+ * value: {
401
+ * type: 'object',
402
+ * objectProperties: {
403
+ * properties: {
404
+ * 'user-id': { type: 'string' },
405
+ * 'valid_name': { type: 'string' },
406
+ * 'api-key': { type: 'string' }
407
+ * }
408
+ * }
409
+ * }
410
+ * });
411
+ *
412
+ * const result = toDestructured(objectDef);
413
+ * console.log(result.toString());
414
+ * // "{ 'user-id': userId, valid_name, 'api-key': apiKey }"
415
+ * ```
416
+ */
89
417
  const toDestructured = (typeDefinition, { skipEmpty } = {}) => {
90
418
  return List.fromKeys(typeDefinition.value.objectProperties?.properties).toObject(key => {
91
419
  return isIdentifierName(key) ? key : List.toKeyValue(key, camelCase(key));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@skmtc/core",
3
- "version": "0.0.794",
3
+ "version": "0.0.796",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/skmtc/skmtc.git"
@@ -3,17 +3,169 @@ import type { LogRecord } from '../deps/jsr.io/@std/log/0.224.14/logger.js';
3
3
  import { BaseHandler } from '../deps/jsr.io/@std/log/0.224.14/base_handler.js';
4
4
  import type { BaseHandlerOptions } from '../deps/jsr.io/@std/log/0.224.14/base_handler.js';
5
5
  import type { CoreContext } from './CoreContext.js';
6
+ /**
7
+ * Configuration options for the {@link ResultsHandler}.
8
+ */
6
9
  export interface ResultsHandlerOptions extends BaseHandlerOptions {
10
+ /** The CoreContext instance to capture results to */
7
11
  context: CoreContext;
8
12
  }
13
+ /**
14
+ * Custom log handler that captures warning and error results for SKMTC processing.
15
+ *
16
+ * The `ResultsHandler` extends Deno's standard library BaseHandler to provide
17
+ * specialized logging behavior for the SKMTC pipeline. It integrates with the
18
+ * CoreContext to capture warnings and errors as structured results that can be
19
+ * analyzed and reported after processing completes.
20
+ *
21
+ * This handler ensures that important processing issues are captured and stored
22
+ * in the context's results system rather than just being logged to the console.
23
+ *
24
+ * ## Key Features
25
+ *
26
+ * - **Result Capture**: Automatically captures WARN and ERROR logs as results
27
+ * - **Immediate Flushing**: Critical errors trigger immediate flush
28
+ * - **Lifecycle Management**: Proper setup and cleanup with event handlers
29
+ * - **Context Integration**: Seamlessly integrates with CoreContext results system
30
+ *
31
+ * @example Setting up the handler
32
+ * ```typescript
33
+ * import { getLogger } from '@std/log';
34
+ * import { ResultsHandler, CoreContext } from '@skmtc/core';
35
+ *
36
+ * const context = new CoreContext({
37
+ * // ... context options
38
+ * });
39
+ *
40
+ * const handler = new ResultsHandler('WARN', {
41
+ * context: context,
42
+ * formatter: '[{levelName}] {msg}'
43
+ * });
44
+ *
45
+ * const logger = getLogger();
46
+ * logger.addHandler(handler);
47
+ *
48
+ * // Now warnings and errors will be captured as results
49
+ * logger.warning('Schema validation issue detected');
50
+ * logger.error('Failed to process operation');
51
+ * ```
52
+ *
53
+ * @example Integration in pipeline
54
+ * ```typescript
55
+ * class ProcessingPipeline {
56
+ * async process(document: OasDocument) {
57
+ * const context = new CoreContext(options);
58
+ *
59
+ * // Set up results handler
60
+ * const handler = new ResultsHandler('WARN', { context });
61
+ * const logger = getLogger();
62
+ * logger.addHandler(handler);
63
+ *
64
+ * try {
65
+ * const result = await this.processDocument(document, context);
66
+ *
67
+ * // Check captured results
68
+ * if (context.results.hasWarnings()) {
69
+ * console.log('Processing completed with warnings');
70
+ * }
71
+ *
72
+ * return result;
73
+ * } finally {
74
+ * handler.destroy();
75
+ * }
76
+ * }
77
+ * }
78
+ * ```
79
+ */
9
80
  export declare class ResultsHandler extends BaseHandler {
10
81
  #private;
82
+ /** The CoreContext instance for capturing results */
11
83
  context: CoreContext;
84
+ /**
85
+ * Creates a new ResultsHandler instance.
86
+ *
87
+ * @param levelName - The minimum log level to handle
88
+ * @param options - Handler configuration including CoreContext
89
+ *
90
+ * @example
91
+ * ```typescript
92
+ * const context = new CoreContext(contextOptions);
93
+ * const handler = new ResultsHandler('WARN', {
94
+ * context,
95
+ * formatter: '[{levelName}] {msg}'
96
+ * });
97
+ * ```
98
+ */
12
99
  constructor(levelName: LevelName, options: ResultsHandlerOptions);
100
+ /**
101
+ * Sets up the handler with event listeners.
102
+ *
103
+ * Registers cleanup callbacks for process termination to ensure
104
+ * proper resource cleanup and result flushing.
105
+ *
106
+ * @override
107
+ */
13
108
  setup(): void;
109
+ /**
110
+ * Handles incoming log records.
111
+ *
112
+ * Processes log records through the base handler and triggers
113
+ * immediate flushing for critical errors above ERROR level.
114
+ *
115
+ * @param logRecord - The log record to handle
116
+ *
117
+ * @override
118
+ */
14
119
  handle(logRecord: LogRecord): void;
120
+ /**
121
+ * Captures log messages as results in the context.
122
+ *
123
+ * Converts log level names to result types and captures them
124
+ * in the associated CoreContext for later analysis.
125
+ *
126
+ * @param levelName - The log level name ('WARN' or 'ERROR')
127
+ *
128
+ * @throws {Error} When an unsupported log level is provided
129
+ *
130
+ * @example
131
+ * ```typescript
132
+ * // This is called automatically by the logging system
133
+ * handler.log('WARN'); // Captures as 'warning' result
134
+ * handler.log('ERROR'); // Captures as 'error' result
135
+ * ```
136
+ */
15
137
  log(levelName: string): void;
138
+ /**
139
+ * Flushes any buffered content.
140
+ *
141
+ * This implementation resets the internal buffer. Override
142
+ * this method in subclasses to implement custom flushing behavior.
143
+ *
144
+ * @override
145
+ */
16
146
  flush(): void;
147
+ /**
148
+ * Destroys the handler and cleans up resources.
149
+ *
150
+ * Flushes any remaining content and removes event listeners
151
+ * to prevent memory leaks.
152
+ *
153
+ * @override
154
+ *
155
+ * @example
156
+ * ```typescript
157
+ * const handler = new ResultsHandler('WARN', { context });
158
+ *
159
+ * try {
160
+ * // Use handler
161
+ * logger.addHandler(handler);
162
+ * await processDocument();
163
+ * } finally {
164
+ * // Always clean up
165
+ * handler.destroy();
166
+ * }
167
+ * ```
168
+ */
17
169
  destroy(): void;
18
170
  }
19
171
  //# sourceMappingURL=ResultsHandler.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"ResultsHandler.d.ts","sourceRoot":"","sources":["../../src/context/ResultsHandler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,SAAS,EAAa,MAAM,4CAA4C,CAAA;AACtF,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,4CAA4C,CAAA;AAC3E,OAAO,EAAE,WAAW,EAAE,MAAM,kDAAkD,CAAA;AAC9E,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,kDAAkD,CAAA;AAC1F,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAA;AAGnD,MAAM,WAAW,qBAAsB,SAAQ,kBAAkB;IAC/D,OAAO,EAAE,WAAW,CAAA;CACrB;AAED,qBAAa,cAAe,SAAQ,WAAW;;IAC7C,OAAO,EAAE,WAAW,CAAA;gBAMR,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,qBAAqB;IAMvD,KAAK;IAML,MAAM,CAAC,SAAS,EAAE,SAAS;IASpC,GAAG,CAAC,SAAS,EAAE,MAAM;IAWrB,KAAK;IAMI,OAAO;CAKjB"}
1
+ {"version":3,"file":"ResultsHandler.d.ts","sourceRoot":"","sources":["../../src/context/ResultsHandler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,SAAS,EAAa,MAAM,4CAA4C,CAAA;AACtF,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,4CAA4C,CAAA;AAC3E,OAAO,EAAE,WAAW,EAAE,MAAM,kDAAkD,CAAA;AAC9E,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,kDAAkD,CAAA;AAC1F,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAA;AAGnD;;GAEG;AACH,MAAM,WAAW,qBAAsB,SAAQ,kBAAkB;IAC/D,qDAAqD;IACrD,OAAO,EAAE,WAAW,CAAA;CACrB;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkEG;AACH,qBAAa,cAAe,SAAQ,WAAW;;IAC7C,qDAAqD;IACrD,OAAO,EAAE,WAAW,CAAA;IAOpB;;;;;;;;;;;;;;OAcG;gBACS,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,qBAAqB;IAMhE;;;;;;;OAOG;IACM,KAAK;IAMd;;;;;;;;;OASG;IACM,MAAM,CAAC,SAAS,EAAE,SAAS;IASpC;;;;;;;;;;;;;;;;OAgBG;IACH,GAAG,CAAC,SAAS,EAAE,MAAM;IAWrB;;;;;;;OAOG;IACH,KAAK;IAWL;;;;;;;;;;;;;;;;;;;;;OAqBG;IACM,OAAO;CAKjB"}