@progress/kendo-react-mcp 1.0.4 → 1.0.5

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/LICENSE.md ADDED
@@ -0,0 +1,15 @@
1
+ This project has been released under the [Apache License, version 2.0](http://www.apache.org/licenses/LICENSE-2.0.html), the text of which is included below. This license applies ONLY to the source of this repository and does not extend to any other Kendo UI distribution or variant, or any other 3rd party libraries used in a repository. For licensing information about KendoReact, see the [License Agreements page](https://www.telerik.com/purchase/license-agreement/progress-kendoreact).
2
+
3
+ > Copyright © 2025 Progress Software Corporation and/or its subsidiaries or affiliates.
4
+
5
+ > Licensed under the Apache License, Version 2.0 (the "License");
6
+ > you may not use this file except in compliance with the License.
7
+ > You may obtain a copy of the License at
8
+
9
+ > [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
10
+
11
+ > Unless required by applicable law or agreed to in writing, software
12
+ > distributed under the License is distributed on an "AS IS" BASIS,
13
+ > WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ > See the License for the specific language governing permissions and
15
+ > limitations under the License.
package/dist/index.js CHANGED
@@ -1,23 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
3
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
4
- import { z } from 'zod';
5
- import { ReactComponents, Suite, GrpcErrors, REACT_SUITE_NAME, } from './lib/constants.js';
6
- import { query as contextApiQuery } from './lib/grpc-client.js';
7
- import fs from 'fs';
8
- import path from 'path';
9
- import { fileURLToPath } from 'url';
10
- import { log } from './lib/logger.js';
11
- import { LicenseError } from './lib/read-license.js';
12
- const __filename = fileURLToPath(import.meta.url);
13
- const __dirname = path.dirname(__filename);
14
- const packageJsonPath = path.resolve(__dirname, '../package.json');
15
- const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));
16
- const server = new McpServer({
17
- name: 'kendo-and-kendo-resources',
18
- version: packageJson.version,
19
- });
20
- server.tool('kendo_react_assistant', `Answers questions and retrieves documentation about Kendo UI for React.
2
+ var A=Object.defineProperty;var _=(e,r,o)=>r in e?A(e,r,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[r]=o;var u=(e,r,o)=>_(e,typeof r!="symbol"?r+"":r,o);import{McpServer as M}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as O}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as T}from"zod";var h="Kendo UI for React",g="react",S=["ActionSheet","AIPrompt","Animation","AppBar","ArcGauge","AutoComplete","Avatar","Badge","Barcode","BottomNavigation","Breadcrumb","Button","ButtonGroup","Calendar","Card","Chart","Checkbox","Chip","ChipList","ChunkProgressBar","CircularGauge","ColorGradient","ColorPalette","ColorPicker","ComboBox","ContextMenu","ConversationalUI","DataGrid","Grid","DataQuery","DateMath","DateInput","DatePicker","DateRangePicker","DateTimePicker","Dialog","Drag&Drop","Drawer","Drawing","DropDownButton","DropDownList","DropDownTree","Editor","Error","ExcelExport","ExpansionPanel","ExternalDropZone","FileSaver","FileManager","Filter","FlatColorPicker","FloatingActionButton","FloatingLabel","FontIcon","Form","Gantt","Gauge","General","GridLayout","Hint","Input","Label","LinearGauge","ListBox","ListView","Loader","Map","MaskedTextBox","Menu","MultiColumnComboBox","MultiSelect","MultiSelectTree","MultiViewCalendar","Notification","NumericTextBox","OrgChart","PageTemplates/BuildingBlocks","Pager","PanelBar","PDFProcessing","PDFViewer","PivotGrid","Popover","Popup","ProgressBar","QRCode","RadialGauge","RadioButton","RadioGroup","RangeSlider","Rating","Ripple","Sankey","Scheduler","ScrollView","Signature","Skeleton","Slider","Sortable","Sparkline","SplitButton","Splitter","Spreadsheet","StackLayout","Stepper","StockChart","SVGIcon","Switch","TabStrip","TaskBoard","TextArea","TextBox","TileLayout","Timeline","TimePicker","Toolbar","Tooltip","TreeList","TreeView","Typography","Upload","VSCodeExtension","Window"];import{dirname as N,join as B}from"path";import{fileURLToPath as G}from"url";import{readFileSync as L}from"node:fs";import a from"node:fs";import p from"node:path";import U from"@grpc/proto-loader";import l from"@grpc/grpc-js";var E=["TELERIK_LICENSE","KENDO_UI_LICENSE"],y="TELERIK_LICENSE_PATH",c=(e=>(e[e.UNAUTHENTICATED=16]="UNAUTHENTICATED",e[e.RESOURCE_EXHAUSTED=8]="RESOURCE_EXHAUSTED",e[e.PERMISSION_DENIED=7]="PERMISSION_DENIED",e))(c||{}),v=!1,i=process.env.DEBUG_LOG_FILE,x=!!(i&&typeof i=="string");if(x){let e=p.resolve(i),r=p.dirname(e);if(r!=="."&&r!==process.cwd()&&!a.existsSync(r))try{a.mkdirSync(r,{recursive:!0})}catch(o){console.error("Error creating log directory:",o)}if(!a.existsSync(e))try{a.writeFileSync(e,"")}catch(o){console.error("Error creating log file:",o)}}v=x&&!!i&&a.existsSync(p.resolve(i));function n(...e){if(v&&i){let r=`${new Date().toISOString()}: ${e.join(" ")}
3
+ `,o=p.resolve(i);a.appendFile(o,r,t=>{t&&console.error("Error writing to log file:",t)})}}var s=process.env[y],m=process.env[E[0]]||process.env[E[1]],d=class extends Error{constructor(e){super(e),this.name="LicenseError"}};function R(){if(!s&&!m)throw new d(`No license found. Please set one of the following environment variables: ${E.join(", ")} or ${y}`);let e;if(s)try{e=L(s,"utf8"),n("License key read from file: ",s)}catch{throw new d(`Error reading license file: ${s}. Please verify the file exists and is readable.`)}return m&&(e=m,n("License key read from environment variable.")),e}var k=class{constructor(e,r){u(this,"client");u(this,"isDev");this.contextApiUrl=e,this.protoPath=r;let o=U.loadSync(this.protoPath,{keepCase:!0,longs:String,enums:String,defaults:!0,oneofs:!0});this.isDev=this.contextApiUrl?.includes("localhost")||this.contextApiUrl?.includes("127.0.0.1"),n("Using ContextApi URl:",this.contextApiUrl);let t=l.loadPackageDefinition(o);this.client=new t.ContextQueryService(this.contextApiUrl||"contextapi.telerik.com:443",this.isDev?l.credentials.createInsecure():l.credentials.createSsl())}async query(e){let r=this.isDev?"fake_license":R(),o=new l.Metadata;if(r&&typeof r=="string"){r=r.replace(/^\uFEFF/,"");try{o.add("x-license-key",r)}catch(t){return n("Error adding license key to metadata:",t),Promise.reject(new Error(`Failed to use license key: ${t.message}`))}}return r&&typeof r=="string"&&o.add("x-license-key",r),new Promise((t,I)=>{this.client.query(e,o,(f,D)=>{f?I(f):t(D)})})}};var b=B(N(G(import.meta.url)),"../proto/service.proto"),F=new k("contextapi.telerik.com:443",b);async function C(e){return F.query(e)}import q from"fs";import w from"path";import{fileURLToPath as V}from"url";var H=V(import.meta.url),$=w.dirname(H),K=w.resolve($,"../package.json"),J=JSON.parse(q.readFileSync(K,"utf-8")),P=new M({name:"kendo-and-kendo-resources",version:J.version});P.tool("kendo_react_assistant",`Answers questions and retrieves documentation about Kendo UI for React.
21
4
  Use this tool when the user asks about Kendo UI for React features, specific components (e.g., Grid, Chart, Editor), implementation details, or general usage.
22
5
  Provide the user's detailed question as the 'query'. If the question pertains to a specific Kendo UI for React component,
23
6
  specify its name in the 'component' parameter. This tool can be automatically triggered when the following phrases are detected in the user's input/prompt:
@@ -29,60 +12,8 @@ specify its name in the 'component' parameter. This tool can be automatically tr
29
12
  - '@kendo';
30
13
  - '@kendoreact';
31
14
  - '@ask_kendo';
32
- - '@help_kendo'.`, {
33
- query: z.string().describe('The query to search for.'),
34
- component: z
35
- .enum(ReactComponents)
36
- .describe('The component to search for. If not specified, you can use General.'),
37
- }, async ({ query, component }) => {
38
- log('Calling tool: ', JSON.stringify({ query, component }));
39
- if (component === 'Grid') {
40
- component = 'DataGrid';
41
- }
42
- try {
43
- const response = await contextApiQuery({
44
- query,
45
- component: component.toLocaleLowerCase(),
46
- lib_name: Suite,
47
- text_matches_count: 3,
48
- code_matches_count: 0,
49
- allowed_types: ['documentation'],
50
- });
51
- log('Response from context API: ', JSON.stringify(response));
52
- const content = [
53
- {
54
- type: 'text',
55
- text: response.values.join('\n\n'),
56
- },
57
- ];
58
- log('Response from tool: ', JSON.stringify(content));
59
- return {
60
- content,
61
- };
62
- }
63
- catch (error) {
64
- log('Error calling context API: ', JSON.stringify(error));
65
- if (error?.code === GrpcErrors.UNAUTHENTICATED) {
66
- throw new Error('Error: You are not authenticated. Please verify the Telerik License Key provided is valid.');
67
- }
68
- else if (error?.code === GrpcErrors.RESOURCE_EXHAUSTED) {
69
- throw new Error(`Error: You have exceeded the extension quota. Upgrade to subscription licensing in order to unlock full access. Message: ${error.message}.`);
70
- }
71
- else if (error?.code === GrpcErrors.PERMISSION_DENIED) {
72
- throw new Error(`Error: You do not have permission to access this resource. Please verify that you have a valid ${REACT_SUITE_NAME} license key.`);
73
- }
74
- else if (error instanceof LicenseError) {
75
- log('License error: ', error.message);
76
- throw error;
77
- }
78
- else {
79
- throw new Error(`Error: An error occurred while calling the service. Please try again later.\n\nError Message: ${error.message}`);
80
- }
81
- }
82
- });
83
- async function startServer() {
84
- const transport = new StdioServerTransport();
85
- log('Starting server...');
86
- await server.connect(transport);
87
- }
88
- startServer();
15
+ - '@help_kendo'.`,{query:T.string().describe("The query to search for."),component:T.enum(S).describe("The component to search for. If not specified, you can use General.")},async({query:e,component:r})=>{n("Calling tool: ",JSON.stringify({query:e,component:r})),r==="Grid"&&(r="DataGrid");try{let o=await C({query:e,component:r.toLocaleLowerCase(),lib_name:g,text_matches_count:3,code_matches_count:0,allowed_types:["documentation"]});n("Response from context API: ",JSON.stringify(o));let t=[{type:"text",text:o.values.join(`
16
+
17
+ `)}];return n("Response from tool: ",JSON.stringify(t)),{content:t}}catch(o){throw n("Error calling context API: ",JSON.stringify(o)),o?.code===c.UNAUTHENTICATED?new Error("Error: You are not authenticated. Please verify the Telerik License Key provided is valid."):o?.code===c.RESOURCE_EXHAUSTED?new Error(`Error: You have exceeded the extension quota. Upgrade to subscription licensing in order to unlock full access. Message: ${o.message}.`):o?.code===c.PERMISSION_DENIED?new Error(`Error: You do not have permission to access this resource. Please verify that you have a valid ${h} license key.`):o instanceof d?(n("License error: ",o.message),o):new Error(`Error: An error occurred while calling the service. Please try again later.
18
+
19
+ Error Message: ${o.message}`)}});async function j(){let e=new O;n("Starting server..."),await P.connect(e)}j();
@@ -1,10 +1,3 @@
1
- export declare const LICENSE_ENV_VARS: string[];
2
- export declare const LICENSE_ENV_PATH_VAR = "TELERIK_LICENSE_PATH";
3
1
  export declare const REACT_SUITE_NAME = "Kendo UI for React";
4
2
  export declare const Suite = "react";
5
3
  export declare const ReactComponents: readonly ["ActionSheet", "AIPrompt", "Animation", "AppBar", "ArcGauge", "AutoComplete", "Avatar", "Badge", "Barcode", "BottomNavigation", "Breadcrumb", "Button", "ButtonGroup", "Calendar", "Card", "Chart", "Checkbox", "Chip", "ChipList", "ChunkProgressBar", "CircularGauge", "ColorGradient", "ColorPalette", "ColorPicker", "ComboBox", "ContextMenu", "ConversationalUI", "DataGrid", "Grid", "DataQuery", "DateMath", "DateInput", "DatePicker", "DateRangePicker", "DateTimePicker", "Dialog", "Drag&Drop", "Drawer", "Drawing", "DropDownButton", "DropDownList", "DropDownTree", "Editor", "Error", "ExcelExport", "ExpansionPanel", "ExternalDropZone", "FileSaver", "FileManager", "Filter", "FlatColorPicker", "FloatingActionButton", "FloatingLabel", "FontIcon", "Form", "Gantt", "Gauge", "General", "GridLayout", "Hint", "Input", "Label", "LinearGauge", "ListBox", "ListView", "Loader", "Map", "MaskedTextBox", "Menu", "MultiColumnComboBox", "MultiSelect", "MultiSelectTree", "MultiViewCalendar", "Notification", "NumericTextBox", "OrgChart", "PageTemplates/BuildingBlocks", "Pager", "PanelBar", "PDFProcessing", "PDFViewer", "PivotGrid", "Popover", "Popup", "ProgressBar", "QRCode", "RadialGauge", "RadioButton", "RadioGroup", "RangeSlider", "Rating", "Ripple", "Sankey", "Scheduler", "ScrollView", "Signature", "Skeleton", "Slider", "Sortable", "Sparkline", "SplitButton", "Splitter", "Spreadsheet", "StackLayout", "Stepper", "StockChart", "SVGIcon", "Switch", "TabStrip", "TaskBoard", "TextArea", "TextBox", "TileLayout", "Timeline", "TimePicker", "Toolbar", "Tooltip", "TreeList", "TreeView", "Typography", "Upload", "VSCodeExtension", "Window"];
6
- export declare enum GrpcErrors {
7
- UNAUTHENTICATED = 16,
8
- RESOURCE_EXHAUSTED = 8,
9
- PERMISSION_DENIED = 7
10
- }
@@ -1,5 +1,3 @@
1
- type Response = {
1
+ export declare function query(queryParams: any): Promise<{
2
2
  values: string[];
3
- };
4
- export declare function query(queryParams: any): Promise<Response>;
5
- export {};
3
+ }>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@progress/kendo-react-mcp",
3
- "version": "1.0.4",
3
+ "version": "1.0.5",
4
4
  "type": "module",
5
5
  "bin": "./dist/index.js",
6
6
  "license": "See LICENSE.md",
@@ -28,5 +28,8 @@
28
28
  "@grpc/proto-loader": "^0.7.15",
29
29
  "@modelcontextprotocol/sdk": "^1.8.0",
30
30
  "tslib": "^2.3.0"
31
+ },
32
+ "devDependencies": {
33
+ "@local/mcp-common": "*"
31
34
  }
32
35
  }
@@ -9,6 +9,8 @@ message ContextQueryRequest {
9
9
  int32 code_matches_count = 4;
10
10
  repeated string allowed_types = 5;
11
11
  string component = 6;
12
+ string userId = 7;
13
+ string filters_json = 8;
12
14
  }
13
15
 
14
16
  message Item {
@@ -1,135 +0,0 @@
1
- export const LICENSE_ENV_VARS = ['TELERIK_LICENSE', 'KENDO_UI_LICENSE'];
2
- export const LICENSE_ENV_PATH_VAR = 'TELERIK_LICENSE_PATH';
3
- export const REACT_SUITE_NAME = 'Kendo UI for React';
4
- export const Suite = 'react';
5
- export const ReactComponents = [
6
- 'ActionSheet',
7
- 'AIPrompt',
8
- 'Animation',
9
- 'AppBar',
10
- 'ArcGauge',
11
- 'AutoComplete',
12
- 'Avatar',
13
- 'Badge',
14
- 'Barcode',
15
- 'BottomNavigation',
16
- 'Breadcrumb',
17
- 'Button',
18
- 'ButtonGroup',
19
- 'Calendar',
20
- 'Card',
21
- 'Chart',
22
- 'Checkbox',
23
- 'Chip',
24
- 'ChipList',
25
- 'ChunkProgressBar',
26
- 'CircularGauge',
27
- 'ColorGradient',
28
- 'ColorPalette',
29
- 'ColorPicker',
30
- 'ComboBox',
31
- 'ContextMenu',
32
- 'ConversationalUI',
33
- 'DataGrid',
34
- 'Grid',
35
- 'DataQuery',
36
- 'DateMath',
37
- 'DateInput',
38
- 'DatePicker',
39
- 'DateRangePicker',
40
- 'DateTimePicker',
41
- 'Dialog',
42
- 'Drag&Drop',
43
- 'Drawer',
44
- 'Drawing',
45
- 'DropDownButton',
46
- 'DropDownList',
47
- 'DropDownTree',
48
- 'Editor',
49
- 'Error',
50
- 'ExcelExport',
51
- 'ExpansionPanel',
52
- 'ExternalDropZone',
53
- 'FileSaver',
54
- 'FileManager',
55
- 'Filter',
56
- 'FlatColorPicker',
57
- 'FloatingActionButton',
58
- 'FloatingLabel',
59
- 'FontIcon',
60
- 'Form',
61
- 'Gantt',
62
- 'Gauge',
63
- 'General',
64
- 'GridLayout',
65
- 'Hint',
66
- 'Input',
67
- 'Label',
68
- 'LinearGauge',
69
- 'ListBox',
70
- 'ListView',
71
- 'Loader',
72
- 'Map',
73
- 'MaskedTextBox',
74
- 'Menu',
75
- 'MultiColumnComboBox',
76
- 'MultiSelect',
77
- 'MultiSelectTree',
78
- 'MultiViewCalendar',
79
- 'Notification',
80
- 'NumericTextBox',
81
- 'OrgChart',
82
- 'PageTemplates/BuildingBlocks',
83
- 'Pager',
84
- 'PanelBar',
85
- 'PDFProcessing',
86
- 'PDFViewer',
87
- 'PivotGrid',
88
- 'Popover',
89
- 'Popup',
90
- 'ProgressBar',
91
- 'QRCode',
92
- 'RadialGauge',
93
- 'RadioButton',
94
- 'RadioGroup',
95
- 'RangeSlider',
96
- 'Rating',
97
- 'Ripple',
98
- 'Sankey',
99
- 'Scheduler',
100
- 'ScrollView',
101
- 'Signature',
102
- 'Skeleton',
103
- 'Slider',
104
- 'Sortable',
105
- 'Sparkline',
106
- 'SplitButton',
107
- 'Splitter',
108
- 'Spreadsheet',
109
- 'StackLayout',
110
- 'Stepper',
111
- 'StockChart',
112
- 'SVGIcon',
113
- 'Switch',
114
- 'TabStrip',
115
- 'TaskBoard',
116
- 'TextArea',
117
- 'TextBox',
118
- 'TileLayout',
119
- 'Timeline',
120
- 'TimePicker',
121
- 'Toolbar',
122
- 'Tooltip',
123
- 'TreeList',
124
- 'TreeView',
125
- 'Typography',
126
- 'Upload',
127
- 'VSCodeExtension',
128
- 'Window',
129
- ];
130
- export var GrpcErrors;
131
- (function (GrpcErrors) {
132
- GrpcErrors[GrpcErrors["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED";
133
- GrpcErrors[GrpcErrors["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED";
134
- GrpcErrors[GrpcErrors["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED";
135
- })(GrpcErrors || (GrpcErrors = {}));
@@ -1,45 +0,0 @@
1
- import protoLoader from '@grpc/proto-loader';
2
- import grpc from '@grpc/grpc-js';
3
- import { dirname, join } from 'path';
4
- import { fileURLToPath } from 'url';
5
- import { readLicense } from './read-license.js';
6
- import { log } from './logger.js';
7
- const protoPath = join(dirname(fileURLToPath(import.meta.url)), '../../proto/service.proto');
8
- const proto = protoLoader.loadSync(protoPath, {
9
- keepCase: true,
10
- longs: String,
11
- enums: String,
12
- defaults: true,
13
- oneofs: true,
14
- });
15
- const protoDescriptor = grpc.loadPackageDefinition(proto);
16
- const service = protoDescriptor.ContextQueryService;
17
- const client = new service('contextapi.telerik.com:443', grpc.credentials.createSsl());
18
- export async function query(queryParams) {
19
- let license = readLicense();
20
- const metadata = new grpc.Metadata();
21
- if (license && typeof license === 'string') {
22
- // Check for BOM character and trim it
23
- license = license.replace(/^\uFEFF/, '');
24
- try {
25
- metadata.add('x-license-key', license);
26
- }
27
- catch (error) {
28
- log('Error adding license key to metadata:', error);
29
- return Promise.reject(new Error(`Failed to use license key: ${error.message}`));
30
- }
31
- }
32
- if (license && typeof license === 'string') {
33
- metadata.add('x-license-key', license);
34
- }
35
- return new Promise((resolve, reject) => {
36
- client.query(queryParams, metadata, (err, response) => {
37
- if (err) {
38
- reject(err);
39
- }
40
- else {
41
- resolve(response);
42
- }
43
- });
44
- });
45
- }
@@ -1 +0,0 @@
1
- export declare function log(...args: any[]): void;
@@ -1,43 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- let LOG_ENABLED = false;
4
- const LOG_FILE = process.env.DEBUG_LOG_FILE;
5
- const LOG_FILE_DEFINED = !!(LOG_FILE && typeof LOG_FILE === 'string');
6
- // check if the log file is a valid path
7
- if (LOG_FILE_DEFINED) {
8
- const resolvedLogFile = path.resolve(LOG_FILE);
9
- const logDir = path.dirname(resolvedLogFile);
10
- // Only create directory if it's not the current directory and doesn't exist
11
- if (logDir !== '.' && logDir !== process.cwd() && !fs.existsSync(logDir)) {
12
- try {
13
- fs.mkdirSync(logDir, { recursive: true });
14
- }
15
- catch (err) {
16
- console.error('Error creating log directory:', err);
17
- }
18
- }
19
- // Create the log file if it doesn't exist
20
- if (!fs.existsSync(resolvedLogFile)) {
21
- try {
22
- fs.writeFileSync(resolvedLogFile, '');
23
- }
24
- catch (err) {
25
- console.error('Error creating log file:', err);
26
- }
27
- }
28
- }
29
- LOG_ENABLED = LOG_FILE_DEFINED && !!LOG_FILE && fs.existsSync(path.resolve(LOG_FILE));
30
- export function log(...args) {
31
- if (LOG_ENABLED && LOG_FILE) {
32
- // write a new line to the file with the date and time
33
- const date = new Date();
34
- const dateString = date.toISOString();
35
- const logString = `${dateString}: ${args.join(' ')}\n`;
36
- const resolvedLogFile = path.resolve(LOG_FILE);
37
- fs.appendFile(resolvedLogFile, logString, (err) => {
38
- if (err) {
39
- console.error('Error writing to log file:', err);
40
- }
41
- });
42
- }
43
- }
@@ -1,4 +0,0 @@
1
- export declare class LicenseError extends Error {
2
- constructor(message: string);
3
- }
4
- export declare function readLicense(): string | undefined;
@@ -1,32 +0,0 @@
1
- import { LICENSE_ENV_VARS, LICENSE_ENV_PATH_VAR } from './constants.js';
2
- import { readFileSync } from 'node:fs';
3
- import { log } from './logger.js';
4
- const LICENSE_PATH = process.env[LICENSE_ENV_PATH_VAR];
5
- const LICENSE_KEY = process.env[LICENSE_ENV_VARS[0]] || process.env[LICENSE_ENV_VARS[1]];
6
- // create a custom LicenseError class
7
- export class LicenseError extends Error {
8
- constructor(message) {
9
- super(message);
10
- this.name = 'LicenseError';
11
- }
12
- }
13
- export function readLicense() {
14
- if (!LICENSE_PATH && !LICENSE_KEY) {
15
- throw new LicenseError(`No license found. Please set one of the following environment variables: ${LICENSE_ENV_VARS.join(', ')} or ${LICENSE_ENV_PATH_VAR}`);
16
- }
17
- let licenseKey;
18
- if (LICENSE_PATH) {
19
- try {
20
- licenseKey = readFileSync(LICENSE_PATH, 'utf8');
21
- log('License key read from file: ', LICENSE_PATH);
22
- }
23
- catch (error) {
24
- throw new LicenseError(`Error reading license file: ${LICENSE_PATH}. Please verify the file exists and is readable.`);
25
- }
26
- }
27
- if (LICENSE_KEY) {
28
- licenseKey = LICENSE_KEY;
29
- log('License key read from environment variable.');
30
- }
31
- return licenseKey;
32
- }