creat01deployengine 1.0.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 (48) hide show
  1. package/AI_USAGE.md +62 -0
  2. package/LICENSE +9 -0
  3. package/README.md +67 -0
  4. package/dist/client.d.ts +53 -0
  5. package/dist/client.js +161 -0
  6. package/dist/errors.d.ts +28 -0
  7. package/dist/errors.js +36 -0
  8. package/dist/index.d.ts +38 -0
  9. package/dist/index.js +29 -0
  10. package/dist/logging/index.d.ts +2 -0
  11. package/dist/logging/index.js +2 -0
  12. package/dist/logging/reporter.d.ts +30 -0
  13. package/dist/logging/reporter.js +38 -0
  14. package/dist/models/common.d.ts +15 -0
  15. package/dist/models/common.js +1 -0
  16. package/dist/models/index.d.ts +4 -0
  17. package/dist/models/index.js +4 -0
  18. package/dist/models/infrastructure.d.ts +21 -0
  19. package/dist/models/infrastructure.js +1 -0
  20. package/dist/models/projects.d.ts +12 -0
  21. package/dist/models/projects.js +1 -0
  22. package/dist/resources/authentication.d.ts +10 -0
  23. package/dist/resources/authentication.js +26 -0
  24. package/dist/resources/base.d.ts +18 -0
  25. package/dist/resources/base.js +33 -0
  26. package/dist/resources/feedback.d.ts +6 -0
  27. package/dist/resources/feedback.js +10 -0
  28. package/dist/resources/index.d.ts +35 -0
  29. package/dist/resources/index.js +35 -0
  30. package/dist/resources/load-balancers.d.ts +10 -0
  31. package/dist/resources/load-balancers.js +20 -0
  32. package/dist/resources/machines.d.ts +8 -0
  33. package/dist/resources/machines.js +14 -0
  34. package/dist/resources/payments.d.ts +11 -0
  35. package/dist/resources/payments.js +20 -0
  36. package/dist/resources/projects.d.ts +22 -0
  37. package/dist/resources/projects.js +34 -0
  38. package/dist/resources/security-groups.d.ts +10 -0
  39. package/dist/resources/security-groups.js +21 -0
  40. package/dist/resources/tracking.d.ts +6 -0
  41. package/dist/resources/tracking.js +12 -0
  42. package/dist/tracking/index.d.ts +2 -0
  43. package/dist/tracking/index.js +2 -0
  44. package/dist/tracking/tracker.d.ts +29 -0
  45. package/dist/tracking/tracker.js +72 -0
  46. package/dist/version.d.ts +2 -0
  47. package/dist/version.js +2 -0
  48. package/package.json +55 -0
package/AI_USAGE.md ADDED
@@ -0,0 +1,62 @@
1
+ # AI usage guide — TypeScript
2
+
3
+ Use this decision order when generating code with `creat01deployengine`.
4
+
5
+ 1. Use `DeployEngineClient` only in trusted Node.js/server code and read the
6
+ management API key from `DEPLOYENGINE_API_KEY` in the environment.
7
+ 2. Browser code may import `creat01deployengine/tracking` and
8
+ `creat01deployengine/logging` with a project-scoped `writeKey` only.
9
+ 3. Prefer `client.api.<resource>` methods over `client.request`.
10
+ 4. Do not retry writes unless an idempotency key is provided.
11
+ 5. Catch typed errors and retain `requestId` for support diagnostics.
12
+
13
+ ## Method selection
14
+
15
+ ```text
16
+ resource CRUD -> list/get/create/update/delete
17
+ deployment history -> api.projects.deployments
18
+ release history -> api.projects.releases
19
+ deployment validation -> api.projects.precheck
20
+ deploy/restart with progress -> api.projects.deployStream/restartStream
21
+ machine recommendation/state -> api.machines.recommendations/agentStatus
22
+ workflow task CRUD -> api.workflows.list/get/create/update/delete
23
+ certificate CRUD -> api.certificates.list/get/create/update/delete
24
+ domain CRUD -> api.domains.list/get/create/update/delete
25
+ alert-contact CRUD -> api.alerts.list/get/create/update/delete
26
+ load-balancer update/sync -> api.loadBalancers.update/sync
27
+ bind project to load balancer -> api.loadBalancers.bindProject
28
+ firewall update/apply/rule -> api.securityGroups.update/apply/addRule
29
+ payment/refund -> api.payments.createOrder/refund
30
+ send/login with code -> api.authentication.sendCode/loginWithCode
31
+ password login -> api.authentication.passwordLogin
32
+ feedback link -> api.feedback.createTicketLink
33
+ event batch -> api.tracking.collect
34
+ browser analytics -> Tracker.track/identify/flush/close
35
+ browser-safe logs -> LogReporter.debug/info/warn/error
36
+ ```
37
+
38
+ ```ts
39
+ import {
40
+ DeployEngineClient,
41
+ DeployEngineError,
42
+ } from "creat01deployengine"
43
+
44
+ const client = new DeployEngineClient({
45
+ apiKey: process.env.DEPLOYENGINE_API_KEY,
46
+ })
47
+
48
+ try {
49
+ for await (const event of client.api.projects.deployStream(projectId, body)) {
50
+ console.log(event)
51
+ }
52
+ } catch (error) {
53
+ if (error instanceof DeployEngineError) {
54
+ console.error(error.statusCode, error.code, error.requestId)
55
+ }
56
+ throw error
57
+ }
58
+ ```
59
+
60
+ Scopes: `read`, `deploy`, `machines`, `databases`, `certificates`,
61
+ `monitoring`, `infrastructure`, and `business`. A 403 is an authorization
62
+ problem; do not expose or silently replace the credential.
package/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Creat01
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,67 @@
1
+ # creat01deployengine TypeScript SDK
2
+
3
+ Official ESM client for Node.js 18+ and modern browsers.
4
+
5
+ ```bash
6
+ npm install creat01deployengine
7
+ ```
8
+
9
+ ## Management API (trusted servers only)
10
+
11
+ ```ts
12
+ import { DeployEngineClient } from "creat01deployengine"
13
+
14
+ const client = new DeployEngineClient({
15
+ apiKey: process.env.DEPLOYENGINE_API_KEY,
16
+ baseUrl: "https://deployengine.creat01.com",
17
+ })
18
+ const projects = await client.api.projects.list({ page: 1, pageSize: 20 })
19
+ await client.api.securityGroups.apply(12)
20
+ ```
21
+
22
+ Never include a management `apiKey` or bearer `accessToken` in browser,
23
+ desktop, or mobile bundles.
24
+
25
+ ## Browser-safe tracking and logging
26
+
27
+ ```ts
28
+ import { Tracker } from "creat01deployengine/tracking"
29
+ import { LogReporter } from "creat01deployengine/logging"
30
+
31
+ const tracker = new Tracker({
32
+ baseUrl: "https://deployengine.creat01.com",
33
+ appId: "app_xxx",
34
+ projectName: "shop",
35
+ writeKey: "wk_xxx",
36
+ })
37
+ tracker.track("checkout_started", { sku: "A-1" }, "user-1")
38
+ new LogReporter(tracker, { service: "web", environment: "production" })
39
+ .error("render failed", { traceId: "trace-1" })
40
+ await tracker.close()
41
+ ```
42
+
43
+ ## Resource map
44
+
45
+ | `client.api` member | Purpose | Typical scope |
46
+ |---|---|---|
47
+ | `projects` | CRUD, precheck, deployments, releases, streams | `read`, `deploy` |
48
+ | `machines` | CRUD, recommendations, Agent status | `machines` |
49
+ | `workflows` | Generic workflow task CRUD access | `read`, `deploy` |
50
+ | `certificates` | Generic certificate CRUD access | `certificates` |
51
+ | `domains` | Generic domain CRUD access | `read` |
52
+ | `loadBalancers` | Update, remote sync, project binding | `infrastructure` |
53
+ | `securityGroups` | Update, apply, add firewall rule | `infrastructure` |
54
+ | `alerts` | Generic alert-contact CRUD access | `monitoring` |
55
+ | `payments` | Create orders and refunds | `business` |
56
+ | `authentication` | Project SMS/email/password login | `business` |
57
+ | `feedback` | Customer feedback links | `business` |
58
+ | `tracking` | Low-level event ingestion | tracking write key |
59
+
60
+ ```ts
61
+ for await (const event of client.api.projects.deployStream(7, body)) {
62
+ console.log(event)
63
+ }
64
+ ```
65
+
66
+ Responses are unwrapped and failures become typed errors. Reads can retry;
67
+ writes retry only with an idempotency key. See `AI_USAGE.md` for task recipes.
@@ -0,0 +1,53 @@
1
+ /** Configuration for an authenticated DeployEngine management client. */
2
+ export interface ClientOptions {
3
+ /** Secret management API key. Never include this in browser bundles. */
4
+ apiKey?: string;
5
+ /** Bearer access token used when an API key is unavailable. */
6
+ accessToken?: string;
7
+ /** DeployEngine origin, without a required trailing slash. */
8
+ baseUrl?: string;
9
+ /** Per-request timeout in milliseconds. Defaults to 30 seconds. */
10
+ timeoutMs?: number;
11
+ /** Safe retry count for reads or idempotent writes. Defaults to two. */
12
+ maxRetries?: number;
13
+ /** Custom Fetch implementation, primarily for runtimes and tests. */
14
+ fetch?: typeof fetch;
15
+ }
16
+ type RequestOptions = {
17
+ query?: Record<string, unknown>;
18
+ body?: unknown;
19
+ headers?: Record<string, string>;
20
+ idempotencyKey?: string;
21
+ signal?: AbortSignal;
22
+ };
23
+ /**
24
+ * Low-level authenticated management client.
25
+ * Use `DeployEngineClient` for the convenient `api` resource registry.
26
+ */
27
+ export declare class DeployEngine {
28
+ /** Normalized DeployEngine origin used for every request. */
29
+ readonly baseUrl: string;
30
+ private auth;
31
+ private timeoutMs;
32
+ private maxRetries;
33
+ private fetcher;
34
+ constructor(options: ClientOptions);
35
+ /**
36
+ * Send an API request and return the unwrapped `data` field.
37
+ *
38
+ * GET/HEAD requests may retry automatically. Writes retry only when
39
+ * `idempotencyKey` is present. API failures become typed SDK errors.
40
+ * Prefer a domain resource such as `client.api.projects` in application code.
41
+ */
42
+ request<T = unknown>(method: string, path: string, options?: RequestOptions): Promise<T>;
43
+ private delay;
44
+ /**
45
+ * Stream decoded Server-Sent Event `data:` payloads.
46
+ *
47
+ * JSON payloads are returned as `T`; plain-text payloads remain strings.
48
+ * Consuming a stream may start a side-effecting deployment or restart.
49
+ */
50
+ stream<T = unknown>(method: string, path: string, body?: unknown): AsyncGenerator<T | string>;
51
+ }
52
+ export {};
53
+ /** Authenticated transport used by all DeployEngine management resources. */
package/dist/client.js ADDED
@@ -0,0 +1,161 @@
1
+ import { AuthenticationError, ConflictError, DeployEngineError, NotFoundError, PermissionDeniedError, RateLimitError, ValidationError, } from "./errors.js";
2
+ import { VERSION } from "./version.js";
3
+ const errors = {
4
+ 400: ValidationError,
5
+ 401: AuthenticationError,
6
+ 403: PermissionDeniedError,
7
+ 404: NotFoundError,
8
+ 409: ConflictError,
9
+ 422: ValidationError,
10
+ 429: RateLimitError,
11
+ };
12
+ const retryable = new Set([429, 502, 503, 504]);
13
+ /**
14
+ * Low-level authenticated management client.
15
+ * Use `DeployEngineClient` for the convenient `api` resource registry.
16
+ */
17
+ export class DeployEngine {
18
+ /** Normalized DeployEngine origin used for every request. */
19
+ baseUrl;
20
+ auth;
21
+ timeoutMs;
22
+ maxRetries;
23
+ fetcher;
24
+ constructor(options) {
25
+ if (!options.apiKey && !options.accessToken)
26
+ throw new TypeError("apiKey or accessToken is required");
27
+ this.baseUrl = (options.baseUrl ?? "https://deployengine.creat01.com").replace(/\/$/, "");
28
+ this.auth = options.apiKey
29
+ ? { "X-API-KEY": options.apiKey }
30
+ : { Authorization: `Bearer ${options.accessToken}` };
31
+ this.timeoutMs = options.timeoutMs ?? 30_000;
32
+ this.maxRetries = Math.max(0, options.maxRetries ?? 2);
33
+ this.fetcher = options.fetch ?? globalThis.fetch;
34
+ }
35
+ /**
36
+ * Send an API request and return the unwrapped `data` field.
37
+ *
38
+ * GET/HEAD requests may retry automatically. Writes retry only when
39
+ * `idempotencyKey` is present. API failures become typed SDK errors.
40
+ * Prefer a domain resource such as `client.api.projects` in application code.
41
+ */
42
+ async request(method, path, options = {}) {
43
+ const url = new URL(path, `${this.baseUrl}/`);
44
+ for (const [key, value] of Object.entries(options.query ?? {}))
45
+ if (value !== undefined && value !== null)
46
+ url.searchParams.set(key, String(value));
47
+ const headers = {
48
+ ...this.auth,
49
+ "User-Agent": `creat01deployengine-typescript/${VERSION}`,
50
+ "X-DeployEngine-SDK-Version": VERSION,
51
+ "X-Request-ID": crypto.randomUUID(),
52
+ ...options.headers,
53
+ };
54
+ if (options.body !== undefined)
55
+ headers["Content-Type"] = "application/json";
56
+ if (options.idempotencyKey)
57
+ headers["Idempotency-Key"] = options.idempotencyKey;
58
+ const canRetry = ["GET", "HEAD"].includes(method.toUpperCase()) ||
59
+ Boolean(options.idempotencyKey);
60
+ for (let attempt = 0;; attempt++) {
61
+ const controller = new AbortController();
62
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
63
+ try {
64
+ const response = await this.fetcher(url, {
65
+ method,
66
+ headers,
67
+ body: options.body === undefined
68
+ ? undefined
69
+ : JSON.stringify(options.body),
70
+ signal: options.signal ?? controller.signal,
71
+ });
72
+ const raw = await response.text();
73
+ let payload = {};
74
+ try {
75
+ payload = raw ? JSON.parse(raw) : {};
76
+ }
77
+ catch {
78
+ payload = {};
79
+ }
80
+ const bodyStatus = Number(payload?.status_code ?? response.status);
81
+ if (response.ok && bodyStatus < 400)
82
+ return (payload && Object.hasOwn(payload, "data") ? payload.data : payload);
83
+ if (canRetry &&
84
+ retryable.has(response.status) &&
85
+ attempt < this.maxRetries) {
86
+ await this.delay(attempt, response.headers.get("Retry-After"));
87
+ continue;
88
+ }
89
+ const ErrorType = errors[response.status] ?? DeployEngineError;
90
+ throw new ErrorType(payload?.detail ??
91
+ payload?.message ??
92
+ raw.slice(0, 500) ??
93
+ "DeployEngine request failed", response.status, payload?.code, response.headers.get("X-Request-ID") ?? undefined, payload?.data, retryable.has(response.status));
94
+ }
95
+ catch (error) {
96
+ if (error instanceof DeployEngineError ||
97
+ !canRetry ||
98
+ attempt >= this.maxRetries)
99
+ throw error;
100
+ await this.delay(attempt);
101
+ }
102
+ finally {
103
+ clearTimeout(timer);
104
+ }
105
+ }
106
+ }
107
+ delay(attempt, retryAfter) {
108
+ const seconds = retryAfter && /^\d+$/.test(retryAfter) ? Number(retryAfter) : 0;
109
+ return new Promise((resolve) => setTimeout(resolve, seconds ? seconds * 1000 : 250 * 2 ** attempt + Math.random() * 100));
110
+ }
111
+ /**
112
+ * Stream decoded Server-Sent Event `data:` payloads.
113
+ *
114
+ * JSON payloads are returned as `T`; plain-text payloads remain strings.
115
+ * Consuming a stream may start a side-effecting deployment or restart.
116
+ */
117
+ async *stream(method, path, body) {
118
+ const headers = {
119
+ ...this.auth,
120
+ Accept: "text/event-stream",
121
+ "X-Request-ID": crypto.randomUUID(),
122
+ };
123
+ if (body !== undefined)
124
+ headers["Content-Type"] = "application/json";
125
+ const response = await this.fetcher(new URL(path, `${this.baseUrl}/`), {
126
+ method,
127
+ headers,
128
+ body: body === undefined ? undefined : JSON.stringify(body),
129
+ });
130
+ if (!response.ok || !response.body)
131
+ throw new DeployEngineError(`Stream request failed (${response.status})`, response.status);
132
+ const reader = response.body
133
+ .pipeThrough(new TextDecoderStream())
134
+ .getReader();
135
+ let buffer = "";
136
+ try {
137
+ while (true) {
138
+ const { done, value } = await reader.read();
139
+ if (done)
140
+ break;
141
+ buffer += value;
142
+ const lines = buffer.split(/\r?\n/);
143
+ buffer = lines.pop() ?? "";
144
+ for (const line of lines)
145
+ if (line.startsWith("data:")) {
146
+ const data = line.slice(5).trim();
147
+ try {
148
+ yield JSON.parse(data);
149
+ }
150
+ catch {
151
+ yield data;
152
+ }
153
+ }
154
+ }
155
+ }
156
+ finally {
157
+ reader.releaseLock();
158
+ }
159
+ }
160
+ }
161
+ /** Authenticated transport used by all DeployEngine management resources. */
@@ -0,0 +1,28 @@
1
+ /** Typed errors raised by DeployEngine management requests. */
2
+ export declare class DeployEngineError extends Error {
3
+ statusCode?: number | undefined;
4
+ code?: string | undefined;
5
+ requestId?: string | undefined;
6
+ details?: unknown | undefined;
7
+ retryable: boolean;
8
+ /** Create an error containing server diagnostics and retry metadata. */
9
+ constructor(message: string, statusCode?: number | undefined, code?: string | undefined, requestId?: string | undefined, details?: unknown | undefined, retryable?: boolean);
10
+ }
11
+ /** The credential is missing, invalid, or expired (HTTP 401). */
12
+ export declare class AuthenticationError extends DeployEngineError {
13
+ }
14
+ /** The credential lacks the required API scope (HTTP 403). */
15
+ export declare class PermissionDeniedError extends DeployEngineError {
16
+ }
17
+ /** The resource is missing or inaccessible to this account (HTTP 404). */
18
+ export declare class NotFoundError extends DeployEngineError {
19
+ }
20
+ /** The operation conflicts with current resource state (HTTP 409). */
21
+ export declare class ConflictError extends DeployEngineError {
22
+ }
23
+ /** Request fields or query parameters are invalid (HTTP 400/422). */
24
+ export declare class ValidationError extends DeployEngineError {
25
+ }
26
+ /** A server rate limit was exceeded and the operation may be retryable. */
27
+ export declare class RateLimitError extends DeployEngineError {
28
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,36 @@
1
+ /** Typed errors raised by DeployEngine management requests. */
2
+ export class DeployEngineError extends Error {
3
+ statusCode;
4
+ code;
5
+ requestId;
6
+ details;
7
+ retryable;
8
+ /** Create an error containing server diagnostics and retry metadata. */
9
+ constructor(message, statusCode, code, requestId, details, retryable = false) {
10
+ super(message);
11
+ this.statusCode = statusCode;
12
+ this.code = code;
13
+ this.requestId = requestId;
14
+ this.details = details;
15
+ this.retryable = retryable;
16
+ this.name = new.target.name;
17
+ }
18
+ }
19
+ /** The credential is missing, invalid, or expired (HTTP 401). */
20
+ export class AuthenticationError extends DeployEngineError {
21
+ }
22
+ /** The credential lacks the required API scope (HTTP 403). */
23
+ export class PermissionDeniedError extends DeployEngineError {
24
+ }
25
+ /** The resource is missing or inaccessible to this account (HTTP 404). */
26
+ export class NotFoundError extends DeployEngineError {
27
+ }
28
+ /** The operation conflicts with current resource state (HTTP 409). */
29
+ export class ConflictError extends DeployEngineError {
30
+ }
31
+ /** Request fields or query parameters are invalid (HTTP 400/422). */
32
+ export class ValidationError extends DeployEngineError {
33
+ }
34
+ /** A server rate limit was exceeded and the operation may be retryable. */
35
+ export class RateLimitError extends DeployEngineError {
36
+ }
@@ -0,0 +1,38 @@
1
+ /** Main package entry point for management, tracking, logging, models, and errors. */
2
+ export * from "./client.js";
3
+ export * from "./errors.js";
4
+ export * from "./resources/index.js";
5
+ export * from "./tracking/index.js";
6
+ export * from "./logging/index.js";
7
+ export * from "./models/index.js";
8
+ export * from "./version.js";
9
+ import { DeployEngine, type ClientOptions } from "./client.js";
10
+ /** Management client with all supported domain resources under `api`. */
11
+ export declare class DeployEngineClient extends DeployEngine {
12
+ /** Domain resources such as `projects`, `machines`, and `securityGroups`. */
13
+ readonly api: {
14
+ projects: import("./resources/projects.js").Projects;
15
+ machines: import("./resources/machines.js").Machines;
16
+ loadBalancers: import("./resources/load-balancers.js").LoadBalancers;
17
+ securityGroups: import("./resources/security-groups.js").SecurityGroups;
18
+ workflows: import("./resources/base.js").Resource<unknown>;
19
+ certificates: import("./resources/base.js").Resource<unknown>;
20
+ domains: import("./resources/base.js").Resource<unknown>;
21
+ alerts: import("./resources/base.js").Resource<unknown>;
22
+ feedback: import("./resources/feedback.js").Feedback;
23
+ payments: import("./resources/payments.js").Payments;
24
+ authentication: import("./resources/authentication.js").Authentication;
25
+ tracking: import("./resources/tracking.js").TrackingAdmin;
26
+ };
27
+ /**
28
+ * Create a management client and install every domain resource.
29
+ * @example
30
+ * ```ts
31
+ * const client = new DeployEngineClient({
32
+ * apiKey: process.env.DEPLOYENGINE_API_KEY
33
+ * })
34
+ * const projects = await client.api.projects.list()
35
+ * ```
36
+ */
37
+ constructor(options: ClientOptions);
38
+ }
package/dist/index.js ADDED
@@ -0,0 +1,29 @@
1
+ /** Main package entry point for management, tracking, logging, models, and errors. */
2
+ export * from "./client.js";
3
+ export * from "./errors.js";
4
+ export * from "./resources/index.js";
5
+ export * from "./tracking/index.js";
6
+ export * from "./logging/index.js";
7
+ export * from "./models/index.js";
8
+ export * from "./version.js";
9
+ import { DeployEngine } from "./client.js";
10
+ import { resources } from "./resources/index.js";
11
+ /** Management client with all supported domain resources under `api`. */
12
+ export class DeployEngineClient extends DeployEngine {
13
+ /** Domain resources such as `projects`, `machines`, and `securityGroups`. */
14
+ api;
15
+ /**
16
+ * Create a management client and install every domain resource.
17
+ * @example
18
+ * ```ts
19
+ * const client = new DeployEngineClient({
20
+ * apiKey: process.env.DEPLOYENGINE_API_KEY
21
+ * })
22
+ * const projects = await client.api.projects.list()
23
+ * ```
24
+ */
25
+ constructor(options) {
26
+ super(options);
27
+ this.api = resources(this);
28
+ }
29
+ }
@@ -0,0 +1,2 @@
1
+ /** Structured logging exports backed by tracking write-key ingestion. */
2
+ export * from "./reporter.js";
@@ -0,0 +1,2 @@
1
+ /** Structured logging exports backed by tracking write-key ingestion. */
2
+ export * from "./reporter.js";
@@ -0,0 +1,30 @@
1
+ import type { Tracker } from "../tracking/tracker.js";
2
+ /** Static service and environment labels attached to every log event. */
3
+ export interface LogReporterContext {
4
+ service?: string;
5
+ environment?: string;
6
+ }
7
+ /** Per-message structured log metadata. */
8
+ export interface LogOptions {
9
+ attributes?: Record<string, unknown>;
10
+ exception?: unknown;
11
+ traceId?: string;
12
+ userId?: string;
13
+ }
14
+ /** Report structured `$log` events through a browser-safe `Tracker`. */
15
+ export declare class LogReporter {
16
+ private tracker;
17
+ private context;
18
+ /** Bind a tracker and optional static service/environment context. */
19
+ constructor(tracker: Tracker, context?: LogReporterContext);
20
+ /** Report a log with explicit level, attributes, exception, and trace context. */
21
+ log(level: string, message: string, options?: LogOptions): void;
22
+ /** Report a DEBUG event. */
23
+ debug(message: string, options?: {}): void;
24
+ /** Report an INFO event. */
25
+ info(message: string, options?: {}): void;
26
+ /** Report a WARNING event. */
27
+ warn(message: string, options?: {}): void;
28
+ /** Report an ERROR event. */
29
+ error(message: string, options?: {}): void;
30
+ }
@@ -0,0 +1,38 @@
1
+ /** Report structured `$log` events through a browser-safe `Tracker`. */
2
+ export class LogReporter {
3
+ tracker;
4
+ context;
5
+ /** Bind a tracker and optional static service/environment context. */
6
+ constructor(tracker, context = {}) {
7
+ this.tracker = tracker;
8
+ this.context = context;
9
+ }
10
+ /** Report a log with explicit level, attributes, exception, and trace context. */
11
+ log(level, message, options = {}) {
12
+ this.tracker.track("$log", {
13
+ level: level.toUpperCase(),
14
+ message,
15
+ service: this.context.service,
16
+ environment: this.context.environment,
17
+ trace_id: options.traceId,
18
+ attributes: options.attributes ?? {},
19
+ exception: options.exception,
20
+ }, options.userId);
21
+ }
22
+ /** Report a DEBUG event. */
23
+ debug(message, options = {}) {
24
+ this.log("DEBUG", message, options);
25
+ }
26
+ /** Report an INFO event. */
27
+ info(message, options = {}) {
28
+ this.log("INFO", message, options);
29
+ }
30
+ /** Report a WARNING event. */
31
+ warn(message, options = {}) {
32
+ this.log("WARNING", message, options);
33
+ }
34
+ /** Report an ERROR event. */
35
+ error(message, options = {}) {
36
+ this.log("ERROR", message, options);
37
+ }
38
+ }
@@ -0,0 +1,15 @@
1
+ /** A page of API results with one-based pagination metadata. */
2
+ export interface Page<T> {
3
+ items: T[];
4
+ page: number;
5
+ pageSize: number;
6
+ total: number;
7
+ }
8
+ /** Optional controls accepted by advanced request integrations. */
9
+ export interface RequestOptions {
10
+ timeoutMs?: number;
11
+ maxRetries?: number;
12
+ signal?: AbortSignal;
13
+ headers?: Record<string, string>;
14
+ idempotencyKey?: string;
15
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,4 @@
1
+ /** Public SDK request and response models. */
2
+ export * from "./common.js";
3
+ export * from "./projects.js";
4
+ export * from "./infrastructure.js";
@@ -0,0 +1,4 @@
1
+ /** Public SDK request and response models. */
2
+ export * from "./common.js";
3
+ export * from "./projects.js";
4
+ export * from "./infrastructure.js";
@@ -0,0 +1,21 @@
1
+ /** DeployEngine-managed load balancer summary. */
2
+ export interface LoadBalancer {
3
+ id: number;
4
+ name: string;
5
+ enabled: boolean;
6
+ gatewayMachineId: number;
7
+ }
8
+ /** Host firewall policy summary. */
9
+ export interface SecurityGroup {
10
+ id: number;
11
+ name: string;
12
+ description?: string;
13
+ }
14
+ /** Ingress or egress nftables rule accepted by security-group APIs. */
15
+ export interface SecurityGroupRule {
16
+ direction: "ingress" | "egress";
17
+ protocol: string;
18
+ portStart?: number;
19
+ portEnd?: number;
20
+ source?: string;
21
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,12 @@
1
+ /** Project fields commonly returned by DeployEngine APIs. */
2
+ export interface Project {
3
+ id: number;
4
+ name: string;
5
+ status?: string;
6
+ createdAt?: string;
7
+ }
8
+ /** Minimum supported body for creating a project. */
9
+ export interface CreateProjectRequest {
10
+ name: string;
11
+ machineId?: number;
12
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,10 @@
1
+ import { Resource } from "./base.js";
2
+ /** Project-facing unified-login operations requiring the `business` scope. */
3
+ export declare class Authentication extends Resource {
4
+ /** Send a verification code to an SMS phone number or email address. */
5
+ sendCode(kind: "sms" | "email", projectName: string, identifier: string): Promise<unknown>;
6
+ /** Exchange an SMS/email code for a project end-user login result. */
7
+ loginWithCode(kind: "sms" | "email", projectName: string, identifier: string, code: string): Promise<unknown>;
8
+ /** Authenticate a project end user with the password-login request body. */
9
+ passwordLogin(body: unknown): Promise<unknown>;
10
+ }
@@ -0,0 +1,26 @@
1
+ import { Resource } from "./base.js";
2
+ /** Project-facing unified-login operations requiring the `business` scope. */
3
+ export class Authentication extends Resource {
4
+ /** Send a verification code to an SMS phone number or email address. */
5
+ sendCode(kind, projectName, identifier) {
6
+ return this.client.request("POST", `${this.prefix}/${kind}/send-code`, {
7
+ body: { projectName, [kind === "sms" ? "phone" : "email"]: identifier },
8
+ });
9
+ }
10
+ /** Exchange an SMS/email code for a project end-user login result. */
11
+ loginWithCode(kind, projectName, identifier, code) {
12
+ return this.client.request("POST", `${this.prefix}/${kind}/login`, {
13
+ body: {
14
+ projectName,
15
+ [kind === "sms" ? "phone" : "email"]: identifier,
16
+ code,
17
+ },
18
+ });
19
+ }
20
+ /** Authenticate a project end user with the password-login request body. */
21
+ passwordLogin(body) {
22
+ return this.client.request("POST", `${this.prefix}/password/login`, {
23
+ body,
24
+ });
25
+ }
26
+ }
@@ -0,0 +1,18 @@
1
+ import type { DeployEngine } from "../client.js";
2
+ /** Generic CRUD resource used directly or extended by domain resources. */
3
+ export declare class Resource<T = unknown> {
4
+ protected client: DeployEngine;
5
+ protected prefix: string;
6
+ /** Bind a management client to an API path prefix. */
7
+ constructor(client: DeployEngine, prefix: string);
8
+ /** List visible resources, optionally filtered by API query fields. */
9
+ list(query?: Record<string, unknown>): Promise<T[]>;
10
+ /** Fetch one resource by its numeric or string API identifier. */
11
+ get(id: string | number): Promise<T>;
12
+ /** Create a resource; pass an idempotency key to make retries safe. */
13
+ create<D = unknown>(body: D, idempotencyKey?: string): Promise<T>;
14
+ /** Replace a resource with the supplied request body. */
15
+ update<D = unknown>(id: string | number, body: D): Promise<T>;
16
+ /** Permanently delete one resource. */
17
+ delete(id: string | number): Promise<unknown>;
18
+ }
@@ -0,0 +1,33 @@
1
+ /** Generic CRUD resource used directly or extended by domain resources. */
2
+ export class Resource {
3
+ client;
4
+ prefix;
5
+ /** Bind a management client to an API path prefix. */
6
+ constructor(client, prefix) {
7
+ this.client = client;
8
+ this.prefix = prefix;
9
+ }
10
+ /** List visible resources, optionally filtered by API query fields. */
11
+ list(query) {
12
+ return this.client.request("GET", this.prefix, { query });
13
+ }
14
+ /** Fetch one resource by its numeric or string API identifier. */
15
+ get(id) {
16
+ return this.client.request("GET", `${this.prefix}/${id}`);
17
+ }
18
+ /** Create a resource; pass an idempotency key to make retries safe. */
19
+ create(body, idempotencyKey) {
20
+ return this.client.request("POST", this.prefix, {
21
+ body,
22
+ idempotencyKey,
23
+ });
24
+ }
25
+ /** Replace a resource with the supplied request body. */
26
+ update(id, body) {
27
+ return this.client.request("PUT", `${this.prefix}/${id}`, { body });
28
+ }
29
+ /** Permanently delete one resource. */
30
+ delete(id) {
31
+ return this.client.request("DELETE", `${this.prefix}/${id}`);
32
+ }
33
+ }
@@ -0,0 +1,6 @@
1
+ import { Resource } from "./base.js";
2
+ /** Customer-feedback link operations in the `business` capability. */
3
+ export declare class Feedback extends Resource {
4
+ /** Create a short-lived feedback submission link, optionally for a project. */
5
+ createTicketLink(projectId?: number): Promise<unknown>;
6
+ }
@@ -0,0 +1,10 @@
1
+ import { Resource } from "./base.js";
2
+ /** Customer-feedback link operations in the `business` capability. */
3
+ export class Feedback extends Resource {
4
+ /** Create a short-lived feedback submission link, optionally for a project. */
5
+ createTicketLink(projectId) {
6
+ return this.client.request("POST", `${this.prefix}/ticket-link`, {
7
+ query: { projectId },
8
+ });
9
+ }
10
+ }
@@ -0,0 +1,35 @@
1
+ /** Domain resource registry installed on `DeployEngineClient.api`. */
2
+ import type { DeployEngine } from "../client.js";
3
+ import { Authentication } from "./authentication.js";
4
+ import { Feedback } from "./feedback.js";
5
+ import { LoadBalancers } from "./load-balancers.js";
6
+ import { Machines } from "./machines.js";
7
+ import { Payments } from "./payments.js";
8
+ import { Projects } from "./projects.js";
9
+ import { Resource } from "./base.js";
10
+ import { SecurityGroups } from "./security-groups.js";
11
+ import { TrackingAdmin } from "./tracking.js";
12
+ export * from "./base.js";
13
+ export * from "./projects.js";
14
+ export * from "./machines.js";
15
+ export * from "./load-balancers.js";
16
+ export * from "./security-groups.js";
17
+ export * from "./payments.js";
18
+ export * from "./authentication.js";
19
+ export * from "./feedback.js";
20
+ export * from "./tracking.js";
21
+ /** Construct all resource clients with their canonical API prefixes. */
22
+ export declare function resources(client: DeployEngine): {
23
+ projects: Projects;
24
+ machines: Machines;
25
+ loadBalancers: LoadBalancers;
26
+ securityGroups: SecurityGroups;
27
+ workflows: Resource<unknown>;
28
+ certificates: Resource<unknown>;
29
+ domains: Resource<unknown>;
30
+ alerts: Resource<unknown>;
31
+ feedback: Feedback;
32
+ payments: Payments;
33
+ authentication: Authentication;
34
+ tracking: TrackingAdmin;
35
+ };
@@ -0,0 +1,35 @@
1
+ import { Authentication } from "./authentication.js";
2
+ import { Feedback } from "./feedback.js";
3
+ import { LoadBalancers } from "./load-balancers.js";
4
+ import { Machines } from "./machines.js";
5
+ import { Payments } from "./payments.js";
6
+ import { Projects } from "./projects.js";
7
+ import { Resource } from "./base.js";
8
+ import { SecurityGroups } from "./security-groups.js";
9
+ import { TrackingAdmin } from "./tracking.js";
10
+ export * from "./base.js";
11
+ export * from "./projects.js";
12
+ export * from "./machines.js";
13
+ export * from "./load-balancers.js";
14
+ export * from "./security-groups.js";
15
+ export * from "./payments.js";
16
+ export * from "./authentication.js";
17
+ export * from "./feedback.js";
18
+ export * from "./tracking.js";
19
+ /** Construct all resource clients with their canonical API prefixes. */
20
+ export function resources(client) {
21
+ return {
22
+ projects: new Projects(client, "/api/projects"),
23
+ machines: new Machines(client, "/api/machines"),
24
+ loadBalancers: new LoadBalancers(client, "/api/load-balancers"),
25
+ securityGroups: new SecurityGroups(client, "/api/security-groups"),
26
+ workflows: new Resource(client, "/api/workflow-tasks"),
27
+ certificates: new Resource(client, "/api/certificates"),
28
+ domains: new Resource(client, "/api/domains"),
29
+ alerts: new Resource(client, "/api/alert/contacts"),
30
+ feedback: new Feedback(client, "/api/feedback"),
31
+ payments: new Payments(client, "/api/orders"),
32
+ authentication: new Authentication(client, "/api/unified-login"),
33
+ tracking: new TrackingAdmin(client, "/api/tracking"),
34
+ };
35
+ }
@@ -0,0 +1,10 @@
1
+ import { Resource } from "./base.js";
2
+ /** DeployEngine-managed load balancer operations (`infrastructure` scope). */
3
+ export declare class LoadBalancers extends Resource {
4
+ /** Partially update a load balancer from an API request body. */
5
+ update(id: string | number, body: unknown): Promise<unknown>;
6
+ /** Synchronize configuration to its gateway using a stable retry key. */
7
+ sync(id: number): Promise<unknown>;
8
+ /** Bind a project with an optional listener/upstream binding specification. */
9
+ bindProject(id: number, projectId: number, bindingSpec?: {}): Promise<unknown>;
10
+ }
@@ -0,0 +1,20 @@
1
+ import { Resource } from "./base.js";
2
+ /** DeployEngine-managed load balancer operations (`infrastructure` scope). */
3
+ export class LoadBalancers extends Resource {
4
+ /** Partially update a load balancer from an API request body. */
5
+ update(id, body) {
6
+ return this.client.request("PATCH", `${this.prefix}/${id}`, { body });
7
+ }
8
+ /** Synchronize configuration to its gateway using a stable retry key. */
9
+ sync(id) {
10
+ return this.client.request("POST", `${this.prefix}/${id}/sync`, {
11
+ idempotencyKey: `lb-sync-${id}`,
12
+ });
13
+ }
14
+ /** Bind a project with an optional listener/upstream binding specification. */
15
+ bindProject(id, projectId, bindingSpec = {}) {
16
+ return this.client.request("POST", `${this.prefix}/${id}/projects`, {
17
+ body: { projectId, bindingSpec },
18
+ });
19
+ }
20
+ }
@@ -0,0 +1,8 @@
1
+ import { Resource } from "./base.js";
2
+ /** Machine inventory and diagnostics operations requiring `machines` scope. */
3
+ export declare class Machines extends Resource {
4
+ /** Recommend machine sizing from the supplied workload requirements. */
5
+ recommendations(body: unknown): Promise<unknown>;
6
+ /** Return the current DeployEngine Agent state for a machine. */
7
+ agentStatus(id: number): Promise<unknown>;
8
+ }
@@ -0,0 +1,14 @@
1
+ import { Resource } from "./base.js";
2
+ /** Machine inventory and diagnostics operations requiring `machines` scope. */
3
+ export class Machines extends Resource {
4
+ /** Recommend machine sizing from the supplied workload requirements. */
5
+ recommendations(body) {
6
+ return this.client.request("POST", "/api/machines/recommendations", {
7
+ body,
8
+ });
9
+ }
10
+ /** Return the current DeployEngine Agent state for a machine. */
11
+ agentStatus(id) {
12
+ return this.client.request("GET", `/api/machines/${id}/agent/status`);
13
+ }
14
+ }
@@ -0,0 +1,11 @@
1
+ import { Resource } from "./base.js";
2
+ /** Unified-payment operations requiring the `business` scope. */
3
+ export declare class Payments extends Resource {
4
+ /**
5
+ * Create a payment order.
6
+ * Reuse `idempotencyKey` only for retries of the same logical order.
7
+ */
8
+ createOrder(body: unknown, idempotencyKey?: string): Promise<unknown>;
9
+ /** Request a partial or full refund in the API's configured fee unit. */
10
+ refund(orderNo: string, refundFee: number, reason?: string): Promise<unknown>;
11
+ }
@@ -0,0 +1,20 @@
1
+ import { Resource } from "./base.js";
2
+ /** Unified-payment operations requiring the `business` scope. */
3
+ export class Payments extends Resource {
4
+ /**
5
+ * Create a payment order.
6
+ * Reuse `idempotencyKey` only for retries of the same logical order.
7
+ */
8
+ createOrder(body, idempotencyKey) {
9
+ return this.client.request("POST", "/api/orders/create_v2", {
10
+ body,
11
+ idempotencyKey,
12
+ });
13
+ }
14
+ /** Request a partial or full refund in the API's configured fee unit. */
15
+ refund(orderNo, refundFee, reason) {
16
+ return this.client.request("POST", `/api/orders/${orderNo}/refund`, {
17
+ body: { refundFee, reason },
18
+ });
19
+ }
20
+ }
@@ -0,0 +1,22 @@
1
+ import { Resource } from "./base.js";
2
+ /** Project, deployment, and release operations (`read`/`deploy` scopes). */
3
+ export declare class Projects extends Resource {
4
+ /** List deployment records belonging to a project. */
5
+ deployments(id: number): Promise<unknown>;
6
+ /** List release-history records belonging to a project. */
7
+ releases(id: number): Promise<unknown>;
8
+ /** Validate deployment configuration without starting a deployment. */
9
+ precheck(id: number, body: unknown): Promise<unknown>;
10
+ /**
11
+ * Start a deployment and asynchronously yield decoded SSE progress events.
12
+ * @example
13
+ * ```ts
14
+ * for await (const event of client.api.projects.deployStream(7, body)) {
15
+ * console.log(event)
16
+ * }
17
+ * ```
18
+ */
19
+ deployStream(id: number, body: unknown): AsyncGenerator<unknown, any, any>;
20
+ /** Restart a deployed project and yield its SSE progress events. */
21
+ restartStream(id: number, body?: unknown): AsyncGenerator<unknown, any, any>;
22
+ }
@@ -0,0 +1,34 @@
1
+ import { Resource } from "./base.js";
2
+ /** Project, deployment, and release operations (`read`/`deploy` scopes). */
3
+ export class Projects extends Resource {
4
+ /** List deployment records belonging to a project. */
5
+ deployments(id) {
6
+ return this.client.request("GET", `/api/projects/${id}/deployments`);
7
+ }
8
+ /** List release-history records belonging to a project. */
9
+ releases(id) {
10
+ return this.client.request("GET", `/api/projects/${id}/release-history`);
11
+ }
12
+ /** Validate deployment configuration without starting a deployment. */
13
+ precheck(id, body) {
14
+ return this.client.request("POST", `/api/projects/${id}/deploy-precheck`, {
15
+ body,
16
+ });
17
+ }
18
+ /**
19
+ * Start a deployment and asynchronously yield decoded SSE progress events.
20
+ * @example
21
+ * ```ts
22
+ * for await (const event of client.api.projects.deployStream(7, body)) {
23
+ * console.log(event)
24
+ * }
25
+ * ```
26
+ */
27
+ deployStream(id, body) {
28
+ return this.client.stream("POST", `/api/projects/${id}/deploy-stream`, body);
29
+ }
30
+ /** Restart a deployed project and yield its SSE progress events. */
31
+ restartStream(id, body = {}) {
32
+ return this.client.stream("POST", `/api/projects/${id}/restart-stream`, body);
33
+ }
34
+ }
@@ -0,0 +1,10 @@
1
+ import { Resource } from "./base.js";
2
+ /** Host firewall policy operations requiring `infrastructure` scope. */
3
+ export declare class SecurityGroups extends Resource {
4
+ /** Partially update a DeployEngine-managed nftables security group. */
5
+ update(id: string | number, body: unknown): Promise<unknown>;
6
+ /** Apply the current policy to associated machines using a stable retry key. */
7
+ apply(id: number): Promise<unknown>;
8
+ /** Add a firewall rule; provide an idempotency key for safe retries. */
9
+ addRule(id: number, body: unknown, idempotencyKey?: string): Promise<unknown>;
10
+ }
@@ -0,0 +1,21 @@
1
+ import { Resource } from "./base.js";
2
+ /** Host firewall policy operations requiring `infrastructure` scope. */
3
+ export class SecurityGroups extends Resource {
4
+ /** Partially update a DeployEngine-managed nftables security group. */
5
+ update(id, body) {
6
+ return this.client.request("PATCH", `${this.prefix}/${id}`, { body });
7
+ }
8
+ /** Apply the current policy to associated machines using a stable retry key. */
9
+ apply(id) {
10
+ return this.client.request("POST", `${this.prefix}/${id}/apply`, {
11
+ idempotencyKey: `sg-apply-${id}`,
12
+ });
13
+ }
14
+ /** Add a firewall rule; provide an idempotency key for safe retries. */
15
+ addRule(id, body, idempotencyKey) {
16
+ return this.client.request("POST", `${this.prefix}/${id}/rules`, {
17
+ body,
18
+ idempotencyKey,
19
+ });
20
+ }
21
+ }
@@ -0,0 +1,6 @@
1
+ import { Resource } from "./base.js";
2
+ /** Low-level event ingestion using a project-scoped tracking write key. */
3
+ export declare class TrackingAdmin extends Resource {
4
+ /** Send an event batch without exposing a management API key. */
5
+ collect(appId: string, projectName: string, writeKey: string, events: unknown[]): Promise<unknown>;
6
+ }
@@ -0,0 +1,12 @@
1
+ import { Resource } from "./base.js";
2
+ /** Low-level event ingestion using a project-scoped tracking write key. */
3
+ export class TrackingAdmin extends Resource {
4
+ /** Send an event batch without exposing a management API key. */
5
+ collect(appId, projectName, writeKey, events) {
6
+ return this.client.request("POST", `${this.prefix}/v1/collect`, {
7
+ headers: { "X-Write-Key": writeKey },
8
+ body: { app_id: appId, project_name: projectName, events },
9
+ idempotencyKey: `tracking-${appId}-${crypto.randomUUID()}`,
10
+ });
11
+ }
12
+ }
@@ -0,0 +1,2 @@
1
+ /** Browser-safe tracking exports; use only project-scoped write keys. */
2
+ export * from "./tracker.js";
@@ -0,0 +1,2 @@
1
+ /** Browser-safe tracking exports; use only project-scoped write keys. */
2
+ export * from "./tracker.js";
@@ -0,0 +1,29 @@
1
+ /** Browser-safe event tracker configuration. */
2
+ export interface TrackerOptions {
3
+ /** DeployEngine public origin. */
4
+ baseUrl: string;
5
+ appId: string;
6
+ projectName: string;
7
+ writeKey: string;
8
+ /** Flush immediately when the queue reaches this size. Defaults to 20. */
9
+ flushAt?: number;
10
+ /** Periodic flush interval; set to zero to disable. Defaults to 5000 ms. */
11
+ flushIntervalMs?: number;
12
+ }
13
+ /** Queue and deliver browser-safe analytics events using a tracking write key. */
14
+ export declare class Tracker {
15
+ private options;
16
+ private queue;
17
+ private timer?;
18
+ private anonymousId;
19
+ constructor(options: TrackerOptions);
20
+ /** Queue an event and flush automatically when `flushAt` is reached. */
21
+ track(event: string, properties?: Record<string, unknown>, userId?: string): void;
22
+ /** Associate an anonymous visitor with an application user and traits. */
23
+ identify(anonymousId: string, userId: string, traits?: Record<string, unknown>): Promise<any>;
24
+ /** Deliver queued events; failed batches are restored for a later retry. */
25
+ flush(): Promise<void>;
26
+ /** Stop periodic delivery and flush all remaining events. */
27
+ close(): Promise<void>;
28
+ private send;
29
+ }
@@ -0,0 +1,72 @@
1
+ /** Queue and deliver browser-safe analytics events using a tracking write key. */
2
+ export class Tracker {
3
+ options;
4
+ queue = [];
5
+ timer;
6
+ anonymousId = crypto.randomUUID();
7
+ constructor(options) {
8
+ this.options = options;
9
+ if (options.flushIntervalMs !== 0)
10
+ this.timer = setInterval(() => void this.flush(), options.flushIntervalMs ?? 5000);
11
+ }
12
+ /** Queue an event and flush automatically when `flushAt` is reached. */
13
+ track(event, properties = {}, userId) {
14
+ this.queue.push({
15
+ event_name: event,
16
+ properties,
17
+ user_id: userId,
18
+ anonymous_id: this.anonymousId,
19
+ timestamp: new Date().toISOString(),
20
+ event_id: crypto.randomUUID(),
21
+ });
22
+ if (this.queue.length >= (this.options.flushAt ?? 20))
23
+ void this.flush();
24
+ }
25
+ /** Associate an anonymous visitor with an application user and traits. */
26
+ identify(anonymousId, userId, traits = {}) {
27
+ return this.send("/api/tracking/v1/identify", {
28
+ app_id: this.options.appId,
29
+ project_name: this.options.projectName,
30
+ anonymous_id: anonymousId,
31
+ user_id: userId,
32
+ traits,
33
+ });
34
+ }
35
+ /** Deliver queued events; failed batches are restored for a later retry. */
36
+ async flush() {
37
+ if (!this.queue.length)
38
+ return;
39
+ const events = this.queue.splice(0);
40
+ try {
41
+ await this.send("/api/tracking/v1/collect", {
42
+ app_id: this.options.appId,
43
+ project_name: this.options.projectName,
44
+ events,
45
+ });
46
+ }
47
+ catch (error) {
48
+ this.queue.unshift(...events);
49
+ throw error;
50
+ }
51
+ }
52
+ /** Stop periodic delivery and flush all remaining events. */
53
+ close() {
54
+ if (this.timer)
55
+ clearInterval(this.timer);
56
+ return this.flush();
57
+ }
58
+ async send(path, body) {
59
+ const response = await fetch(`${this.options.baseUrl.replace(/\/$/, "")}${path}`, {
60
+ method: "POST",
61
+ headers: {
62
+ "Content-Type": "application/json",
63
+ "X-Write-Key": this.options.writeKey,
64
+ },
65
+ body: JSON.stringify(body),
66
+ keepalive: true,
67
+ });
68
+ if (!response.ok)
69
+ throw new Error(`Tracking request failed (${response.status})`);
70
+ return response.json();
71
+ }
72
+ }
@@ -0,0 +1,2 @@
1
+ /** Installed SDK version included in diagnostic request headers. */
2
+ export declare const VERSION = "1.0.0";
@@ -0,0 +1,2 @@
1
+ /** Installed SDK version included in diagnostic request headers. */
2
+ export const VERSION = "1.0.0";
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "creat01deployengine",
3
+ "version": "1.0.0",
4
+ "description": "Official TypeScript SDK for DeployEngine",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ },
13
+ "./tracking": {
14
+ "types": "./dist/tracking/index.d.ts",
15
+ "import": "./dist/tracking/index.js"
16
+ },
17
+ "./logging": {
18
+ "types": "./dist/logging/index.d.ts",
19
+ "import": "./dist/logging/index.js"
20
+ },
21
+ "./errors": {
22
+ "types": "./dist/errors.d.ts",
23
+ "import": "./dist/errors.js"
24
+ }
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "README.md",
29
+ "AI_USAGE.md",
30
+ "LICENSE"
31
+ ],
32
+ "sideEffects": false,
33
+ "scripts": {
34
+ "clean": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\"",
35
+ "build": "npm run clean && tsc -p tsconfig.json",
36
+ "check": "tsc -p tsconfig.json --noEmit",
37
+ "test": "npm run build && node --test test/*.test.mjs",
38
+ "prepublishOnly": "npm run check && npm test"
39
+ },
40
+ "engines": {
41
+ "node": ">=18"
42
+ },
43
+ "devDependencies": {
44
+ "typescript": "^5.9.2"
45
+ },
46
+ "license": "MIT",
47
+ "publishConfig": {
48
+ "access": "public"
49
+ },
50
+ "directories": {
51
+ "test": "test"
52
+ },
53
+ "keywords": [],
54
+ "author": ""
55
+ }