@defarm/sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,34 @@
1
+ # @defarm/sdk
2
+
3
+ SDK TypeScript para integração com a API da DeFarm via gateway.
4
+
5
+ ## Instalação
6
+
7
+ ```bash
8
+ npm install @defarm/sdk
9
+ ```
10
+
11
+ ## Exemplo
12
+
13
+ ```ts
14
+ import { DefarmSdk } from "@defarm/sdk";
15
+
16
+ const sdk = new DefarmSdk({ gatewayBaseUrl: "https://gateway.defarm.net" });
17
+ const auth = await sdk.auth.login("email", "senha");
18
+ sdk.setAccessToken(auth.access_token);
19
+
20
+ const circuits = await sdk.circuits.list();
21
+ console.log(circuits);
22
+ ```
23
+
24
+ ## Testes
25
+
26
+ ```bash
27
+ npm test
28
+ ```
29
+
30
+ ## Publicação no npm
31
+
32
+ ```bash
33
+ npm publish --access public
34
+ ```
@@ -0,0 +1,8 @@
1
+ import { HttpMethod, SdkConfig } from "./types.js";
2
+ export declare class DefarmHttpClient {
3
+ private readonly config;
4
+ private accessToken?;
5
+ constructor(config: SdkConfig);
6
+ setAccessToken(token?: string): void;
7
+ request<T>(method: HttpMethod, path: string, body?: unknown): Promise<T>;
8
+ }
package/dist/client.js ADDED
@@ -0,0 +1,48 @@
1
+ import { request as undiciRequest } from "undici";
2
+ import { DefarmApiError } from "./types.js";
3
+ export class DefarmHttpClient {
4
+ config;
5
+ accessToken;
6
+ constructor(config) {
7
+ this.config = {
8
+ timeoutMs: 20000,
9
+ ...config,
10
+ };
11
+ }
12
+ setAccessToken(token) {
13
+ this.accessToken = token;
14
+ }
15
+ async request(method, path, body) {
16
+ const url = `${this.config.gatewayBaseUrl.replace(/\/$/, "")}${path}`;
17
+ const headers = {
18
+ "content-type": "application/json",
19
+ };
20
+ if (this.accessToken) {
21
+ headers.authorization = `Bearer ${this.accessToken}`;
22
+ }
23
+ const response = await undiciRequest(url, {
24
+ method,
25
+ headers,
26
+ body: body == null ? undefined : JSON.stringify(body),
27
+ headersTimeout: this.config.timeoutMs,
28
+ bodyTimeout: this.config.timeoutMs,
29
+ });
30
+ const text = await response.body.text();
31
+ const parsed = text ? safeJsonParse(text) : null;
32
+ if (response.statusCode < 200 || response.statusCode >= 300) {
33
+ const message = parsed?.message ||
34
+ parsed?.error ||
35
+ `HTTP ${response.statusCode} on ${path}`;
36
+ throw new DefarmApiError(message, response.statusCode, parsed);
37
+ }
38
+ return parsed ?? {};
39
+ }
40
+ }
41
+ function safeJsonParse(text) {
42
+ try {
43
+ return JSON.parse(text);
44
+ }
45
+ catch {
46
+ return { raw: text };
47
+ }
48
+ }
@@ -0,0 +1,14 @@
1
+ import { DefarmHttpClient } from "./client.js";
2
+ import { AuthApi, CircuitsApi, EventsApi, ItemsApi, WorkspaceApi } from "./modules.js";
3
+ import { SdkConfig } from "./types.js";
4
+ export * from "./types.js";
5
+ export declare class DefarmSdk {
6
+ readonly auth: AuthApi;
7
+ readonly workspace: WorkspaceApi;
8
+ readonly circuits: CircuitsApi;
9
+ readonly items: ItemsApi;
10
+ readonly events: EventsApi;
11
+ readonly http: DefarmHttpClient;
12
+ constructor(config: SdkConfig);
13
+ setAccessToken(token?: string): void;
14
+ }
package/dist/index.js ADDED
@@ -0,0 +1,22 @@
1
+ import { DefarmHttpClient } from "./client.js";
2
+ import { AuthApi, CircuitsApi, EventsApi, ItemsApi, WorkspaceApi } from "./modules.js";
3
+ export * from "./types.js";
4
+ export class DefarmSdk {
5
+ auth;
6
+ workspace;
7
+ circuits;
8
+ items;
9
+ events;
10
+ http;
11
+ constructor(config) {
12
+ this.http = new DefarmHttpClient(config);
13
+ this.auth = new AuthApi(this.http);
14
+ this.workspace = new WorkspaceApi(this.http);
15
+ this.circuits = new CircuitsApi(this.http);
16
+ this.items = new ItemsApi(this.http);
17
+ this.events = new EventsApi(this.http);
18
+ }
19
+ setAccessToken(token) {
20
+ this.http.setAccessToken(token);
21
+ }
22
+ }
@@ -0,0 +1,45 @@
1
+ import { DefarmHttpClient } from "./client.js";
2
+ import { AuthResponse, Circuit, Event, Item } from "./types.js";
3
+ export declare class AuthApi {
4
+ private readonly http;
5
+ constructor(http: DefarmHttpClient);
6
+ login(email: string, password: string): Promise<AuthResponse>;
7
+ refresh(refreshToken: string): Promise<AuthResponse>;
8
+ whoami(): Promise<AuthResponse["user"]>;
9
+ logout(refreshToken?: string): Promise<{
10
+ message?: string;
11
+ }>;
12
+ }
13
+ export declare class WorkspaceApi {
14
+ private readonly http;
15
+ constructor(http: DefarmHttpClient);
16
+ list(): Promise<{
17
+ workspaces: unknown[];
18
+ count: number;
19
+ }>;
20
+ status(): Promise<import("./types.js").AuthUser>;
21
+ }
22
+ export declare class CircuitsApi {
23
+ private readonly http;
24
+ constructor(http: DefarmHttpClient);
25
+ list(): Promise<Circuit[]>;
26
+ show(id: string): Promise<Circuit>;
27
+ members(id: string): Promise<unknown>;
28
+ join(id: string, message?: string): Promise<unknown>;
29
+ }
30
+ export declare class ItemsApi {
31
+ private readonly http;
32
+ constructor(http: DefarmHttpClient);
33
+ list(circuitId?: string): Promise<Item[]>;
34
+ show(id: string): Promise<unknown>;
35
+ create(payload: Record<string, unknown>): Promise<unknown>;
36
+ update(id: string, payload: Record<string, unknown>): Promise<unknown>;
37
+ }
38
+ export declare class EventsApi {
39
+ private readonly http;
40
+ constructor(http: DefarmHttpClient);
41
+ list(circuitId?: string): Promise<Event[]>;
42
+ show(id: string): Promise<Event>;
43
+ add(payload: Record<string, unknown>): Promise<unknown>;
44
+ update(id: string, payload: Record<string, unknown>): Promise<unknown>;
45
+ }
@@ -0,0 +1,91 @@
1
+ export class AuthApi {
2
+ http;
3
+ constructor(http) {
4
+ this.http = http;
5
+ }
6
+ async login(email, password) {
7
+ return this.http.request("POST", "/auth/login", { email, password });
8
+ }
9
+ async refresh(refreshToken) {
10
+ return this.http.request("POST", "/auth/refresh", { refresh_token: refreshToken });
11
+ }
12
+ async whoami() {
13
+ return this.http.request("GET", "/auth/me");
14
+ }
15
+ async logout(refreshToken) {
16
+ return this.http.request("POST", "/auth/logout", {
17
+ refresh_token: refreshToken,
18
+ });
19
+ }
20
+ }
21
+ export class WorkspaceApi {
22
+ http;
23
+ constructor(http) {
24
+ this.http = http;
25
+ }
26
+ async list() {
27
+ return this.http.request("GET", "/auth/workspaces");
28
+ }
29
+ async status() {
30
+ return this.http.request("GET", "/auth/me");
31
+ }
32
+ }
33
+ export class CircuitsApi {
34
+ http;
35
+ constructor(http) {
36
+ this.http = http;
37
+ }
38
+ async list() {
39
+ const res = await this.http.request("GET", "/api/circuits");
40
+ return Array.isArray(res) ? res : res.circuits || [];
41
+ }
42
+ async show(id) {
43
+ return this.http.request("GET", `/api/circuits/${id}`);
44
+ }
45
+ async members(id) {
46
+ return this.http.request("GET", `/api/circuits/${id}/members`);
47
+ }
48
+ async join(id, message) {
49
+ return this.http.request("POST", `/api/circuits/${id}/join-requests`, message ? { message } : {});
50
+ }
51
+ }
52
+ export class ItemsApi {
53
+ http;
54
+ constructor(http) {
55
+ this.http = http;
56
+ }
57
+ async list(circuitId) {
58
+ const qs = circuitId ? `?circuit_id=${encodeURIComponent(circuitId)}` : "";
59
+ const res = await this.http.request("GET", `/api/items${qs}`);
60
+ return Array.isArray(res) ? res : res.items || [];
61
+ }
62
+ async show(id) {
63
+ return this.http.request("GET", `/api/items/${id}`);
64
+ }
65
+ async create(payload) {
66
+ return this.http.request("POST", "/api/items", payload);
67
+ }
68
+ async update(id, payload) {
69
+ return this.http.request("PUT", `/api/items/${id}`, payload);
70
+ }
71
+ }
72
+ export class EventsApi {
73
+ http;
74
+ constructor(http) {
75
+ this.http = http;
76
+ }
77
+ async list(circuitId) {
78
+ const qs = circuitId ? `?circuit_id=${encodeURIComponent(circuitId)}` : "";
79
+ const res = await this.http.request("GET", `/api/events${qs}`);
80
+ return Array.isArray(res) ? res : res.events || [];
81
+ }
82
+ async show(id) {
83
+ return this.http.request("GET", `/api/events/${id}`);
84
+ }
85
+ async add(payload) {
86
+ return this.http.request("POST", "/api/events", payload);
87
+ }
88
+ async update(id, payload) {
89
+ return this.http.request("PUT", `/api/events/${id}/status`, payload);
90
+ }
91
+ }
@@ -0,0 +1,57 @@
1
+ export type WorkspaceType = "partner" | "producer" | "processor" | "certifier";
2
+ export type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
3
+ export interface SdkConfig {
4
+ gatewayBaseUrl: string;
5
+ timeoutMs?: number;
6
+ }
7
+ export interface AuthTokens {
8
+ access_token: string;
9
+ refresh_token?: string;
10
+ token_type?: string;
11
+ expires_in?: number;
12
+ }
13
+ export interface AuthUser {
14
+ id: string;
15
+ email: string;
16
+ full_name?: string;
17
+ workspace: {
18
+ id: string;
19
+ name: string;
20
+ slug: string;
21
+ workspace_type: WorkspaceType;
22
+ role: string;
23
+ };
24
+ }
25
+ export interface AuthResponse extends AuthTokens {
26
+ user: AuthUser;
27
+ }
28
+ export interface Circuit {
29
+ id: string;
30
+ name: string;
31
+ description?: string;
32
+ visibility?: string;
33
+ circuit_type?: string;
34
+ status?: string;
35
+ }
36
+ export interface Item {
37
+ id: string;
38
+ dfid: string;
39
+ value_chain: string;
40
+ country: string;
41
+ year: number;
42
+ status: string;
43
+ metadata?: Record<string, unknown>;
44
+ }
45
+ export interface Event {
46
+ id: string;
47
+ event_type: string;
48
+ status?: string;
49
+ item_id?: string;
50
+ circuit_id?: string;
51
+ payload?: Record<string, unknown>;
52
+ }
53
+ export declare class DefarmApiError extends Error {
54
+ status: number;
55
+ details?: unknown;
56
+ constructor(message: string, status: number, details?: unknown);
57
+ }
package/dist/types.js ADDED
@@ -0,0 +1,9 @@
1
+ export class DefarmApiError extends Error {
2
+ status;
3
+ details;
4
+ constructor(message, status, details) {
5
+ super(message);
6
+ this.status = status;
7
+ this.details = details;
8
+ }
9
+ }
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@defarm/sdk",
3
+ "version": "0.1.0",
4
+ "description": "DeFarm SDK for CLI and partner integrations",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/defarm-repo/engines.git",
9
+ "directory": "tooling/defarm-sdk"
10
+ },
11
+ "homepage": "https://defarm.net",
12
+ "bugs": {
13
+ "url": "https://github.com/defarm-repo/engines/issues"
14
+ },
15
+ "keywords": [
16
+ "defarm",
17
+ "traceability",
18
+ "agri",
19
+ "sdk",
20
+ "stellar"
21
+ ],
22
+ "type": "module",
23
+ "main": "dist/index.js",
24
+ "types": "dist/index.d.ts",
25
+ "files": ["dist"],
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "scripts": {
30
+ "build": "tsc -p tsconfig.json",
31
+ "check": "tsc -p tsconfig.json --noEmit",
32
+ "test": "npm run build && node --test test/*.test.mjs",
33
+ "prepublishOnly": "npm run check && npm run test"
34
+ },
35
+ "dependencies": {
36
+ "undici": "^6.19.8"
37
+ },
38
+ "devDependencies": {
39
+ "typescript": "^5.6.3"
40
+ }
41
+ }