@phala/cloud 0.1.1-beta.1 → 0.1.1-beta.3

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.
@@ -1,1128 +0,0 @@
1
- // src/types/client.ts
2
- import { z } from "zod";
3
- var ApiErrorSchema = z.object({
4
- detail: z.union([
5
- z.string(),
6
- z.array(
7
- z.object({
8
- msg: z.string(),
9
- type: z.string().optional(),
10
- ctx: z.record(z.unknown()).optional()
11
- })
12
- ),
13
- z.record(z.unknown())
14
- ]),
15
- type: z.string().optional(),
16
- code: z.string().optional()
17
- });
18
- var RequestError = class _RequestError extends Error {
19
- constructor(message, options) {
20
- super(message);
21
- this.name = "RequestError";
22
- this.isRequestError = true;
23
- this.status = options?.status;
24
- this.statusText = options?.statusText;
25
- this.data = options?.data;
26
- this.request = options?.request;
27
- this.response = options?.response;
28
- this.detail = options?.detail || message;
29
- this.code = options?.code;
30
- this.type = options?.type;
31
- }
32
- /**
33
- * Create RequestError from FetchError
34
- */
35
- static fromFetchError(error) {
36
- const parseResult = ApiErrorSchema.safeParse(error.data);
37
- if (parseResult.success) {
38
- return new _RequestError(error.message, {
39
- status: error.status ?? void 0,
40
- statusText: error.statusText ?? void 0,
41
- data: error.data,
42
- request: error.request ?? void 0,
43
- response: error.response ?? void 0,
44
- detail: parseResult.data.detail,
45
- code: parseResult.data.code ?? void 0,
46
- type: parseResult.data.type ?? void 0
47
- });
48
- }
49
- return new _RequestError(error.message, {
50
- status: error.status ?? void 0,
51
- statusText: error.statusText ?? void 0,
52
- data: error.data,
53
- request: error.request ?? void 0,
54
- response: error.response ?? void 0,
55
- detail: error.data?.detail || "Unknown API error",
56
- code: error.status?.toString() ?? void 0
57
- });
58
- }
59
- /**
60
- * Create RequestError from generic Error
61
- */
62
- static fromError(error, request) {
63
- return new _RequestError(error.message, {
64
- request: request ?? void 0,
65
- detail: error.message
66
- });
67
- }
68
- };
69
-
70
- // src/client.ts
71
- import { ofetch } from "ofetch";
72
- import debug from "debug";
73
- var SUPPORTED_API_VERSIONS = ["2025-05-31"];
74
- var logger = debug("phala::api-client");
75
- function formatHeaders(headers) {
76
- return Object.entries(headers).map(([key, value]) => ` -H "${key}: ${value}"`).join("\n");
77
- }
78
- function formatBody(body) {
79
- if (!body) return "";
80
- const bodyStr = typeof body === "string" ? body : JSON.stringify(body, null, 2);
81
- return ` -d '${bodyStr.replace(/'/g, "\\'")}'`;
82
- }
83
- function formatResponse(status, statusText, headers, body) {
84
- const headerEntries = [];
85
- headers.forEach((value, key) => {
86
- headerEntries.push(`${key}: ${value}`);
87
- });
88
- const headerStr = headerEntries.join("\n");
89
- const bodyStr = typeof body === "string" ? body : JSON.stringify(body, null, 2);
90
- return [
91
- `< HTTP/1.1 ${status} ${statusText}`,
92
- headerStr ? `< ${headerStr.replace(/\n/g, "\n< ")}` : "",
93
- "",
94
- bodyStr
95
- ].filter(Boolean).join("\n");
96
- }
97
- var Client = class {
98
- constructor(config = {}) {
99
- const resolvedConfig = {
100
- ...config,
101
- apiKey: config.apiKey || process?.env?.PHALA_CLOUD_API_KEY,
102
- baseURL: config.baseURL || process?.env?.PHALA_CLOUD_API_PREFIX || "https://cloud-api.phala.network/api/v1"
103
- };
104
- const version = resolvedConfig.version && SUPPORTED_API_VERSIONS.includes(resolvedConfig.version) ? resolvedConfig.version : SUPPORTED_API_VERSIONS[0];
105
- this.config = resolvedConfig;
106
- if (!resolvedConfig.useCookieAuth && !resolvedConfig.apiKey) {
107
- throw new Error(
108
- "API key is required. Provide it via config.apiKey or set PHALA_CLOUD_API_KEY environment variable."
109
- );
110
- }
111
- const { apiKey, baseURL, timeout, headers, useCookieAuth, onResponseError, ...fetchOptions } = resolvedConfig;
112
- const requestHeaders = {
113
- "X-Phala-Version": version,
114
- "Content-Type": "application/json"
115
- };
116
- if (headers && typeof headers === "object") {
117
- Object.entries(headers).forEach(([key, value]) => {
118
- if (typeof value === "string") {
119
- requestHeaders[key] = value;
120
- }
121
- });
122
- }
123
- if (!useCookieAuth && apiKey) {
124
- requestHeaders["X-API-Key"] = apiKey;
125
- }
126
- this.fetchInstance = ofetch.create({
127
- baseURL,
128
- timeout: timeout || 3e4,
129
- headers: requestHeaders,
130
- ...useCookieAuth ? { credentials: "include" } : {},
131
- ...fetchOptions,
132
- // Log request in cURL format
133
- onRequest({ request, options }) {
134
- if (logger.enabled) {
135
- const method = options.method || "GET";
136
- const url = typeof request === "string" ? request : request.url;
137
- const fullUrl = url.startsWith("http") ? url : `${baseURL}${url}`;
138
- const headerObj = {};
139
- if (options.headers && typeof options.headers === "object") {
140
- Object.entries(options.headers).forEach(([key, value]) => {
141
- if (typeof value === "string") {
142
- headerObj[key] = value;
143
- }
144
- });
145
- }
146
- const curlCommand = [
147
- `> curl -X ${method} "${fullUrl}"`,
148
- formatHeaders(headerObj),
149
- options.body ? formatBody(options.body) : ""
150
- ].filter(Boolean).join("\n");
151
- logger("\n=== REQUEST ===\n%s\n", curlCommand);
152
- }
153
- },
154
- // Log response in cURL format
155
- onResponse({ request, response, options }) {
156
- if (logger.enabled) {
157
- const method = options.method || "GET";
158
- const url = typeof request === "string" ? request : request.url;
159
- logger(
160
- "\n=== RESPONSE [%s %s] (%dms) ===\n%s\n",
161
- method,
162
- url,
163
- response.headers.get("x-response-time") || "?",
164
- formatResponse(response.status, response.statusText, response.headers, response._data)
165
- );
166
- }
167
- },
168
- // Generic handlers for response error (similar to request.ts)
169
- onResponseError: ({ request, response, options }) => {
170
- console.warn(`HTTP ${response.status}: ${response.url}`);
171
- if (logger.enabled) {
172
- const method = options.method || "GET";
173
- const url = typeof request === "string" ? request : request.url;
174
- logger(
175
- "\n=== ERROR RESPONSE [%s %s] ===\n%s\n",
176
- method,
177
- url,
178
- formatResponse(response.status, response.statusText, response.headers, response._data)
179
- );
180
- }
181
- if (onResponseError) {
182
- onResponseError({ request, response, options });
183
- }
184
- }
185
- });
186
- }
187
- /**
188
- * Get the underlying ofetch instance for advanced usage
189
- */
190
- get raw() {
191
- return this.fetchInstance;
192
- }
193
- // ===== Direct methods (throw on error) =====
194
- /**
195
- * Perform GET request (throws on error)
196
- */
197
- async get(request, options) {
198
- return this.fetchInstance(request, {
199
- ...options,
200
- method: "GET"
201
- });
202
- }
203
- /**
204
- * Perform POST request (throws on error)
205
- */
206
- async post(request, body, options) {
207
- return this.fetchInstance(request, {
208
- ...options,
209
- method: "POST",
210
- body
211
- });
212
- }
213
- /**
214
- * Perform PUT request (throws on error)
215
- */
216
- async put(request, body, options) {
217
- return this.fetchInstance(request, {
218
- ...options,
219
- method: "PUT",
220
- body
221
- });
222
- }
223
- /**
224
- * Perform PATCH request (throws on error)
225
- */
226
- async patch(request, body, options) {
227
- return this.fetchInstance(request, {
228
- ...options,
229
- method: "PATCH",
230
- body
231
- });
232
- }
233
- /**
234
- * Perform DELETE request (throws on error)
235
- */
236
- async delete(request, options) {
237
- return this.fetchInstance(request, {
238
- ...options,
239
- method: "DELETE"
240
- });
241
- }
242
- // ===== Safe methods (return SafeResult) =====
243
- /**
244
- * Safe wrapper for any request method (zod-style result)
245
- */
246
- async safeRequest(fn) {
247
- try {
248
- const data = await fn();
249
- return { success: true, data };
250
- } catch (error) {
251
- if (error && typeof error === "object" && "data" in error) {
252
- const requestError2 = RequestError.fromFetchError(error);
253
- return { success: false, error: requestError2 };
254
- }
255
- if (error instanceof Error) {
256
- const requestError2 = RequestError.fromError(error);
257
- return { success: false, error: requestError2 };
258
- }
259
- const requestError = new RequestError("Unknown error occurred", {
260
- detail: "Unknown error occurred"
261
- });
262
- return { success: false, error: requestError };
263
- }
264
- }
265
- /**
266
- * Safe GET request (returns SafeResult)
267
- */
268
- async safeGet(request, options) {
269
- return this.safeRequest(() => this.get(request, options));
270
- }
271
- /**
272
- * Safe POST request (returns SafeResult)
273
- */
274
- async safePost(request, body, options) {
275
- return this.safeRequest(() => this.post(request, body, options));
276
- }
277
- /**
278
- * Safe PUT request (returns SafeResult)
279
- */
280
- async safePut(request, body, options) {
281
- return this.safeRequest(() => this.put(request, body, options));
282
- }
283
- /**
284
- * Safe PATCH request (returns SafeResult)
285
- */
286
- async safePatch(request, body, options) {
287
- return this.safeRequest(() => this.patch(request, body, options));
288
- }
289
- /**
290
- * Safe DELETE request (returns SafeResult)
291
- */
292
- async safeDelete(request, options) {
293
- return this.safeRequest(() => this.delete(request, options));
294
- }
295
- /**
296
- * Extend client with additional actions
297
- *
298
- * @example
299
- * ```typescript
300
- * const client = createClient({ apiKey: 'xxx' })
301
- * .extend(publicActions)
302
- * .extend(cvmActions)
303
- *
304
- * await client.getCurrentUser() // Method call instead of function call
305
- * ```
306
- */
307
- extend(actions) {
308
- const actionsObj = typeof actions === "function" ? actions(this) : actions;
309
- const extended = Object.create(this);
310
- for (const [key, action] of Object.entries(actionsObj)) {
311
- if (typeof action === "function") {
312
- extended[key] = (...args) => action(this, ...args);
313
- }
314
- }
315
- return extended;
316
- }
317
- };
318
- function createClient(config = {}) {
319
- return new Client(config);
320
- }
321
-
322
- // src/utils/validate-parameters.ts
323
- function validateActionParameters(parameters) {
324
- if (parameters?.schema !== void 0 && parameters?.schema !== false) {
325
- if (typeof parameters.schema !== "object" || parameters.schema === null || !("parse" in parameters.schema) || typeof parameters.schema.parse !== "function") {
326
- throw new Error("Invalid schema: must be a Zod schema object, false, or undefined");
327
- }
328
- }
329
- }
330
- function safeValidateActionParameters(parameters) {
331
- if (parameters?.schema !== void 0 && parameters?.schema !== false) {
332
- if (typeof parameters.schema !== "object" || parameters.schema === null || !("parse" in parameters.schema) || typeof parameters.schema.parse !== "function") {
333
- return {
334
- success: false,
335
- error: {
336
- name: "ZodError",
337
- message: "Invalid schema: must be a Zod schema object, false, or undefined",
338
- issues: [
339
- {
340
- code: "invalid_type",
341
- expected: "object",
342
- received: typeof parameters.schema,
343
- path: ["schema"],
344
- message: "Invalid schema: must be a Zod schema object, false, or undefined"
345
- }
346
- ]
347
- }
348
- };
349
- }
350
- }
351
- return void 0;
352
- }
353
-
354
- // src/utils/define-action.ts
355
- function defineSimpleAction(schema, fn) {
356
- function action(client, parameters) {
357
- return _actionImpl(client, parameters);
358
- }
359
- async function _actionImpl(client, parameters) {
360
- validateActionParameters(parameters);
361
- const response = await fn(client);
362
- if (parameters?.schema === false) {
363
- return response;
364
- }
365
- const actualSchema = parameters?.schema || schema;
366
- return actualSchema.parse(response);
367
- }
368
- function safeAction(client, parameters) {
369
- return _safeActionImpl(client, parameters);
370
- }
371
- async function _safeActionImpl(client, parameters) {
372
- const parameterValidationError = safeValidateActionParameters(parameters);
373
- if (parameterValidationError) {
374
- return parameterValidationError;
375
- }
376
- const httpResult = await (async () => {
377
- try {
378
- const data = await fn(client);
379
- return { success: true, data };
380
- } catch (error) {
381
- if (error && typeof error === "object" && "isRequestError" in error) {
382
- return { success: false, error };
383
- }
384
- if (error && typeof error === "object" && "issues" in error) {
385
- return { success: false, error };
386
- }
387
- return {
388
- success: false,
389
- error: {
390
- name: "Error",
391
- message: error instanceof Error ? error.message : String(error)
392
- }
393
- };
394
- }
395
- })();
396
- if (!httpResult.success) {
397
- return httpResult;
398
- }
399
- if (parameters?.schema === false) {
400
- return { success: true, data: httpResult.data };
401
- }
402
- const actualSchema = parameters?.schema || schema;
403
- return actualSchema.safeParse(httpResult.data);
404
- }
405
- return {
406
- action,
407
- safeAction
408
- };
409
- }
410
- function defineAction(schema, fn) {
411
- function action(client, ...args) {
412
- const [params, parameters] = args;
413
- return _actionImpl(client, params, parameters);
414
- }
415
- async function _actionImpl(client, params, parameters) {
416
- validateActionParameters(parameters);
417
- const response = await fn(client, params);
418
- if (parameters?.schema === false) {
419
- return response;
420
- }
421
- const actualSchema = parameters?.schema || schema;
422
- return actualSchema.parse(response);
423
- }
424
- function safeAction(client, ...args) {
425
- const [params, parameters] = args;
426
- return _safeActionImpl(client, params, parameters);
427
- }
428
- async function _safeActionImpl(client, params, parameters) {
429
- const parameterValidationError = safeValidateActionParameters(parameters);
430
- if (parameterValidationError) {
431
- return parameterValidationError;
432
- }
433
- const httpResult = await (async () => {
434
- try {
435
- const data = await fn(client, params);
436
- return { success: true, data };
437
- } catch (error) {
438
- if (error && typeof error === "object" && "isRequestError" in error) {
439
- return { success: false, error };
440
- }
441
- if (error && typeof error === "object" && "issues" in error) {
442
- return { success: false, error };
443
- }
444
- return {
445
- success: false,
446
- error: {
447
- name: "Error",
448
- message: error instanceof Error ? error.message : String(error)
449
- }
450
- };
451
- }
452
- })();
453
- if (!httpResult.success) {
454
- return httpResult;
455
- }
456
- if (parameters?.schema === false) {
457
- return { success: true, data: httpResult.data };
458
- }
459
- const actualSchema = parameters?.schema || schema;
460
- return actualSchema.safeParse(httpResult.data);
461
- }
462
- return {
463
- action,
464
- safeAction
465
- };
466
- }
467
-
468
- // src/actions/get_current_user.ts
469
- import { z as z2 } from "zod";
470
- var CurrentUserSchema = z2.object({
471
- username: z2.string(),
472
- email: z2.string(),
473
- credits: z2.number(),
474
- granted_credits: z2.number(),
475
- avatar: z2.string(),
476
- team_name: z2.string(),
477
- team_tier: z2.string()
478
- }).passthrough();
479
- var { action: getCurrentUser, safeAction: safeGetCurrentUser } = defineSimpleAction(
480
- CurrentUserSchema,
481
- async (client) => {
482
- return await client.get("/auth/me");
483
- }
484
- );
485
-
486
- // src/types/supported_chains.ts
487
- import { anvil, base, mainnet } from "viem/chains";
488
- var SUPPORTED_CHAINS = {
489
- [mainnet.id]: mainnet,
490
- [base.id]: base,
491
- [anvil.id]: anvil
492
- };
493
-
494
- // src/types/kms_info.ts
495
- import { z as z3 } from "zod";
496
- var KmsInfoBaseSchema = z3.object({
497
- id: z3.string(),
498
- slug: z3.string().nullable(),
499
- url: z3.string(),
500
- version: z3.string(),
501
- chain_id: z3.number().nullable(),
502
- kms_contract_address: z3.string().nullable().transform((val) => val),
503
- gateway_app_id: z3.string().nullable().transform((val) => val)
504
- }).passthrough();
505
- var KmsInfoSchema = KmsInfoBaseSchema.transform((data) => {
506
- if (data.chain_id != null) {
507
- const chain = SUPPORTED_CHAINS[data.chain_id];
508
- if (chain) {
509
- return { ...data, chain };
510
- }
511
- }
512
- return data;
513
- });
514
-
515
- // src/actions/get_available_nodes.ts
516
- import { z as z4 } from "zod";
517
- var AvailableOSImageSchema = z4.object({
518
- name: z4.string(),
519
- is_dev: z4.boolean(),
520
- version: z4.union([
521
- z4.tuple([z4.number(), z4.number(), z4.number()]),
522
- z4.tuple([z4.number(), z4.number(), z4.number(), z4.number()])
523
- ]),
524
- os_image_hash: z4.string().nullable().optional()
525
- }).passthrough();
526
- var TeepodCapacitySchema = z4.object({
527
- teepod_id: z4.number(),
528
- name: z4.string(),
529
- listed: z4.boolean(),
530
- resource_score: z4.number(),
531
- remaining_vcpu: z4.number(),
532
- remaining_memory: z4.number(),
533
- remaining_cvm_slots: z4.number(),
534
- images: z4.array(AvailableOSImageSchema),
535
- support_onchain_kms: z4.boolean().optional(),
536
- fmspc: z4.string().nullable().optional(),
537
- device_id: z4.string().nullable().optional(),
538
- region_identifier: z4.string().nullable().optional(),
539
- default_kms: z4.string().nullable().optional(),
540
- kms_list: z4.array(z4.string()).default([])
541
- }).passthrough();
542
- var ResourceThresholdSchema = z4.object({
543
- max_instances: z4.number().nullable().optional(),
544
- max_vcpu: z4.number().nullable().optional(),
545
- max_memory: z4.number().nullable().optional(),
546
- max_disk: z4.number().nullable().optional()
547
- }).passthrough();
548
- var AvailableNodesSchema = z4.object({
549
- tier: z4.string(),
550
- // TeamTier is string enum
551
- capacity: ResourceThresholdSchema,
552
- nodes: z4.array(TeepodCapacitySchema),
553
- kms_list: z4.array(KmsInfoSchema)
554
- }).passthrough();
555
- var { action: getAvailableNodes, safeAction: safeGetAvailableNodes } = defineSimpleAction(
556
- AvailableNodesSchema,
557
- async (client) => {
558
- return await client.get("/teepods/available");
559
- }
560
- );
561
-
562
- // src/actions/list-instance-types.ts
563
- import { z as z5 } from "zod";
564
- var ListInstanceTypesRequestSchema = z5.object({
565
- page: z5.number().int().min(1).optional().default(1),
566
- page_size: z5.number().int().min(1).max(1e3).optional().default(100)
567
- }).strict();
568
- var InstanceTypeSchema = z5.object({
569
- id: z5.string(),
570
- name: z5.string(),
571
- description: z5.string(),
572
- vcpu: z5.number(),
573
- memory_mb: z5.number(),
574
- hourly_rate: z5.string(),
575
- requires_gpu: z5.boolean(),
576
- public: z5.boolean(),
577
- enabled: z5.boolean()
578
- }).passthrough();
579
- var PaginatedInstanceTypesSchema = z5.object({
580
- items: z5.array(InstanceTypeSchema),
581
- total: z5.number(),
582
- page: z5.number(),
583
- page_size: z5.number(),
584
- pages: z5.number()
585
- }).strict();
586
- var { action: listInstanceTypes, safeAction: safeListInstanceTypes } = defineAction(PaginatedInstanceTypesSchema, async (client, request) => {
587
- const validatedRequest = ListInstanceTypesRequestSchema.parse(request ?? {});
588
- const queryParams = new URLSearchParams();
589
- queryParams.append("page", validatedRequest.page.toString());
590
- queryParams.append("page_size", validatedRequest.page_size.toString());
591
- return await client.get(`/api/instance-types?${queryParams.toString()}`);
592
- });
593
-
594
- // src/actions/workspaces/list_workspaces.ts
595
- import { z as z6 } from "zod";
596
- var WorkspaceResponseSchema = z6.object({
597
- id: z6.string(),
598
- name: z6.string(),
599
- slug: z6.string().nullable(),
600
- tier: z6.string(),
601
- role: z6.string(),
602
- created_at: z6.string()
603
- }).passthrough();
604
- var PaginationMetadataSchema = z6.object({
605
- has_more: z6.boolean(),
606
- next_cursor: z6.string().nullable(),
607
- total: z6.number().nullable()
608
- }).passthrough();
609
- var ListWorkspacesSchema = z6.object({
610
- data: z6.array(WorkspaceResponseSchema),
611
- pagination: PaginationMetadataSchema
612
- }).passthrough();
613
- var { action: listWorkspaces, safeAction: safeListWorkspaces } = defineAction(ListWorkspacesSchema, async (client, request) => {
614
- const queryParams = new URLSearchParams();
615
- if (request?.cursor) queryParams.append("cursor", request.cursor);
616
- if (request?.limit) queryParams.append("limit", request.limit.toString());
617
- const url = queryParams.toString() ? `/workspaces?${queryParams.toString()}` : "/workspaces";
618
- return await client.get(url);
619
- });
620
-
621
- // src/actions/workspaces/get_workspace.ts
622
- var { action: getWorkspace, safeAction: safeGetWorkspace } = defineAction(WorkspaceResponseSchema, async (client, teamSlug) => {
623
- return await client.get(`/workspaces/${teamSlug}`);
624
- });
625
-
626
- // src/types/cvm_info.ts
627
- import { z as z7 } from "zod";
628
- var VmInfoSchema = z7.object({
629
- id: z7.string(),
630
- name: z7.string(),
631
- status: z7.string(),
632
- uptime: z7.string(),
633
- app_url: z7.string().nullable(),
634
- app_id: z7.string(),
635
- instance_id: z7.string().nullable(),
636
- configuration: z7.any().optional(),
637
- // TODO: add VmConfiguration schema if needed
638
- exited_at: z7.string().nullable(),
639
- boot_progress: z7.string().nullable(),
640
- boot_error: z7.string().nullable(),
641
- shutdown_progress: z7.string().nullable(),
642
- image_version: z7.string().nullable()
643
- });
644
- var ManagedUserSchema = z7.object({
645
- id: z7.number(),
646
- username: z7.string()
647
- });
648
- var CvmNodeSchema = z7.object({
649
- id: z7.number(),
650
- name: z7.string(),
651
- region_identifier: z7.string().optional()
652
- });
653
- var CvmNetworkUrlsSchema = z7.object({
654
- app: z7.string(),
655
- instance: z7.string()
656
- });
657
- var CvmInfoSchema = z7.object({
658
- hosted: VmInfoSchema,
659
- name: z7.string(),
660
- managed_user: ManagedUserSchema.optional().nullable(),
661
- node: CvmNodeSchema.optional().nullable(),
662
- listed: z7.boolean().default(false),
663
- status: z7.string(),
664
- in_progress: z7.boolean().default(false),
665
- dapp_dashboard_url: z7.string().nullable(),
666
- syslog_endpoint: z7.string().nullable(),
667
- allow_upgrade: z7.boolean().default(false),
668
- project_id: z7.string().nullable(),
669
- // HashedId is represented as string in JS
670
- project_type: z7.string().nullable(),
671
- billing_period: z7.string().nullable(),
672
- kms_info: KmsInfoSchema.nullable(),
673
- vcpu: z7.number().nullable(),
674
- memory: z7.number().nullable(),
675
- disk_size: z7.number().nullable(),
676
- gateway_domain: z7.string().nullable(),
677
- public_urls: z7.array(CvmNetworkUrlsSchema)
678
- }).partial();
679
- var CvmLegacyDetailSchema = z7.object({
680
- id: z7.number(),
681
- name: z7.string(),
682
- status: z7.string(),
683
- in_progress: z7.boolean(),
684
- teepod_id: z7.number().nullable(),
685
- teepod: CvmNodeSchema,
686
- app_id: z7.string(),
687
- vm_uuid: z7.string().nullable(),
688
- instance_id: z7.string().nullable(),
689
- vcpu: z7.number().nullable(),
690
- memory: z7.number().nullable(),
691
- disk_size: z7.number().nullable(),
692
- base_image: z7.string(),
693
- encrypted_env_pubkey: z7.string().nullable(),
694
- listed: z7.boolean(),
695
- project_id: z7.string().nullable(),
696
- project_type: z7.string().nullable(),
697
- public_sysinfo: z7.boolean(),
698
- public_logs: z7.boolean(),
699
- dapp_dashboard_url: z7.string().nullable(),
700
- syslog_endpoint: z7.string().nullable(),
701
- kms_info: KmsInfoSchema.nullable(),
702
- contract_address: z7.string().nullable(),
703
- deployer_address: z7.string().nullable(),
704
- scheduled_delete_at: z7.string().nullable(),
705
- public_urls: z7.array(CvmNetworkUrlsSchema),
706
- gateway_domain: z7.string().nullable()
707
- });
708
-
709
- // src/actions/cvms/get_cvm_info.ts
710
- import { z as z8 } from "zod";
711
- var GetCvmInfoRequestSchema = z8.object({
712
- id: z8.string().optional(),
713
- uuid: z8.string().regex(/^[0-9a-f]{8}[-]?[0-9a-f]{4}[-]?4[0-9a-f]{3}[-]?[89ab][0-9a-f]{3}[-]?[0-9a-f]{12}$/i).optional(),
714
- app_id: z8.string().refine(
715
- (val) => !val.startsWith("app_") && val.length === 40,
716
- "app_id should be 40 characters without prefix"
717
- ).transform((val) => val.startsWith("app_") ? val : `app_${val}`).optional(),
718
- instance_id: z8.string().refine(
719
- (val) => !val.startsWith("instance_") && val.length === 40,
720
- "instance_id should be 40 characters without prefix"
721
- ).transform((val) => val.startsWith("instance_") ? val : `instance_${val}`).optional()
722
- }).refine(
723
- (data) => !!(data.id || data.uuid || data.app_id || data.instance_id),
724
- "One of id, uuid, app_id, or instance_id must be provided"
725
- ).transform((data) => ({
726
- cvmId: data.id || data.uuid || data.app_id || data.instance_id,
727
- _raw: data
728
- }));
729
- var { action: getCvmInfo, safeAction: safeGetCvmInfo } = defineAction(CvmLegacyDetailSchema, async (client, request) => {
730
- const validatedRequest = GetCvmInfoRequestSchema.parse(request);
731
- return await client.get(`/cvms/${validatedRequest.cvmId}`);
732
- });
733
-
734
- // src/actions/cvms/get_cvm_list.ts
735
- import { z as z9 } from "zod";
736
- var GetCvmListRequestSchema = z9.object({
737
- page: z9.number().int().min(1).optional(),
738
- page_size: z9.number().int().min(1).optional(),
739
- node_id: z9.number().int().min(1).optional()
740
- }).strict();
741
- var GetCvmListSchema = z9.object({
742
- items: z9.array(CvmInfoSchema),
743
- total: z9.number(),
744
- page: z9.number(),
745
- page_size: z9.number(),
746
- pages: z9.number()
747
- }).strict();
748
- var { action: getCvmList, safeAction: safeGetCvmList } = defineAction(GetCvmListSchema, async (client, request) => {
749
- const validatedRequest = GetCvmListRequestSchema.parse(request ?? {});
750
- return await client.get("/cvms/paginated", { params: validatedRequest });
751
- });
752
-
753
- // src/actions/cvms/provision_cvm.ts
754
- import { z as z10 } from "zod";
755
- var ProvisionCvmSchema = z10.object({
756
- app_id: z10.string().nullable().optional(),
757
- app_env_encrypt_pubkey: z10.string().nullable().optional(),
758
- compose_hash: z10.string(),
759
- fmspc: z10.string().nullable().optional(),
760
- device_id: z10.string().nullable().optional(),
761
- os_image_hash: z10.string().nullable().optional(),
762
- teepod_id: z10.number().nullable().optional(),
763
- // Will be transformed to node_id
764
- node_id: z10.number().nullable().optional(),
765
- kms_id: z10.string().nullable().optional()
766
- }).passthrough().transform((data) => {
767
- if ("teepod_id" in data && data.teepod_id !== void 0) {
768
- const { teepod_id, ...rest } = data;
769
- return { ...rest, node_id: teepod_id };
770
- }
771
- return data;
772
- });
773
- var ProvisionCvmRequestSchema = z10.object({
774
- node_id: z10.number().optional(),
775
- // recommended
776
- teepod_id: z10.number().optional(),
777
- // deprecated, for compatibility
778
- name: z10.string(),
779
- image: z10.string(),
780
- vcpu: z10.number(),
781
- memory: z10.number(),
782
- disk_size: z10.number(),
783
- compose_file: z10.object({
784
- allowed_envs: z10.array(z10.string()).optional(),
785
- pre_launch_script: z10.string().optional(),
786
- docker_compose_file: z10.string().optional(),
787
- name: z10.string().optional(),
788
- kms_enabled: z10.boolean().optional(),
789
- public_logs: z10.boolean().optional(),
790
- public_sysinfo: z10.boolean().optional(),
791
- gateway_enabled: z10.boolean().optional(),
792
- // recommended
793
- tproxy_enabled: z10.boolean().optional()
794
- // deprecated, for compatibility
795
- }),
796
- listed: z10.boolean().optional(),
797
- instance_type: z10.string().nullable().optional(),
798
- kms_id: z10.string().optional(),
799
- env_keys: z10.array(z10.string()).optional()
800
- }).passthrough();
801
- function autofillComposeFileName(appCompose) {
802
- if (appCompose.compose_file && !appCompose.compose_file.name) {
803
- return {
804
- ...appCompose,
805
- compose_file: {
806
- ...appCompose.compose_file,
807
- name: appCompose.name
808
- }
809
- };
810
- }
811
- return appCompose;
812
- }
813
- function handleGatewayCompatibility(appCompose) {
814
- if (!appCompose.compose_file) {
815
- return appCompose;
816
- }
817
- const composeFile = { ...appCompose.compose_file };
818
- if (typeof composeFile.gateway_enabled === "boolean" && typeof composeFile.tproxy_enabled === "boolean") {
819
- delete composeFile.tproxy_enabled;
820
- } else if (typeof composeFile.tproxy_enabled === "boolean" && typeof composeFile.gateway_enabled === "undefined") {
821
- composeFile.gateway_enabled = composeFile.tproxy_enabled;
822
- delete composeFile.tproxy_enabled;
823
- if (typeof window !== "undefined" ? window.console : globalThis.console) {
824
- console.warn(
825
- "[phala/cloud] tproxy_enabled is deprecated, please use gateway_enabled instead. See docs for migration."
826
- );
827
- }
828
- }
829
- return {
830
- ...appCompose,
831
- compose_file: composeFile
832
- };
833
- }
834
- var { action: provisionCvm, safeAction: safeProvisionCvm } = defineAction(ProvisionCvmSchema, async (client, appCompose) => {
835
- const body = handleGatewayCompatibility(autofillComposeFileName(appCompose));
836
- let requestBody = { ...body };
837
- if (typeof body.node_id === "number") {
838
- requestBody = { ...body, teepod_id: body.node_id };
839
- delete requestBody.node_id;
840
- } else if (typeof body.teepod_id === "number") {
841
- console.warn("[phala/cloud] teepod_id is deprecated, please use node_id instead.");
842
- }
843
- return await client.post("/cvms/provision", requestBody);
844
- });
845
-
846
- // src/actions/cvms/commit_cvm_provision.ts
847
- import { z as z11 } from "zod";
848
- var CommitCvmProvisionSchema = z11.object({
849
- id: z11.number(),
850
- name: z11.string(),
851
- status: z11.string(),
852
- teepod_id: z11.number(),
853
- teepod: z11.object({
854
- id: z11.number(),
855
- name: z11.string()
856
- }).nullable(),
857
- user_id: z11.number().nullable(),
858
- app_id: z11.string().nullable(),
859
- vm_uuid: z11.string().nullable(),
860
- instance_id: z11.string().nullable(),
861
- app_url: z11.string().nullable(),
862
- base_image: z11.string().nullable(),
863
- vcpu: z11.number(),
864
- memory: z11.number(),
865
- disk_size: z11.number(),
866
- manifest_version: z11.number().nullable(),
867
- version: z11.string().nullable(),
868
- runner: z11.string().nullable(),
869
- docker_compose_file: z11.string().nullable(),
870
- features: z11.array(z11.string()).nullable(),
871
- created_at: z11.string(),
872
- encrypted_env_pubkey: z11.string().nullable().optional(),
873
- app_auth_contract_address: z11.string().nullable().optional(),
874
- deployer_address: z11.string().nullable().optional()
875
- }).passthrough();
876
- var CommitCvmProvisionRequestSchema = z11.object({
877
- encrypted_env: z11.string().optional().nullable(),
878
- app_id: z11.string(),
879
- compose_hash: z11.string().optional(),
880
- kms_id: z11.string().optional(),
881
- contract_address: z11.string().optional(),
882
- deployer_address: z11.string().optional(),
883
- env_keys: z11.array(z11.string()).optional().nullable()
884
- }).passthrough();
885
- var { action: commitCvmProvision, safeAction: safeCommitCvmProvision } = defineAction(CommitCvmProvisionSchema, async (client, payload) => {
886
- return await client.post("/cvms", payload);
887
- });
888
-
889
- // src/actions/cvms/get_cvm_compose_file.ts
890
- import { z as z13 } from "zod";
891
-
892
- // src/types/app_compose.ts
893
- import { z as z12 } from "zod";
894
- var LooseAppComposeSchema = z12.object({
895
- allowed_envs: z12.array(z12.string()).optional(),
896
- docker_compose_file: z12.string(),
897
- features: z12.array(z12.string()).optional(),
898
- name: z12.string().optional(),
899
- manifest_version: z12.number().optional(),
900
- kms_enabled: z12.boolean().optional(),
901
- public_logs: z12.boolean().optional(),
902
- public_sysinfo: z12.boolean().optional(),
903
- tproxy_enabled: z12.boolean().optional(),
904
- pre_launch_script: z12.string().optional()
905
- }).passthrough();
906
-
907
- // src/actions/cvms/get_cvm_compose_file.ts
908
- var GetCvmComposeFileRequestSchema = z13.object({
909
- id: z13.string().optional(),
910
- uuid: z13.string().regex(/^[0-9a-f]{8}[-]?[0-9a-f]{4}[-]?4[0-9a-f]{3}[-]?[89ab][0-9a-f]{3}[-]?[0-9a-f]{12}$/i).optional(),
911
- app_id: z13.string().refine(
912
- (val) => !val.startsWith("app_") && val.length === 40,
913
- "app_id should be 40 characters without prefix"
914
- ).transform((val) => val.startsWith("app_") ? val : `app_${val}`).optional(),
915
- instance_id: z13.string().refine(
916
- (val) => !val.startsWith("instance_") && val.length === 40,
917
- "instance_id should be 40 characters without prefix"
918
- ).transform((val) => val.startsWith("instance_") ? val : `instance_${val}`).optional()
919
- }).refine(
920
- (data) => !!(data.id || data.uuid || data.app_id || data.instance_id),
921
- "One of id, uuid, app_id, or instance_id must be provided"
922
- ).transform((data) => ({
923
- cvmId: data.id || data.uuid || data.app_id || data.instance_id,
924
- _raw: data
925
- }));
926
- var { action: getCvmComposeFile, safeAction: safeGetCvmComposeFile } = defineAction(LooseAppComposeSchema, async (client, request) => {
927
- const validatedRequest = GetCvmComposeFileRequestSchema.parse(request);
928
- return await client.get(`/cvms/${validatedRequest.cvmId}/compose_file`);
929
- });
930
-
931
- // src/actions/cvms/provision_cvm_compose_file_update.ts
932
- import { z as z14 } from "zod";
933
- var ProvisionCvmComposeFileUpdateRequestSchema = z14.object({
934
- id: z14.string().optional(),
935
- uuid: z14.string().regex(/^[0-9a-f]{8}[-]?[0-9a-f]{4}[-]?4[0-9a-f]{3}[-]?[89ab][0-9a-f]{3}[-]?[0-9a-f]{12}$/i).optional(),
936
- app_id: z14.string().refine(
937
- (val) => !val.startsWith("app_") && val.length === 40,
938
- "app_id should be 40 characters without prefix"
939
- ).transform((val) => val.startsWith("app_") ? val : `app_${val}`).optional(),
940
- instance_id: z14.string().refine(
941
- (val) => !val.startsWith("instance_") && val.length === 40,
942
- "instance_id should be 40 characters without prefix"
943
- ).transform((val) => val.startsWith("instance_") ? val : `instance_${val}`).optional(),
944
- app_compose: LooseAppComposeSchema,
945
- update_env_vars: z14.boolean().optional().nullable()
946
- }).refine(
947
- (data) => !!(data.id || data.uuid || data.app_id || data.instance_id),
948
- "One of id, uuid, app_id, or instance_id must be provided"
949
- ).transform((data) => ({
950
- cvmId: data.id || data.uuid || data.app_id || data.instance_id,
951
- request: data.app_compose,
952
- update_env_vars: data.update_env_vars,
953
- _raw: data
954
- }));
955
- var ProvisionCvmComposeFileUpdateResultSchema = z14.object({
956
- app_id: z14.string().nullable(),
957
- device_id: z14.string().nullable(),
958
- compose_hash: z14.string(),
959
- kms_info: KmsInfoSchema.nullable().optional()
960
- }).passthrough();
961
- var { action: provisionCvmComposeFileUpdate, safeAction: safeProvisionCvmComposeFileUpdate } = defineAction(ProvisionCvmComposeFileUpdateResultSchema, async (client, request) => {
962
- const validatedRequest = ProvisionCvmComposeFileUpdateRequestSchema.parse(request);
963
- return await client.post(
964
- `/cvms/${validatedRequest.cvmId}/compose_file/provision`,
965
- validatedRequest.request
966
- );
967
- });
968
-
969
- // src/actions/cvms/commit_cvm_compose_file_update.ts
970
- import { z as z15 } from "zod";
971
- var CommitCvmComposeFileUpdateRequestSchema = z15.object({
972
- id: z15.string().optional(),
973
- uuid: z15.string().regex(/^[0-9a-f]{8}[-]?[0-9a-f]{4}[-]?4[0-9a-f]{3}[-]?[89ab][0-9a-f]{3}[-]?[0-9a-f]{12}$/i).optional(),
974
- app_id: z15.string().refine(
975
- (val) => !val.startsWith("app_") && val.length === 40,
976
- "app_id should be 40 characters without prefix"
977
- ).transform((val) => val.startsWith("app_") ? val : `app_${val}`).optional(),
978
- instance_id: z15.string().refine(
979
- (val) => !val.startsWith("instance_") && val.length === 40,
980
- "instance_id should be 40 characters without prefix"
981
- ).transform((val) => val.startsWith("instance_") ? val : `instance_${val}`).optional(),
982
- compose_hash: z15.string().min(1, "Compose hash is required"),
983
- encrypted_env: z15.string().optional(),
984
- env_keys: z15.array(z15.string()).optional(),
985
- update_env_vars: z15.boolean().optional().nullable()
986
- }).refine(
987
- (data) => !!(data.id || data.uuid || data.app_id || data.instance_id),
988
- "One of id, uuid, app_id, or instance_id must be provided"
989
- ).transform((data) => ({
990
- cvmId: data.id || data.uuid || data.app_id || data.instance_id,
991
- compose_hash: data.compose_hash,
992
- encrypted_env: data.encrypted_env,
993
- env_keys: data.env_keys,
994
- update_env_vars: !!data.update_env_vars,
995
- _raw: data
996
- }));
997
- var CommitCvmComposeFileUpdateSchema = z15.any().transform(() => void 0);
998
- var { action: commitCvmComposeFileUpdate, safeAction: safeCommitCvmComposeFileUpdate } = defineAction(
999
- CommitCvmComposeFileUpdateSchema,
1000
- async (client, request) => {
1001
- const validatedRequest = CommitCvmComposeFileUpdateRequestSchema.parse(request);
1002
- return await client.patch(`/cvms/${validatedRequest.cvmId}/compose_file`, {
1003
- compose_hash: validatedRequest.compose_hash,
1004
- encrypted_env: validatedRequest.encrypted_env,
1005
- env_keys: validatedRequest.env_keys
1006
- });
1007
- }
1008
- );
1009
-
1010
- // src/actions/kms/get_kms_info.ts
1011
- import { z as z16 } from "zod";
1012
- var GetKmsInfoRequestSchema = z16.object({
1013
- kms_id: z16.string().min(1, "KMS ID is required")
1014
- });
1015
- var { action: getKmsInfo, safeAction: safeGetKmsInfo } = defineAction(KmsInfoSchema, async (client, request) => {
1016
- const validatedRequest = GetKmsInfoRequestSchema.parse(request);
1017
- return await client.get(`/kms/${validatedRequest.kms_id}`);
1018
- });
1019
-
1020
- // src/actions/kms/get_kms_list.ts
1021
- import { z as z17 } from "zod";
1022
- var GetKmsListRequestSchema = z17.object({
1023
- page: z17.number().int().min(1).optional(),
1024
- page_size: z17.number().int().min(1).optional(),
1025
- is_onchain: z17.boolean().optional()
1026
- }).strict();
1027
- var GetKmsListSchema = z17.object({
1028
- items: z17.array(KmsInfoSchema),
1029
- total: z17.number(),
1030
- page: z17.number(),
1031
- page_size: z17.number(),
1032
- pages: z17.number()
1033
- }).strict();
1034
- var { action: getKmsList, safeAction: safeGetKmsList } = defineAction(GetKmsListSchema, async (client, request) => {
1035
- const validatedRequest = GetKmsListRequestSchema.parse(request ?? {});
1036
- return await client.get("/kms", { params: validatedRequest });
1037
- });
1038
-
1039
- // src/actions/kms/get_app_env_encrypt_pubkey.ts
1040
- import { z as z18 } from "zod";
1041
- var GetAppEnvEncryptPubKeyRequestSchema = z18.object({
1042
- kms: z18.string().min(1, "KMS ID or slug is required"),
1043
- app_id: z18.string().refine(
1044
- (val) => val.length === 40 || val.startsWith("0x") && val.length === 42,
1045
- "App ID must be exactly 40 characters or 42 characters with 0x prefix"
1046
- )
1047
- }).strict();
1048
- var GetAppEnvEncryptPubKeySchema = z18.object({
1049
- public_key: z18.string(),
1050
- signature: z18.string()
1051
- }).strict();
1052
- var { action: getAppEnvEncryptPubKey, safeAction: safeGetAppEnvEncryptPubKey } = defineAction(GetAppEnvEncryptPubKeySchema, async (client, payload) => {
1053
- const validatedRequest = GetAppEnvEncryptPubKeyRequestSchema.parse(payload);
1054
- return await client.get(`/kms/${validatedRequest.kms}/pubkey/${validatedRequest.app_id}`);
1055
- });
1056
-
1057
- export {
1058
- ApiErrorSchema,
1059
- RequestError,
1060
- createClient,
1061
- validateActionParameters,
1062
- safeValidateActionParameters,
1063
- defineSimpleAction,
1064
- defineAction,
1065
- CurrentUserSchema,
1066
- getCurrentUser,
1067
- safeGetCurrentUser,
1068
- SUPPORTED_CHAINS,
1069
- KmsInfoSchema,
1070
- AvailableNodesSchema,
1071
- getAvailableNodes,
1072
- safeGetAvailableNodes,
1073
- ListInstanceTypesRequestSchema,
1074
- InstanceTypeSchema,
1075
- PaginatedInstanceTypesSchema,
1076
- listInstanceTypes,
1077
- safeListInstanceTypes,
1078
- WorkspaceResponseSchema,
1079
- PaginationMetadataSchema,
1080
- ListWorkspacesSchema,
1081
- listWorkspaces,
1082
- safeListWorkspaces,
1083
- getWorkspace,
1084
- safeGetWorkspace,
1085
- VmInfoSchema,
1086
- ManagedUserSchema,
1087
- CvmNodeSchema,
1088
- CvmNetworkUrlsSchema,
1089
- CvmInfoSchema,
1090
- CvmLegacyDetailSchema,
1091
- GetCvmInfoRequestSchema,
1092
- getCvmInfo,
1093
- safeGetCvmInfo,
1094
- GetCvmListRequestSchema,
1095
- GetCvmListSchema,
1096
- getCvmList,
1097
- safeGetCvmList,
1098
- ProvisionCvmSchema,
1099
- ProvisionCvmRequestSchema,
1100
- provisionCvm,
1101
- safeProvisionCvm,
1102
- CommitCvmProvisionSchema,
1103
- CommitCvmProvisionRequestSchema,
1104
- commitCvmProvision,
1105
- safeCommitCvmProvision,
1106
- GetCvmComposeFileRequestSchema,
1107
- getCvmComposeFile,
1108
- safeGetCvmComposeFile,
1109
- ProvisionCvmComposeFileUpdateRequestSchema,
1110
- ProvisionCvmComposeFileUpdateResultSchema,
1111
- provisionCvmComposeFileUpdate,
1112
- safeProvisionCvmComposeFileUpdate,
1113
- CommitCvmComposeFileUpdateRequestSchema,
1114
- CommitCvmComposeFileUpdateSchema,
1115
- commitCvmComposeFileUpdate,
1116
- safeCommitCvmComposeFileUpdate,
1117
- GetKmsInfoRequestSchema,
1118
- getKmsInfo,
1119
- safeGetKmsInfo,
1120
- GetKmsListRequestSchema,
1121
- GetKmsListSchema,
1122
- getKmsList,
1123
- safeGetKmsList,
1124
- GetAppEnvEncryptPubKeyRequestSchema,
1125
- GetAppEnvEncryptPubKeySchema,
1126
- getAppEnvEncryptPubKey,
1127
- safeGetAppEnvEncryptPubKey
1128
- };