Passa al contenuto principale

JavaScript SDK

Official TypeScript/JavaScript SDK for ArchiCore API.

Installation

npm install @archicore/sdk
# or
yarn add @archicore/sdk
# or
pnpm add @archicore/sdk

Requirements

  • Node.js 16+
  • TypeScript 4.5+ (optional, for type safety)

Quick Start

import { ArchiCore } from '@archicore/sdk';

const client = new ArchiCore({ apiKey: 'your-api-key' });

// List all projects
const projects = await client.projects.list();
console.log(projects);

Configuration

const client = new ArchiCore({
apiKey: 'your-api-key', // Required
baseUrl: 'https://api.archicore.io/api/v1', // Optional
timeout: 30000, // Optional, in milliseconds
});

Projects

List Projects

const projects = await client.projects.list();
// Returns: Project[]

Get Project

const project = await client.projects.get('project-id');
// Returns: Project

Create Project

const project = await client.projects.create({
name: 'my-project',
source: '/path/to/project', // Optional
githubUrl: 'https://github.com/user/repo', // Optional
});

Delete Project

await client.projects.delete('project-id');

Index Project

const status = await client.projects.index('project-id', {
force: true // Optional, re-index even if already indexed
});

Find code by natural language:

const results = await client.projects.search('project-id', {
query: 'authentication middleware',
limit: 10, // Optional, default 10
threshold: 0.7, // Optional, similarity threshold 0-1
});

for (const result of results) {
console.log(`${result.file}:${result.line} (${result.score})`);
console.log(result.code);
}

Response Type

interface SearchResult {
file: string;
line: number;
code: string;
score: number;
context?: string;
}

AI Assistant

Ask Questions

const answer = await client.projects.ask('project-id', {
question: 'How does the authentication system work?',
context: 'Focus on JWT implementation', // Optional
});

console.log(answer.response);
console.log(answer.sources); // Code references
console.log(answer.confidence);

Response Type

interface AskResponse {
response: string;
sources?: Array<{
file: string;
line: number;
code: string;
}>;
confidence?: number;
}

Metrics

Get Project Metrics

const metrics = await client.projects.metrics('project-id');

console.log(`Files: ${metrics.totalFiles}`);
console.log(`Lines: ${metrics.totalLines}`);
console.log(`Complexity: ${metrics.complexity?.average}`);

Response Type

interface Metrics {
totalFiles: number;
totalLines: number;
totalSymbols: number;
languages: Record<string, number>;
complexity?: {
average: number;
max: number;
};
}

Security

Get Security Report

const report = await client.projects.security('project-id');

console.log(`Critical: ${report.summary.critical}`);
console.log(`High: ${report.summary.high}`);

for (const vuln of report.vulnerabilities) {
console.log(`[${vuln.severity}] ${vuln.type}: ${vuln.message}`);
console.log(` ${vuln.file}:${vuln.line}`);
}

Response Type

interface SecurityReport {
vulnerabilities: Array<{
severity: 'critical' | 'high' | 'medium' | 'low';
type: string;
message: string;
file: string;
line: number;
}>;
summary: {
critical: number;
high: number;
medium: number;
low: number;
};
}

Impact Analysis

Analyze Changes

const impact = await client.projects.analyze('project-id', {
files: ['src/auth/login.ts', 'src/auth/session.ts'],
});

console.log(`Risk: ${impact.riskLevel}`);
console.log(`Affected files: ${impact.affectedFiles.length}`);
console.log(`Suggestions:`);
for (const suggestion of impact.suggestions || []) {
console.log(` - ${suggestion}`);
}

Response Type

interface ImpactAnalysis {
affectedFiles: string[];
affectedSymbols: string[];
riskLevel: 'low' | 'medium' | 'high';
suggestions?: string[];
}

Enterprise Analysis

For large projects (50K+ files).

Get Estimate

const estimate = await client.projects.enterpriseEstimate('project-id');

console.log(`Total files: ${estimate.totalFiles}`);
console.log(`Recommended tier: ${estimate.recommendation}`);
console.log(`Languages:`, estimate.languageDistribution);

Start Enterprise Indexing

// Quick analysis
const task = await client.projects.enterpriseIndex('project-id', {
tier: 'quick',
sampling: { strategy: 'smart' }
});

// Standard with focus directories
const task = await client.projects.enterpriseIndex('project-id', {
tier: 'standard',
sampling: { strategy: 'hot-files' },
focusDirectories: ['src/core', 'src/api']
});

console.log(`Task ID: ${task.taskId}`);

Preview Files

const preview = await client.projects.enterpriseFilesPreview('project-id', {
tier: 'standard',
strategy: 'smart'
});

console.log(`Would analyze ${preview.totalSelected} files`);
console.log(`Sample:`, preview.files.slice(0, 5));

Check Incremental Changes

// Since date
const changes = await client.projects.enterpriseIncremental('project-id', {
since: '2024-01-01'
});

// Since commit
const changes = await client.projects.enterpriseIncremental('project-id', {
since: 'abc123f'
});

console.log(`Changed files: ${changes.changedFiles}`);

Webhooks

List Webhooks

const webhooks = await client.webhooks.list();

Create Webhook

const webhook = await client.webhooks.create({
url: 'https://your-server.com/webhook',
events: ['project.indexed', 'analysis.complete'],
projectId: 'project-id', // Optional, all projects if omitted
secret: 'webhook-secret', // Optional
});

Delete Webhook

await client.webhooks.delete('webhook-id');

Error Handling

import {
ArchiCore,
ArchiCoreError,
AuthenticationError,
RateLimitError,
NotFoundError,
ValidationError
} from '@archicore/sdk';

try {
await client.projects.get('project-id');
} catch (error) {
if (error instanceof AuthenticationError) {
// Invalid or expired API key (401)
console.log('Please check your API key');
} else if (error instanceof RateLimitError) {
// Rate limit exceeded (429)
console.log(`Retry after ${error.retryAfter} seconds`);
console.log(`Limit: ${error.limit}, Remaining: ${error.remaining}`);
} else if (error instanceof NotFoundError) {
// Resource not found (404)
console.log('Project not found');
} else if (error instanceof ValidationError) {
// Invalid request (400)
console.log('Invalid parameters');
} else if (error instanceof ArchiCoreError) {
// Other API errors
console.log(`Error: ${error.message} (${error.code})`);
}
}

TypeScript Types

All types are exported:

import type {
ArchiCoreConfig,
Project,
SearchResult,
AskResponse,
Metrics,
SecurityReport,
ImpactAnalysis,
Webhook,
EnterpriseEstimate,
EnterpriseIndexOptions,
EnterpriseFilesPreview,
IncrementalChanges,
} from '@archicore/sdk';

CommonJS Usage

const { ArchiCore } = require('@archicore/sdk');

const client = new ArchiCore({ apiKey: 'your-api-key' });

Examples

CI/CD Integration

// analyze-pr.ts
import { ArchiCore } from '@archicore/sdk';

async function analyzePR(projectId: string, changedFiles: string[]) {
const client = new ArchiCore({ apiKey: process.env.ARCHICORE_API_KEY! });

// Get impact analysis
const impact = await client.projects.analyze(projectId, { files: changedFiles });

if (impact.riskLevel === 'high') {
console.log('::warning::High impact changes detected');
console.log(`Affected: ${impact.affectedFiles.length} files`);
}

// Run security scan
const security = await client.projects.security(projectId);
if (security.summary.critical > 0 || security.summary.high > 0) {
console.log('::error::Security issues found');
process.exit(1);
}
}

Slack Bot

import { ArchiCore } from '@archicore/sdk';

const client = new ArchiCore({ apiKey: process.env.ARCHICORE_API_KEY! });

app.post('/slack/ask', async (req, res) => {
const { text, project_id } = req.body;

const answer = await client.projects.ask(project_id, {
question: text
});

res.json({
response_type: 'in_channel',
text: answer.response
});
});