@hupu-tech/shaper 0.0.0-stage → 0.2.2

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 (82) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/LICENSE +3 -0
  3. package/README.md +282 -2
  4. package/dist/api.d.ts +29 -0
  5. package/dist/auth.d.ts +80 -0
  6. package/dist/cli.js +14 -0
  7. package/dist/cloud-service.d.ts +55 -0
  8. package/dist/cloud.d.ts +71 -0
  9. package/dist/config.d.ts +21 -0
  10. package/dist/core.d.ts +17 -0
  11. package/dist/credentials.d.ts +23 -0
  12. package/dist/dev-runner.js +1 -0
  13. package/dist/dev.d.ts +66 -0
  14. package/dist/index.d.ts +9 -0
  15. package/dist/index.js +1 -0
  16. package/dist/legacy-cloud.d.ts +25 -0
  17. package/dist/runtime.d.ts +54 -0
  18. package/dist/runtime.js +1 -0
  19. package/dist/shared-2ZNSJXPO.js +15 -0
  20. package/dist/shared-BTZI42QW.js +17 -0
  21. package/dist/workspace.d.ts +84 -0
  22. package/package.json +73 -4
  23. package/skills/compat/hupu-cloud/SKILL.md +8 -0
  24. package/skills/core/hupu-business/SKILL.md +14 -0
  25. package/skills/core/hupu-business/references/runtime.md +55 -0
  26. package/skills/core/shaper-backend/SKILL.md +35 -0
  27. package/skills/core/shaper-backend/references/legacy.md +41 -0
  28. package/skills/core/shaper-backend/references/node-server.md +44 -0
  29. package/skills/core/shaper-design/SKILL.md +16 -0
  30. package/skills/core/shaper-development/SKILL.md +54 -0
  31. package/skills/core/shaper-game-development/SKILL.md +16 -0
  32. package/skills/core/shaper-product/SKILL.md +17 -0
  33. package/skills/core/shaper-product/references/ecosystem.md +10 -0
  34. package/skills/core/shaper-release/SKILL.md +17 -0
  35. package/skills/game/shaper-idle-game/SKILL.md +16 -0
  36. package/skills/manifest.json +18 -0
  37. package/templates/cloud-service/README.md +32 -0
  38. package/templates/cloud-service/cloud.json +30 -0
  39. package/templates/cloud-service/handlers.cjs +46 -0
  40. package/templates/cloud-service/migrations/202610250001_init.sql +5 -0
  41. package/templates/cloud-service/migrations/202610250002_events.sql +8 -0
  42. package/templates/h5/docs/design.md +3 -0
  43. package/templates/h5/docs/product.md +3 -0
  44. package/templates/h5/docs/validation.md +3 -0
  45. package/templates/h5/index.html +24 -0
  46. package/templates/h5/package-lock.json +828 -0
  47. package/templates/h5/package.json +15 -0
  48. package/templates/h5/public/.gitkeep +0 -0
  49. package/templates/h5/shaper.config.json +7 -0
  50. package/templates/h5/src/main.js +7 -0
  51. package/templates/h5/src/style.css +21 -0
  52. package/templates/h5/vite.config.js +4 -0
  53. package/templates/phaser/docs/design.md +3 -0
  54. package/templates/phaser/docs/product.md +3 -0
  55. package/templates/phaser/docs/validation.md +3 -0
  56. package/templates/phaser/index.html +2 -0
  57. package/templates/phaser/package-lock.json +1287 -0
  58. package/templates/phaser/package.json +19 -0
  59. package/templates/phaser/public/.gitkeep +0 -0
  60. package/templates/phaser/shaper.config.json +7 -0
  61. package/templates/phaser/src/game/create-game.ts +5 -0
  62. package/templates/phaser/src/game/rules/scoring.ts +2 -0
  63. package/templates/phaser/src/game/scenes/PlayScene.ts +15 -0
  64. package/templates/phaser/src/main.ts +4 -0
  65. package/templates/phaser/src/styles.css +1 -0
  66. package/templates/phaser/tsconfig.json +21 -0
  67. package/templates/phaser/vite.config.ts +4 -0
  68. package/templates/react/docs/design.md +3 -0
  69. package/templates/react/docs/product.md +3 -0
  70. package/templates/react/docs/validation.md +3 -0
  71. package/templates/react/index.html +2 -0
  72. package/templates/react/package-lock.json +1329 -0
  73. package/templates/react/package.json +22 -0
  74. package/templates/react/public/.gitkeep +0 -0
  75. package/templates/react/shaper.config.json +7 -0
  76. package/templates/react/src/app/App.tsx +5 -0
  77. package/templates/react/src/app/styles.css +1 -0
  78. package/templates/react/src/main.tsx +6 -0
  79. package/templates/react/tsconfig.json +21 -0
  80. package/templates/react/vite.config.ts +4 -0
  81. package/vendor/cloud-server/hupu-cloud-server-0.1.0.tgz +0 -0
  82. package/vendor/cloud-server/release.json +12 -0
package/dist/core.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { AuthManager } from './auth.js';
2
+ import { ShaperApi } from './api.js';
3
+ import { CloudApi } from './cloud.js';
4
+ import { LegacyCloudApi } from './legacy-cloud.js';
5
+ export declare class Shaper {
6
+ readonly auth: AuthManager;
7
+ readonly api: ShaperApi;
8
+ readonly cloud: CloudApi;
9
+ readonly legacyCloud: LegacyCloudApi;
10
+ constructor(auth: AuthManager);
11
+ static create(server?: string): Promise<Shaper>;
12
+ status(path?: string): Promise<{
13
+ server: string;
14
+ identity: unknown;
15
+ project?: {};
16
+ }>;
17
+ }
@@ -0,0 +1,23 @@
1
+ import { z } from 'zod';
2
+ declare const tokensSchema: z.ZodObject<{
3
+ accessToken: z.ZodString;
4
+ refreshToken: z.ZodOptional<z.ZodString>;
5
+ expiresAt: z.ZodNumber;
6
+ scope: z.ZodString;
7
+ }, z.core.$strict>;
8
+ export type Tokens = z.infer<typeof tokensSchema>;
9
+ export interface CredentialStore {
10
+ read(server: string): Promise<Tokens | undefined>;
11
+ write(server: string, tokens: Tokens): Promise<void>;
12
+ remove(server: string): Promise<void>;
13
+ }
14
+ /** One shared login per Shaper origin. Project directories never contain these files. */
15
+ export declare class FileCredentials implements CredentialStore {
16
+ private path;
17
+ read(server: string): Promise<Tokens | undefined>;
18
+ write(server: string, tokens: Tokens): Promise<void>;
19
+ remove(server: string): Promise<void>;
20
+ }
21
+ export declare function withCredentialLock<T>(server: string, action: () => Promise<T>): Promise<T>;
22
+ export declare function acquireLoginLock(server: string): Promise<() => Promise<void>>;
23
+ export {};
@@ -0,0 +1 @@
1
+ import{d as S,j as v,k as E,t as y}from"./shared-2ZNSJXPO.js";import{createServer as C}from"node:http";import{createServer as R}from"node:net";import{spawn as k}from"node:child_process";import{randomBytes as T,timingSafeEqual as b}from"node:crypto";import{join as I}from"node:path";import{mkdir as x}from"node:fs/promises";async function H(){let t=await v(process.argv[2]),m=process.argv[3],u=await E(t),l=await new Promise((e,o)=>{let n=R();n.once("error",o),n.listen(0,"127.0.0.1",()=>{let s=n.address();if(!s||typeof s=="string")return o(new Error("No free port"));n.close(()=>e(s.port))})}),c=u.devUrl.replaceAll("{port}",String(l));if(new URL(c).hostname!=="127.0.0.1"&&new URL(c).hostname!=="localhost")throw new Error("devUrl must be loopback");let h=T(32).toString("base64url"),r,a=!0,p=!1,g=!1,d=C(async(e,o)=>{let n=Buffer.from(e.headers.authorization??""),s=Buffer.from(`Bearer ${h}`);if(n.length!==s.length||!b(n,s)){o.writeHead(401).end();return}if(o.setHeader("Content-Type","application/json"),o.setHeader("Cache-Control","no-store"),e.method==="GET"&&e.url==="/status"){o.end(JSON.stringify({id:m,running:a,ready:p}));return}if(e.method==="POST"&&e.url==="/stop"){o.end(JSON.stringify({stopped:!0})),await i();return}o.writeHead(404).end()});async function i(){if(!g){if(g=!0,r?.pid)if(process.platform==="win32")k("taskkill",["/pid",String(r.pid),"/T","/F"],{stdio:"ignore"});else try{process.kill(-r.pid,"SIGTERM")}catch(e){if(e.code!=="ESRCH")throw e}setTimeout(()=>{if(r?.pid&&process.platform!=="win32")try{process.kill(-r.pid,"SIGKILL")}catch(e){e.code!=="ESRCH"&&console.error("Unable to terminate the development process group")}d.close(),process.exit(0)},3e3)}}await new Promise((e,o)=>{d.once("error",o),d.listen(0,"127.0.0.1",e)});let f=d.address();if(!f||typeof f=="string")throw new Error("No control port");let w=y(t);await x(w,{recursive:!0,mode:448}),await S(I(w,"session.json"),{id:m,root:t,controlUrl:`http://127.0.0.1:${f.port}`,token:h,url:c,startedAt:new Date().toISOString()}),r=k(u.devCommand.replaceAll("{port}",String(l)),{cwd:t,shell:!0,detached:process.platform!=="win32",stdio:["ignore","inherit","inherit"],env:{...process.env,SHAPER_DEV_PORT:String(l)}}),r.once("error",e=>{console.error(e.message),a=!1,i()}),r.once("exit",e=>{console.error(`Development process exited: ${e}`),a=!1,p=!1,i()}),setInterval(()=>{!a||p||fetch(c,{signal:AbortSignal.timeout(1e3),redirect:"error"}).then(e=>{p=e.ok}).catch(()=>{})},250).unref(),process.on("SIGTERM",()=>void i()),process.on("SIGINT",()=>void i())}H().catch(t=>{console.error(t instanceof Error?t.message:"Development runner failed"),process.exitCode=1});
package/dist/dev.d.ts ADDED
@@ -0,0 +1,66 @@
1
+ import { z } from 'zod';
2
+ export declare const sessionSchema: z.ZodObject<{
3
+ id: z.ZodString;
4
+ root: z.ZodString;
5
+ controlUrl: z.ZodString;
6
+ token: z.ZodString;
7
+ url: z.ZodString;
8
+ startedAt: z.ZodString;
9
+ }, z.core.$strict>;
10
+ export declare function sessionDirectory(root: string): string;
11
+ export declare function devStatus(path: string): Promise<{
12
+ running: boolean;
13
+ root: string;
14
+ ready?: never;
15
+ url?: never;
16
+ sessionId?: never;
17
+ } | {
18
+ root: string;
19
+ running: boolean;
20
+ ready: boolean;
21
+ url: string;
22
+ sessionId: string;
23
+ } | {
24
+ ready?: never;
25
+ root: string;
26
+ running: boolean;
27
+ url: string;
28
+ sessionId: string;
29
+ }>;
30
+ export declare function startDev(path: string): Promise<{
31
+ running: boolean;
32
+ root: string;
33
+ ready?: never;
34
+ url?: never;
35
+ sessionId?: never;
36
+ } | {
37
+ root: string;
38
+ running: boolean;
39
+ ready: boolean;
40
+ url: string;
41
+ sessionId: string;
42
+ } | {
43
+ ready?: never;
44
+ root: string;
45
+ running: boolean;
46
+ url: string;
47
+ sessionId: string;
48
+ }>;
49
+ export declare function stopDev(path: string): Promise<{
50
+ sessionId?: never;
51
+ stopped: boolean;
52
+ alreadyStopped: boolean;
53
+ } | {
54
+ alreadyStopped?: never;
55
+ stopped: boolean;
56
+ sessionId: string;
57
+ }>;
58
+ export declare function devLogs(path: string): Promise<{
59
+ root: string;
60
+ log: string;
61
+ message?: never;
62
+ } | {
63
+ root: string;
64
+ log: string;
65
+ message: string;
66
+ }>;
@@ -0,0 +1,9 @@
1
+ export { Shaper } from './core.js';
2
+ export { AuthManager } from './auth.js';
3
+ export { ShaperApi } from './api.js';
4
+ export { CloudApi, type DeployInput, type CloudRequestResult, type CloudStatus, type CloudRouteTable } from './cloud.js';
5
+ export { LegacyCloudApi } from './legacy-cloud.js';
6
+ export { ShaperError } from './config.js';
7
+ export { initProject, linkProject, buildProject, checkProject, deployWeb, publishWeb } from './workspace.js';
8
+ export { startDev, stopDev, devStatus, devLogs } from './dev.js';
9
+ export { initCloudService, buildCloudService } from './cloud-service.js';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ import{a as o,b as r,c as a,d as c,e as f,f as m,g as S}from"./shared-BTZI42QW.js";import{a as e,m as t,n as p,o as u,q as l,r as i,s as d,u as x,v as s,w as y,x as C}from"./shared-2ZNSJXPO.js";export{o as AuthManager,f as CloudApi,m as LegacyCloudApi,S as Shaper,r as ShaperApi,e as ShaperError,c as buildCloudService,u as buildProject,d as checkProject,l as deployWeb,C as devLogs,x as devStatus,a as initCloudService,t as initProject,p as linkProject,i as publishWeb,s as startDev,y as stopDev};
@@ -0,0 +1,25 @@
1
+ import { ShaperApi, type RequestResult } from './api.js';
2
+ /** 仅用于维护旧执行器资源。与 CloudApi 无继承、无自动回退。 */
3
+ export declare class LegacyCloudApi {
4
+ readonly api: ShaperApi;
5
+ constructor(api: ShaperApi);
6
+ private base;
7
+ capabilities(path: string): Promise<unknown>;
8
+ environments(path: string): Promise<unknown>;
9
+ create(path: string, environment: string, postgres?: boolean): Promise<RequestResult>;
10
+ status(path: string, environment: string): Promise<unknown>;
11
+ functions(path: string, environment: string): Promise<unknown>;
12
+ deployFunction(path: string, environment: string, name: string, directory: string, key?: string): Promise<RequestResult>;
13
+ invoke(path: string, environment: string, name: string, payload: unknown, key?: string): Promise<RequestResult>;
14
+ logs(path: string, environment: string, name: string): Promise<unknown>;
15
+ sql(path: string, environment: string, sql: string, key?: string): Promise<RequestResult>;
16
+ listObjects(path: string, environment: string, prefix?: string, cursor?: string): Promise<unknown>;
17
+ putObject(path: string, environment: string, objectKey: string, file: string, key?: string): Promise<RequestResult>;
18
+ getObject(path: string, environment: string, objectKey: string, destination: string): Promise<{
19
+ key: string;
20
+ bytes: number;
21
+ path: string;
22
+ }>;
23
+ deleteObject(path: string, environment: string, objectKey: string, key?: string): Promise<RequestResult>;
24
+ private checkContained;
25
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Browser-only helpers for the existing Shaper ColorboxAI host bridge.
3
+ * This module carries no developer credentials and installs no replacement host SDK.
4
+ */
5
+ export interface HupuUserResponse {
6
+ code: number;
7
+ data?: {
8
+ islogin?: number | string;
9
+ isLogin?: boolean;
10
+ nickname?: string;
11
+ nickName?: string;
12
+ avatar?: string;
13
+ userHeadUrl?: string;
14
+ puid?: string;
15
+ userId?: string;
16
+ };
17
+ }
18
+ export interface HupuShare {
19
+ title: string;
20
+ link: string;
21
+ text?: string;
22
+ imageUrl?: string;
23
+ }
24
+ export interface HupuBridge {
25
+ auth?: {
26
+ getUserInfo(): Promise<HupuUserResponse>;
27
+ };
28
+ social?: {
29
+ share(input: HupuShare): Promise<unknown> | unknown;
30
+ };
31
+ }
32
+ type BridgeHost = {
33
+ ColorboxAI?: HupuBridge;
34
+ };
35
+ export declare class HupuRuntimeError extends Error {
36
+ readonly code: 'HOST_UNAVAILABLE' | 'LOGIN_REQUIRED' | 'INVALID_LINK';
37
+ constructor(code: 'HOST_UNAVAILABLE' | 'LOGIN_REQUIRED' | 'INVALID_LINK', message: string);
38
+ }
39
+ export declare function hupuClient(host?: BridgeHost): {
40
+ available(): boolean;
41
+ user(): Promise<{
42
+ signedIn: false;
43
+ displayName?: never;
44
+ avatarUrl?: never;
45
+ userId?: never;
46
+ } | {
47
+ signedIn: true;
48
+ displayName: string;
49
+ avatarUrl: string;
50
+ userId: string;
51
+ }>;
52
+ share(input: HupuShare): Promise<unknown>;
53
+ };
54
+ export {};
@@ -0,0 +1 @@
1
+ var t=class extends Error{constructor(n,e){super(e);this.code=n}};function a(s=globalThis){return{available(){return!!s.ColorboxAI?.auth?.getUserInfo},async user(){let r=s.ColorboxAI?.auth;if(!r?.getUserInfo)throw new t("HOST_UNAVAILABLE","\u8BF7\u5728 Shaper \u9884\u89C8\u6216\u864E\u6251\u5E94\u7528\u5BB9\u5668\u4E2D\u9A8C\u8BC1\u767B\u5F55\u3002");let n=await r.getUserInfo(),e=n.data;return n.code===200&&(e?.islogin===1||e?.islogin==="1"||e?.isLogin===!0)?{signedIn:!0,displayName:e?.nickname??e?.nickName??"",avatarUrl:e?.avatar??e?.userHeadUrl??"",userId:e?.puid??e?.userId??""}:{signedIn:!1}},async share(r){let n=s.ColorboxAI?.social;if(!n?.share)throw new t("HOST_UNAVAILABLE","\u5F53\u524D\u5BB9\u5668\u672A\u63D0\u4F9B\u864E\u6251\u5206\u4EAB\u80FD\u529B\u3002");let e;try{e=new URL(r.link)}catch{throw new t("INVALID_LINK","\u5206\u4EAB\u9700\u8981\u5B8C\u6574\u7684 HTTPS \u94FE\u63A5\u3002")}if(e.protocol!=="https:")throw new t("INVALID_LINK","\u5206\u4EAB\u9700\u8981\u5B8C\u6574\u7684 HTTPS \u94FE\u63A5\u3002");return await n.share(r)}}}export{t as HupuRuntimeError,a as hupuClient};
@@ -0,0 +1,15 @@
1
+ import{homedir as nt}from"node:os";import{join as C,resolve as ot,dirname as it}from"node:path";import{mkdir as at,readFile as st,rename as ct,writeFile as pt,lstat as dt,rm as lt}from"node:fs/promises";import{randomUUID as ut}from"node:crypto";import{z as P}from"zod";var a=class extends Error{constructor(n,r,o){super(r);this.code=n;this.details=o}},ft=P.object({schemaVersion:P.literal(1),server:P.string().url()}).strict();function b(){return ot(process.env.SHAPER_CONFIG_HOME??C(nt(),".config","shaper"))}function k(t){let e=new URL(t);if(e.username||e.password||e.search||e.hash||e.pathname!=="/"||e.protocol!=="https:"&&!(e.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(e.hostname)))throw new a("INVALID_SERVER","\u670D\u52A1\u5730\u5740\u5FC5\u987B\u662F HTTPS origin\uFF1B\u672C\u673A\u5F00\u53D1\u5141\u8BB8\u56DE\u73AF HTTP\u3002");return e.origin}async function v(t,e){await at(it(t),{recursive:!0,mode:448});try{if((await dt(t)).isSymbolicLink())throw new a("UNSAFE_FILE",`\u914D\u7F6E\u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5\uFF1A${t}`)}catch(r){if(r.code!=="ENOENT")throw r}let n=`${t}.${ut()}.tmp`;try{await pt(n,JSON.stringify(e,null,2)+`
2
+ `,{mode:384,flag:"wx"}),await ct(n,t)}finally{await lt(n,{force:!0})}}async function N(t){return JSON.parse(await st(t,"utf8"))}async function Ft(){if(process.env.SHAPER_SERVER)return k(process.env.SHAPER_SERVER);try{return k(ft.parse(await N(C(b(),"config.json"))).server)}catch(t){if(t.code==="ENOENT")return"https://shaper.hupu.com";throw new a("INVALID_CONFIG","\u7528\u6237\u914D\u7F6E\u65E0\u6CD5\u8BFB\u53D6\uFF0C\u8BF7\u4F7F\u7528 shaper config --server \u91CD\u65B0\u8BBE\u7F6E\u670D\u52A1\u5730\u5740\u3002")}}async function Vt(t){await v(C(b(),"config.json"),{schemaVersion:1,server:k(t)})}function $t(t){return{code:t instanceof a?t.code:"OPERATION_FAILED",message:t instanceof Error?t.message:"\u64CD\u4F5C\u672A\u5B8C\u6210",...t instanceof a&&t.details!==void 0?{details:t.details}:{}}}import{realpath as J,mkdir as M,readdir as U,readFile as I,writeFile as A,lstat as W,cp as wt,appendFile as ht}from"node:fs/promises";import{resolve as T,join as d,relative as F,sep as V,dirname as mt,basename as gt,isAbsolute as B}from"node:path";import{fileURLToPath as Et}from"node:url";import{randomUUID as q,createHash as Q}from"node:crypto";import{spawn as It}from"node:child_process";import yt from"adm-zip";import Nt from"open";import{z as g}from"zod";import X from"proper-lockfile";var R=T(mt(Et(import.meta.url)),".."),St=g.object({schemaVersion:g.literal(1),devCommand:g.string().min(1).max(500),buildCommand:g.string().min(1).max(500),outputDir:g.string().min(1),devUrl:g.string().default("http://127.0.0.1:{port}")}).passthrough(),vt=g.object({schemaVersion:g.literal(1),appId:g.string().min(1).max(200),server:g.string().url()}).strict();async function y(t){if(!t||!B(t))throw new a("WORKSPACE_REQUIRED","\u8BF7\u6307\u5B9A\u5DE5\u7A0B\u7684\u7EDD\u5BF9\u8DEF\u5F84\u3002");return J(T(t))}async function D(t){let e=d(t,".shaper");if(await M(e,{recursive:!0,mode:448}),(await W(e)).isSymbolicLink())throw new a("UNSAFE_WORKSPACE",".shaper \u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5\u3002");return e}async function j(t){return St.parse(await N(d(t,"shaper.config.json")))}async function $(t,e){let n=vt.parse(await N(d(t,".shaper","project.json")));if(n.server!==e)throw new a("SERVER_MISMATCH","\u6B64\u5DE5\u7A0B\u7ED1\u5B9A\u7684 Shaper \u670D\u52A1\u4E0E\u5F53\u524D\u767B\u5F55\u670D\u52A1\u4E0D\u540C\u3002\u8BF7\u663E\u5F0F\u5207\u6362\u670D\u52A1\u6216\u91CD\u65B0\u5173\u8054\u3002");return n}async function Y(t,e,n){let r=await D(t);await v(d(r,"project.json"),{schemaVersion:1,appId:e,server:n})}async function Zt(t,e,n={}){if(!e||!B(e))throw new a("WORKSPACE_REQUIRED","\u8BF7\u6307\u5B9A\u5DE5\u7A0B\u7684\u7EDD\u5BF9\u8DEF\u5F84\u3002");await M(e,{recursive:!0});let r=await y(e),o=await D(r),i=await X.lock(o,{retries:0});try{let s;try{s=await $(r,t.auth.server)}catch(p){if(p.code!=="ENOENT")throw p}if(s&&n.appId&&n.appId!==s.appId)throw new a("ALREADY_LINKED",`\u5F53\u524D\u76EE\u5F55\u5C5E\u4E8E ${s.appId}\uFF0C\u4E0E\u63D0\u793A\u8BCD\u4E2D\u7684 ${n.appId} \u4E0D\u4E00\u81F4\u3002\u8BF7\u56DE\u5230\u539F\u5E94\u7528\u7EE7\u7EED\uFF0C\u6216\u6362\u4E00\u4E2A\u7A7A\u76EE\u5F55\uFF1Binit \u4E0D\u4F1A\u8986\u76D6\u7ED1\u5B9A\u3002`);let l=(await U(r)).filter(p=>![".git",".shaper",".shaper.lock",".DS_Store"].includes(p));if(!s&&l.length&&n.template)throw new a("EXISTING_PROJECT","\u6A21\u677F\u53EA\u7528\u4E8E\u7A7A\u76EE\u5F55\uFF1B\u8BF7\u4FDD\u7559\u5DF2\u6709\u9879\u76EE\u7684\u6784\u5EFA\u65B9\u5F0F\u3002");if(n.template&&!["h5","react","phaser"].includes(n.template))throw new a("INVALID_TEMPLATE","\u652F\u6301 h5\u3001react\u3001phaser \u6A21\u677F\u3002");let c=new Set;for(let p of["shaper.config.json","shaper.project.json",".shaper/config.json"]){let E=await N(d(r,p)).catch(m=>{if(m.code!=="ENOENT")throw m});for(let m of[E?.appId,E?.applicationId])typeof m=="string"&&m.startsWith("app_")&&c.add(m)}let u=s?.appId??n.appId??[...c][0];if(c.size>1||u&&[...c].some(p=>p!==u))throw new a("APP_ID_CONFLICT","\u539F\u9879\u76EE\u5E94\u7528 ID \u4E0E\u76EE\u6807\u4E0D\u4E00\u81F4\uFF0C\u8BF7\u6838\u5BF9\u65E7\u9879\u76EE\u914D\u7F6E\uFF1B\u4E0D\u4F1A\u521B\u5EFA\u6216\u5207\u6362\u5E94\u7528\u3002");let f=d(o,"init.json"),h=s?void 0:await N(f).catch(p=>{if(p.code!=="ENOENT")throw p});if(!s&&h&&(!h.appId||h.server!==t.auth.server||u&&u!==h.appId))throw new a("INIT_CONFLICT","\u5B58\u5728\u672A\u5B8C\u6210\u7684\u521D\u59CB\u5316\uFF0C\u8BF7\u6838\u5BF9 .shaper/init.json \u4E2D\u7684\u539F\u5E94\u7528\u548C\u670D\u52A1\uFF0C\u4E0D\u8981\u53E6\u5EFA\u5E94\u7528\u3002");if(!u&&!h&&l.length)throw new a("APP_REQUIRED","\u5DF2\u6709\u9879\u76EE\u5C1A\u672A\u8BC6\u522B\u5230\u5E94\u7528 ID\u3002\u8BF7\u5148\u786E\u8BA4\u539F\u5E94\u7528\uFF0C\u518D\u4F7F\u7528 init --app\uFF1B\u65B0\u4F5C\u54C1\u8BF7\u4ECE\u7F51\u9875\u5F00\u59CB\u521B\u4F5C\u5E76\u643A\u5E26\u9884\u5206\u914D ID\u3002");let w=u??h?.appId??`app_${q().replaceAll("-","").slice(0,10)}`;!h&&!s&&(h={appId:w,server:t.auth.server},await v(f,h));let O;try{O=await t.project(w)}catch(p){if(!(p instanceof a)||!["AUTH_REQUIRED","INVALID_TOKEN","PROJECT_NOT_AUTHORIZED","INSUFFICIENT_SCOPE","NOT_FOUND"].includes(p.code))throw p;let E=await t.auth.start({appId:w,...n.name?{applicationName:n.name}:{},initialize:!s&&c.size===0,reauthorize:!0});if(E.status==="pending"){if(!n.waitForAuthorization)return{root:r,appId:w,...E,status:"awaiting_confirmation",next:"\u5728\u6D4F\u89C8\u5668\u5B8C\u6210\u767B\u5F55\u548C\u521B\u5EFA/\u5173\u8054\u786E\u8BA4\uFF0C\u6388\u6743\u5B8C\u6210\u540E\u4F7F\u7528\u540C\u4E00\u76EE\u5F55\u548C\u53C2\u6570\u91CD\u8BD5 init\u3002"};process.stderr.write(`\u8BF7\u5728\u6D4F\u89C8\u5668\u786E\u8BA4\u521B\u5EFA\u6216\u5173\u8054\u5E94\u7528\uFF1A${E.authorizationUrl}
3
+ `),await t.auth.wait(E.flowId)}O=await t.project(w)}let et=O.name;if(s)return n.installDependencies!==!1&&await I(d(o,"install-pending"),"utf8").catch(E=>{if(E.code==="ENOENT")return"";throw E})&&(await L("npm ci",r),await A(d(o,"install-pending"),"")),{root:r,...s,alreadyInitialized:!0};if(l.length===0){let p=n.template??"h5";if(!["h5","react","phaser"].includes(p))throw new a("INVALID_TEMPLATE","\u652F\u6301 h5\u3001react\u3001phaser \u6A21\u677F\u3002");let E=d(R,"templates",p);for(let m of(await U(E)).filter(S=>!["node_modules","dist"].includes(S)))await wt(d(E,m),d(r,m),{recursive:!0,force:!1,errorOnExist:!0});n.installDependencies!==!1&&await A(d(o,"install-pending"),`npm ci
4
+ `)}else{if(n.template)throw new a("EXISTING_PROJECT","\u6A21\u677F\u53EA\u7528\u4E8E\u7A7A\u76EE\u5F55\uFF1B\u5DF2\u6709\u5DE5\u7A0B\u76F4\u63A5 init\uFF0C\u4FDD\u7559\u6280\u672F\u6808\u548C\u6E90\u7801\u3002");try{await j(r)}catch(p){if(p.code!=="ENOENT")throw p;await v(d(r,"shaper.config.json"),{schemaVersion:1,devCommand:"npm run dev -- --host 127.0.0.1 --port {port} --strictPort",buildCommand:"npm run build",outputDir:"dist"})}}try{await I(d(r,"package.json"))}catch(p){if(p.code!=="ENOENT")throw p;if(await I(d(r,"index.html")).catch(m=>{if(m.code!=="ENOENT")throw m})!==void 0){for(let m of["package.json","package-lock.json","vite.config.js"])try{let S=await I(d(R,"templates/h5",m));if(m==="package.json"){let K=JSON.parse(S.toString("utf8"));K.scripts.check="vite build",S=Buffer.from(JSON.stringify(K,null,2)+`
5
+ `)}await A(d(r,m),S,{flag:"wx"})}catch(S){if(S.code!=="EEXIST")throw S}n.installDependencies!==!1&&await A(d(o,"install-pending"),`npm ci
6
+ `)}}await Z(r),await Y(r,w,t.auth.server);let rt=await I(d(o,"install-pending"),"utf8").catch(p=>{if(p.code==="ENOENT")return"";throw p});return n.installDependencies!==!1&&rt&&(await L("npm ci",r),await A(d(o,"install-pending"),"")),{root:r,name:et,appId:w}}finally{await i()}}async function te(t,e,n){let r=await y(e),o=await X.lock(await D(r),{retries:0});try{let i=await t.project(n);return await Y(r,i.appId,t.auth.server),await Z(r),{root:r,appId:i.appId,name:i.name}}finally{await o()}}async function Z(t){let e=d(t,".gitignore"),n=await I(e,"utf8").catch(f=>{if(f.code==="ENOENT")return"";throw f}),o=["/.shaper/","/.shaper.lock/","/node_modules/","/dist/",".env",".env.*","!.env.example"].filter(f=>!n.split(`
7
+ `).includes(f));o.length&&await ht(e,`
8
+ # Shaper local state and generated files
9
+ ${o.join(`
10
+ `)}
11
+ `);let i=d(t,"AGENTS.md"),s=await I(i,"utf8").catch(f=>{if(f.code==="ENOENT")return"";throw f}),l="<!-- shaper:project -->",c=`
12
+ ${l}
13
+ Read docs/product.md for goals and rules, docs/design.md for experience and implementation decisions, and docs/validation.md for actual evidence when these files exist. Use the globally installed shaper-development skill for local development and shaper-release for web delivery. For Hupu login/share use hupu-business; for functions or databases use shaper-backend. Pass this project's absolute path to project tools. Read shaper.config.json for commands and query shaper_status for live identity. Web publishing belongs to Shaper; cloud functions are deployed separately.
14
+ <!-- /shaper:project -->
15
+ `,u=s.includes(l)?s.replace(/<!-- shaper:project -->[\s\S]*?<!-- \/shaper:project -->\n?/,c.trimStart()):s+c;u!==s&&await A(i,u)}async function L(t,e){await new Promise((n,r)=>{let o=It(t,{cwd:e,shell:!0,stdio:["ignore","pipe","pipe"]});o.stdout.on("data",i=>process.stderr.write(i)),o.stderr.on("data",i=>process.stderr.write(i)),o.once("error",r),o.once("exit",i=>i===0?n():r(new a("COMMAND_FAILED",`\u5DE5\u7A0B\u547D\u4EE4\u9000\u51FA\u7801\uFF1A${i??"signal"}`)))})}async function xt(t){let e=await y(t),n=await j(e);await L(n.buildCommand,e);let r=await z(e,n.outputDir);return await I(d(r,"index.html")),{root:e,output:r}}async function z(t,e){let n=await J(T(t,e)),r=F(t,n);if(r===".."||r.startsWith(`..${V}`)||T(t,r)!==n)throw new a("INVALID_OUTPUT","\u8F93\u51FA\u76EE\u5F55\u5FC5\u987B\u4F4D\u4E8E\u5DE5\u7A0B\u5185\u90E8\u3002");return n}async function At(t,e={files:300,bytes:200*1024*1024}){let n=await J(t),r=new yt,o=0,i=0;async function s(l){for(let c of(await U(l,{withFileTypes:!0})).sort((u,f)=>u.name.localeCompare(f.name))){if(/^(\.git|\.shaper|node_modules|\.DS_Store)$/.test(c.name))continue;if(/^(\.env(?:\..*)?|credentials\.json|.*\.(pem|key))$/i.test(c.name))throw new a("SECRET_FILE_IN_PACKAGE",`\u8F93\u51FA\u76EE\u5F55\u5305\u542B\u654F\u611F\u914D\u7F6E\u6587\u4EF6\uFF1A${c.name}`);let u=d(l,c.name);if(c.isSymbolicLink())throw new a("SYMLINK_IN_PACKAGE",`\u4EA4\u4ED8\u5185\u5BB9\u4E2D\u4E0D\u5141\u8BB8\u7B26\u53F7\u94FE\u63A5\uFF1A${c.name}`);if(c.isDirectory()){await s(u);continue}if(!c.isFile())throw new a("INVALID_PACKAGE_FILE","\u4EA4\u4ED8\u76EE\u5F55\u5305\u542B\u975E\u5E38\u89C4\u6587\u4EF6\u3002");let f=await W(u);if(o+=f.size,i++,i>e.files||o>e.bytes)throw new a("PACKAGE_TOO_LARGE","\u4EA4\u4ED8\u5305\u8D85\u8FC7\u6587\u4EF6\u6570\u6216\u5927\u5C0F\u9650\u5236\u3002");r.addFile(F(n,u).split(V).join("/"),await I(u))}}await s(n);for(let l of r.getEntries())l.header.time=new Date(2e3,0,1);return{content:r.toBuffer(),files:i,bytes:o}}async function ee(t,e,n={}){let r=await y(e),o=await $(r,t.auth.server),i=n.build===!1?await z(r,(await j(r)).outputDir):(await xt(r)).output,s=await At(i),l=Q("sha256").update(s.content).digest("hex"),c=await D(r),u=d(c,"web-deploy.json"),f=q();try{let w=g.object({sha256:g.string(),key:g.string(),appId:g.string(),server:g.string()}).passthrough().parse(await N(u));w.sha256===l&&w.appId===o.appId&&w.server===t.auth.server&&(f=w.key)}catch(w){if(w.code!=="ENOENT")throw w}await v(u,{sha256:l,key:f,appId:o.appId,server:t.auth.server});let h=await t.request(`/api/v1/developer/projects/${encodeURIComponent(o.appId)}/web/deploy`,{method:"POST",file:s.content,key:f});return await v(u,{sha256:l,key:f,appId:o.appId,server:t.auth.server,response:h}),h}async function re(t,e,n,r,o){let i=await y(e),s=await $(i,t.auth.server),l=o?await I(await z(i,o)):void 0;if(l&&l.length>2*1024*1024)throw new a("INVALID_COVER","\u5C01\u9762\u4E0D\u80FD\u8D85\u8FC7 2 MiB\u3002");let c=l?{filename:gt(o),base64:l.toString("base64")}:void 0,u={versionId:n,description:r,...c?{cover:c}:{}},f=Q("sha256").update(JSON.stringify({appId:s.appId,body:u})).digest("hex"),h=await t.request(`/api/v1/developer/projects/${encodeURIComponent(s.appId)}/web/publish`,{method:"POST",body:u,key:f});if(h.result?.confirmationUrl){let w=new URL(h.result.confirmationUrl);if(w.origin!==t.auth.server||w.pathname!=="/applications/create")throw new a("INVALID_CONFIRMATION_URL","\u786E\u8BA4\u9875\u9762\u5730\u5740\u4E0D\u6B63\u786E");try{await Nt(w.href,{wait:!1})}catch{}}return{...h,submitted:!1,next:"\u5728\u6D4F\u89C8\u5668\u6838\u5BF9\u5E94\u7528\u4FE1\u606F\u5E76\u70B9\u51FB\u63D0\u4EA4\u5BA1\u6838\u3002\u901A\u8FC7\u5E94\u7528\u7248\u672C\u72B6\u6001\u67E5\u8BE2\u6700\u7EC8\u7ED3\u679C\u3002"}}async function ne(t){let e=await y(t),n=await j(e),r=[];try{await I(d(e,"package.json"))}catch{r.push("package.json \u4E0D\u5B58\u5728")}let o=T(e,n.outputDir),i=F(e,o);return(i===".."||i.startsWith(`..${V}`))&&r.push("outputDir \u8D85\u51FA\u5DE5\u7A0B\u76EE\u5F55"),{root:e,passed:r.length===0,findings:r,checks:["project configuration","package manifest","output path"],notRun:["application behavior","build","cloud connectivity"]}}import{createHash as jt,randomUUID as Tt}from"node:crypto";import{open as _t,mkdir as bt,readFile as Rt}from"node:fs/promises";import{join as _}from"node:path";import{spawn as Dt}from"node:child_process";import{z as x}from"zod";import Ot from"proper-lockfile";var Pt=x.object({id:x.string(),root:x.string(),controlUrl:x.string().url(),token:x.string(),url:x.string().url(),startedAt:x.string()}).strict();function G(t){return _(b(),"sessions",jt("sha256").update(t).digest("hex"))}async function tt(t){let e=Pt.parse(await N(_(G(t),"session.json")));if(e.root!==t||new URL(e.controlUrl).hostname!=="127.0.0.1")throw new a("INVALID_DEV_SESSION","\u672C\u5730\u5F00\u53D1\u4F1A\u8BDD\u8BB0\u5F55\u4E0D\u6B63\u786E\u3002");return e}async function H(t){let e=await y(t),n;try{n=await tt(e)}catch(r){if(r.code==="ENOENT")return{running:!1,root:e};throw r}try{let r=await fetch(`${n.controlUrl}/status`,{headers:{Authorization:`Bearer ${n.token}`},redirect:"error",signal:AbortSignal.timeout(1500)}),o=await r.json();if(!r.ok||o.id!==n.id)throw new Error("Session mismatch");return{root:e,running:o.running,ready:o.ready,url:n.url,sessionId:n.id}}catch{return{root:e,running:!1,url:n.url,sessionId:n.id}}}async function fe(t){let e=await y(t);await j(e);let n=G(e);await bt(n,{recursive:!0,mode:448});let r=await Ot.lock(n,{retries:0});try{let o=await H(e);if(o.running)return o;let i=await _t(_(n,"dev.log"),"w",384),s=Dt(process.execPath,[_(R,"dist","dev-runner.js"),e,Tt()],{cwd:e,detached:!0,stdio:["ignore",i.fd,i.fd],windowsHide:!0});await new Promise((l,c)=>{s.once("spawn",l),s.once("error",c)}),s.unref(),await i.close();for(let l=0;l<120;l++){await new Promise(u=>setTimeout(u,250));let c=await H(e);if(c.running&&c.ready)return c}throw new a("DEV_NOT_READY","\u5F00\u53D1\u670D\u52A1\u672A\u5728 30 \u79D2\u5185\u5C31\u7EEA\uFF0C\u8BF7\u67E5\u770B shaper logs\u3002\u8FD0\u884C\u72B6\u6001\u53EF\u901A\u8FC7 shaper status \u67E5\u8BE2\u3002")}finally{await r()}}async function we(t){let e=await y(t);if(!(await H(e)).running)return{stopped:!0,alreadyStopped:!0};let r=await tt(e);if(!(await fetch(`${r.controlUrl}/stop`,{method:"POST",headers:{Authorization:`Bearer ${r.token}`},redirect:"error",signal:AbortSignal.timeout(1e4)})).ok)throw new a("DEV_STOP_FAILED","\u5F00\u53D1\u4F1A\u8BDD\u672A\u80FD\u505C\u6B62\u3002");for(let i=0;i<30;i++){await new Promise(s=>setTimeout(s,200));try{await fetch(`${r.controlUrl}/status`,{headers:{Authorization:`Bearer ${r.token}`},redirect:"error",signal:AbortSignal.timeout(500)})}catch{return{stopped:!0,sessionId:r.id}}}throw new a("DEV_STOP_PENDING","\u505C\u6B62\u8BF7\u6C42\u5DF2\u53D1\u9001\uFF0C\u4F46\u4F1A\u8BDD\u4ECD\u672A\u9000\u51FA\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002")}async function he(t){let e=await y(t);try{let n=await Rt(_(G(e),"dev.log"),"utf8");return{root:e,log:n.slice(-16e3)}}catch(n){if(n.code==="ENOENT")return{root:e,log:"",message:"\u5C1A\u65E0\u672C\u5730\u8FD0\u884C\u65E5\u5FD7"};throw n}}export{a,b,k as c,v as d,N as e,Ft as f,Vt as g,$t as h,R as i,y as j,j as k,$ as l,Zt as m,te as n,xt as o,At as p,ee as q,re as r,ne as s,G as t,H as u,fe as v,we as w,he as x};
@@ -0,0 +1,17 @@
1
+ import{a,b as Y,c as A,d as ie,f as ae,h as C,i as O,j as S,k as ne,l as _,p as oe,u as ce}from"./shared-2ZNSJXPO.js";import*as w from"oauth4webapi";import{createHash as Ce}from"node:crypto";import{chmod as de,lstat as he,mkdir as $e,readFile as De,rm as Le,writeFile as xe}from"node:fs/promises";import{join as Z}from"node:path";import{execFile as Oe}from"node:child_process";import{promisify as Ue}from"node:util";import je from"proper-lockfile";import{z as T}from"zod";var pe=T.object({accessToken:T.string().min(1),refreshToken:T.string().min(1).optional(),expiresAt:T.number(),scope:T.string()}).strict(),Pe=T.object({schemaVersion:T.literal(1),server:T.string(),tokens:pe}).strict(),ue=Ue(Oe),U;async function le(n){await $e(n,{recursive:!0,mode:448});let e=await he(n);if(!e.isDirectory()||e.isSymbolicLink())throw new a("UNSAFE_AUTH_DIRECTORY","\u767B\u5F55\u76EE\u5F55\u5FC5\u987B\u662F\u5F53\u524D\u7528\u6237\u7684\u771F\u5B9E\u76EE\u5F55\u3002");if(process.platform==="win32"){if(!U){let{stdout:t}=await ue("whoami.exe",["/user","/fo","csv","/nh"],{windowsHide:!0});if(U=t.match(/S-1-\d+(?:-\d+)+/)?.[0],!U)throw new a("AUTH_DIRECTORY_UNAVAILABLE","\u65E0\u6CD5\u786E\u5B9A\u5F53\u524D Windows \u7528\u6237\u3002")}await ue("icacls.exe",[n,"/inheritance:r","/grant:r",`*${U}:(OI)(CI)F`,"/remove:g","*S-1-1-0","*S-1-5-11","*S-1-5-32-545"],{windowsHide:!0})}else{if(e.uid!==process.getuid?.())throw new a("UNSAFE_AUTH_DIRECTORY","\u767B\u5F55\u76EE\u5F55\u4E0D\u5C5E\u4E8E\u5F53\u524D\u7528\u6237\u3002");await de(n,448)}}function we(n){return Ce("sha256").update(A(n)).digest("hex")}async function fe(n){await le(Y());let e=Z(Y(),n);return await le(e),e}var j=class{async path(e){return Z(await fe("credentials"),`${we(e)}.json`)}async read(e){let t=await this.path(e);try{let r=await he(t);if(!r.isFile()||r.isSymbolicLink())throw new a("UNSAFE_CREDENTIAL_FILE","\u767B\u5F55\u51ED\u8BC1\u5FC5\u987B\u662F\u666E\u901A\u6587\u4EF6\u3002");if(process.platform!=="win32"){if(r.uid!==process.getuid?.())throw new a("UNSAFE_CREDENTIAL_FILE","\u767B\u5F55\u51ED\u8BC1\u4E0D\u5C5E\u4E8E\u5F53\u524D\u7528\u6237\u3002");await de(t,384)}let s=Pe.safeParse(JSON.parse(await De(t,"utf8")));if(!s.success||s.data.server!==A(e))throw new a("INVALID_CREDENTIAL_FILE","\u767B\u5F55\u51ED\u8BC1\u6587\u4EF6\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5\u7528\u6237\u914D\u7F6E\u76EE\u5F55\u3002");return s.data.tokens}catch(r){if(r.code==="ENOENT")return;throw r instanceof SyntaxError?new a("INVALID_CREDENTIAL_FILE","\u767B\u5F55\u51ED\u8BC1\u6587\u4EF6\u65E0\u6548\uFF0C\u8BF7\u68C0\u67E5\u7528\u6237\u914D\u7F6E\u76EE\u5F55\u3002"):r}}async write(e,t){await ie(await this.path(e),{schemaVersion:1,server:A(e),tokens:pe.parse(t)})}async remove(e){await Le(await this.path(e),{force:!0})}};async function me(n,e,t){let r=Z(await fe("locks"),`${we(n)}-${e}`);await xe(r,"",{flag:"a",mode:384});try{return await je.lock(r,{stale:12e4,retries:{retries:t,minTimeout:100,maxTimeout:1e3}})}catch(s){throw e==="login"&&s.code==="ELOCKED"?new a("AUTH_ALREADY_PENDING","\u5176\u4ED6\u7EC8\u7AEF\u6216 Agent \u6B63\u5728\u8FDE\u63A5 Shaper\uFF0C\u8BF7\u5148\u5B8C\u6210\u8BE5\u7F51\u9875\u6388\u6743\u3002"):s}}async function P(n,e){let t=await me(n,"tokens",30);try{return await e()}finally{await t()}}async function Q(n){return me(n,"login",0)}import{createServer as Fe}from"node:http";import{randomUUID as qe}from"node:crypto";import*as y from"oauth4webapi";import ze from"open";var I={client_id:"shaper-cli",token_endpoint_auth_method:"none"},F=class{constructor(e){this.release=e}id=qe();listener;timer;abort=new AbortController;state={flowId:this.id,status:"pending"};handling;released;status(){return{...this.state}}async finish(e){this.state.status==="pending"&&(this.state={flowId:this.id,status:e?"failed":"complete",...e?{message:e}:{}}),clearTimeout(this.timer),this.listener?.close(),this.released??=this.release(),await this.released}async close(){this.abort.abort(),this.handling&&await this.handling,await this.finish("\u6388\u6743\u5DF2\u53D6\u6D88\uFF0C\u8BF7\u91CD\u65B0\u53D1\u8D77\u3002")}async start(e){let{metadata:t}=e;if(!t.authorization_endpoint)throw new a("AUTH_UNAVAILABLE","\u670D\u52A1\u672A\u63D0\u4F9B\u7F51\u9875\u6388\u6743\u5165\u53E3\u3002");let r=y.generateRandomState(),s="";this.listener=Fe((l,p)=>{if(l.method!=="GET"||!l.url?.startsWith("/oauth/callback?")||this.handling||this.state.status!=="pending"){p.writeHead(404).end();return}let h;try{h=y.validateAuthResponse(t,I,new URL(l.url,s),r)}catch{let f=new URL(l.url,s).searchParams;f.get("state")===r&&f.has("error")&&this.finish("\u7F51\u9875\u6388\u6743\u5DF2\u53D6\u6D88\u3002"),p.writeHead(400,{"Content-Type":"text/plain; charset=utf-8"}).end("\u6388\u6743\u672A\u5B8C\u6210\u3002");return}this.handling=(async()=>{try{let f=await y.authorizationCodeGrantRequest(t,I,y.None(),h,s,e.verifier,{[y.allowInsecureRequests]:e.server.startsWith("http://"),signal:AbortSignal.any([this.abort.signal,AbortSignal.timeout(2e4)]),additionalParameters:{resource:`${e.server}/api/v1/developer`}}),v=await y.processAuthorizationCodeResponse(t,I,f);this.abort.signal.throwIfAborted(),await e.save(v),await this.finish(),p.writeHead(200,{"Content-Type":"text/html; charset=utf-8","Cache-Control":"no-store","Content-Security-Policy":"default-src 'none'; style-src 'unsafe-inline'"}).end('<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>Shaper \u5DF2\u8FDE\u63A5</title><h1>\u5F00\u53D1\u5DE5\u5177\u5DF2\u8FDE\u63A5</h1><p>\u53EF\u4EE5\u5173\u95ED\u6B64\u9875\u9762\uFF0C\u56DE\u5230 IDE \u6216\u7EC8\u7AEF\u7EE7\u7EED\u3002</p></html>')}catch{await this.finish("\u6388\u6743\u672A\u5B8C\u6210\uFF0C\u8BF7\u91CD\u65B0\u53D1\u8D77\u767B\u5F55\u3002"),p.writeHead(400,{"Content-Type":"text/plain; charset=utf-8"}).end("\u6388\u6743\u672A\u5B8C\u6210\u3002")}})()});let i=this.listener;await new Promise((l,p)=>{i.once("error",p),i.listen(0,"127.0.0.1",()=>{i.off("error",p),l()})});let u=i.address();if(!u||typeof u=="string")throw new a("CALLBACK_UNAVAILABLE","\u65E0\u6CD5\u542F\u52A8\u672C\u5730\u6388\u6743\u56DE\u8C03\u3002");s=`http://127.0.0.1:${u.port}/oauth/callback`;let o=new URL(t.authorization_endpoint),c={client_id:I.client_id,response_type:"code",redirect_uri:s,code_challenge:e.challenge,code_challenge_method:"S256",state:r,scope:e.scope,resource:`${e.server}/api/v1/developer`,prompt:"consent",...e.initialize?{shaper_init:"true"}:{},...e.applicationName?{shaper_name:e.applicationName}:{},...e.connection?{shaper_connection:e.connection}:{},...e.appId?{shaper_app:e.appId}:{}};for(let[l,p]of Object.entries(c))o.searchParams.set(l,p);if(this.timer=setTimeout(()=>{this.close()},3e5),this.timer.unref(),e.openBrowser!==!1)try{await ze(o.href,{wait:!1})}catch{}return{flowId:this.id,status:"pending",authorizationUrl:o.href,expiresIn:300}}};var X="openid offline_access projects:read projects:write web:deploy web:publish",He=`${X} cloud:read cloud:write`,Ve=(...n)=>[...new Set(n.flatMap(e=>e.split(" ")).filter(Boolean))].join(" "),q=class{constructor(e,t=new j){this.credentials=t;this.server=A(e)}flows=new Map;metadata;server;options(){return{[w.allowInsecureRequests]:this.server.startsWith("http://"),signal:AbortSignal.timeout(2e4)}}async discovery(){if(!this.metadata){let e=new URL(`${this.server}/api/oauth`),t=await w.processDiscoveryResponse(e,await w.discoveryRequest(e,this.options()));for(let r of["authorization_endpoint","token_endpoint","revocation_endpoint"]){let s=t[r];if(s&&new URL(s).origin!==this.server)throw new a("UNTRUSTED_AUTH_ENDPOINT","\u6388\u6743\u670D\u52A1\u8FD4\u56DE\u4E86\u5176\u4ED6\u6765\u6E90\u7684\u5730\u5740\u3002")}this.metadata=t}return this.metadata}async save(e,t){let r=e.refresh_token??t?.refreshToken;await this.credentials.write(this.server,{accessToken:e.access_token,expiresAt:Date.now()+(e.expires_in??900)*1e3,scope:e.scope??t?.scope??X,...r?{refreshToken:r}:{}})}async accessToken(){return P(this.server,async()=>{let e=await this.credentials.read(this.server);if(!e)throw new a("AUTH_REQUIRED","\u8BF7\u8FD0\u884C shaper login\uFF0C\u6216\u8C03\u7528 shaper_auth_start\u3002\u767B\u5F55\u7531\u672C\u673A\u6240\u6709\u9879\u76EE\u5171\u7528\u3002");if(e.expiresAt>Date.now()+6e4)return e.accessToken;if(!e.refreshToken)throw new a("AUTH_REQUIRED","\u6388\u6743\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002");let t=await this.discovery();try{let r=await w.refreshTokenGrantRequest(t,I,w.None(),e.refreshToken,{...this.options(),additionalParameters:{resource:`${this.server}/api/v1/developer`}}),s=await w.processRefreshTokenResponse(t,I,r);return await this.save(s,e),s.access_token}catch(r){throw r instanceof w.ResponseBodyError&&r.error==="invalid_grant"?new a("AUTH_REQUIRED","\u6388\u6743\u5DF2\u8FC7\u671F\u6216\u5DF2\u64A4\u9500\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u3002"):new a("AUTH_REFRESH_FAILED","\u6682\u65F6\u65E0\u6CD5\u7EED\u671F\u767B\u5F55\uFF0C\u8BF7\u68C0\u67E5\u7F51\u7EDC\u540E\u91CD\u8BD5\uFF1B\u539F\u767B\u5F55\u51ED\u8BC1\u5DF2\u4FDD\u7559\u3002")}})}async request(e,t){let r=await this.accessToken(),s=await fetch(`${this.server}/api/v1/developer/${e}`,{method:t===void 0?"GET":"POST",headers:{Authorization:`Bearer ${r}`,Accept:"application/json","Content-Type":"application/json"},...t===void 0?{}:{body:JSON.stringify(t)},redirect:"error",signal:AbortSignal.timeout(2e4)}),i=await s.json();if(!s.ok)throw new a(i.code??"AUTH_SERVICE_ERROR",i.message??"\u65E0\u6CD5\u8BFB\u53D6\u767B\u5F55\u72B6\u6001");return i}async identity(){return this.request("me")}async start(e={}){let t=[...this.flows.values()].find(i=>i.status().status==="pending");if(t)throw new a("AUTH_IN_PROGRESS","\u8BF7\u5148\u5B8C\u6210\u5F53\u524D\u6D4F\u89C8\u5668\u6388\u6743\uFF0C\u518D\u91CD\u8BD5\u521D\u59CB\u5316\u3002",{flowId:t.id});let r=await Q(this.server),s;try{let i;try{i=await this.identity()}catch(h){if(!(h instanceof a)||!["AUTH_REQUIRED","INVALID_TOKEN"].includes(h.code))throw h}let u=e.cloud?He:X,o=i&&u.split(" ").filter(h=>!["openid","offline_access"].includes(h)).every(h=>i.grant.scopes.includes(h));if(i&&o&&!e.reauthorize&&(!e.appId||i.grant.allApps||i.grant.appIds.includes(e.appId)))return await r(),{status:"complete",authenticated:!0,reused:!0,...i};let c=w.generateRandomCodeVerifier(),l=await w.calculatePKCECodeChallenge(c),p=i?await this.request("authorization",{codeChallenge:l}):void 0;for(let[h,f]of this.flows)f.status().status!=="pending"&&this.flows.delete(h);return s=new F(r),this.flows.set(s.id,s),await s.start({metadata:await this.discovery(),server:this.server,verifier:c,challenge:l,scope:Ve(u,p?.scopes.join(" ")??""),...e.initialize?{initialize:!0}:{},...e.applicationName?{applicationName:e.applicationName}:{},...p?{connection:p.connection}:{},...e.appId?{appId:e.appId}:{},...e.openBrowser===void 0?{}:{openBrowser:e.openBrowser},save:h=>P(this.server,()=>this.save(h))})}catch(i){throw s?await s.close():await r(),i}}status(e){let t=this.flows.get(e);if(!t)throw new a("AUTH_FLOW_NOT_FOUND","\u6388\u6743\u6D41\u7A0B\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5728\u53D1\u8D77\u6388\u6743\u7684 Agent \u6216\u7EC8\u7AEF\u4E2D\u67E5\u8BE2\u3002");return t.status()}async wait(e){for(;this.status(e).status==="pending";)await new Promise(r=>setTimeout(r,250));let t=this.status(e);if(t.status!=="complete")throw new a("AUTH_FAILED",t.message??"\u6388\u6743\u672A\u5B8C\u6210");return{authenticated:!0,...await this.identity()}}async logout(){let e=await Q(this.server);try{return await P(this.server,async()=>{let t=await this.credentials.read(this.server);if(t)try{let r=await w.revocationRequest(await this.discovery(),I,w.None(),t.refreshToken??t.accessToken,{...this.options(),additionalParameters:{token_type_hint:t.refreshToken?"refresh_token":"access_token"}});await w.processRevocationResponse(r)}catch{throw new a("REVOKE_FAILED","\u670D\u52A1\u7AEF\u64A4\u9500\u672A\u5B8C\u6210\uFF0C\u5DF2\u4FDD\u7559\u767B\u5F55\u51ED\u8BC1\uFF0C\u8BF7\u91CD\u8BD5\u6216\u5728\u7F51\u9875\u64A4\u9500\u6388\u6743\u3002")}await this.credentials.remove(this.server)}),{revoked:!0}}finally{await e()}}async close(){await Promise.all([...this.flows.values()].map(e=>e.close()))}};var z=class{constructor(e){this.auth=e}async request(e,t={}){if(!e.startsWith("/api/v1/developer/"))throw new a("INVALID_API_PATH","\u4E0D\u652F\u6301\u7684\u63A5\u53E3\u8DEF\u5F84");let r=new Headers({Accept:"application/json"});t.anonymous||r.set("Authorization",`Bearer ${await this.auth.accessToken()}`),t.key&&r.set("idempotency-key",t.key);let s;if(t.file){let o=new FormData;o.set("file",new Blob([new Uint8Array(t.file)],{type:"application/zip"}),"shaper.zip"),s=o}else t.body!==void 0&&(r.set("Content-Type","application/json"),s=JSON.stringify(t.body));let i;try{i=await fetch(`${this.auth.server}${e}`,{method:t.method??"GET",headers:r,...s?{body:s}:{},redirect:"error",signal:AbortSignal.timeout(18e4)})}catch{throw new a("NETWORK_ERROR","\u670D\u52A1\u8BF7\u6C42\u4E2D\u65AD\uFF0C\u7ED3\u679C\u5C1A\u672A\u786E\u8BA4\u3002\u8BF7\u8054\u7CFB\u5E73\u53F0\u6838\u67E5\uFF0C\u52FF\u91CD\u590D\u521B\u5EFA\u8D44\u6E90\u3002",t.key?{idempotencyKey:t.key}:void 0)}let u=await i.json();if(!i.ok)throw new a(u.code??"API_ERROR",u.message??`\u8BF7\u6C42\u5931\u8D25\uFF1A${i.status}`);return u}async me(){return this.auth.identity()}async projects(){return this.request("/api/v1/developer/projects")}async project(e){return this.request(`/api/v1/developer/projects/${encodeURIComponent(e)}`)}};import{createHash as Be}from"node:crypto";import{builtinModules as Je}from"node:module";import{readFile as N,writeFile as ee,mkdir as ye,lstat as M,realpath as H}from"node:fs/promises";import{resolve as R,join as m,relative as D,sep as B,dirname as ge,isAbsolute as Me}from"node:path";import{build as Ke}from"esbuild";import{z as d}from"zod";var ve=d.object({name:d.literal("@hupu/cloud-server"),version:d.string().regex(/^\d+\.\d+\.\d+$/)}).strict(),Se=d.object({method:d.enum(["GET","POST","PUT","PATCH","DELETE","HEAD"]),path:d.string().regex(/^\/(?:[a-zA-Z0-9_-]+\/?)*$/),access:d.enum(["public","user"]),handler:d.string().regex(/^[a-zA-Z][a-zA-Z0-9_]{0,79}$/)}).strict(),We=d.object({version:d.literal(1),runtime:d.literal("nodejs20"),memoryMB:d.number().int().min(128).max(2048),timeoutSeconds:d.number().int().min(1).max(60),routes:d.array(Se).max(100),serverSdk:ve}).strict().superRefine((n,e)=>{let t=new Set,r=new Map;for(let s of n.routes){let i=`${s.method} ${s.path}`;(t.has(i)||s.path.startsWith("/__hupu")||r.has(s.path)&&r.get(s.path)!==s.access)&&e.addIssue({code:"custom",message:"\u8DEF\u7531\u91CD\u590D\u3001\u4F7F\u7528\u4FDD\u7559\u8DEF\u5F84\u6216\u540C\u4E00\u8DEF\u5F84\u7684\u9274\u6743\u8981\u6C42\u4E0D\u4E00\u81F4\u3002"}),t.add(i),r.set(s.path,s.access)}}),Ge=ve.extend({archive:d.string().regex(/^[a-z0-9.-]+\.tgz$/),sha256:d.string().regex(/^[a-f0-9]{64}$/),templateHashes:d.record(d.string(),d.string())}),J=n=>Be("sha256").update(n).digest("hex"),Ee=/(?:^|\/)(?:\.env(?:\.[^/]*)?|credentials\.json)$|\.(?:pem|key)$/i;function b(n,e){let t=D(n,e);if(Me(t)||t===".."||t.startsWith(`..${B}`))throw new a("INVALID_FUNCTION_PATH","\u4E91\u51FD\u6570\u6587\u4EF6\u5FC5\u987B\u4F4D\u4E8E\u5F00\u53D1\u8005\u5DE5\u7A0B\u5185\u3002")}async function $(n,e,t){let r=await H(e);if(b(n,r),Ee.test(r))throw new a("SECRET_FILE","\u4E0D\u80FD\u5C06\u51ED\u8BC1\u6587\u4EF6\u6253\u5165\u4E91\u51FD\u6570\u3002");let s=await M(r);if(!s.isFile()||s.size>t)throw new a("INVALID_FUNCTION_FILE","\u6587\u4EF6\u7C7B\u578B\u6216\u5927\u5C0F\u4E0D\u7B26\u5408\u8981\u6C42\u3002");return N(r,"utf8")}async function V(n,e){b(n,e);let t=n;for(let r of D(n,e).split(B).filter(Boolean)){t=m(t,r),await ye(t).catch(i=>{if(i.code!=="EEXIST")throw i});let s=await M(t);if(!s.isDirectory()||s.isSymbolicLink())throw new a("UNSAFE_FUNCTION_PATH","\u51FD\u6570\u76EE\u5F55\u4E0D\u80FD\u7ECF\u8FC7\u7B26\u53F7\u94FE\u63A5\u3002")}}async function Te(){let n=m(O,"vendor/cloud-server"),e=Ge.parse(JSON.parse(await N(m(n,"release.json"),"utf8"))),t=await N(m(n,e.archive));if(J(t)!==e.sha256)throw new a("SDK_ASSET_MISMATCH","Toolkit \u5185\u7F6E SDK \u53D1\u884C\u5305\u6821\u9A8C\u5931\u8D25\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5 Toolkit\u3002");return{release:e,archive:t}}async function Ut(n,e="cloud/functions/api"){let t=await S(n);if(!/^[a-zA-Z0-9_-]+(?:\/[a-zA-Z0-9_-]+)*$/.test(e))throw new a("INVALID_FUNCTION_PATH","\u8BF7\u4F7F\u7528\u5DE5\u7A0B\u5185\u7684\u76F8\u5BF9\u76EE\u5F55\uFF0C\u4F8B\u5982 functions/api\u3002");let{release:r,archive:s}=await Te(),i=new Map;for(let[c,l]of Object.entries(r.templateHashes)){if(!/^[a-zA-Z0-9_./-]+$/.test(c)||c.split("/").includes(".."))throw new a("SDK_ASSET_MISMATCH","\u6A21\u677F\u8DEF\u5F84\u4E0D\u6B63\u786E\u3002");let p=await N(m(O,"templates/cloud-service",c),"utf8");if(J(p)!==l)throw new a("SDK_ASSET_MISMATCH","\u6807\u51C6\u6A21\u677F\u4E0E SDK \u53D1\u884C\u8BB0\u5F55\u4E0D\u4E00\u81F4\u3002");i.set(c,p)}let u=e==="cloud/functions/api";if(u){let c=JSON.parse(i.get("cloud.json")),{routes:l,...p}=c;i.set("cloud.json",JSON.stringify(p,null,2)+`
2
+ `),i.set("../../gateway/routes.json",JSON.stringify({version:1,routes:l},null,2)+`
3
+ `);for(let[h,f]of[...i])h.startsWith("migrations/")&&(i.delete(h),i.set("../../database/"+h,f));for(let h of i.keys())if(h.startsWith("../")){let f=R(t,e,h);b(t,f);try{throw await M(f),new a("CLOUD_LAYOUT_EXISTS","\u6570\u636E\u5E93\u6216\u7F51\u5173\u58F0\u660E\u5DF2\u5B58\u5728\uFF0C\u8BF7\u6CBF\u7528\u73B0\u6709\u4E91\u5DE5\u7A0B\u3002")}catch(v){if(v.code!=="ENOENT")throw v}}}let o=R(t,e);await V(t,ge(o)),await ye(o).catch(c=>{throw c.code==="EEXIST"?new a("FUNCTION_EXISTS","\u76EE\u5F55\u5DF2\u5B58\u5728\uFF0C\u8BF7\u76F4\u63A5\u4FEE\u6539\u73B0\u6709\u6E90\u7801\u540E\u91CD\u65B0\u90E8\u7F72\uFF1B\u4E0D\u4F1A\u8986\u76D6\u3002"):c}),i.set("package.json",JSON.stringify({name:`hupu-function-${e.split("/").at(-1)}`,private:!0,version:"0.1.0",engines:{node:">=20"},dependencies:{[r.name]:`file:vendor/${r.archive}`},hupuCloud:{schemaVersion:1,entry:"handlers.cjs",manifest:"cloud.json",...u?{gateway:"../../gateway/routes.json"}:{}}},null,2)+`
4
+ `),i.set(".gitignore",`node_modules/
5
+ .env
6
+ .env.*
7
+ !vendor/*.tgz
8
+ `),i.set("README.md",u?`# \u5E94\u7528\u540E\u7AEF
9
+
10
+ \u6E90\u7801\u548C\u8FD0\u884C\u53C2\u6570\u5728\u6B64\u76EE\u5F55\uFF0C\u8DEF\u7531\u5728 ../../gateway/routes.json\uFF0C\u8FC1\u79FB\u5728 ../../database/migrations\u3002
11
+
12
+ \u5728\u9879\u76EE\u6839\u76EE\u5F55\u6267\u884C shaper cloud enable\uFF0C\u67E5\u8BE2\u8FD4\u56DE operationId \u81F3 succeeded\uFF1B\u6309\u987A\u5E8F\u63D0\u4EA4\u6570\u636E\u5E93\u8FC1\u79FB\u5E76\u67E5\u8BE2\u5B8C\u6210\uFF0C\u518D\u6267\u884C shaper cloud deploy\u3002\u6784\u5EFA\u81EA\u52A8\u7EC4\u5408 manifest\uFF0C\u4E0D\u91CD\u590D\u7EF4\u62A4\u8DEF\u7531\u3002
13
+
14
+ \u4F7F\u7528\u7B2C\u4E09\u65B9\u4F9D\u8D56\u65F6\u5728\u6B64\u76EE\u5F55 npm install \u5E76\u63D0\u4EA4 package-lock.json\u3002\u521D\u59CB\u5316\u4E0D\u4F1A\u5F00\u901A\u6216\u90E8\u7F72\u4E91\u8D44\u6E90\u3002
15
+ `:await N(m(O,"templates/cloud-service/README.md"),"utf8"));for(let[c,l]of i)await V(t,ge(m(o,c))),await ee(m(o,c),l,{flag:"wx"});return await V(t,m(o,"vendor")),await ee(m(o,"vendor",r.archive),s,{flag:"wx"}),{directory:e,files:[...i.keys(),`vendor/${r.archive}`],serverSdk:{name:r.name,version:r.version},next:u?"\u4FEE\u6539 cloud/functions/api \u6E90\u7801\u4E0E\u8FD0\u884C\u914D\u7F6E\u3001cloud/gateway/routes.json \u8DEF\u7531\u3001cloud/database/migrations \u8FC1\u79FB\uFF1B\u786E\u8BA4\u8FC1\u79FB\u5B8C\u6210\u540E\u90E8\u7F72\u3002":"\u4FEE\u6539 handlers.cjs/cloud.json\uFF1B\u786E\u8BA4\u6570\u636E\u5E93\u8FC1\u79FB\u5B8C\u6210\u540E\u90E8\u7F72\u3002"}}async function Ie(n,e){let t=await S(n);if(!e)try{await M(m(t,"cloud/functions/api/package.json")),e="cloud/functions/api"}catch(g){if(g.code!=="ENOENT")throw g;e="functions/api"}let r=await H(R(t,e));b(t,r);let s=JSON.parse(await $(t,m(r,"package.json"),65536)),i=d.object({schemaVersion:d.literal(1),entry:d.string().regex(/\.(?:cjs|js|ts)$/),manifest:d.string(),gateway:d.string().optional()}).strict().parse(s.hupuCloud),u=JSON.parse(await $(t,R(r,i.manifest),65536)),o=u.routes;if(i.gateway){if(u.routes!==void 0)throw new a("DUPLICATE_ROUTES","\u8DEF\u7531\u53EA\u7EF4\u62A4\u5728 gateway \u58F0\u660E\u4E2D\uFF0C\u4E0D\u80FD\u540C\u65F6\u5199\u5165\u8FD0\u884C\u914D\u7F6E\u3002");o=d.object({version:d.literal(1),routes:d.array(Se).max(100)}).strict().parse(JSON.parse(await $(t,R(r,i.gateway),65536))).routes}let c=We.parse({...u,routes:o}),{release:l}=await Te();if(c.serverSdk.version!==l.version)throw new a("SERVER_SDK_UNSUPPORTED","\u6B64 Toolkit \u4E0D\u652F\u6301\u6307\u5B9A SDK \u7248\u672C\uFF0C\u8BF7\u540C\u6B65\u5347\u7EA7 Toolkit \u4E0E Cloud \u670D\u52A1\u3002");let p=s.dependencies?.[l.name];if(p===`file:vendor/${l.archive}`){let g=await H(m(r,"vendor",l.archive));if(b(t,g),J(await N(g))!==l.sha256)throw new a("SDK_ASSET_MISMATCH","\u9879\u76EE\u4E2D\u7684 SDK \u53D1\u884C\u5305\u4E0E\u5F53\u524D Toolkit \u4E0D\u4E00\u81F4\u3002")}else if(p!==l.version)throw new a("SDK_DEPENDENCY_REQUIRED","package.json \u5FC5\u987B\u4F7F\u7528\u6A21\u677F\u5185\u7F6E SDK \u5305\u6216\u7CBE\u786E\u7248\u672C\uFF0C\u4E0D\u80FD\u4F7F\u7528\u6D6E\u52A8\u7248\u672C\u3002");let h=R(r,i.entry);await $(t,h,8*1024*1024);let f=await Ke({absWorkingDir:t,entryPoints:[h],outfile:"app.cjs",write:!1,bundle:!0,platform:"node",format:"cjs",target:"node20",metafile:!0,sourcemap:!1,external:[l.name],logLevel:"silent",plugins:[{name:"hupu-source-policy",setup(g){g.onLoad({filter:/.*/},async E=>{let k=await H(E.path);if(Ee.test(k))throw new a("SECRET_FILE","\u6784\u5EFA\u56FE\u5305\u542B\u51ED\u8BC1\u6587\u4EF6\u3002");k.includes(`${B}node_modules${B}`)||b(t,k)}),g.onResolve({filter:/^@hupu\/cloud-server\//},()=>({errors:[{text:"\u53EA\u80FD\u4ECE @hupu/cloud-server \u516C\u5171\u5165\u53E3\u5BFC\u5165\u3002"}]}))}}]}),v=f.outputFiles[0].text,Ne=new Set(Je.flatMap(g=>[g,`node:${g}`]));for(let g of Object.values(f.metafile.outputs))for(let E of g.imports)if(E.external&&E.path!==l.name&&!Ne.has(E.path))throw new a("UNBUNDLED_DEPENDENCY",`\u4F9D\u8D56\u6CA1\u6709\u6253\u5305\uFF1A${E.path}`);if(Buffer.byteLength(v)>8*1024*1024||/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/.test(v))throw new a("INVALID_ARTIFACT","\u5236\u54C1\u8FC7\u5927\u6216\u5305\u542B\u79C1\u94A5\u3002");let te=JSON.stringify(c,null,2)+`
16
+ `,re=J(te+`
17
+ `+v),x=m(t,".shaper/cloud-build",re);await V(t,x);for(let[g,E]of[["cloud.json",te],["app.cjs",v]]){let k=m(x,g);try{await ee(k,E,{flag:"wx"})}catch(se){if(se.code!=="EEXIST"||await $(t,k,8*1024*1024)!==E)throw se}}return{directory:D(t,r),manifestFile:D(t,m(x,"cloud.json")),bundleFile:D(t,m(x,"app.cjs")),sha256:re,bytes:Buffer.byteLength(v),serverSdk:c.serverSdk,routes:c.routes}}import{createHash as ke}from"node:crypto";import{resolve as Ye,relative as Ze,sep as Qe}from"node:path";import{readFile as Xe,realpath as et,stat as tt}from"node:fs/promises";var K=class{constructor(e){this.api=e}async status(e){return this.api.request(`${(await this.target(e)).url}/status`)}async operation(e,t){if(!/^op_[a-zA-Z0-9-]{1,64}$/.test(t))throw new a("INVALID_OPERATION_ID","\u9700\u8981\u6709\u6548\u7684\u4E91\u64CD\u4F5C\u7F16\u53F7\u3002");return this.api.request(`${(await this.target(e)).url}/operations/${t}`)}async enable(e){return this.api.request(`${(await this.target(e)).url}/enable`,{method:"POST",body:{}})}async deploy(e,t={},r){await this.target(e);let s=t.manifestFile!==void 0||t.bundleFile!==void 0;if(s&&(t.directory!==void 0||!t.manifestFile||!t.bundleFile))throw new a("INVALID_DEPLOY_INPUT","\u9009\u62E9\u6E90\u7801\u76EE\u5F55\uFF0C\u6216\u540C\u65F6\u63D0\u4F9B manifest \u548C bundle\u3002\u4E24\u79CD\u8F93\u5165\u4E0D\u80FD\u6DF7\u7528\u3002");let i=s?{manifestFile:t.manifestFile,bundleFile:t.bundleFile}:await Ie(e,t.directory),u=await this.upload(e,i.manifestFile,i.bundleFile,r);return{artifact:i,...u}}async routes(e){return this.api.request(`${(await this.target(e)).url}/routes`)}async migrate(e,t,r,s){if(!/^[0-9]{8,20}_[a-zA-Z0-9_-]+$/.test(t))throw new a("INVALID_MIGRATION","\u8FC1\u79FB\u7248\u672C\u683C\u5F0F\u4E3A\u65F6\u95F4\u6233_\u540D\u79F0\u3002");let{root:i,url:u}=await this.target(e),o=await this.source(i,r,6e4),c=s??ke("sha256").update(`${t}:${o}`).digest("hex");return this.api.request(`${u}/migrations`,{method:"POST",body:{version:t,dialect:"postgresql",sql:o,idempotencyKey:c}})}async source(e,t,r){let s=await et(Ye(e,t));if(this.checkContained(e,s),/(?:^|\/)(?:\.env(?:\..*)?|credentials\.json)$|\.(?:pem|key)$/i.test(s))throw new a("SECRET_FILE","\u4E0D\u80FD\u4E0A\u4F20\u51ED\u8BC1\u6587\u4EF6\u3002");if((await tt(s)).size>r)throw new a("ARTIFACT_TOO_LARGE","\u6587\u4EF6\u8D85\u8FC7\u5141\u8BB8\u5927\u5C0F\u3002");return Xe(s,"utf8")}async upload(e,t,r,s){let{root:i,url:u}=await this.target(e),o=JSON.parse(await this.source(i,t,65536));if(o.serverSdk!=null){let[p,h]=await Promise.all([this.status(e),this.api.request(`${u}/capabilities`)]),f=h.serverSdk;if(!f||f.name!==o.serverSdk.name||!f.versions.includes(o.serverSdk.version)||f.packaging!=="platform-external")throw new a("SERVER_SDK_UNSUPPORTED","\u5F53\u524D\u5E94\u7528\u4E0D\u652F\u6301\u6B64 SDK\uFF1B\u8BF7\u8054\u7CFB\u5E73\u53F0\u7BA1\u7406\u5458\u68C0\u67E5\u670D\u52A1\u914D\u7F6E\u6216\u5347\u7EA7 Toolkit\u3002");if(p.status!=="ready")throw new a("CLOUD_NOT_READY","\u8BF7\u5148\u5F00\u901A\u5E94\u7528\u4E91\u670D\u52A1\uFF0C\u5E76\u901A\u8FC7 cloud status \u786E\u8BA4\u8D44\u6E90 ready\u3002")}let c=await this.source(i,r,8*1024*1024),l=s??ke("sha256").update(JSON.stringify({manifest:o,bundle:c})).digest("hex");return this.api.request(`${u}/deployments`,{method:"POST",body:{manifest:o,bundle:c,idempotencyKey:l}})}async target(e){let t=await S(e),r=await _(t,this.api.auth.server),s=`/api/v1/developer/projects/${encodeURIComponent(r.appId)}/cloud-v2`;return{root:t,url:s}}checkContained(e,t){let r=Ze(e,t);if(r===".."||r.startsWith(`..${Qe}`))throw new a("INVALID_FILE_PATH","\u5236\u54C1\u6587\u4EF6\u5FC5\u987B\u4F4D\u4E8E\u5DE5\u7A0B\u76EE\u5F55\u5185\u3002")}};import{createHash as rt,randomUUID as L}from"node:crypto";import{resolve as W,relative as Ae,sep as _e,dirname as st,basename as it}from"node:path";import{readFile as at,writeFile as nt,realpath as Re,stat as ot}from"node:fs/promises";var G=class{constructor(e){this.api=e}async base(e,t){let r=await S(e),s=await _(r,this.api.auth.server),i=`/api/v1/developer/projects/${encodeURIComponent(s.appId)}/cloud`;if(t&&!/^[a-z][a-z0-9-]{0,31}$/.test(t))throw new a("INVALID_ENVIRONMENT","\u73AF\u5883\u540D\u5FC5\u987B\u662F\u5C0F\u5199\u5B57\u6BCD\u5F00\u5934\uFF0C\u5305\u542B\u5B57\u6BCD\u3001\u6570\u5B57\u3001\u8FDE\u5B57\u7B26\uFF0C\u6700\u591A 32 \u4F4D\u3002");return{root:r,url:t?`${i}/environments/${encodeURIComponent(t)}`:i}}async capabilities(e){return this.api.request(`${(await this.base(e)).url}/capabilities`)}async environments(e){return this.api.request(`${(await this.base(e)).url}/environments`)}async create(e,t,r=!1){let{url:s}=await this.base(e),i=rt("sha256").update(`environment:${s}:${t}:${r}`).digest("hex");return this.api.request(`${s}/environments`,{method:"POST",body:{name:t,postgres:r},key:i})}async status(e,t){return this.api.request((await this.base(e,t)).url)}async functions(e,t){return this.api.request(`${(await this.base(e,t)).url}/functions`)}async deployFunction(e,t,r,s,i){let{root:u,url:o}=await this.base(e,t),c=await S(W(u,s)),l=Ae(u,c);if(l===".."||l.startsWith(`..${_e}`))throw new a("INVALID_FUNCTION_PATH","\u51FD\u6570\u4EE3\u7801\u5FC5\u987B\u4F4D\u4E8E\u5DE5\u7A0B\u76EE\u5F55\u5185\u3002");let p=await oe(c,{files:1e3,bytes:30*1024*1024});return this.api.request(`${o}/functions/${encodeURIComponent(r)}/deploy`,{method:"POST",file:p.content,key:i??L()})}async invoke(e,t,r,s,i){return this.api.request(`${(await this.base(e,t)).url}/functions/${encodeURIComponent(r)}/invoke`,{method:"POST",body:s,key:i??L()})}async logs(e,t,r){return this.api.request(`${(await this.base(e,t)).url}/functions/${encodeURIComponent(r)}/logs`)}async sql(e,t,r,s){return this.api.request(`${(await this.base(e,t)).url}/database/query`,{method:"POST",body:{sql:r},key:s??L()})}async listObjects(e,t,r="",s){let i=new URLSearchParams({prefix:r,...s?{cursor:s}:{}});return this.api.request(`${(await this.base(e,t)).url}/storage?${i}`)}async putObject(e,t,r,s,i){let{root:u,url:o}=await this.base(e,t),c=await Re(W(u,s));if(this.checkContained(u,c),/(?:^|\/)(?:\.env(?:\..*)?|credentials\.json)$|\.(?:pem|key)$/i.test(c))throw new a("SECRET_FILE","\u51ED\u8BC1\u6587\u4EF6\u4E0D\u80FD\u4F5C\u4E3A\u4E1A\u52A1\u5BF9\u8C61\u4E0A\u4F20\u3002");if((await ot(c)).size>10*1024*1024)throw new a("OBJECT_TOO_LARGE","\u5BF9\u8C61\u4E0D\u80FD\u8D85\u8FC7 10 MiB\u3002");return this.api.request(`${o}/storage/object?${new URLSearchParams({key:r})}`,{method:"POST",file:await at(c),key:i??L()})}async getObject(e,t,r,s){let{root:i,url:u}=await this.base(e,t),o=W(await Re(st(W(i,s))),it(s));this.checkContained(i,o);let c=await this.api.request(`${u}/storage/object?${new URLSearchParams({key:r})}`);return await nt(o,Buffer.from(c.base64,"base64"),{flag:"wx",mode:384}),{key:r,bytes:c.bytes,path:o}}async deleteObject(e,t,r,s){return this.api.request(`${(await this.base(e,t)).url}/storage/object?${new URLSearchParams({key:r})}`,{method:"DELETE",key:s??L()})}checkContained(e,t){let r=Ae(e,t);if(r===".."||r.startsWith(`..${_e}`))throw new a("INVALID_FILE_PATH","\u5BF9\u8C61\u6587\u4EF6\u5FC5\u987B\u4F4D\u4E8E\u5DE5\u7A0B\u76EE\u5F55\u5185\u3002")}};var be=class n{constructor(e){this.auth=e;this.api=new z(e),this.cloud=new K(this.api),this.legacyCloud=new G(this.api)}api;cloud;legacyCloud;static async create(e){return new n(new q(e??await ae()))}async status(e){let t;try{t={authenticated:!0,...await this.api.me()}}catch(s){t={authenticated:!1,error:C(s)}}let r;if(e){let s=await S(e),i;try{let o=await _(s,this.auth.server);try{let c=await this.api.project(o.appId);i={...o,authorized:!0,name:c.name,versions:c.versions}}catch(c){i={...o,authorized:!1,error:C(c)}}}catch(o){i={linked:!1,error:C(o)}}let u;try{u=await ne(s)}catch(o){u={error:C(o)}}r={root:s,binding:i,config:u,dev:await ce(s)}}return{server:this.auth.server,identity:t,...r?{project:r}:{}}}};export{q as a,z as b,Ut as c,Ie as d,K as e,G as f,be as g};
@@ -0,0 +1,84 @@
1
+ import { z } from 'zod';
2
+ import { ShaperApi, type RequestResult } from './api.js';
3
+ export declare const packageRoot: string;
4
+ declare const configSchema: z.ZodObject<{
5
+ schemaVersion: z.ZodLiteral<1>;
6
+ devCommand: z.ZodString;
7
+ buildCommand: z.ZodString;
8
+ outputDir: z.ZodString;
9
+ devUrl: z.ZodDefault<z.ZodString>;
10
+ }, z.core.$loose>;
11
+ export type ProjectConfig = z.infer<typeof configSchema>;
12
+ export declare function workspaceRoot(path: string): Promise<string>;
13
+ export declare function projectConfig(root: string): Promise<ProjectConfig>;
14
+ export declare function binding(root: string, server: string): Promise<{
15
+ schemaVersion: 1;
16
+ appId: string;
17
+ server: string;
18
+ }>;
19
+ export declare function initProject(api: ShaperApi, path: string, options?: {
20
+ name?: string;
21
+ appId?: string;
22
+ installDependencies?: boolean;
23
+ template?: string;
24
+ waitForAuthorization?: boolean;
25
+ }): Promise<{
26
+ flowId: `${string}-${string}-${string}-${string}-${string}`;
27
+ authorizationUrl: string;
28
+ expiresIn: number;
29
+ root: string;
30
+ appId: string;
31
+ status: string;
32
+ next: string;
33
+ name?: never;
34
+ } | {
35
+ schemaVersion: 1;
36
+ appId: string;
37
+ server: string;
38
+ root: string;
39
+ alreadyInitialized: boolean;
40
+ name?: never;
41
+ } | {
42
+ root: string;
43
+ name: string;
44
+ appId: string;
45
+ }>;
46
+ export declare function linkProject(api: ShaperApi, path: string, appId: string): Promise<{
47
+ root: string;
48
+ appId: string;
49
+ name: string;
50
+ }>;
51
+ export declare function runCommand(command: string, root: string): Promise<void>;
52
+ export declare function buildProject(path: string): Promise<{
53
+ root: string;
54
+ output: string;
55
+ }>;
56
+ export declare function archiveDirectory(directory: string, limits?: {
57
+ files: number;
58
+ bytes: number;
59
+ }): Promise<{
60
+ content: Buffer<ArrayBufferLike>;
61
+ files: number;
62
+ bytes: number;
63
+ }>;
64
+ export declare function deployWeb(api: ShaperApi, path: string, options?: {
65
+ build?: boolean;
66
+ }): Promise<RequestResult>;
67
+ export declare function publishWeb(api: ShaperApi, path: string, versionId: string, description: string, coverPath?: string): Promise<{
68
+ status: 'running' | 'succeeded' | 'failed' | 'uncertain';
69
+ result: {
70
+ status: string;
71
+ confirmationUrl: string;
72
+ } | null;
73
+ error_code: string | null;
74
+ submitted: boolean;
75
+ next: string;
76
+ }>;
77
+ export declare function checkProject(path: string): Promise<{
78
+ root: string;
79
+ passed: boolean;
80
+ findings: string[];
81
+ checks: string[];
82
+ notRun: string[];
83
+ }>;
84
+ export {};
package/package.json CHANGED
@@ -1,6 +1,75 @@
1
1
  {
2
2
  "name": "@hupu-tech/shaper",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.2",
4
+ "description": "Shaper local developer tools, MCP server and Hupu integration skills",
5
+ "type": "module",
6
+ "bin": {
7
+ "shaper": "dist/cli.js"
8
+ },
9
+ "exports": {
10
+ ".": "./dist/index.js",
11
+ "./runtime": "./dist/runtime.js"
12
+ },
13
+ "types": "dist/index.d.ts",
14
+ "files": [
15
+ "dist/*.js",
16
+ "dist/*.d.ts",
17
+ "skills",
18
+ "templates",
19
+ "README.md",
20
+ "LICENSE",
21
+ "vendor/cloud-server/*.tgz",
22
+ "vendor/cloud-server/release.json",
23
+ "CHANGELOG.md"
24
+ ],
25
+ "engines": {
26
+ "node": ">=22.14"
27
+ },
28
+ "scripts": {
29
+ "build": "node scripts/build.mjs",
30
+ "dev": "tsc -p tsconfig.json --watch",
31
+ "typecheck": "tsc --noEmit",
32
+ "test": "node --import tsx --test test/*.test.ts",
33
+ "verify": "npm run build && npm test && npm run check:skills",
34
+ "prepack": "npm run build && npm run check:skills && npm run check:package",
35
+ "check:skills": "node scripts/check-skills.mjs",
36
+ "sync:cloud-sdk": "node scripts/sync-cloud-sdk.mjs",
37
+ "pack:skills": "node scripts/pack-skills.mjs",
38
+ "prepublishOnly": "npm run verify",
39
+ "check:package": "node scripts/check-package.mjs"
40
+ },
41
+ "license": "UNLICENSED",
42
+ "packageManager": "pnpm@10.33.0",
43
+ "publishConfig": {
44
+ "access": "public",
45
+ "registry": "https://registry.npmjs.org/"
46
+ },
47
+ "dependencies": {
48
+ "@iarna/toml": "2.2.5",
49
+ "@modelcontextprotocol/sdk": "1.32.1",
50
+ "adm-zip": "0.6.1",
51
+ "commander": "15.0.0",
52
+ "esbuild": "0.25.11",
53
+ "execa": "10.2.1",
54
+ "jsonc-parser": "3.3.1",
55
+ "oauth4webapi": "3.8.8",
56
+ "open": "11.0.4",
57
+ "proper-lockfile": "4.1.2",
58
+ "zod": "4.6.7"
59
+ },
60
+ "devDependencies": {
61
+ "@types/node": "26.6.5",
62
+ "@types/proper-lockfile": "4.1.4",
63
+ "tar-stream": "3.2.2",
64
+ "tsx": "4.23.15",
65
+ "typescript": "7.0.2"
66
+ },
67
+ "keywords": [
68
+ "shaper",
69
+ "mcp",
70
+ "cli",
71
+ "agent-skills",
72
+ "hupu",
73
+ "game-development"
74
+ ]
75
+ }
@@ -0,0 +1,8 @@
1
+ ---
2
+ name: hupu-cloud
3
+ description: 兼容旧项目中对 hupu-cloud 的引用;新后端任务使用 shaper-backend。
4
+ ---
5
+
6
+ # 旧名称兼容
7
+
8
+ 后端职责已迁移到 shaper-backend。继续当前任务前读取同次发行安装的 shaper-backend 技能;若缺失,修复官方技能安装。保留现有项目与云资源,不因技能改名重新初始化或创建环境。
@@ -0,0 +1,14 @@
1
+ ---
2
+ name: hupu-business
3
+ description: 在 Shaper 网页中接入虎扑用户资料、分享和 cloud.request 业务请求,处理普通浏览器与虎扑容器的差异。开发者授权使用 Shaper CLI 登录流程。
4
+ ---
5
+
6
+ # 虎扑业务接入
7
+
8
+ 页面使用 Shaper 容器提供的 `window.ColorboxAI`。开发者 CLI 的 OAuth 只管理项目,不是应用用户登录。新工具保持既有虎扑桥接协议;不要套用 Maker 的 SDK 名称或注入方式。
9
+
10
+ 用户资料、分享和云业务请求的具体调用见 [references/runtime.md](references/runtime.md)。需要这些能力时读取该文档;玩家认证复用已有 SDK 的 cloud.request 内部逻辑。
11
+
12
+ 在代码中区分三种状态:桥接不存在、未登录、已登录。普通本地浏览器没有真实桥接时显示可理解的提示。测试替身只能用于明确标注的本地测试,不能用来证明虎扑登录或分享已经跑通。
13
+
14
+ 先在本地验证布局、输入和错误状态,再在 Shaper 预览或真实虎扑容器中验证用户态。账号标识可以用于显示,业务后端仍从经过验证的用户凭据判断身份。开发者 token 和云管理凭证始终不进入网页。
@@ -0,0 +1,55 @@
1
+ # 既有虎扑桥接
2
+
3
+ Shaper 发布壳提供 `window.ColorboxAI`。不额外从第三方 CDN 装一份替代 SDK。
4
+
5
+ 读取当前用户:
6
+
7
+ ```js
8
+ const result = await window.ColorboxAI.auth.getUserInfo();
9
+ const signedIn = result.code === 200 && (
10
+ result.data?.islogin === 1 ||
11
+ result.data?.islogin === '1' ||
12
+ result.data?.isLogin === true
13
+ );
14
+ ```
15
+
16
+ 展示昵称可读取 `nickname`/`nickName`,头像读取 `avatar`/`userHeadUrl`。未登录时使用容器已有的登录引导,不编造 `auth.login()` 等未经确认的接口。页面如需要主动唤起登录,先检查当前容器 SDK 的该能力契约。
17
+
18
+ 用户点击分享按钮时:
19
+
20
+ ```js
21
+ const result = await window.ColorboxAI.social.share({
22
+ title: '我的作品',
23
+ link: publishedHttpsUrl,
24
+ text: '一起来玩',
25
+ imageUrl: publicCoverUrl
26
+ });
27
+ ```
28
+
29
+ 保留宿主返回结果,按实际契约显示完成、取消或失败;仅调用返回不能证明用户已分享。
30
+
31
+ 包的 `@hupu-tech/shaper/runtime` 导出 `hupuClient()`,是上述接口的小型浏览器适配器,可选使用:
32
+
33
+ ```js
34
+ import { hupuClient } from '@hupu-tech/shaper/runtime';
35
+ const hupu = hupuClient();
36
+ const user = await hupu.user();
37
+ ```
38
+
39
+ `available()` 读取桥接可用性,`user()` 返回 `signedIn` 和展示资料,`share()` 保留宿主结果。它不保存用户凭证,不自动引入云管理 SDK。包未发布阶段,应使用交付的本地 npm 包;不要假设公共 registry 中已存在此版本。
40
+
41
+ 调用应用自己的云业务接口时,直接复用已有 SDK:
42
+
43
+ ```js
44
+ const response = await window.ColorboxAI.cloud.request({
45
+ url: `${apiBase}/votes`,
46
+ method: 'POST',
47
+ data: { matchId, teamId },
48
+ envId,
49
+ auth: true
50
+ });
51
+ ```
52
+
53
+ `apiBase` 是已经部署并验证的 HTTPS 业务接口地址,`envId` 是对应环境的公开运行配置;两者都不是平台密钥。SDK 内部处理玩家登录和认证。根据实际接口契约检查 HTTP `statusCode` 与业务 `code/message/data`,业务函数仍负责数据权限。
54
+
55
+ 先确认 HTTP 函数、路由及环境认证配置已由平台就绪,再验证用户请求。当前新 MCP 的事件函数部署/管理调用不会自动产生 HTTP 业务地址;需要 HTTP 服务时沿用现有部署入口。管理操作成功不能替代真实容器内的业务请求验收。