@hupu-tech/shaper 0.2.5 → 0.2.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +8 -0
- package/README.md +9 -1
- package/dist/api.d.ts +1 -0
- package/dist/cli.js +2 -2
- package/dist/dev-runner.js +5 -1
- package/dist/dev.d.ts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -1
- package/dist/launcher.js +1 -1
- package/dist/{shared-TLHBDBPL.js → shared-3SHRGRIW.js} +1 -1
- package/dist/shared-COXNB4AR.js +1 -0
- package/dist/shared-WK7DKUR5.js +17 -0
- package/dist/shared-Z5NOVHRW.js +13 -0
- package/dist/web-preview.d.ts +12 -0
- package/dist/workspace.d.ts +32 -2
- package/package.json +6 -3
- package/skills/core/shaper-release/SKILL.md +3 -3
- package/dist/shared-C4252CVV.js +0 -17
- package/dist/shared-VUHAWCVD.js +0 -13
- package/dist/shared-YVV543ON.js +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.6 — 2026-11-13
|
|
4
|
+
|
|
5
|
+
- 本地开发预览由工具内部加载云端真实运行壳,校验并固定会话版本;支持有效缓存回退、资源代理和 HMR。
|
|
6
|
+
- 网页 deploy 返回完整预览链接、有效期及二维码;新增 preview / shaper_web_preview 刷新同一版本,不重新上传。
|
|
7
|
+
- status 查询原上传结果并保留当前发布版本;预览失败不丢失已成功交付的版本信息。
|
|
8
|
+
- 增加 Codex Git 插件市场生成与校验,插件精确固定 Toolkit 版本,复用七个核心技能和 MCP。
|
|
9
|
+
- 服务端需先上线配套预览运行包、网页预览及交付状态接口;本版本不自动部署服务端。首次加载运行壳失败且无有效缓存时会明确停止,不回退裸预览。
|
|
10
|
+
|
|
3
11
|
## 0.2.5 — 2026-11-13
|
|
4
12
|
|
|
5
13
|
- 旧版下载项目默认保持原流程;新版工具在授权和写入前停止接入,保留身份冲突保护,取消自动替换旧指导。
|
package/README.md
CHANGED
|
@@ -48,10 +48,12 @@ shaper build # 构建
|
|
|
48
48
|
|
|
49
49
|
```bash
|
|
50
50
|
shaper deploy
|
|
51
|
+
shaper preview # 刷新最近一次已确认交付的预览和二维码
|
|
52
|
+
shaper preview --version VersionID # 获取指定版本预览,不重新上传
|
|
51
53
|
shaper publish --version VersionID --description "本次更新说明"
|
|
52
54
|
```
|
|
53
55
|
|
|
54
|
-
`deploy`
|
|
56
|
+
`deploy` 构建并上传,成功后返回版本 ID、完整云端预览链接、有效期和本地二维码 PNG 路径;MCP 同时返回二维码图片。链接过期后用 `preview` 刷新同一版本。二维码对应云端地址,可供手机访问;本机开发链接仅供本机使用。上传超时后用 `status` 查看 `project.web` 的原请求结果,不要重新上传。预览确认后,将 `VersionID` 替换为实际版本 ID;在打开的浏览器页面核对资料,确认提交后进入审核。
|
|
55
57
|
|
|
56
58
|
## 其他 AI 工具
|
|
57
59
|
|
|
@@ -114,3 +116,9 @@ shaper install --ide cursor
|
|
|
114
116
|
Copyright © 2026 Hupu。`UNLICENSED`,保留所有权利,详见 LICENSE。
|
|
115
117
|
|
|
116
118
|
旧版下载项目继续使用原技能。新版 init 检测到旧标识会停止,不修改工程、指导或应用绑定;当前尚未开放自动升级。普通源码仍可配置 workingDirectory 和构建命令接入新版工具。旧云资源保持原维护入口。
|
|
119
|
+
|
|
120
|
+
## Codex 插件市场
|
|
121
|
+
|
|
122
|
+
支持以仓库市场分发技能与 MCP,复用现有运行时,不要求全局安装 CLI。安装范围、已有配置迁移边界和发布顺序见 [Codex 插件接入](docs/codex-plugin.md)。市场生成命令为 `npm run build:plugins`;当前未发布公共市场。
|
|
123
|
+
|
|
124
|
+
0.2.6 的运行壳、预览链接与二维码能力需要服务端部署配套 API;升级 npm 包或插件不会自动部署服务器。
|
package/dist/api.d.ts
CHANGED
package/dist/cli.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{c as L,d as F,e as K,f as C}from"./shared-TLHBDBPL.js";import{g as r}from"./shared-C4252CVV.js";import{c as j,d as S,e as x}from"./shared-YVV543ON.js";import{b as D,f as A,g as q,h as w,m as f,o as v,p as h,r as b,s as k,t as _}from"./shared-VUHAWCVD.js";import{Command as G}from"commander";import{readFile as T}from"node:fs/promises";import{resolve as c}from"node:path";import{McpServer as W}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as J}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as n}from"zod";import{isAbsolute as U}from"node:path";var d=n.string().min(1).refine(U,"workspace must be an absolute path").describe("Absolute local project directory. Never infer from the MCP process working directory."),u=n.string().regex(/^[a-z][a-z0-9-]{0,31}$/),P=n.string().min(1).max(64),m=n.string().min(16).max(100).optional();function B(e,o={}){let a=new W({name:"shaper",version:C},{instructions:"Use installed Shaper skills for workflows. Always pass the intended absolute workspace. All sessions share one login per Shaper server. Reuse it; request additional permissions only when needed. Browser consent adds permissions without replacing existing access. Local binding contains only the server and app ID, never tokens. Never choose a recent app as a fallback. Web delivery and backend service deployment have separate targets. Queued, running or uncertain results do not confirm completion. Writes wait for completion; if still pending, use hupu_cloud_status. Never create cloud resources without explicit user approval."});function i(t,M,N,Q,E="write"){a.registerTool(M,{description:N,inputSchema:t,annotations:{readOnlyHint:E==="read",destructiveHint:E==="destructive",openWorldHint:!0}},async H=>{try{let R=await Q(H);return{content:[{type:"text",text:JSON.stringify(R,null,2)}]}}catch(R){return{isError:!0,content:[{type:"text",text:JSON.stringify(w(R))}]}}})}return i({workspace:d.optional()},"shaper_status","Read current identity, local project binding and development session. Does not start services.",t=>e.status(t.workspace),"read"),i({cloud:n.boolean().default(!1),openBrowser:n.boolean().default(!0),appId:n.string().min(1).max(200).optional(),reauthorize:n.boolean().default(!1)},"shaper_auth_start","Reuse the global login when permissions suffice. Otherwise start browser consent and return a flow ID. appId adds access to an existing application; cloud=true adds cloud permissions. Existing permissions are retained. reauthorize=true opens consent explicitly.",t=>e.auth.start(t)),i({flowId:n.string()},"shaper_auth_status","Read browser authorization result for a flow started by this MCP session.",t=>e.auth.status(t.flowId),"read"),i({},"shaper_logout","Sign out globally for this Shaper server. All local projects and Agent sessions share this login.",()=>e.auth.logout(),"destructive"),i({},"shaper_projects","List applications available to this authorization.",()=>e.api.projects(),"read"),i({workspace:d,template:n.enum(["h5","react","phaser"]).optional(),name:P.optional(),appId:n.string().optional(),installDependencies:n.boolean().default(!0)},"shaper_init","Create a vanilla HTML, React or Phaser project and a Shaper application, or initialize an existing source directory. Resolve existing identity first; missing apps require browser creation consent. A pending result requires finishing authorization and retrying with the same workspace/appId. Legacy downloaded projects return LEGACY_PROJECT_UPGRADE_REQUIRED: stop and preserve their original workflow; never bypass through link or removing markers. Other existing projects may return configuration_required: inspect their actual entry, build tool and output, then supply shaper.config.json without moving sources. Never overwrite a conflicting existing binding.",t=>f(e.api,t.workspace,t)),i({workspace:d,appId:n.string()},"shaper_link","Associate the local source directory with an existing authorized Shaper application.",t=>v(e.api,t.workspace,t.appId)),i({workspace:d},"shaper_dev_start","Start a local development server using shaper.config.json and return its verified URL.",t=>j(t.workspace)),i({workspace:d},"shaper_dev_stop","Stop the development session managed for this project.",t=>S(t.workspace)),i({workspace:d},"shaper_dev_logs","Read recent local development output.",t=>x(t.workspace),"read"),i({workspace:d},"shaper_build","Run the project build command and verify the web output.",t=>h(t.workspace)),i({workspace:d},"shaper_check","Check project configuration; this is not a behavior or cloud connectivity test.",t=>_(t.workspace),"read"),i({workspace:d},"shaper_web_deploy","Build and upload web code through Shaper; return request status, validation and preview details.",t=>b(e.api,t.workspace)),i({workspace:d,versionId:n.string(),description:n.string().min(1),coverPath:n.string().optional()},"shaper_web_publish","Prepare review details and open a browser confirmation page. This does NOT submit review: the user edits details and submits in the browser. Cover is optional here and can be supplied in the browser.",t=>k(e.api,t.workspace,t.versionId,t.description,t.coverPath)),i({workspace:d},"hupu_cloud_status","Read application cloud readiness, current release, pending and recent operations. No test/production environments or resource profiles are selected by developers.",t=>e.cloud.status(t.workspace),"read"),i({workspace:d},"hupu_cloud_create","Request cloud creation and open browser confirmation. Only the user may confirm in the browser; chat approval or an existing token is insufficient. Return the confirmation URL and wait for the user; use hupu_cloud_status to check the result.",t=>e.cloud.create(t.workspace)),i({workspace:d,directory:n.string().optional(),manifestFile:n.string().optional(),bundleFile:n.string().optional(),idempotencyKey:m},"hupu_cloud_deploy","Publish the whole backend service and its declared routes. Default: build cloud/functions/api (legacy functions/api is detected). Alternatively pass both manifestFile and bundleFile, without directory. Confirm required migrations have completed before deploying. Waits for completion; use hupu_cloud_status if still pending. One application has one active service.",t=>e.cloud.deploy(t.workspace,{...t.directory!==void 0?{directory:t.directory}:{},...t.manifestFile!==void 0?{manifestFile:t.manifestFile}:{},...t.bundleFile!==void 0?{bundleFile:t.bundleFile}:{}},t.idempotencyKey)),i({workspace:d,version:n.string(),file:n.string(),idempotencyKey:m},"hupu_cloud_database_migrate","Submit a versioned PostgreSQL migration file. Waits for completion. If queued/running remains, use hupu_cloud_status; only succeeded allows dependent changes. Applied versions are immutable.",t=>e.cloud.migrate(t.workspace,t.version,t.file,t.idempotencyKey)),o.legacyCloud&&(i({workspace:d},"hupu_legacy_cloud_capabilities","Read Hupu Cloud runtimes, database dialect and environment-creation capabilities for this app.",t=>e.legacyCloud.capabilities(t.workspace),"read"),i({workspace:d},"hupu_legacy_cloud_environments","List cloud environments belonging to this Shaper application.",t=>e.legacyCloud.environments(t.workspace),"read"),i({workspace:d,environment:u,postgres:n.boolean().default(!1)},"hupu_legacy_cloud_create","Provision an environment for this app using the platform-approved plan. This may incur cloud charges. PostgreSQL must be requested at creation.",t=>e.legacyCloud.create(t.workspace,t.environment,t.postgres)),i({workspace:d,environment:u},"hupu_legacy_cloud_status","Refresh the readiness of this Hupu Cloud environment.",t=>e.legacyCloud.status(t.workspace,t.environment),"read"),i({workspace:d,environment:u},"hupu_legacy_cloud_functions","List cloud functions and deployment states.",t=>e.legacyCloud.functions(t.workspace,t.environment),"read"),i({workspace:d,environment:u,name:P,directory:n.string(),idempotencyKey:m},"hupu_legacy_cloud_function_deploy","Legacy event-function deployment only (index.js exporting main). For new HTTP backends use the backend template and hupu_cloud_deploy.",t=>e.legacyCloud.deployFunction(t.workspace,t.environment,t.name,t.directory,t.idempotencyKey)),i({workspace:d,environment:u,name:P,payload:n.unknown(),idempotencyKey:m},"hupu_legacy_cloud_function_invoke","Invoke a cloud function with JSON input; report execution status and output.",t=>e.legacyCloud.invoke(t.workspace,t.environment,t.name,t.payload,t.idempotencyKey)),i({workspace:d,environment:u,name:P},"hupu_legacy_cloud_function_logs","Read recent function logs.",t=>e.legacyCloud.logs(t.workspace,t.environment,t.name),"read"),i({workspace:d,environment:u,sql:n.string().min(1).max(6e4),idempotencyKey:m},"hupu_legacy_cloud_database_query","Execute privileged PostgreSQL SQL in the selected app environment. This can mutate or delete data; follow the requested business scope.",t=>e.legacyCloud.sql(t.workspace,t.environment,t.sql,t.idempotencyKey),"destructive"),i({workspace:d,environment:u,prefix:n.string().optional(),cursor:n.string().optional()},"hupu_legacy_cloud_storage_list","List private cloud objects, with pagination.",t=>e.legacyCloud.listObjects(t.workspace,t.environment,t.prefix,t.cursor),"read"),i({workspace:d,environment:u,objectKey:n.string(),file:n.string(),idempotencyKey:m},"hupu_legacy_cloud_storage_upload","Upload a project file (maximum 10 MiB) to private application storage. Replaces the same object key.",t=>e.legacyCloud.putObject(t.workspace,t.environment,t.objectKey,t.file,t.idempotencyKey)),i({workspace:d,environment:u,objectKey:n.string(),destination:n.string()},"hupu_legacy_cloud_storage_download","Download a cloud object to a new file inside the project; existing files are never overwritten.",t=>e.legacyCloud.getObject(t.workspace,t.environment,t.objectKey,t.destination)),i({workspace:d,environment:u,objectKey:n.string(),idempotencyKey:m},"hupu_legacy_cloud_storage_delete","Delete the explicitly requested object from application storage.",t=>e.legacyCloud.deleteObject(t.workspace,t.environment,t.objectKey,t.idempotencyKey),"destructive")),a}async function z(e={}){let o=await r.create(),a=B(o,e);await a.connect(new J);let i=async()=>{await o.auth.close(),await a.close()};process.once("SIGTERM",()=>{i()}),process.once("SIGINT",()=>{i()}),process.stdin.once("end",()=>{i()})}var l=new G().name("shaper").description("Shaper \u672C\u5730\u5F00\u53D1\u3001\u7F51\u9875\u4EA4\u4ED8\u4E0E\u864E\u6251\u4E91\u5DE5\u5177").version(C).enablePositionalOptions(),y=e=>process.stdout.write(JSON.stringify(e,null,2)+`
|
|
3
|
-
`),s=e=>async(...o)=>{y(await e(...o))};l.command("install").description("\u5168\u5C40\u5B89\u88C5 MCP \u548C Skills \u5230\u6307\u5B9A IDE").requiredOption("--ide <names>","codex,cursor,claude").option("--dev","\u76F4\u63A5\u4F7F\u7528\u5F53\u524D\u672C\u5730\u5305\u8FD0\u884C MCP \u548C\u6280\u80FD\uFF0C\u4E0D\u590D\u5236\u53D1\u884C\u5FEB\u7167").option("--skills <names>","\u9644\u52A0\u4E13\u4E1A\u6280\u80FD\uFF0C\u9017\u53F7\u5206\u9694").action(s(async e=>L(e.ide.split(","),{skills:e.skills?.split(","),dev:e.dev===!0})));l.command("update").description("\u5B89\u88C5\u6307\u5B9A\u53D1\u5E03\u7248\u672C\uFF0C\u4FDD\u7559\u539F IDE \u8BBE\u7F6E").requiredOption("--version <version>").requiredOption("--ide <names>").action(s(async e=>L(e.ide.split(","),{version:e.version})));l.command("uninstall").description("\u79FB\u9664\u672C\u5DE5\u5177\u7BA1\u7406\u7684 IDE \u914D\u7F6E\u548C\u6280\u80FD\u94FE\u63A5").action(s(F));l.command("doctor").description("\u68C0\u67E5\u5B89\u88C5\u4E0E\u9879\u76EE\u72B6\u6001").option("--cwd <directory>").action(s(async e=>({installation:await K(),status:await(await r.create()).status(e.cwd&&c(e.cwd))})));l.command("config").description("\u67E5\u770B\u6216\u8BBE\u7F6E CLI / MCP \u5171\u7528\u7684\u9ED8\u8BA4\u670D\u52A1\uFF1B\u4E0D\u9700\u8981\u767B\u5F55").option("--server <origin>","\u4FDD\u5B58\u9ED8\u8BA4\u670D\u52A1\u5730\u5740").action(s(async e=>(e.server&&await q(e.server),{server:await A(),configDirectory:D(),source:process.env.SHAPER_SERVER?"SHAPER_SERVER":"global config or default",...e.server?{saved:!0,configuredServer:e.server,restartMcp:!0}:{}})));l.command("login").description("\u8FDE\u63A5\u5168\u5C40\u8D26\u53F7\uFF1B\u5DF2\u6709\u6743\u9650\u76F4\u63A5\u590D\u7528").option("--server <origin>").option("--cloud","\u8FFD\u52A0\u4E91\u51FD\u6570\u548C\u6570\u636E\u5E93\u7BA1\u7406\u6743\u9650").option("--app <appId>","\u4E3A\u5DF2\u6709\u5E94\u7528\u8865\u5145\u6388\u6743").option("--reauthorize","\u6253\u5F00\u7F51\u9875\u589E\u52A0\u6388\u6743\u8303\u56F4").option("--no-browser","\u4EC5\u8F93\u51FA\u6388\u6743\u94FE\u63A5").action(async e=>{let o=await r.create(e.server);try{let a=await o.auth.start({cloud:e.cloud===!0,openBrowser:e.browser!==!1,reauthorize:e.reauthorize===!0,...e.app?{appId:e.app}:{}});y(a),a.status==="pending"&&y(await o.auth.wait(a.flowId)),e.server&&await q(o.auth.server)}finally{await o.auth.close()}});l.command("logout").description("\u9000\u51FA\u5168\u5C40\u8D26\u53F7\uFF0C\u5F53\u524D\u670D\u52A1\u7684\u6240\u6709\u672C\u5730\u9879\u76EE\u90FD\u9700\u8981\u91CD\u65B0\u767B\u5F55").action(s(async()=>(await r.create()).auth.logout()));l.command("whoami").description("\u8BFB\u53D6\u5F53\u524D\u767B\u5F55\u8EAB\u4EFD\u4E0E\u6388\u6743\u8303\u56F4").action(s(async()=>(await r.create()).api.me()));l.command("init").argument("[directory]","\u5DE5\u7A0B\u76EE\u5F55",".").option("--name <name>").option("--app <appId>","\u5173\u8054\u6307\u5B9A\u5E94\u7528\uFF1B\u5C1A\u672A\u521B\u5EFA\u65F6\u5728\u6D4F\u89C8\u5668\u786E\u8BA4\u521B\u5EFA").option("--template <name>","\u7A7A\u76EE\u5F55\u6A21\u677F\uFF1Ah5\u3001react\u3001phaser").option("--no-install","\u8DF3\u8FC7\u4F9D\u8D56\u5B89\u88C5").action(s(async(e,o)=>f((await r.create()).api,c(e),{...o.name?{name:o.name}:{},...o.app?{appId:o.app}:{},waitForAuthorization:!0,template:o.template,installDependencies:o.install!==!1})));l.command("link").requiredOption("--app <appId>").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(s(async e=>v((await r.create()).api,c(e.cwd),e.app)));l.command("projects").action(s(async()=>(await r.create()).api.projects()));l.command("status").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(s(async e=>(await r.create()).status(c(e.cwd))));l.command("dev").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(s(async e=>j(c(e.cwd))));l.command("stop").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(s(async e=>S(c(e.cwd))));l.command("logs").description("\u8BFB\u53D6\u672C\u5730\u5F00\u53D1\u670D\u52A1\u65E5\u5FD7").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(s(async e=>x(c(e.cwd))));l.command("build").description("\u6784\u5EFA\u7F51\u9875\u5236\u54C1").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(s(async e=>h(c(e.cwd))));l.command("check").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(async e=>{let o=await _(c(e.cwd));y(o),o.passed||(process.exitCode=1)});l.command("deploy").description("\u6784\u5EFA\u7F51\u9875\u5E76\u4EA4\u4ED8\u5230 Shaper \u9884\u89C8").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(s(async e=>b((await r.create()).api,c(e.cwd))));l.command("publish").description("\u6253\u5F00\u6D4F\u89C8\u5668\u786E\u8BA4\u6307\u5B9A\u7248\u672C\u7684\u5BA1\u6838\u63D0\u4EA4").requiredOption("--version <versionId>").requiredOption("--description <text>").option("--cover <file>","\u53EF\u9009\u5DE5\u7A0B\u5185\u5C01\u9762\uFF0C\u4E5F\u53EF\u5728\u6D4F\u89C8\u5668\u8865\u5145").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(s(async e=>k((await r.create()).api,c(e.cwd),e.version,e.description,e.cover)));var I=l.command("cloud").description("\u5E94\u7528\u4E91\u670D\u52A1\uFF1A\u521B\u5EFA\u3001\u90E8\u7F72\u3001\u6570\u636E\u5E93\u8FC1\u79FB\u548C\u72B6\u6001"),O=e=>async(...o)=>{let a=await e(...o);y(a),a.status==="failed"&&(process.exitCode=1)};function g(e,o,a){return e.command(o).description(a).option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".")}g(I,"status","\u67E5\u770B\u4E91\u670D\u52A1\u3001\u5F53\u524D\u7248\u672C\u53CA\u6B63\u5728\u5904\u7406\u6216\u6700\u8FD1\u5B8C\u6210\u7684\u64CD\u4F5C").action(O(async e=>(await r.create()).cloud.status(c(e.cwd))));g(I,"create","\u6253\u5F00\u7F51\u9875\u786E\u8BA4\u5F00\u901A\u5E94\u7528\u4E91\u670D\u52A1").action(O(async e=>(await r.create()).cloud.create(c(e.cwd))));g(I,"deploy","\u53D1\u5E03\u540E\u53F0\u670D\u52A1\u4E0E cloud.json \u8DEF\u7531\uFF1B\u9ED8\u8BA4\u4ECE cloud/functions/api \u6784\u5EFA").option("--directory <directory>","\u6E90\u7801\u76EE\u5F55\uFF1B\u4E0D\u80FD\u4E0E\u5236\u54C1\u53C2\u6570\u6DF7\u7528").option("--manifest <file>","\u5DF2\u6709\u5236\u54C1\u7684 manifest\uFF1B\u987B\u540C\u65F6\u63D0\u4F9B --bundle").option("--bundle <file>","\u5DF2\u6709\u5236\u54C1\u7684 bundle\uFF1B\u987B\u540C\u65F6\u63D0\u4F9B --manifest").option("--key <key>","\u8BF7\u6C42\u5E42\u7B49\u952E\uFF1B\u9ED8\u8BA4\u6309\u5185\u5BB9\u751F\u6210").action(O(async e=>(await r.create()).cloud.deploy(c(e.cwd),{...e.directory!==void 0?{directory:e.directory}:{},...e.manifest!==void 0?{manifestFile:e.manifest}:{},...e.bundle!==void 0?{bundleFile:e.bundle}:{}},e.key)));var V=I.command("db").description("\u5E94\u7528\u7684\u6570\u636E\u5E93\u53D8\u66F4");g(V,"migrate","\u63D0\u4EA4\u7248\u672C\u5316 PostgreSQL \u8FC1\u79FB").requiredOption("--version <version>").requiredOption("--file <file>").option("--key <key>").action(O(async e=>(await r.create()).cloud.migrate(c(e.cwd),e.version,e.file,e.key)));var Y=l.command("legacy").description("\u5B58\u91CF\u7CFB\u7EDF\u517C\u5BB9\u5DE5\u5177"),Z=Y.command("cloud").description("\u65E7\u4E8B\u4EF6\u51FD\u6570\u6267\u884C\u5668\uFF1B\u4E0D\u80FD\u64CD\u4F5C\u65B0\u7248\u5E94\u7528\u4E91\u8D44\u6E90");function p(e,o){return g(Z,e,o)}p("capabilities","\u8BFB\u53D6\u8FD0\u884C\u65F6\u3001\u6570\u636E\u5E93\u65B9\u8A00\u4E0E\u5957\u9910\u914D\u7F6E").action(s(async e=>(await r.create()).legacyCloud.capabilities(c(e.cwd))));p("list","\u5217\u51FA\u5F53\u524D\u5E94\u7528\u7684\u4E91\u73AF\u5883").action(s(async e=>(await r.create()).legacyCloud.environments(c(e.cwd))));p("create <environment>","\u6309\u5E73\u53F0\u5957\u9910\u5F00\u901A\u4E91\u73AF\u5883\uFF0C\u53EF\u80FD\u4EA7\u751F\u8D39\u7528").option("--postgres","\u540C\u65F6\u5F00\u901A PostgreSQL").action(s(async(e,o)=>(await r.create()).legacyCloud.create(c(o.cwd),e,o.postgres===!0)));p("status <environment>","\u8BFB\u53D6\u771F\u5B9E\u4E91\u73AF\u5883\u72B6\u6001").action(s(async(e,o)=>(await r.create()).legacyCloud.status(c(o.cwd),e)));p("functions <environment>","\u5217\u51FA\u4E91\u51FD\u6570\u53CA\u72B6\u6001").action(s(async(e,o)=>(await r.create()).legacyCloud.functions(c(o.cwd),e)));p("deploy <environment> <name> <directory>","\u90E8\u7F72\u5DF2\u6253\u5305\u7684\u4E91\u51FD\u6570\u76EE\u5F55").option("--key <key>","\u8BF7\u6C42\u5E42\u7B49\u952E").action(s(async(e,o,a,i)=>(await r.create()).legacyCloud.deployFunction(c(i.cwd),e,o,a,i.key)));p("invoke <environment> <name>","\u6267\u884C\u4E91\u51FD\u6570").option("--input <file>","JSON \u8F93\u5165\u6587\u4EF6").option("--key <key>").action(s(async(e,o,a)=>(await r.create()).legacyCloud.invoke(c(a.cwd),e,o,a.input?JSON.parse(await T(a.input,"utf8")):{},a.key)));p("logs <environment> <name>","\u67E5\u770B\u4E91\u51FD\u6570\u65E5\u5FD7").action(s(async(e,o,a)=>(await r.create()).legacyCloud.logs(c(a.cwd),e,o)));p("sql <environment>","\u6267\u884C\u6570\u636E\u5E93\u7BA1\u7406 SQL").requiredOption("--file <file>","SQL \u6587\u4EF6").option("--key <key>").action(s(async(e,o)=>(await r.create()).legacyCloud.sql(c(o.cwd),e,await T(o.file,"utf8"),o.key)));p("storage-list <environment>","\u5217\u51FA\u4E91\u5B58\u50A8\u5BF9\u8C61").option("--prefix <prefix>").option("--cursor <cursor>").action(s(async(e,o)=>(await r.create()).legacyCloud.listObjects(c(o.cwd),e,o.prefix,o.cursor)));p("storage-put <environment> <objectKey> <file>","\u4E0A\u4F20\u5DE5\u7A0B\u5185\u6587\u4EF6\u5230\u79C1\u6709\u4E91\u5B58\u50A8").option("--key <key>").action(s(async(e,o,a,i)=>(await r.create()).legacyCloud.putObject(c(i.cwd),e,o,a,i.key)));p("storage-get <environment> <objectKey> <destination>","\u4E0B\u8F7D\u5230\u5DE5\u7A0B\u5185\u7684\u65B0\u6587\u4EF6").action(s(async(e,o,a,i)=>(await r.create()).legacyCloud.getObject(c(i.cwd),e,o,a)));p("storage-delete <environment> <objectKey>","\u5220\u9664\u6307\u5B9A\u4E91\u5B58\u50A8\u5BF9\u8C61").option("--key <key>").action(s(async(e,o,a)=>(await r.create()).legacyCloud.deleteObject(c(a.cwd),e,o,a.key)));l.command("mcp").command("serve").description("\u542F\u52A8 stdio MCP \u670D\u52A1").option("--legacy-cloud","\u989D\u5916\u5F00\u653E\u65E7\u4E91\u7EF4\u62A4\u5DE5\u5177").action(async e=>z({legacyCloud:e.legacyCloud===!0}));try{await l.parseAsync()}catch(e){process.stderr.write(JSON.stringify(w(e))+`
|
|
2
|
+
import{c as D,d as M,e as Q,f as S}from"./shared-3SHRGRIW.js";import{g as r}from"./shared-WK7DKUR5.js";import{d as x,e as P,f as I}from"./shared-COXNB4AR.js";import{b as z,f as N,g as E,h as v,j as f,o as h,q as b,r as _,t as k,u as C,v as j}from"./shared-Z5NOVHRW.js";import{Command as X}from"commander";import{readFile as H}from"node:fs/promises";import{resolve as c}from"node:path";import{McpServer as G}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as V}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as n}from"zod";import{isAbsolute as Y}from"node:path";import{readFile as Z}from"node:fs/promises";var d=n.string().min(1).refine(Y,"workspace must be an absolute path").describe("Absolute local project directory. Never infer from the MCP process working directory."),u=n.string().regex(/^[a-z][a-z0-9-]{0,31}$/),O=n.string().min(1).max(64),m=n.string().min(16).max(100).optional();function $(e,o={}){let s=new G({name:"shaper",version:S},{instructions:"Use installed Shaper skills for workflows. Always pass the intended absolute workspace. All sessions share one login per Shaper server. Reuse it; request additional permissions only when needed. Browser consent adds permissions without replacing existing access. Local binding contains only the server and app ID, never tokens. Never choose a recent app as a fallback. Web delivery and backend service deployment have separate targets. Queued, running or uncertain results do not confirm completion. Writes wait for completion; if still pending, use hupu_cloud_status for backend operations and shaper_status for web delivery. Never create cloud resources without explicit user approval."});function i(t,L,J,U,F="write"){s.registerTool(L,{description:J,inputSchema:t,annotations:{readOnlyHint:F==="read",destructiveHint:F==="destructive",openWorldHint:!0}},async B=>{try{let w=await U(B),A=[{type:"text",text:JSON.stringify(w,null,2)}];if(L==="shaper_web_deploy"||L==="shaper_web_preview"){let K=w,T=K.preview?.qrCodePath??K.result?.preview?.qrCodePath;if(T)try{A.push({type:"image",mimeType:"image/png",data:(await Z(T)).toString("base64")})}catch{}}return{content:A}}catch(w){return{isError:!0,content:[{type:"text",text:JSON.stringify(v(w))}]}}})}return i({workspace:d.optional()},"shaper_status","Read identity, project versions/current published version, local development session and the last web delivery outcome. Does not start services or repeat uploads.",t=>e.status(t.workspace),"read"),i({cloud:n.boolean().default(!1),openBrowser:n.boolean().default(!0),appId:n.string().min(1).max(200).optional(),reauthorize:n.boolean().default(!1)},"shaper_auth_start","Reuse the global login when permissions suffice. Otherwise start browser consent and return a flow ID. appId adds access to an existing application; cloud=true adds cloud permissions. Existing permissions are retained. reauthorize=true opens consent explicitly.",t=>e.auth.start(t)),i({flowId:n.string()},"shaper_auth_status","Read browser authorization result for a flow started by this MCP session.",t=>e.auth.status(t.flowId),"read"),i({},"shaper_logout","Sign out globally for this Shaper server. All local projects and Agent sessions share this login.",()=>e.auth.logout(),"destructive"),i({},"shaper_projects","List applications available to this authorization.",()=>e.api.projects(),"read"),i({workspace:d,template:n.enum(["h5","react","phaser"]).optional(),name:O.optional(),appId:n.string().optional(),installDependencies:n.boolean().default(!0)},"shaper_init","Create a vanilla HTML, React or Phaser project and a Shaper application, or initialize an existing source directory. Resolve existing identity first; missing apps require browser creation consent. A pending result requires finishing authorization and retrying with the same workspace/appId. Legacy downloaded projects return LEGACY_PROJECT_UPGRADE_REQUIRED: stop and preserve their original workflow; never bypass through link or removing markers. Other existing projects may return configuration_required: inspect their actual entry, build tool and output, then supply shaper.config.json without moving sources. Never overwrite a conflicting existing binding.",t=>h(e.api,t.workspace,t)),i({workspace:d,appId:n.string()},"shaper_link","Associate the local source directory with an existing authorized Shaper application.",t=>b(e.api,t.workspace,t.appId)),i({workspace:d},"shaper_dev_start","Start a local development server using shaper.config.json and return its verified URL.",t=>x(t.workspace)),i({workspace:d},"shaper_dev_stop","Stop the development session managed for this project.",t=>P(t.workspace)),i({workspace:d},"shaper_dev_logs","Read recent local development output.",t=>I(t.workspace),"read"),i({workspace:d},"shaper_build","Run the project build command and verify the web output.",t=>_(t.workspace)),i({workspace:d},"shaper_check","Check project configuration; this is not a behavior or cloud connectivity test.",t=>j(t.workspace),"read"),i({workspace:d},"shaper_web_deploy","Build and upload web code through Shaper; return request status, validation and preview details.",t=>k(e.api,t.workspace)),i({workspace:d,versionId:n.string().min(1).optional()},"shaper_web_preview","Get or refresh a cloud preview URL, expiry and QR image for an uploaded version. Defaults to the last confirmed local delivery. Never rebuilds, uploads or submits review.",t=>f(e.api,t.workspace,t.versionId)),i({workspace:d,versionId:n.string(),description:n.string().min(1),coverPath:n.string().optional()},"shaper_web_publish","Prepare review details and open a browser confirmation page. This does NOT submit review: the user edits details and submits in the browser. Cover is optional here and can be supplied in the browser.",t=>C(e.api,t.workspace,t.versionId,t.description,t.coverPath)),i({workspace:d},"hupu_cloud_status","Read application cloud readiness, current release, pending and recent operations. No test/production environments or resource profiles are selected by developers.",t=>e.cloud.status(t.workspace),"read"),i({workspace:d},"hupu_cloud_create","Request cloud creation and open browser confirmation. Only the user may confirm in the browser; chat approval or an existing token is insufficient. Return the confirmation URL and wait for the user; use hupu_cloud_status to check the result.",t=>e.cloud.create(t.workspace)),i({workspace:d,directory:n.string().optional(),manifestFile:n.string().optional(),bundleFile:n.string().optional(),idempotencyKey:m},"hupu_cloud_deploy","Publish the whole backend service and its declared routes. Default: build cloud/functions/api (legacy functions/api is detected). Alternatively pass both manifestFile and bundleFile, without directory. Confirm required migrations have completed before deploying. Waits for completion; use hupu_cloud_status if still pending. One application has one active service.",t=>e.cloud.deploy(t.workspace,{...t.directory!==void 0?{directory:t.directory}:{},...t.manifestFile!==void 0?{manifestFile:t.manifestFile}:{},...t.bundleFile!==void 0?{bundleFile:t.bundleFile}:{}},t.idempotencyKey)),i({workspace:d,version:n.string(),file:n.string(),idempotencyKey:m},"hupu_cloud_database_migrate","Submit a versioned PostgreSQL migration file. Waits for completion. If queued/running remains, use hupu_cloud_status; only succeeded allows dependent changes. Applied versions are immutable.",t=>e.cloud.migrate(t.workspace,t.version,t.file,t.idempotencyKey)),o.legacyCloud&&(i({workspace:d},"hupu_legacy_cloud_capabilities","Read Hupu Cloud runtimes, database dialect and environment-creation capabilities for this app.",t=>e.legacyCloud.capabilities(t.workspace),"read"),i({workspace:d},"hupu_legacy_cloud_environments","List cloud environments belonging to this Shaper application.",t=>e.legacyCloud.environments(t.workspace),"read"),i({workspace:d,environment:u,postgres:n.boolean().default(!1)},"hupu_legacy_cloud_create","Provision an environment for this app using the platform-approved plan. This may incur cloud charges. PostgreSQL must be requested at creation.",t=>e.legacyCloud.create(t.workspace,t.environment,t.postgres)),i({workspace:d,environment:u},"hupu_legacy_cloud_status","Refresh the readiness of this Hupu Cloud environment.",t=>e.legacyCloud.status(t.workspace,t.environment),"read"),i({workspace:d,environment:u},"hupu_legacy_cloud_functions","List cloud functions and deployment states.",t=>e.legacyCloud.functions(t.workspace,t.environment),"read"),i({workspace:d,environment:u,name:O,directory:n.string(),idempotencyKey:m},"hupu_legacy_cloud_function_deploy","Legacy event-function deployment only (index.js exporting main). For new HTTP backends use the backend template and hupu_cloud_deploy.",t=>e.legacyCloud.deployFunction(t.workspace,t.environment,t.name,t.directory,t.idempotencyKey)),i({workspace:d,environment:u,name:O,payload:n.unknown(),idempotencyKey:m},"hupu_legacy_cloud_function_invoke","Invoke a cloud function with JSON input; report execution status and output.",t=>e.legacyCloud.invoke(t.workspace,t.environment,t.name,t.payload,t.idempotencyKey)),i({workspace:d,environment:u,name:O},"hupu_legacy_cloud_function_logs","Read recent function logs.",t=>e.legacyCloud.logs(t.workspace,t.environment,t.name),"read"),i({workspace:d,environment:u,sql:n.string().min(1).max(6e4),idempotencyKey:m},"hupu_legacy_cloud_database_query","Execute privileged PostgreSQL SQL in the selected app environment. This can mutate or delete data; follow the requested business scope.",t=>e.legacyCloud.sql(t.workspace,t.environment,t.sql,t.idempotencyKey),"destructive"),i({workspace:d,environment:u,prefix:n.string().optional(),cursor:n.string().optional()},"hupu_legacy_cloud_storage_list","List private cloud objects, with pagination.",t=>e.legacyCloud.listObjects(t.workspace,t.environment,t.prefix,t.cursor),"read"),i({workspace:d,environment:u,objectKey:n.string(),file:n.string(),idempotencyKey:m},"hupu_legacy_cloud_storage_upload","Upload a project file (maximum 10 MiB) to private application storage. Replaces the same object key.",t=>e.legacyCloud.putObject(t.workspace,t.environment,t.objectKey,t.file,t.idempotencyKey)),i({workspace:d,environment:u,objectKey:n.string(),destination:n.string()},"hupu_legacy_cloud_storage_download","Download a cloud object to a new file inside the project; existing files are never overwritten.",t=>e.legacyCloud.getObject(t.workspace,t.environment,t.objectKey,t.destination)),i({workspace:d,environment:u,objectKey:n.string(),idempotencyKey:m},"hupu_legacy_cloud_storage_delete","Delete the explicitly requested object from application storage.",t=>e.legacyCloud.deleteObject(t.workspace,t.environment,t.objectKey,t.idempotencyKey),"destructive")),s}async function W(e={}){let o=await r.create(),s=$(o,e);await s.connect(new V);let i=async()=>{await o.auth.close(),await s.close()};process.once("SIGTERM",()=>{i()}),process.once("SIGINT",()=>{i()}),process.stdin.once("end",()=>{i()})}var l=new X().name("shaper").description("Shaper \u672C\u5730\u5F00\u53D1\u3001\u7F51\u9875\u4EA4\u4ED8\u4E0E\u864E\u6251\u4E91\u5DE5\u5177").version(S).enablePositionalOptions(),y=e=>process.stdout.write(JSON.stringify(e,null,2)+`
|
|
3
|
+
`),a=e=>async(...o)=>{y(await e(...o))};l.command("install").description("\u5168\u5C40\u5B89\u88C5 MCP \u548C Skills \u5230\u6307\u5B9A IDE").requiredOption("--ide <names>","codex,cursor,claude").option("--dev","\u76F4\u63A5\u4F7F\u7528\u5F53\u524D\u672C\u5730\u5305\u8FD0\u884C MCP \u548C\u6280\u80FD\uFF0C\u4E0D\u590D\u5236\u53D1\u884C\u5FEB\u7167").option("--skills <names>","\u9644\u52A0\u4E13\u4E1A\u6280\u80FD\uFF0C\u9017\u53F7\u5206\u9694").action(a(async e=>D(e.ide.split(","),{skills:e.skills?.split(","),dev:e.dev===!0})));l.command("update").description("\u5B89\u88C5\u6307\u5B9A\u53D1\u5E03\u7248\u672C\uFF0C\u4FDD\u7559\u539F IDE \u8BBE\u7F6E").requiredOption("--version <version>").requiredOption("--ide <names>").action(a(async e=>D(e.ide.split(","),{version:e.version})));l.command("uninstall").description("\u79FB\u9664\u672C\u5DE5\u5177\u7BA1\u7406\u7684 IDE \u914D\u7F6E\u548C\u6280\u80FD\u94FE\u63A5").action(a(M));l.command("doctor").description("\u68C0\u67E5\u5B89\u88C5\u4E0E\u9879\u76EE\u72B6\u6001").option("--cwd <directory>").action(a(async e=>({installation:await Q(),status:await(await r.create()).status(e.cwd&&c(e.cwd))})));l.command("config").description("\u67E5\u770B\u6216\u8BBE\u7F6E CLI / MCP \u5171\u7528\u7684\u9ED8\u8BA4\u670D\u52A1\uFF1B\u4E0D\u9700\u8981\u767B\u5F55").option("--server <origin>","\u4FDD\u5B58\u9ED8\u8BA4\u670D\u52A1\u5730\u5740").action(a(async e=>(e.server&&await E(e.server),{server:await N(),configDirectory:z(),source:process.env.SHAPER_SERVER?"SHAPER_SERVER":"global config or default",...e.server?{saved:!0,configuredServer:e.server,restartMcp:!0}:{}})));l.command("login").description("\u8FDE\u63A5\u5168\u5C40\u8D26\u53F7\uFF1B\u5DF2\u6709\u6743\u9650\u76F4\u63A5\u590D\u7528").option("--server <origin>").option("--cloud","\u8FFD\u52A0\u4E91\u51FD\u6570\u548C\u6570\u636E\u5E93\u7BA1\u7406\u6743\u9650").option("--app <appId>","\u4E3A\u5DF2\u6709\u5E94\u7528\u8865\u5145\u6388\u6743").option("--reauthorize","\u6253\u5F00\u7F51\u9875\u589E\u52A0\u6388\u6743\u8303\u56F4").option("--no-browser","\u4EC5\u8F93\u51FA\u6388\u6743\u94FE\u63A5").action(async e=>{let o=await r.create(e.server);try{let s=await o.auth.start({cloud:e.cloud===!0,openBrowser:e.browser!==!1,reauthorize:e.reauthorize===!0,...e.app?{appId:e.app}:{}});y(s),s.status==="pending"&&y(await o.auth.wait(s.flowId)),e.server&&await E(o.auth.server)}finally{await o.auth.close()}});l.command("logout").description("\u9000\u51FA\u5168\u5C40\u8D26\u53F7\uFF0C\u5F53\u524D\u670D\u52A1\u7684\u6240\u6709\u672C\u5730\u9879\u76EE\u90FD\u9700\u8981\u91CD\u65B0\u767B\u5F55").action(a(async()=>(await r.create()).auth.logout()));l.command("whoami").description("\u8BFB\u53D6\u5F53\u524D\u767B\u5F55\u8EAB\u4EFD\u4E0E\u6388\u6743\u8303\u56F4").action(a(async()=>(await r.create()).api.me()));l.command("init").argument("[directory]","\u5DE5\u7A0B\u76EE\u5F55",".").option("--name <name>").option("--app <appId>","\u5173\u8054\u6307\u5B9A\u5E94\u7528\uFF1B\u5C1A\u672A\u521B\u5EFA\u65F6\u5728\u6D4F\u89C8\u5668\u786E\u8BA4\u521B\u5EFA").option("--template <name>","\u7A7A\u76EE\u5F55\u6A21\u677F\uFF1Ah5\u3001react\u3001phaser").option("--no-install","\u8DF3\u8FC7\u4F9D\u8D56\u5B89\u88C5").action(a(async(e,o)=>h((await r.create()).api,c(e),{...o.name?{name:o.name}:{},...o.app?{appId:o.app}:{},waitForAuthorization:!0,template:o.template,installDependencies:o.install!==!1})));l.command("link").requiredOption("--app <appId>").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(a(async e=>b((await r.create()).api,c(e.cwd),e.app)));l.command("projects").action(a(async()=>(await r.create()).api.projects()));l.command("status").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(a(async e=>(await r.create()).status(c(e.cwd))));l.command("dev").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(a(async e=>x(c(e.cwd))));l.command("stop").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(a(async e=>P(c(e.cwd))));l.command("logs").description("\u8BFB\u53D6\u672C\u5730\u5F00\u53D1\u670D\u52A1\u65E5\u5FD7").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(a(async e=>I(c(e.cwd))));l.command("build").description("\u6784\u5EFA\u7F51\u9875\u5236\u54C1").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(a(async e=>_(c(e.cwd))));l.command("check").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(async e=>{let o=await j(c(e.cwd));y(o),o.passed||(process.exitCode=1)});l.command("deploy").description("\u6784\u5EFA\u7F51\u9875\u5E76\u4EA4\u4ED8\u5230 Shaper \u9884\u89C8").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(a(async e=>k((await r.create()).api,c(e.cwd))));l.command("preview").description("\u83B7\u53D6\u6216\u5237\u65B0\u5DF2\u4E0A\u4F20\u7248\u672C\u7684\u9884\u89C8\u94FE\u63A5\u548C\u4E8C\u7EF4\u7801\uFF0C\u4E0D\u91CD\u65B0\u6784\u5EFA\u6216\u4E0A\u4F20").option("--version <versionId>","\u9ED8\u8BA4\u4F7F\u7528\u672C\u9879\u76EE\u6700\u8FD1\u4E00\u6B21\u5DF2\u786E\u8BA4\u4EA4\u4ED8\u7684\u7248\u672C").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(a(async e=>f((await r.create()).api,c(e.cwd),e.version)));l.command("publish").description("\u6253\u5F00\u6D4F\u89C8\u5668\u786E\u8BA4\u6307\u5B9A\u7248\u672C\u7684\u5BA1\u6838\u63D0\u4EA4").requiredOption("--version <versionId>").requiredOption("--description <text>").option("--cover <file>","\u53EF\u9009\u5DE5\u7A0B\u5185\u5C01\u9762\uFF0C\u4E5F\u53EF\u5728\u6D4F\u89C8\u5668\u8865\u5145").option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".").action(a(async e=>C((await r.create()).api,c(e.cwd),e.version,e.description,e.cover)));var R=l.command("cloud").description("\u5E94\u7528\u4E91\u670D\u52A1\uFF1A\u521B\u5EFA\u3001\u90E8\u7F72\u3001\u6570\u636E\u5E93\u8FC1\u79FB\u548C\u72B6\u6001"),q=e=>async(...o)=>{let s=await e(...o);y(s),s.status==="failed"&&(process.exitCode=1)};function g(e,o,s){return e.command(o).description(s).option("--cwd <directory>","\u5DE5\u7A0B\u76EE\u5F55",".")}g(R,"status","\u67E5\u770B\u4E91\u670D\u52A1\u3001\u5F53\u524D\u7248\u672C\u53CA\u6B63\u5728\u5904\u7406\u6216\u6700\u8FD1\u5B8C\u6210\u7684\u64CD\u4F5C").action(q(async e=>(await r.create()).cloud.status(c(e.cwd))));g(R,"create","\u6253\u5F00\u7F51\u9875\u786E\u8BA4\u5F00\u901A\u5E94\u7528\u4E91\u670D\u52A1").action(q(async e=>(await r.create()).cloud.create(c(e.cwd))));g(R,"deploy","\u53D1\u5E03\u540E\u53F0\u670D\u52A1\u4E0E cloud.json \u8DEF\u7531\uFF1B\u9ED8\u8BA4\u4ECE cloud/functions/api \u6784\u5EFA").option("--directory <directory>","\u6E90\u7801\u76EE\u5F55\uFF1B\u4E0D\u80FD\u4E0E\u5236\u54C1\u53C2\u6570\u6DF7\u7528").option("--manifest <file>","\u5DF2\u6709\u5236\u54C1\u7684 manifest\uFF1B\u987B\u540C\u65F6\u63D0\u4F9B --bundle").option("--bundle <file>","\u5DF2\u6709\u5236\u54C1\u7684 bundle\uFF1B\u987B\u540C\u65F6\u63D0\u4F9B --manifest").option("--key <key>","\u8BF7\u6C42\u5E42\u7B49\u952E\uFF1B\u9ED8\u8BA4\u6309\u5185\u5BB9\u751F\u6210").action(q(async e=>(await r.create()).cloud.deploy(c(e.cwd),{...e.directory!==void 0?{directory:e.directory}:{},...e.manifest!==void 0?{manifestFile:e.manifest}:{},...e.bundle!==void 0?{bundleFile:e.bundle}:{}},e.key)));var ee=R.command("db").description("\u5E94\u7528\u7684\u6570\u636E\u5E93\u53D8\u66F4");g(ee,"migrate","\u63D0\u4EA4\u7248\u672C\u5316 PostgreSQL \u8FC1\u79FB").requiredOption("--version <version>").requiredOption("--file <file>").option("--key <key>").action(q(async e=>(await r.create()).cloud.migrate(c(e.cwd),e.version,e.file,e.key)));var te=l.command("legacy").description("\u5B58\u91CF\u7CFB\u7EDF\u517C\u5BB9\u5DE5\u5177"),oe=te.command("cloud").description("\u65E7\u4E8B\u4EF6\u51FD\u6570\u6267\u884C\u5668\uFF1B\u4E0D\u80FD\u64CD\u4F5C\u65B0\u7248\u5E94\u7528\u4E91\u8D44\u6E90");function p(e,o){return g(oe,e,o)}p("capabilities","\u8BFB\u53D6\u8FD0\u884C\u65F6\u3001\u6570\u636E\u5E93\u65B9\u8A00\u4E0E\u5957\u9910\u914D\u7F6E").action(a(async e=>(await r.create()).legacyCloud.capabilities(c(e.cwd))));p("list","\u5217\u51FA\u5F53\u524D\u5E94\u7528\u7684\u4E91\u73AF\u5883").action(a(async e=>(await r.create()).legacyCloud.environments(c(e.cwd))));p("create <environment>","\u6309\u5E73\u53F0\u5957\u9910\u5F00\u901A\u4E91\u73AF\u5883\uFF0C\u53EF\u80FD\u4EA7\u751F\u8D39\u7528").option("--postgres","\u540C\u65F6\u5F00\u901A PostgreSQL").action(a(async(e,o)=>(await r.create()).legacyCloud.create(c(o.cwd),e,o.postgres===!0)));p("status <environment>","\u8BFB\u53D6\u771F\u5B9E\u4E91\u73AF\u5883\u72B6\u6001").action(a(async(e,o)=>(await r.create()).legacyCloud.status(c(o.cwd),e)));p("functions <environment>","\u5217\u51FA\u4E91\u51FD\u6570\u53CA\u72B6\u6001").action(a(async(e,o)=>(await r.create()).legacyCloud.functions(c(o.cwd),e)));p("deploy <environment> <name> <directory>","\u90E8\u7F72\u5DF2\u6253\u5305\u7684\u4E91\u51FD\u6570\u76EE\u5F55").option("--key <key>","\u8BF7\u6C42\u5E42\u7B49\u952E").action(a(async(e,o,s,i)=>(await r.create()).legacyCloud.deployFunction(c(i.cwd),e,o,s,i.key)));p("invoke <environment> <name>","\u6267\u884C\u4E91\u51FD\u6570").option("--input <file>","JSON \u8F93\u5165\u6587\u4EF6").option("--key <key>").action(a(async(e,o,s)=>(await r.create()).legacyCloud.invoke(c(s.cwd),e,o,s.input?JSON.parse(await H(s.input,"utf8")):{},s.key)));p("logs <environment> <name>","\u67E5\u770B\u4E91\u51FD\u6570\u65E5\u5FD7").action(a(async(e,o,s)=>(await r.create()).legacyCloud.logs(c(s.cwd),e,o)));p("sql <environment>","\u6267\u884C\u6570\u636E\u5E93\u7BA1\u7406 SQL").requiredOption("--file <file>","SQL \u6587\u4EF6").option("--key <key>").action(a(async(e,o)=>(await r.create()).legacyCloud.sql(c(o.cwd),e,await H(o.file,"utf8"),o.key)));p("storage-list <environment>","\u5217\u51FA\u4E91\u5B58\u50A8\u5BF9\u8C61").option("--prefix <prefix>").option("--cursor <cursor>").action(a(async(e,o)=>(await r.create()).legacyCloud.listObjects(c(o.cwd),e,o.prefix,o.cursor)));p("storage-put <environment> <objectKey> <file>","\u4E0A\u4F20\u5DE5\u7A0B\u5185\u6587\u4EF6\u5230\u79C1\u6709\u4E91\u5B58\u50A8").option("--key <key>").action(a(async(e,o,s,i)=>(await r.create()).legacyCloud.putObject(c(i.cwd),e,o,s,i.key)));p("storage-get <environment> <objectKey> <destination>","\u4E0B\u8F7D\u5230\u5DE5\u7A0B\u5185\u7684\u65B0\u6587\u4EF6").action(a(async(e,o,s,i)=>(await r.create()).legacyCloud.getObject(c(i.cwd),e,o,s)));p("storage-delete <environment> <objectKey>","\u5220\u9664\u6307\u5B9A\u4E91\u5B58\u50A8\u5BF9\u8C61").option("--key <key>").action(a(async(e,o,s)=>(await r.create()).legacyCloud.deleteObject(c(s.cwd),e,o,s.key)));l.command("mcp").command("serve").description("\u542F\u52A8 stdio MCP \u670D\u52A1").option("--legacy-cloud","\u989D\u5916\u5F00\u653E\u65E7\u4E91\u7EF4\u62A4\u5DE5\u5177").action(async e=>W({legacyCloud:e.legacyCloud===!0}));try{await l.parseAsync()}catch(e){process.stderr.write(JSON.stringify(v(e))+`
|
|
4
4
|
`),process.exitCode=1}
|
package/dist/dev-runner.js
CHANGED
|
@@ -1 +1,5 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as A,b as R}from"./shared-COXNB4AR.js";import{d as b,l as T,m as _,p as x}from"./shared-Z5NOVHRW.js";import{createServer as M}from"node:http";import{createServer as z}from"node:net";import{spawn as j}from"node:child_process";import{randomBytes as V,timingSafeEqual as F}from"node:crypto";import{join as U}from"node:path";import{mkdir as X,readFile as K,rm as Y}from"node:fs/promises";import{createServer as N,request as O}from"node:http";import{request as k}from"node:https";import{gunzipSync as B,brotliDecompressSync as W,inflateSync as G}from"node:zlib";var $="/__shaper_preview__/",C=8*1024*1024;function I(i){let l={...i};for(let p of String(i.connection??"").split(","))p.trim()&&delete l[p.trim().toLowerCase()];for(let p of["connection","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"])delete l[p];return l}function J(i,l){let p=/<head\b[^>]*>/i;return i=p.test(i)?i.replace(p,s=>`${s}${l.head}`):`${l.head}${i}`,/<\/body>/i.test(i)?i.replace(/<\/body>/i,()=>`${l.body}</body>`):`${i}${l.body}`}async function L(i,l,p){if(!/^[a-zA-Z0-9_-]{1,200}$/.test(p))throw new Error("Invalid preview app identity");let s=new URL(i);if(!["http:","https:"].includes(s.protocol)||!["127.0.0.1","localhost","[::1]"].includes(s.hostname)||s.username||s.password)throw new Error("Preview upstream must be loopback");let v=Object.fromEntries(Object.entries(l).map(([t,e])=>[t,e.replaceAll("__SHAPER_PREVIEW_APP_ID__",p)])),S=s.protocol==="https:"?k:O,y=new Set,m="";function E(t,e){return t===new URL(m).host&&(!e||e===m)}let g=N((t,e)=>{if(!t.url?.startsWith("/")||t.url.startsWith("//")||!E(t.headers.host,t.headers.origin)){e.writeHead(403).end();return}let u=new URL(t.url??"/",m).pathname;if(u.startsWith($)){if(e.setHeader("Cache-Control","no-store"),t.method!=="GET"&&t.method!=="HEAD"){e.writeHead(405).end();return}let o;if(u===`${$}index.html`){e.setHeader("Content-Type","text/html; charset=utf-8"),e.setHeader("Content-Security-Policy","frame-ancestors 'self'");let n=`${s.pathname}${s.search}`.replaceAll("&","&").replaceAll('"',""").replaceAll("<","<");o=v.shell.replaceAll("__SHAPER_PREVIEW_ENTRY__",()=>n)}else if(u===`${$}sdk.js`)e.setHeader("Content-Type","text/javascript; charset=utf-8"),o=v.sdk;else{e.writeHead(404).end();return}e.end(t.method==="HEAD"?void 0:o);return}let a=I(t.headers);if(a.host=s.host,a["accept-encoding"]="identity",t.headers.accept?.includes("text/html"))for(let o of["if-none-match","if-modified-since","range"])delete a[o];let d=S(new URL(`${s.origin}${t.url??"/"}`),{method:t.method,headers:a},o=>{let n=I(o.headers);if(o.on("error",()=>{e.headersSent?e.destroy():e.writeHead(502).end("\u9884\u89C8\u8D44\u6E90\u52A0\u8F7D\u5931\u8D25")}),typeof n.location=="string"&&n.location.startsWith(`${s.origin}/`)&&(n.location=`${m}${n.location.slice(s.origin.length)}`),!(String(n["content-type"]).includes("text/html")&&o.statusCode===200&&t.method!=="HEAD")){e.writeHead(o.statusCode??502,n),o.pipe(e);return}let r=[],f=0;o.on("data",c=>{f+=c.length,f>C?o.destroy(new Error("HTML exceeds preview limit")):r.push(c)}),o.on("end",()=>{try{let c=Buffer.concat(r),w={maxOutputLength:C};if(n["content-encoding"]==="gzip")c=B(c,w);else if(n["content-encoding"]==="br")c=W(c,w);else if(n["content-encoding"]==="deflate")c=G(c,w);else if(n["content-encoding"]&&n["content-encoding"]!=="identity")throw new Error("Unsupported HTML encoding");for(let D of["content-length","content-encoding","etag","last-modified"])delete n[D];n["cache-control"]="no-store",e.writeHead(200,n),e.end(J(c.toString("utf8"),v))}catch{e.writeHead(502).end("\u9884\u89C8\u9875\u9762\u52A0\u8F7D\u5931\u8D25")}})});d.on("error",()=>{e.headersSent||e.writeHead(502),e.end("\u672C\u5730\u5F00\u53D1\u670D\u52A1\u4E0D\u53EF\u7528")}),d.setTimeout(3e4,()=>d.destroy()),t.on("aborted",()=>d.destroy()),e.on("close",()=>d.destroy()),t.pipe(d)});g.on("connection",t=>{y.add(t),t.once("close",()=>y.delete(t))}),g.on("upgrade",(t,e,u)=>{if(!t.url?.startsWith("/")||t.url.startsWith("//")||!E(t.headers.host,t.headers.origin)){e.destroy();return}let a=S(new URL(`${s.origin}${t.url??"/"}`),{headers:{...t.headers,host:s.host,origin:s.origin}});a.on("upgrade",(d,o,n)=>{a.setTimeout(0),o.setTimeout(0),y.add(o),o.once("close",()=>y.delete(o)),e.write(`HTTP/1.1 101 Switching Protocols\r
|
|
2
|
+
${Object.entries(d.headers).map(([P,r])=>`${P}: ${r}`).join(`\r
|
|
3
|
+
`)}\r
|
|
4
|
+
\r
|
|
5
|
+
`),n.length&&e.write(n),u.length&&o.write(u),o.on("error",()=>e.destroy()),e.on("error",()=>o.destroy()),e.on("close",()=>o.destroy()),o.on("close",()=>e.destroy()),o.pipe(e),e.pipe(o)}),a.on("response",d=>{d.resume(),e.destroy()}),a.on("error",()=>e.destroy()),a.setTimeout(1e4,()=>a.destroy()),e.on("close",()=>a.destroy()),a.end()}),await new Promise((t,e)=>{g.once("error",e),g.listen(0,"127.0.0.1",t)});let H=g.address();if(!H||typeof H=="string")throw new Error("No preview port");m=`http://127.0.0.1:${H.port}`;let h=!1;return{url:`${m}${$}index.html`,close:async()=>{if(!h){h=!0;for(let t of y)t.destroy();await new Promise((t,e)=>g.close(u=>u?e(u):t()))}}}}async function Z(){let i=await T(process.argv[2]),l=process.argv[3],p=await _(i),s=await x(i,p),v=await new Promise((r,f)=>{let c=z();c.once("error",f),c.listen(0,"127.0.0.1",()=>{let w=c.address();if(!w||typeof w=="string")return f(new Error("No free port"));c.close(()=>r(w.port))})}),S=p.devUrl.replaceAll("{port}",String(v));if(new URL(S).hostname!=="127.0.0.1"&&new URL(S).hostname!=="localhost")throw new Error("devUrl must be loopback");let y=U(R(i),`runtime-${l}.json`),m=JSON.parse(await K(y,"utf8")),E=A(m.envelope),g=await L(S,E.content,m.appId);await Y(y,{force:!0}),m.source==="cache"&&console.warn("\u4E91\u7AEF\u6682\u4E0D\u53EF\u8FBE\uFF0C\u672C\u6B21\u9884\u89C8\u4F7F\u7528\u5DF2\u6821\u9A8C\u7684\u8FD0\u884C\u73AF\u5883\u7F13\u5B58\u3002"),console.log(`Preview runtime ${E.envelope.version.slice(0,12)}`);let H=V(32).toString("base64url"),h,t=!0,e=!1,u=!1,a=M(async(r,f)=>{let c=Buffer.from(r.headers.authorization??""),w=Buffer.from(`Bearer ${H}`);if(c.length!==w.length||!F(c,w)){f.writeHead(401).end();return}if(f.setHeader("Content-Type","application/json"),f.setHeader("Cache-Control","no-store"),r.method==="GET"&&r.url==="/status"){f.end(JSON.stringify({id:l,running:t,ready:e}));return}if(r.method==="POST"&&r.url==="/stop"){f.end(JSON.stringify({stopped:!0})),await d();return}f.writeHead(404).end()});async function d(){if(!u){if(u=!0,e=!1,t=!1,await g.close(),h?.pid)if(process.platform==="win32")j("taskkill",["/pid",String(h.pid),"/T","/F"],{stdio:"ignore"});else try{process.kill(-h.pid,"SIGTERM")}catch(r){if(r.code!=="ESRCH")throw r}setTimeout(()=>{if(h?.pid&&process.platform!=="win32")try{process.kill(-h.pid,"SIGKILL")}catch(r){r.code!=="ESRCH"&&console.error("Unable to terminate the development process group")}a.close(),process.exit(0)},3e3)}}await new Promise((r,f)=>{a.once("error",f),a.listen(0,"127.0.0.1",r)});let o=a.address();if(!o||typeof o=="string")throw new Error("No control port");let n=R(i);await X(n,{recursive:!0,mode:448}),await b(U(n,"session.json"),{id:l,root:i,controlUrl:`http://127.0.0.1:${o.port}`,token:H,url:g.url,runtimeVersion:E.envelope.version,startedAt:new Date().toISOString()}),h=j(p.devCommand.replaceAll("{port}",String(v)),{cwd:s,shell:!0,detached:process.platform!=="win32",stdio:["ignore","inherit","inherit"],env:{...process.env,SHAPER_DEV_PORT:String(v)}}),h.once("error",r=>{console.error(r.message),t=!1,d()}),h.once("exit",r=>{console.error(`Development process exited: ${r}`),t=!1,e=!1,d()}),setInterval(()=>{!t||e||fetch(S,{signal:AbortSignal.timeout(1e3),redirect:"error"}).then(r=>{e=r.ok}).catch(()=>{})},250).unref(),process.on("SIGTERM",()=>void d()),process.on("SIGINT",()=>void d())}Z().catch(i=>{console.error(i instanceof Error?i.message:"Development runner failed"),process.exit(1)});
|
package/dist/dev.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ export declare const sessionSchema: z.ZodObject<{
|
|
|
6
6
|
token: z.ZodString;
|
|
7
7
|
url: z.ZodString;
|
|
8
8
|
startedAt: z.ZodString;
|
|
9
|
+
runtimeVersion: z.ZodOptional<z.ZodString>;
|
|
9
10
|
}, z.core.$strict>;
|
|
10
11
|
export declare function sessionDirectory(root: string): string;
|
|
11
12
|
export declare function devStatus(path: string): Promise<{
|
package/dist/index.d.ts
CHANGED
|
@@ -7,3 +7,4 @@ export { ShaperError } from './config.js';
|
|
|
7
7
|
export { initProject, linkProject, buildProject, checkProject, deployWeb, publishWeb } from './workspace.js';
|
|
8
8
|
export { startDev, stopDev, devStatus, devLogs } from './dev.js';
|
|
9
9
|
export { initCloudService, buildCloudService } from './cloud-service.js';
|
|
10
|
+
export { previewWeb } from './web-preview.js';
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as
|
|
1
|
+
import{a as d,b as f,c as m,d as x,e as a,f as c,g as h}from"./shared-WK7DKUR5.js";import{c as s,d as v,e as S,f as b}from"./shared-COXNB4AR.js";import{a as e,j as o,o as r,q as t,r as p,t as u,u as i,v as l}from"./shared-Z5NOVHRW.js";export{d as AuthManager,a as CloudApi,c as LegacyCloudApi,h as Shaper,f as ShaperApi,e as ShaperError,x as buildCloudService,p as buildProject,l as checkProject,u as deployWeb,b as devLogs,s as devStatus,m as initCloudService,r as initProject,t as linkProject,o as previewWeb,i as publishWeb,v as startDev,S as stopDev};
|
package/dist/launcher.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{a as R,b as g,c as E,e as s,f as w}from"./shared-
|
|
2
|
+
import{a as R,b as g,c as E,e as s,f as w}from"./shared-3SHRGRIW.js";import{b as d,d as a,e as x,k as f}from"./shared-Z5NOVHRW.js";import{spawn as I}from"node:child_process";import{access as L}from"node:fs/promises";import{join as A}from"node:path";import{fileURLToPath as J,pathToFileURL as V}from"node:url";import{access as b,mkdir as j}from"node:fs/promises";import{join as y}from"node:path";import{execa as N}from"execa";import T from"proper-lockfile";var h=1440*60*1e3,C=3600*1e3,c=()=>y(d(),"updates.json");async function p(){try{return await x(c())}catch{return{}}}function k(t,e=Date.now()){return!t.nextCheckAt||t.nextCheckAt<=e||t.nextCheckAt>e+h}function v(t,e){if(!/^\d+\.\d+\.\d+$/.test(t)||!/^\d+\.\d+\.\d+$/.test(e))return!1;let i=t.split(".").map(Number),n=e.split(".").map(Number);for(let r=0;r<3;r++)if(i[r]!==n[r])return i[r]>n[r];return!1}async function D(t){let e=await s(),i=await p(),n=e.installed?{root:e.runtime,version:e.version}:i.active;if(!n||e.mode!=="pinned"&&e.mode!=="development"&&!v(n.version,w))return t;let r=y(n.root,"dist","cli.js");try{return await b(r),r}catch{return t}}var U={latest:async()=>{let t=await N("npm",["view","@hupu-tech/shaper@latest","version","--json","--fetch-retries=0","--fetch-timeout=10000"],{timeout:15e3,maxBuffer:65536}),e=JSON.parse(t.stdout);if(typeof e!="string"||!/^\d+\.\d+\.\d+$/.test(e))throw new Error("Invalid stable version");return e},prepare:R,verify:t=>g({command:process.execPath,args:[t.entry,"mcp","serve"]})};async function S(t=U){let e=y(d(),"updater");await j(e,{recursive:!0,mode:448});let i;try{i=await T.lock(e,{retries:0})}catch(n){if(n.code==="ELOCKED")return;throw n}try{let n=await p();if(!k(n))return;let r=await s();if(r.mode==="development"||r.mode==="pinned")return;await a(c(),{...n,nextCheckAt:Date.now()+C});try{let o=await t.latest(),u=w;for(let l of[r.version,n.active?.version])l&&v(l,u)&&(u=l);if(!v(o,u)){await a(c(),{...n,nextCheckAt:Date.now()+h,lastResult:"checked"});return}let m=await t.prepare(o);if(m.version!==o)throw new Error("Runtime version mismatch");await t.verify(m),r.installed&&await E(r.ides,{automatic:!0,expectedRuntime:r.runtime,prepared:m}),await a(c(),{active:m,nextCheckAt:Date.now()+h,lastResult:"updated"})}catch{await a(c(),{...n,nextCheckAt:Date.now()+C,lastResult:"failed"})}}finally{await i()}}var P=process.argv.slice(2);if(P[0]==="--shaper-update-worker")await S().catch(()=>{});else{let t=A(f,"dist","cli.js"),e=t,i=await L(A(f,"src","cli.ts")).then(()=>!0,()=>!1),n=["install","update","uninstall"].includes(P[0]??"");if(!i&&!n)try{e=await D(t);let r=await s();if(r.mode!=="development"&&r.mode!=="pinned"&&k(await p())){let o=I(process.execPath,[J(import.meta.url),"--shaper-update-worker"],{detached:!0,stdio:"ignore",windowsHide:!0});o.on("error",()=>{}),o.unref()}}catch{}await import(V(e).href)}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as c,b as p,d as $,e as P,
|
|
1
|
+
import{a as c,b as p,d as $,e as P,k as x}from"./shared-Z5NOVHRW.js";import{mkdir as E,readFile as u,writeFile as M,mkdtemp as ct,lstat as g,readlink as v,symlink as V,unlink as R,rm as k,rename as lt}from"node:fs/promises";import{basename as pt,dirname as D,join as s,resolve as dt}from"node:path";import{homedir as ft,tmpdir as mt}from"node:os";import{execa as tt}from"execa";import{realpath as it}from"node:fs/promises";import{dirname as ot,resolve as st,toNamespacedPath as Z}from"node:path";async function X(e,t){let n=st(ot(e),t);try{return Z(await it(n))}catch(a){if(a.code!=="ENOENT")throw a;return Z(n)}}async function f(e,t,n){if(t===void 0||n===void 0)return!1;let[a,i]=await Promise.all([X(e,t),X(e,n)]);return a===i}import{createHash as ut,randomUUID as et}from"node:crypto";import*as U from"@iarna/toml";import{parse as wt,modify as ht,applyEdits as gt}from"jsonc-parser";import Y from"proper-lockfile";import{Client as Et}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as Nt}from"@modelcontextprotocol/sdk/client/stdio.js";var yt=["codex","cursor","claude"],rt="# >>> Shaper managed MCP >>>",j="# <<< Shaper managed MCP <<<",L=()=>s(p(),"installation.json");async function O(e){return u(e,"utf8").catch(t=>{if(t.code==="ENOENT")return"";throw t})}function It(e){let t=[],n=wt(e||"{}",t,{allowTrailingComma:!0});if(t.length||!n||typeof n!="object"||Array.isArray(n))throw new c("INVALID_IDE_CONFIG","IDE \u914D\u7F6E\u65E0\u6CD5\u89E3\u6790\uFF0C\u8BF7\u5148\u4FEE\u590D\u914D\u7F6E\u6587\u4EF6\u3002");return n}function G(e,t){return JSON.stringify(e)===JSON.stringify(t)}function vt(e,t){return s(t,e==="codex"?".codex/config.toml":e==="cursor"?".cursor/mcp.json":".claude.json")}function at(e,t,n,a){if(e==="codex"){let m=U.parse(t).mcp_servers?.shaper,w=t.indexOf(rt),h=t.indexOf(j),N=w>=0&&h>w;if(m&&(!N||!a||!G(m,a)))throw new c("IDE_CONFIG_CONFLICT","Codex \u7684 shaper MCP \u914D\u7F6E\u4E0D\u5C5E\u4E8E\u672C\u6B21\u5B89\u88C5\uFF0C\u5DF2\u4FDD\u7559\u539F\u914D\u7F6E\u3002");let S=N?t.slice(0,w)+t.slice(h+j.length).replace(/^\r?\n/,""):t,T=n?`${S.trimEnd()}
|
|
2
2
|
|
|
3
3
|
${rt}
|
|
4
4
|
[mcp_servers.shaper]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as i,b as y,c as x,d as I,e as S,k as T,l as E,m as D,n as V}from"./shared-Z5NOVHRW.js";import{createHash as U}from"node:crypto";import{join as k}from"node:path";import{mkdir as $,readFile as z}from"node:fs/promises";import{z as s}from"zod";var v=8*1024*1024,J=10080*60*1e3,M=s.object({protocol:s.literal(1),version:s.string().regex(/^[a-f0-9]{64}$/),sha256:s.string().regex(/^[a-f0-9]{64}$/),payload:s.string().max(v)}).strict(),B=s.object({shell:s.string().min(1),head:s.string(),body:s.string(),sdk:s.string().min(1)}).strict();function P(o){let t=M.parse(o),e=U("sha256").update(t.payload).digest("hex");if(e!==t.sha256||e!==t.version)throw new i("PREVIEW_RUNTIME_INTEGRITY","\u9884\u89C8\u8FD0\u884C\u73AF\u5883\u6821\u9A8C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002");let r=B.parse(JSON.parse(t.payload));if(!r.shell.includes("__SHAPER_PREVIEW_ENTRY__"))throw new i("PREVIEW_RUNTIME_INVALID","\u9884\u89C8\u8FD0\u884C\u73AF\u5883\u4E0D\u517C\u5BB9\uFF0C\u8BF7\u66F4\u65B0 Shaper\u3002");return{envelope:t,content:r}}async function b(o){let t=x(o),e=k(y(),"preview-runtime",U("sha256").update(t).digest("hex")),r=k(e,"current.json"),n;try{n=await fetch(`${t}/api/v1/preview-runtime`,{redirect:"error",signal:AbortSignal.timeout(8e3)})}catch{}if(!n||n.status>=500)try{let a=await z(r);if(a.length>v)throw new Error("Oversized cache");let f=JSON.parse(a.toString()),w=Date.now()-Date.parse(f.fetchedAt);if(!Number.isFinite(w)||w<0||w>J)throw new Error("Expired cache");return{...P(f.envelope),source:"cache"}}catch{throw new i("PREVIEW_RUNTIME_UNAVAILABLE","\u65E0\u6CD5\u52A0\u8F7D\u9884\u89C8\u8FD0\u884C\u73AF\u5883\uFF0C\u4E14\u6CA1\u6709\u6709\u6548\u7F13\u5B58\u3002\u8BF7\u68C0\u67E5\u7F51\u7EDC\u540E\u91CD\u8BD5\uFF1B\u4E0D\u4F1A\u542F\u52A8\u65E0\u58F3\u9884\u89C8\u3002")}if(!n.ok)throw await n.body?.cancel(),new i("PREVIEW_RUNTIME_UNAVAILABLE","\u670D\u52A1\u6682\u4E0D\u652F\u6301\u6B64\u9884\u89C8\u8FD0\u884C\u73AF\u5883\uFF0C\u8BF7\u786E\u8BA4 Shaper \u670D\u52A1\u5DF2\u66F4\u65B0\u3002");let u=[],p=0;for await(let a of n.body){if(p+=a.length,p>v)throw new i("PREVIEW_RUNTIME_INVALID","\u9884\u89C8\u8FD0\u884C\u73AF\u5883\u8D85\u8FC7\u5927\u5C0F\u9650\u5236\u3002");u.push(a)}let l;try{l=P(JSON.parse(Buffer.concat(u).toString()))}catch{throw new i("PREVIEW_RUNTIME_INVALID","\u9884\u89C8\u8FD0\u884C\u73AF\u5883\u6821\u9A8C\u5931\u8D25\u6216\u7248\u672C\u4E0D\u517C\u5BB9\uFF0C\u8BF7\u66F4\u65B0 Shaper \u540E\u91CD\u8BD5\u3002")}return await $(e,{recursive:!0,mode:448}),await I(r,{fetchedAt:new Date().toISOString(),envelope:l.envelope}),{...l,source:"network"}}import{createHash as W,randomUUID as F}from"node:crypto";import{open as H,mkdir as C,readFile as Y,rm as j}from"node:fs/promises";import{join as d}from"node:path";import{spawn as G}from"node:child_process";import{z as c}from"zod";import X from"proper-lockfile";var q=c.object({id:c.string(),root:c.string(),controlUrl:c.string().url(),token:c.string(),url:c.string().url(),startedAt:c.string(),runtimeVersion:c.string().optional()}).strict();function A(o){return d(y(),"sessions",W("sha256").update(o).digest("hex"))}async function R(o){let t=q.parse(await S(d(A(o),"session.json")));if(t.root!==o||new URL(t.controlUrl).hostname!=="127.0.0.1")throw new i("INVALID_DEV_SESSION","\u672C\u5730\u5F00\u53D1\u4F1A\u8BDD\u8BB0\u5F55\u4E0D\u6B63\u786E\u3002");return t}async function _(o){let t=await E(o),e;try{e=await R(t)}catch(r){if(r.code==="ENOENT")return{running:!1,root:t};throw r}try{let r=await fetch(`${e.controlUrl}/status`,{headers:{Authorization:`Bearer ${e.token}`},redirect:"error",signal:AbortSignal.timeout(1500)}),n=await r.json();if(!r.ok||n.id!==e.id)throw new Error("Session mismatch");return{root:t,running:n.running,ready:n.ready,url:e.url,sessionId:e.id}}catch{return{root:t,running:!1,url:e.url,sessionId:e.id}}}async function dt(o){let t=await E(o);await D(t);let e=A(t);await C(e,{recursive:!0,mode:448});let r=await X.lock(e,{retries:0});try{let n=await _(t);if(n.running){if((await R(t)).runtimeVersion)return n;await L(t)}let u=await S(d(t,".shaper","project.json")),p=await V(t,u.server),l=await b(p.server),a=F(),f=d(e,`runtime-${a}.json`);await I(f,{envelope:l.envelope,appId:p.appId,source:l.source});let w=await H(d(e,"dev.log"),"w",384),m=G(process.execPath,[d(T,"dist","dev-runner.js"),t,a],{cwd:t,detached:!0,stdio:["ignore",w.fd,w.fd],windowsHide:!0});try{await new Promise((h,g)=>{m.once("spawn",h),m.once("error",g)})}catch(h){throw await j(f,{force:!0}),h}finally{await w.close()}m.unref();let N=!1;m.once("exit",()=>{N=!0});for(let h=0;h<120;h++){if(await new Promise(O=>setTimeout(O,250)),N)throw await j(f,{force:!0}),new i("DEV_START_FAILED","\u9884\u89C8\u542F\u52A8\u5931\u8D25\uFF0C\u8BF7\u67E5\u770B shaper logs\u3002");let g=await _(t);if(g.running&&g.ready)return g}throw await L(t),new i("DEV_NOT_READY","\u5F00\u53D1\u670D\u52A1\u672A\u5728 30 \u79D2\u5185\u5C31\u7EEA\uFF0C\u8BF7\u67E5\u770B shaper logs\u3002\u5DF2\u505C\u6B62\u672C\u6B21\u4F1A\u8BDD\u3002")}finally{await r()}}async function L(o){let t=await E(o);if(!(await _(t)).running)return{stopped:!0,alreadyStopped:!0};let r=await R(t);if(!(await fetch(`${r.controlUrl}/stop`,{method:"POST",headers:{Authorization:`Bearer ${r.token}`},redirect:"error",signal:AbortSignal.timeout(1e4)})).ok)throw new i("DEV_STOP_FAILED","\u5F00\u53D1\u4F1A\u8BDD\u672A\u80FD\u505C\u6B62\u3002");for(let u=0;u<30;u++){await new Promise(p=>setTimeout(p,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 i("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 lt(o){let t=await E(o);try{let e=await Y(d(A(t),"dev.log"),"utf8");return{root:t,log:e.slice(-16e3)}}catch(e){if(e.code==="ENOENT")return{root:t,log:"",message:"\u5C1A\u65E0\u672C\u5730\u8FD0\u884C\u65E5\u5FD7"};throw e}}export{P as a,A as b,_ as c,dt as d,L as e,lt as f};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import{c as ue}from"./shared-COXNB4AR.js";import{a,b as Y,c as _,d as ie,f as ae,h as k,i as ne,k as O,l as S,m as oe,n as A,s as ce}from"./shared-Z5NOVHRW.js";import*as w from"oauth4webapi";import{createHash as Le}from"node:crypto";import{chmod as he,lstat as pe,mkdir as De,readFile as $e,rm as Ue,writeFile as Oe}from"node:fs/promises";import{join as Z}from"node:path";import{execFile as xe}from"node:child_process";import{promisify as Pe}from"node:util";import je from"proper-lockfile";import{z as T}from"zod";var we=T.object({accessToken:T.string().min(1),refreshToken:T.string().min(1).optional(),expiresAt:T.number(),scope:T.string()}).strict(),Fe=T.object({schemaVersion:T.literal(1),server:T.string(),tokens:we}).strict(),le=Pe(xe),x;async function de(o){await De(o,{recursive:!0,mode:448});let e=await pe(o);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(!x){let{stdout:t}=await le("whoami.exe",["/user","/fo","csv","/nh"],{windowsHide:!0});if(x=t.match(/S-1-\d+(?:-\d+)+/)?.[0],!x)throw new a("AUTH_DIRECTORY_UNAVAILABLE","\u65E0\u6CD5\u786E\u5B9A\u5F53\u524D Windows \u7528\u6237\u3002")}await le("icacls.exe",[o,"/inheritance:r","/grant:r",`*${x}:(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 he(o,448)}}function fe(o){return Le("sha256").update(_(o)).digest("hex")}async function me(o){await de(Y());let e=Z(Y(),o);return await de(e),e}var P=class{async path(e){return Z(await me("credentials"),`${fe(e)}.json`)}async read(e){let t=await this.path(e);try{let r=await pe(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 he(t,384)}let s=Fe.safeParse(JSON.parse(await $e(t,"utf8")));if(!s.success||s.data.server!==_(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:_(e),tokens:we.parse(t)})}async remove(e){await Ue(await this.path(e),{force:!0})}};async function ge(o,e,t){let r=Z(await me("locks"),`${fe(o)}-${e}`);await Oe(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 j(o,e){let t=await ge(o,"tokens",30);try{return await e()}finally{await t()}}async function Q(o){return ge(o,"login",0)}import{createServer as qe}from"node:http";import{randomUUID as He}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=He();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=qe((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 c=i.address();if(!c||typeof c=="string")throw new a("CALLBACK_UNAVAILABLE","\u65E0\u6CD5\u542F\u52A8\u672C\u5730\u6388\u6743\u56DE\u8C03\u3002");s=`http://127.0.0.1:${c.port}/oauth/callback`;let u=new URL(t.authorization_endpoint),n={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(n))u.searchParams.set(l,p);if(this.timer=setTimeout(()=>{this.close()},3e5),this.timer.unref(),e.openBrowser!==!1)try{await ze(u.href,{wait:!1})}catch{}return{flowId:this.id,status:"pending",authorizationUrl:u.href,expiresIn:300}}};var X="openid offline_access projects:read projects:write web:deploy web:publish",Ve=`${X} cloud:read cloud:write`,Be=(...o)=>[...new Set(o.flatMap(e=>e.split(" ")).filter(Boolean))].join(" "),q=class{constructor(e,t=new P){this.credentials=t;this.server=_(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 j(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 c=e.cloud?Ve:X,u=i&&c.split(" ").filter(h=>!["openid","offline_access"].includes(h)).every(h=>i.grant.scopes.includes(h));if(i&&u&&!e.reauthorize&&(!e.appId||i.grant.allApps||i.grant.appIds.includes(e.appId)))return await r(),{status:"complete",authenticated:!0,reused:!0,...i};let n=w.generateRandomCodeVerifier(),l=await w.calculatePKCECodeChallenge(n),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:n,challenge:l,scope:Be(c,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=>j(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 j(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 H=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 u=new FormData;u.set("file",new Blob([new Uint8Array(t.file)],{type:"application/zip"}),"shaper.zip"),s=u}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 c;try{c=await i.json()}catch{throw new a("INVALID_API_RESPONSE",`\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u89E3\u6790\u7684\u54CD\u5E94\uFF08HTTP ${i.status}\uFF09\u3002\u5199\u64CD\u4F5C\u7ED3\u679C\u5C1A\u672A\u786E\u8BA4\uFF0C\u8BF7\u67E5\u8BE2\u539F\u64CD\u4F5C\uFF0C\u4E0D\u8981\u91CD\u590D\u63D0\u4EA4\u3002`)}if(!i.ok)throw new a(c.code??"API_ERROR",c.message??`\u8BF7\u6C42\u5931\u8D25\uFF1A${i.status}`);return c}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 Me}from"node:crypto";import{builtinModules as Je}from"node:module";import{readFile as C,writeFile as ee,mkdir as ve,lstat as J,realpath as z}from"node:fs/promises";import{resolve as b,join as m,relative as D,sep as B,dirname as ye,isAbsolute as Ke}from"node:path";import{build as We}from"esbuild";import{z as d}from"zod";var Se=d.object({name:d.literal("@hupu/cloud-server"),version:d.string().regex(/^\d+\.\d+\.\d+$/)}).strict(),Ee=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(),Ge=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(Ee).max(100),serverSdk:Se}).strict().superRefine((o,e)=>{let t=new Set,r=new Map;for(let s of o.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)}}),Ye=Se.extend({archive:d.string().regex(/^[a-z0-9.-]+\.tgz$/),sha256:d.string().regex(/^[a-f0-9]{64}$/),templateHashes:d.record(d.string(),d.string())}),M=o=>Me("sha256").update(o).digest("hex"),Te=/(?:^|\/)(?:\.env(?:\.[^/]*)?|credentials\.json)$|\.(?:pem|key)$/i;function N(o,e){let t=D(o,e);if(Ke(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 L(o,e,t){let r=await z(e);if(N(o,r),Te.test(r))throw new a("SECRET_FILE","\u4E0D\u80FD\u5C06\u51ED\u8BC1\u6587\u4EF6\u6253\u5165\u4E91\u51FD\u6570\u3002");let s=await J(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 C(r,"utf8")}async function V(o,e){N(o,e);let t=o;for(let r of D(o,e).split(B).filter(Boolean)){t=m(t,r),await ve(t).catch(i=>{if(i.code!=="EEXIST")throw i});let s=await J(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 Ie(){let o=m(O,"vendor/cloud-server"),e=Ye.parse(JSON.parse(await C(m(o,"release.json"),"utf8"))),t=await C(m(o,e.archive));if(M(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 jt(o,e="cloud/functions/api"){let t=await S(o);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 Ie(),i=new Map;for(let[n,l]of Object.entries(r.templateHashes)){if(!/^[a-zA-Z0-9_./-]+$/.test(n)||n.split("/").includes(".."))throw new a("SDK_ASSET_MISMATCH","\u6A21\u677F\u8DEF\u5F84\u4E0D\u6B63\u786E\u3002");let p=await C(m(O,"templates/cloud-service",n),"utf8");if(M(p)!==l)throw new a("SDK_ASSET_MISMATCH","\u6807\u51C6\u6A21\u677F\u4E0E SDK \u53D1\u884C\u8BB0\u5F55\u4E0D\u4E00\u81F4\u3002");i.set(n,p)}let c=e==="cloud/functions/api";if(c){let n=JSON.parse(i.get("cloud.json")),{routes:l,...p}=n;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=b(t,e,h);N(t,f);try{throw await J(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 u=b(t,e);await V(t,ye(u)),await ve(u).catch(n=>{throw n.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"):n}),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",...c?{gateway:"../../gateway/routes.json"}:{}}},null,2)+`
|
|
4
|
+
`),i.set(".gitignore",`node_modules/
|
|
5
|
+
.env
|
|
6
|
+
.env.*
|
|
7
|
+
!vendor/*.tgz
|
|
8
|
+
`),i.set("README.md",c?`# \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 create\uFF0C\u7531\u7528\u6237\u5728\u7F51\u9875\u786E\u8BA4\u5F00\u901A\uFF0C\u901A\u8FC7 shaper cloud status \u786E\u8BA4\u8D44\u6E90 ready\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 C(m(O,"templates/cloud-service/README.md"),"utf8"));for(let[n,l]of i)await V(t,ye(m(u,n))),await ee(m(u,n),l,{flag:"wx"});return await V(t,m(u,"vendor")),await ee(m(u,"vendor",r.archive),s,{flag:"wx"}),{directory:e,files:[...i.keys(),`vendor/${r.archive}`],serverSdk:{name:r.name,version:r.version},next:c?"\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 Re(o,e){let t=await S(o);if(!e)try{await J(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 z(b(t,e));N(t,r);let s=JSON.parse(await L(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),c=JSON.parse(await L(t,b(r,i.manifest),65536)),u=c.routes;if(i.gateway){if(c.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");u=d.object({version:d.literal(1),routes:d.array(Ee).max(100)}).strict().parse(JSON.parse(await L(t,b(r,i.gateway),65536))).routes}let n=Ge.parse({...c,routes:u}),{release:l}=await Ie();if(n.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 z(m(r,"vendor",l.archive));if(N(t,g),M(await C(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=b(r,i.entry);await L(t,h,8*1024*1024);let f=await We({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 R=await z(E.path);if(Te.test(R))throw new a("SECRET_FILE","\u6784\u5EFA\u56FE\u5305\u542B\u51ED\u8BC1\u6587\u4EF6\u3002");R.includes(`${B}node_modules${B}`)||N(t,R)}),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,Ce=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&&!Ce.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(n,null,2)+`
|
|
16
|
+
`,re=M(te+`
|
|
17
|
+
`+v),U=m(t,".shaper/cloud-build",re);await V(t,U);for(let[g,E]of[["cloud.json",te],["app.cjs",v]]){let R=m(U,g);try{await ee(R,E,{flag:"wx"})}catch(se){if(se.code!=="EEXIST"||await L(t,R,8*1024*1024)!==E)throw se}}return{directory:D(t,r),manifestFile:D(t,m(U,"cloud.json")),bundleFile:D(t,m(U,"app.cjs")),sha256:re,bytes:Buffer.byteLength(v),serverSdk:n.serverSdk,routes:n.routes}}import Ze from"open";import{createHash as _e}from"node:crypto";import{resolve as Qe,relative as Xe,sep as et}from"node:path";import{readFile as tt,realpath as rt,stat as st}from"node:fs/promises";var K=class{constructor(e,t=r=>Ze(r,{wait:!1})){this.api=e;this.openBrowser=t}async status(e){return this.api.request(`${(await this.target(e)).url}/status`)}async create(e){let t=await this.api.request(`${(await this.target(e)).url}/create`,{method:"POST",body:{}});if(t.status==="awaiting_confirmation"){let r=new URL(t.confirmationUrl||"",this.api.auth.server);if(r.origin!==new URL(this.api.auth.server).origin||r.pathname!=="/developer/confirm"||!t.confirmationId||r.searchParams.get("requestId")!==t.confirmationId||r.username||r.password)throw new a("INVALID_CONFIRMATION_URL","\u670D\u52A1\u8FD4\u56DE\u7684\u786E\u8BA4\u5730\u5740\u4E0D\u6B63\u786E\u3002");try{await this.openBrowser(r.href)}catch{}return{...t,message:"\u8BF7\u5728\u6D4F\u89C8\u5668\u786E\u8BA4\u5F00\u901A\u4E91\u670D\u52A1\uFF1B\u786E\u8BA4\u540E\u4F7F\u7528 cloud status \u67E5\u770B\u7ED3\u679C\u3002"}}return t}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 Re(e,t.directory),c=await this.upload(e,i.manifestFile,i.bundleFile,r);return{artifact:i,...c}}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:c}=await this.target(e),u=await this.source(i,r,6e4),n=s??_e("sha256").update(`${t}:${u}`).digest("hex");return this.api.request(`${c}/migrations`,{method:"POST",body:{version:t,dialect:"postgresql",sql:u,idempotencyKey:n}})}async source(e,t,r){let s=await rt(Qe(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 st(s)).size>r)throw new a("ARTIFACT_TOO_LARGE","\u6587\u4EF6\u8D85\u8FC7\u5141\u8BB8\u5927\u5C0F\u3002");return tt(s,"utf8")}async upload(e,t,r,s){let{root:i,url:c}=await this.target(e),u=JSON.parse(await this.source(i,t,65536));if(u.serverSdk!=null){let[p,h]=await Promise.all([this.status(e),this.api.request(`${c}/capabilities`)]),f=h.serverSdk;if(!f||f.name!==u.serverSdk.name||!f.versions.includes(u.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 n=await this.source(i,r,8*1024*1024),l=s??_e("sha256").update(JSON.stringify({manifest:u,bundle:n})).digest("hex");return this.api.request(`${c}/deployments`,{method:"POST",body:{manifest:u,bundle:n,idempotencyKey:l}})}async target(e){let t=await S(e),r=await A(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=Xe(e,t);if(r===".."||r.startsWith(`..${et}`))throw new a("INVALID_FILE_PATH","\u5236\u54C1\u6587\u4EF6\u5FC5\u987B\u4F4D\u4E8E\u5DE5\u7A0B\u76EE\u5F55\u5185\u3002")}};import{createHash as it,randomUUID as $}from"node:crypto";import{resolve as W,relative as ke,sep as Ae,dirname as at,basename as nt}from"node:path";import{readFile as ot,writeFile as ct,realpath as be,stat as ut}from"node:fs/promises";var G=class{constructor(e){this.api=e}async base(e,t){let r=await S(e),s=await A(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=it("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:c,url:u}=await this.base(e,t),n=await S(W(c,s)),l=ke(c,n);if(l===".."||l.startsWith(`..${Ae}`))throw new a("INVALID_FUNCTION_PATH","\u51FD\u6570\u4EE3\u7801\u5FC5\u987B\u4F4D\u4E8E\u5DE5\u7A0B\u76EE\u5F55\u5185\u3002");let p=await ce(n,{files:1e3,bytes:30*1024*1024});return this.api.request(`${u}/functions/${encodeURIComponent(r)}/deploy`,{method:"POST",file:p.content,key:i??$()})}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??$()})}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??$()})}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:c,url:u}=await this.base(e,t),n=await be(W(c,s));if(this.checkContained(c,n),/(?:^|\/)(?:\.env(?:\..*)?|credentials\.json)$|\.(?:pem|key)$/i.test(n))throw new a("SECRET_FILE","\u51ED\u8BC1\u6587\u4EF6\u4E0D\u80FD\u4F5C\u4E3A\u4E1A\u52A1\u5BF9\u8C61\u4E0A\u4F20\u3002");if((await ut(n)).size>10*1024*1024)throw new a("OBJECT_TOO_LARGE","\u5BF9\u8C61\u4E0D\u80FD\u8D85\u8FC7 10 MiB\u3002");return this.api.request(`${u}/storage/object?${new URLSearchParams({key:r})}`,{method:"POST",file:await ot(n),key:i??$()})}async getObject(e,t,r,s){let{root:i,url:c}=await this.base(e,t),u=W(await be(at(W(i,s))),nt(s));this.checkContained(i,u);let n=await this.api.request(`${c}/storage/object?${new URLSearchParams({key:r})}`);return await ct(u,Buffer.from(n.base64,"base64"),{flag:"wx",mode:384}),{key:r,bytes:n.bytes,path:u}}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??$()})}checkContained(e,t){let r=ke(e,t);if(r===".."||r.startsWith(`..${Ae}`))throw new a("INVALID_FILE_PATH","\u5BF9\u8C61\u6587\u4EF6\u5FC5\u987B\u4F4D\u4E8E\u5DE5\u7A0B\u76EE\u5F55\u5185\u3002")}};var Ne=class o{constructor(e){this.auth=e;this.api=new H(e),this.cloud=new K(this.api),this.legacyCloud=new G(this.api)}api;cloud;legacyCloud;static async create(e){return new o(new q(e??await ae()))}async status(e){let t;try{t={authenticated:!0,...await this.api.me()}}catch(s){t={authenticated:!1,error:k(s)}}let r;if(e){let s=await S(e),i;try{let n=await A(s,this.auth.server);try{let l=await this.api.project(n.appId);i={...n,authorized:!0,name:l.name,publishedVersionId:l.publishedVersionId,versions:l.versions}}catch(l){i={...n,authorized:!1,error:k(l)}}}catch(n){i={linked:!1,error:k(n)}}let c;try{c=await oe(s)}catch(n){c={error:k(n)}}let u;try{u=await ne(this.api,s)}catch(n){u={error:k(n)}}r={root:s,binding:i,config:c,dev:await ue(s),web:u}}return{server:this.auth.server,identity:t,...r?{project:r}:{}}}};export{q as a,H as b,jt as c,Re as d,K as e,G as f,Ne as g};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import{homedir as ce}from"node:os";import{join as V,resolve as pe,dirname as de}from"node:path";import{mkdir as ue,readFile as le,rename as we,writeFile as fe,lstat as he,rm as me}from"node:fs/promises";import{randomUUID as ge}from"node:crypto";import{z as L}from"zod";var a=class extends Error{constructor(t,n,i){super(n);this.code=t;this.details=i}},Ee=L.object({schemaVersion:L.literal(1),server:L.string().url()}).strict();function D(){return pe(process.env.SHAPER_CONFIG_HOME??V(ce(),".config","shaper"))}function J(e){let r=new URL(e);if(r.username||r.password||r.search||r.hash||r.pathname!=="/"||r.protocol!=="https:"&&!(r.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(r.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 r.origin}async function y(e,r){await ue(de(e),{recursive:!0,mode:448});try{if((await he(e)).isSymbolicLink())throw new a("UNSAFE_FILE",`\u914D\u7F6E\u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5\uFF1A${e}`)}catch(n){if(n.code!=="ENOENT")throw n}let t=`${e}.${ge()}.tmp`;try{await fe(t,JSON.stringify(r,null,2)+`
|
|
2
|
+
`,{mode:384,flag:"wx"}),await we(t,e)}finally{await me(t,{force:!0})}}async function v(e){return JSON.parse(await le(e,"utf8"))}async function qe(){if(process.env.SHAPER_SERVER)return J(process.env.SHAPER_SERVER);try{return J(Ee.parse(await v(V(D(),"config.json"))).server)}catch(e){if(e.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 He(e){await y(V(D(),"config.json"),{schemaVersion:1,server:J(e)})}function B(e){return{code:e instanceof a?e.code:"OPERATION_FAILED",message:e instanceof Error?e.message:"\u64CD\u4F5C\u672A\u5B8C\u6210",...e instanceof a&&e.details!==void 0?{details:e.details}:{}}}import{createHash as oe,randomUUID as Oe}from"node:crypto";import{mkdir as Te,writeFile as Ce,rename as Ue,rm as ke}from"node:fs/promises";import{join as x}from"node:path";import{z as l}from"zod";import{realpath as G,mkdir as Z,readdir as F,readFile as S,writeFile as _,lstat as W,cp as Ie,appendFile as ve}from"node:fs/promises";import{resolve as b,join as E,relative as q,sep as H,dirname as ye,basename as Se,isAbsolute as X}from"node:path";import{fileURLToPath as Ne}from"node:url";import{randomUUID as ee,createHash as te}from"node:crypto";import{spawn as Re}from"node:child_process";import je from"adm-zip";import be from"open";import{z as h}from"zod";import re from"proper-lockfile";var xe=b(ye(Ne(import.meta.url)),".."),Ae=h.object({schemaVersion:h.literal(1),devCommand:h.string().min(1).max(500),buildCommand:h.string().min(1).max(500),outputDir:h.string().min(1),workingDirectory:h.string().min(1).default("."),devUrl:h.string().default("http://127.0.0.1:{port}")}).passthrough(),De=h.object({schemaVersion:h.literal(1),appId:h.string().min(1).max(200),server:h.string().url()}).strict();async function N(e){if(!e||!X(e))throw new a("WORKSPACE_REQUIRED","\u8BF7\u6307\u5B9A\u5DE5\u7A0B\u7684\u7EDD\u5BF9\u8DEF\u5F84\u3002");return G(b(e))}async function P(e,r){return S(E(e,r),"utf8").catch(t=>{if(t.code!=="ENOENT")throw t})}async function ne(e){let r=new Set;for(let t of[".shaper/project.json","shaper.config.json","shaper.project.json",".shaper/config.json","activity.json"]){let n=await P(e,t);if(n===void 0)continue;let i=JSON.parse(n);for(let o of[i?.appId,i?.applicationId,t==="activity.json"?i?.activityId:void 0])typeof o=="string"&&o&&r.add(o)}return r}function ie(e,r){if(e.size>1||r&&[...e].some(t=>t!==r))throw new a("APP_ID_CONFLICT","\u539F\u9879\u76EE\u5E94\u7528 ID \u4E0E\u76EE\u6807\u4E0D\u4E00\u81F4\uFF1B\u5DF2\u505C\u6B62\uFF0C\u4E0D\u4F1A\u521B\u5EFA\u6216\u5207\u6362\u5E94\u7528\u3002")}async function O(e,r){let t=await P(e,"activity.json"),n=t===void 0?void 0:JSON.parse(t)?.activityId,i=await P(e,"AGENTS.md"),o=await P(e,"skills/act-cloudbase/SKILL.md");if(!(n===void 0&&!i?.includes("<!-- COLORBOX:START -->")&&o===void 0))throw ie(await ne(e),r),new a("LEGACY_PROJECT_UPGRADE_REQUIRED","\u8FD9\u662F\u65E7\u7248\u9879\u76EE\uFF0C\u8BF7\u7EE7\u7EED\u4F7F\u7528\u539F\u6709\u6280\u80FD\u548C\u5F00\u53D1\u65B9\u5F0F\u3002\u65B0\u7248\u5DE5\u5177\u672A\u4FEE\u6539\u6B64\u9879\u76EE\uFF0C\u5F53\u524D\u6682\u4E0D\u652F\u6301\u81EA\u52A8\u5347\u7EA7\u3002")}async function T(e){let r=E(e,".shaper");if(await Z(r,{recursive:!0,mode:448}),(await W(r)).isSymbolicLink())throw new a("UNSAFE_WORKSPACE",".shaper \u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5\u3002");return r}async function C(e){return await O(e),Ae.parse(await v(E(e,"shaper.config.json")))}async function R(e,r){await O(e);let t=De.parse(await v(E(e,".shaper","project.json")));if(t.server!==r)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 t}async function ae(e,r,t){let n=await T(e);await y(E(n,"project.json"),{schemaVersion:1,appId:r,server:t})}async function at(e,r,t={}){if(!r||!X(r))throw new a("WORKSPACE_REQUIRED","\u8BF7\u6307\u5B9A\u5DE5\u7A0B\u7684\u7EDD\u5BF9\u8DEF\u5F84\u3002");await Z(r,{recursive:!0});let n=await N(r);await O(n,t.appId);let i=await T(n),o=await re.lock(i,{retries:0});try{let s;try{s=await R(n,e.auth.server)}catch(f){if(f.code!=="ENOENT")throw f}if(s&&t.appId&&t.appId!==s.appId)throw new a("ALREADY_LINKED",`\u5F53\u524D\u76EE\u5F55\u5C5E\u4E8E ${s.appId}\uFF0C\u4E0E\u63D0\u793A\u8BCD\u4E2D\u7684 ${t.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 u=(await F(n)).filter(f=>![".git",".shaper",".shaper.lock",".DS_Store"].includes(f));if(!s&&u.length&&t.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(t.template&&!["h5","react","phaser"].includes(t.template))throw new a("INVALID_TEMPLATE","\u652F\u6301 h5\u3001react\u3001phaser \u6A21\u677F\u3002");let d=await ne(n),c=s?.appId??t.appId??[...d][0];ie(d,c);let p=E(i,"init.json"),w=s?void 0:await v(p).catch(f=>{if(f.code!=="ENOENT")throw f});if(!s&&w&&(!w.appId||w.server!==e.auth.server||c&&c!==w.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(!c&&!w&&u.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 m=c??w?.appId??`app_${ee().replaceAll("-","").slice(0,10)}`;!w&&!s&&(w={appId:m,server:e.auth.server},await y(p,w));let g;try{g=await e.project(m)}catch(f){if(!(f instanceof a)||!["AUTH_REQUIRED","INVALID_TOKEN","PROJECT_NOT_AUTHORIZED","INSUFFICIENT_SCOPE","NOT_FOUND"].includes(f.code))throw f;let I=await e.auth.start({appId:m,...t.name?{applicationName:t.name}:{},initialize:!s&&d.size===0,reauthorize:!0});if(I.status==="pending"){if(!t.waitForAuthorization)return{root:n,appId:m,...I,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${I.authorizationUrl}
|
|
3
|
+
`),await e.auth.wait(I.flowId)}g=await e.project(m)}let M=g.name;if(s)return t.installDependencies!==!1&&await S(E(i,"install-pending"),"utf8").catch(I=>{if(I.code==="ENOENT")return"";throw I})&&(await z("npm ci",n),await _(E(i,"install-pending"),"")),await $(n),{root:n,...s,alreadyInitialized:!0,...await Q(n)};if(u.length===0){let f=t.template??"h5";if(!["h5","react","phaser"].includes(f))throw new a("INVALID_TEMPLATE","\u652F\u6301 h5\u3001react\u3001phaser \u6A21\u677F\u3002");let I=E(xe,"templates",f);for(let j of(await F(I)).filter(A=>!["node_modules","dist"].includes(A)))await Ie(E(I,j),E(n,j),{recursive:!0,force:!1,errorOnExist:!0});t.installDependencies!==!1&&await _(E(i,"install-pending"),`npm ci
|
|
4
|
+
`)}await $(n),await ae(n,m,e.auth.server);let k=await S(E(i,"install-pending"),"utf8").catch(f=>{if(f.code==="ENOENT")return"";throw f});return t.installDependencies!==!1&&k&&(await z("npm ci",n),await _(E(i,"install-pending"),"")),{root:n,name:M,appId:m,...await Q(n)}}finally{await o()}}async function Q(e){try{let r=await C(e);return await K(e,r),{status:"initialized"}}catch(r){if(r.code!=="ENOENT"&&!(r instanceof h.ZodError))throw r;return{status:"configuration_required",next:"\u5E94\u7528\u5DF2\u5173\u8054\u3002\u8BF7\u68C0\u67E5\u5B9E\u9645\u6E90\u7801\u5165\u53E3\u3001\u5305\u7BA1\u7406\u5668\u548C\u6784\u5EFA\u914D\u7F6E\uFF0C\u4FDD\u7559\u539F\u5DE5\u7A0B\uFF0C\u8865\u5145 shaper.config.json \u7684 workingDirectory\u3001devCommand\u3001devUrl\u3001buildCommand\u3001outputDir\uFF1BoutputDir \u76F8\u5BF9\u9879\u76EE\u6839\u76EE\u5F55\u3002\u914D\u7F6E\u540E\u518D\u6B21 init \u5E76\u9A8C\u8BC1\u9884\u89C8\u548C\u6784\u5EFA\u3002"}}}async function K(e,r){let t=await U(e,r.workingDirectory);if(!(await W(t)).isDirectory())throw new a("INVALID_WORKING_DIRECTORY","workingDirectory \u5FC5\u987B\u662F\u5DE5\u7A0B\u5185\u90E8\u76EE\u5F55\u3002");return t}async function ot(e,r,t){let n=await N(r);await O(n,t);let i=await re.lock(await T(n),{retries:0});try{let o=await e.project(t);return await ae(n,o.appId,e.auth.server),await $(n),{root:n,appId:o.appId,name:o.name}}finally{await i()}}async function $(e){let r=E(e,".gitignore"),t=await S(r,"utf8").catch(p=>{if(p.code==="ENOENT")return"";throw p}),i=["/.shaper/","/.shaper.lock/","/node_modules/","/dist/","/credentials.json",".env",".env.*","!.env.example"].filter(p=>!t.split(`
|
|
5
|
+
`).includes(p));i.length&&await ve(r,`
|
|
6
|
+
# Shaper local state and generated files
|
|
7
|
+
${i.join(`
|
|
8
|
+
`)}
|
|
9
|
+
`);let o=E(e,"AGENTS.md"),s=await S(o,"utf8").catch(p=>{if(p.code==="ENOENT")return"";throw p}),u="<!-- shaper:project -->",d=`
|
|
10
|
+
${u}
|
|
11
|
+
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.
|
|
12
|
+
<!-- /shaper:project -->
|
|
13
|
+
`,c=s.includes(u)?s.replace(/<!-- shaper:project -->[\s\S]*?<!-- \/shaper:project -->\n?/,d.trimStart()):s+d;c!==s&&await _(o,c)}async function z(e,r){await new Promise((t,n)=>{let i=Re(e,{cwd:r,shell:!0,stdio:["ignore","pipe","pipe"]});i.stdout.on("data",o=>process.stderr.write(o)),i.stderr.on("data",o=>process.stderr.write(o)),i.once("error",n),i.once("exit",o=>o===0?t():n(new a("COMMAND_FAILED",`\u5DE5\u7A0B\u547D\u4EE4\u9000\u51FA\u7801\uFF1A${o??"signal"}`)))})}async function _e(e){let r=await N(e),t=await C(r);await z(t.buildCommand,await K(r,t));let n=await U(r,t.outputDir);return await S(E(n,"index.html")),{root:r,output:n}}async function U(e,r){let t=await G(b(e,r)),n=q(e,t);if(n===".."||n.startsWith(`..${H}`)||b(e,n)!==t)throw new a("INVALID_OUTPUT","\u8F93\u51FA\u76EE\u5F55\u5FC5\u987B\u4F4D\u4E8E\u5DE5\u7A0B\u5185\u90E8\u3002");return t}async function Pe(e,r={files:300,bytes:200*1024*1024}){let t=await G(e),n=new je,i=0,o=0;async function s(u){for(let d of(await F(u,{withFileTypes:!0})).sort((c,p)=>c.name.localeCompare(p.name))){if(/^(\.git|\.shaper|node_modules|\.DS_Store)$/.test(d.name))continue;if(/^(\.env(?:\..*)?|credentials\.json|.*\.(pem|key))$/i.test(d.name))throw new a("SECRET_FILE_IN_PACKAGE",`\u8F93\u51FA\u76EE\u5F55\u5305\u542B\u654F\u611F\u914D\u7F6E\u6587\u4EF6\uFF1A${d.name}`);let c=E(u,d.name);if(d.isSymbolicLink())throw new a("SYMLINK_IN_PACKAGE",`\u4EA4\u4ED8\u5185\u5BB9\u4E2D\u4E0D\u5141\u8BB8\u7B26\u53F7\u94FE\u63A5\uFF1A${d.name}`);if(d.isDirectory()){await s(c);continue}if(!d.isFile())throw new a("INVALID_PACKAGE_FILE","\u4EA4\u4ED8\u76EE\u5F55\u5305\u542B\u975E\u5E38\u89C4\u6587\u4EF6\u3002");let p=await W(c);if(i+=p.size,o++,o>r.files||i>r.bytes)throw new a("PACKAGE_TOO_LARGE","\u4EA4\u4ED8\u5305\u8D85\u8FC7\u6587\u4EF6\u6570\u6216\u5927\u5C0F\u9650\u5236\u3002");n.addFile(q(t,c).split(H).join("/"),await S(c))}}await s(t);for(let u of n.getEntries())u.header.time=new Date(2e3,0,1);return{content:n.toBuffer(),files:o,bytes:i}}async function st(e,r,t={}){let n=await N(r),i=await R(n,e.auth.server),o=t.build===!1?await U(n,(await C(n)).outputDir):(await _e(n)).output,s=await Pe(o),u=te("sha256").update(s.content).digest("hex"),d=await T(n),c=E(d,"web-deploy.json"),p=ee();try{let g=h.object({sha256:h.string(),key:h.string(),appId:h.string(),server:h.string()}).passthrough().parse(await v(c));g.sha256===u&&g.appId===i.appId&&g.server===e.auth.server&&(p=g.key)}catch(g){if(g.code!=="ENOENT")throw g}await y(c,{sha256:u,key:p,appId:i.appId,server:e.auth.server});let w=await e.request(`/api/v1/developer/projects/${encodeURIComponent(i.appId)}/web/deploy`,{method:"POST",file:s.content,key:p});await y(c,{sha256:u,key:p,appId:i.appId,server:e.auth.server,response:w});let m=h.object({status:h.literal("succeeded"),result:h.object({versionId:h.string()}).passthrough()}).safeParse(w);if(m.success)try{let g=await Y(e,n,m.data.result.versionId);return{...w,result:{...m.data.result,preview:g.preview}}}catch(g){return{...w,result:{...m.data.result,preview:null},previewError:B(g),next:"\u4E0A\u4F20\u5DF2\u5B8C\u6210\u3002\u4F7F\u7528 preview \u83B7\u53D6\u8BE5\u7248\u672C\u94FE\u63A5\u4E0E\u4E8C\u7EF4\u7801\uFF0C\u4E0D\u8981\u91CD\u590D\u4E0A\u4F20\u3002"}}return{...w,next:"\u901A\u8FC7 status \u67E5\u8BE2\u539F\u4EA4\u4ED8\u7ED3\u679C\uFF1B\u4E0D\u8981\u91CD\u65B0\u4E0A\u4F20\u6216\u66F4\u6362\u64CD\u4F5C\u6807\u8BC6\u3002"}}async function ct(e,r,t,n,i){let o=await N(r),s=await R(o,e.auth.server),u=i?await S(await U(o,i)):void 0;if(u&&u.length>2*1024*1024)throw new a("INVALID_COVER","\u5C01\u9762\u4E0D\u80FD\u8D85\u8FC7 2 MiB\u3002");let d=u?{filename:Se(i),base64:u.toString("base64")}:void 0,c={versionId:t,description:n,...d?{cover:d}:{}},p=te("sha256").update(JSON.stringify({appId:s.appId,body:c})).digest("hex"),w=await e.request(`/api/v1/developer/projects/${encodeURIComponent(s.appId)}/web/publish`,{method:"POST",body:c,key:p});if(w.result?.confirmationUrl){let m=new URL(w.result.confirmationUrl);if(m.origin!==e.auth.server||m.pathname!=="/applications/create")throw new a("INVALID_CONFIRMATION_URL","\u786E\u8BA4\u9875\u9762\u5730\u5740\u4E0D\u6B63\u786E");try{await be(m.href,{wait:!1})}catch{}}return{...w,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 pt(e){let r=await N(e),t=await C(r),n=[];await K(r,t);let i=b(r,t.outputDir),o=q(r,i);return(o===".."||o.startsWith(`..${H}`))&&n.push("outputDir \u8D85\u51FA\u5DE5\u7A0B\u76EE\u5F55"),{root:r,passed:n.length===0,findings:n,checks:["project configuration","command directory","output path"],notRun:["application behavior","build","cloud connectivity"]}}var Le=l.object({appId:l.string(),server:l.string(),key:l.string(),response:l.unknown().optional()});async function se(e,r,t){try{let n=Le.parse(await v(x(e,".shaper","web-deploy.json")));if(n.appId!==r||n.server!==t)throw new a("DELIVERY_TARGET_MISMATCH","\u672C\u5730\u4EA4\u4ED8\u8BB0\u5F55\u4E0D\u5C5E\u4E8E\u5F53\u524D\u5E94\u7528\u6216\u670D\u52A1\uFF0C\u8BF7\u660E\u786E\u6307\u5B9A\u7248\u672C\u3002");return n}catch(n){if(n.code==="ENOENT")return;throw n}}async function Je(e,r){let t=await R(r,e.auth.server),n=await se(r,t.appId,t.server);return n?e.request(`/api/v1/developer/projects/${encodeURIComponent(t.appId)}/web/deploy-status?key=${encodeURIComponent(n.key)}`):{status:"not_started"}}var Ve=l.object({appId:l.string(),versionId:l.string(),preview:l.object({previewUrl:l.string().url(),expiresAt:l.iso.datetime(),expiresInSeconds:l.number().positive().max(86400),qrCodeDataUrl:l.string().max(1024*1024).regex(/^data:image\/png;base64,[A-Za-z0-9+/]+={0,2}$/)})});async function Y(e,r,t){let n=await N(r),i=await R(n,e.auth.server);if(!t){let I=await se(n,i.appId,i.server),j=l.object({status:l.literal("succeeded"),result:l.object({versionId:l.string().min(1)})}).safeParse(I?.response);if(j.success)t=j.data.result.versionId;else{let A=l.object({status:l.literal("succeeded"),result:l.object({versionId:l.string().min(1)})}).safeParse(await Je(e,n));A.success&&(t=A.data.result.versionId)}}if(!t)throw new a("PREVIEW_VERSION_REQUIRED","\u5C1A\u65E0\u5DF2\u786E\u8BA4\u4E0A\u4F20\u7684\u7248\u672C\u3002\u8BF7\u5148\u67E5\u8BE2 status\uFF0C\u6216\u660E\u786E\u6307\u5B9A\u9700\u8981\u9884\u89C8\u7684\u7248\u672C\u3002");let o=oe("sha256").update(JSON.stringify([i.server,i.appId,t])).digest("hex"),s=x(D(),"web-previews",o),u=x(s,"preview.json"),d;try{let I=l.object({previewUrl:l.string().url()}).parse(await v(u));new URL(I.previewUrl).origin===e.auth.server&&(d=I.previewUrl)}catch(I){if(I.code!=="ENOENT")throw I}let c=Ve.parse(await e.request(`/api/v1/developer/projects/${encodeURIComponent(i.appId)}/web/preview`,{method:"POST",body:{versionId:t,...d?{previewUrl:d}:{}}})),p=new URL(c.preview.previewUrl);if(c.appId!==i.appId||c.versionId!==t||p.origin!==e.auth.server||p.username||p.password||p.search||p.hash||!/^\/api\/v1\/previews\/[A-Za-z0-9_-]+\/index\.html$/.test(p.pathname))throw new a("INVALID_PREVIEW_RESPONSE","\u670D\u52A1\u8FD4\u56DE\u7684\u9884\u89C8\u4E0E\u5F53\u524D\u5E94\u7528\u6216\u7248\u672C\u4E0D\u5339\u914D\u3002");if(Date.parse(c.preview.expiresAt)<=Date.now())throw new a("PREVIEW_EXPIRED","\u670D\u52A1\u8FD4\u56DE\u7684\u9884\u89C8\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u8BD5\u83B7\u53D6\u9884\u89C8\u3002");let w=Buffer.from(c.preview.qrCodeDataUrl.slice(22),"base64");if(!w.subarray(0,8).equals(Buffer.from("89504e470d0a1a0a","hex")))throw new a("INVALID_PREVIEW_RESPONSE","\u4E8C\u7EF4\u7801\u56FE\u7247\u683C\u5F0F\u4E0D\u6B63\u786E\u3002");await Te(s,{recursive:!0,mode:448});let m=x(s,`${oe("sha256").update(p.href).digest("hex")}.png`),g=x(s,`${Oe()}.tmp`);try{await Ce(g,w,{mode:384,flag:"wx"}),await Ue(g,m)}finally{await ke(g,{force:!0})}let{qrCodeDataUrl:M,...k}=c.preview,f={appId:i.appId,versionId:t,preview:{...k,qrCodePath:m}};return await y(u,f.preview),f}export{a,D as b,J as c,y as d,v as e,qe as f,He as g,B as h,Je as i,Y as j,xe as k,N as l,C as m,R as n,at as o,K as p,ot as q,_e as r,Pe as s,st as t,ct as u,pt as v};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { ShaperApi } from './api.js';
|
|
2
|
+
export declare function webDeliveryStatus(api: ShaperApi, root: string): Promise<unknown>;
|
|
3
|
+
export declare function previewWeb(api: ShaperApi, path: string, versionId?: string): Promise<{
|
|
4
|
+
appId: string;
|
|
5
|
+
versionId: string;
|
|
6
|
+
preview: {
|
|
7
|
+
previewUrl: string;
|
|
8
|
+
expiresAt: string;
|
|
9
|
+
expiresInSeconds: number;
|
|
10
|
+
qrCodePath: string;
|
|
11
|
+
};
|
|
12
|
+
}>;
|
package/dist/workspace.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { ShaperApi
|
|
2
|
+
import { ShaperApi } from './api.js';
|
|
3
3
|
export declare const packageRoot: string;
|
|
4
4
|
declare const configSchema: z.ZodObject<{
|
|
5
5
|
schemaVersion: z.ZodLiteral<1>;
|
|
@@ -81,7 +81,37 @@ export declare function archiveDirectory(directory: string, limits?: {
|
|
|
81
81
|
}>;
|
|
82
82
|
export declare function deployWeb(api: ShaperApi, path: string, options?: {
|
|
83
83
|
build?: boolean;
|
|
84
|
-
}): Promise<
|
|
84
|
+
}): Promise<{
|
|
85
|
+
status: 'running' | 'succeeded' | 'failed' | 'uncertain';
|
|
86
|
+
error_code: string | null;
|
|
87
|
+
result: {
|
|
88
|
+
versionId: string;
|
|
89
|
+
preview: {
|
|
90
|
+
previewUrl: string;
|
|
91
|
+
expiresAt: string;
|
|
92
|
+
expiresInSeconds: number;
|
|
93
|
+
qrCodePath: string;
|
|
94
|
+
};
|
|
95
|
+
};
|
|
96
|
+
} | {
|
|
97
|
+
status: 'running' | 'succeeded' | 'failed' | 'uncertain';
|
|
98
|
+
error_code: string | null;
|
|
99
|
+
result: {
|
|
100
|
+
versionId: string;
|
|
101
|
+
preview: null;
|
|
102
|
+
};
|
|
103
|
+
previewError: {
|
|
104
|
+
code: string;
|
|
105
|
+
message: string;
|
|
106
|
+
details?: {} | null;
|
|
107
|
+
};
|
|
108
|
+
next: string;
|
|
109
|
+
} | {
|
|
110
|
+
status: 'running' | 'succeeded' | 'failed' | 'uncertain';
|
|
111
|
+
result: unknown;
|
|
112
|
+
error_code: string | null;
|
|
113
|
+
next: string;
|
|
114
|
+
}>;
|
|
85
115
|
export declare function publishWeb(api: ShaperApi, path: string, versionId: string, description: string, coverPath?: string): Promise<{
|
|
86
116
|
status: 'running' | 'succeeded' | 'failed' | 'uncertain';
|
|
87
117
|
result: {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hupu-tech/shaper",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.6",
|
|
4
4
|
"description": "Shaper local developer tools, MCP server and Hupu integration skills",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -30,13 +30,16 @@
|
|
|
30
30
|
"dev": "tsc -p tsconfig.json --watch",
|
|
31
31
|
"typecheck": "tsc --noEmit",
|
|
32
32
|
"test": "node --import tsx --test test/*.test.ts",
|
|
33
|
-
"verify": "npm run build && npm test && npm run check:skills",
|
|
33
|
+
"verify": "npm run build && npm test && npm run check:skills && npm run check:plugins",
|
|
34
34
|
"prepack": "npm run build && npm run check:skills && npm run check:package",
|
|
35
35
|
"check:skills": "node scripts/check-skills.mjs",
|
|
36
36
|
"sync:cloud-sdk": "node scripts/sync-cloud-sdk.mjs",
|
|
37
37
|
"pack:skills": "node scripts/pack-skills.mjs",
|
|
38
38
|
"prepublishOnly": "npm run verify",
|
|
39
|
-
"check:package": "node scripts/check-package.mjs"
|
|
39
|
+
"check:package": "node scripts/check-package.mjs",
|
|
40
|
+
"build:plugins": "node scripts/build-plugins.mjs",
|
|
41
|
+
"check:plugins": "node scripts/check-plugins.mjs",
|
|
42
|
+
"check:plugin-runtime": "node scripts/check-plugin-runtime.mjs"
|
|
40
43
|
},
|
|
41
44
|
"license": "UNLICENSED",
|
|
42
45
|
"packageManager": "pnpm@10.33.0",
|
|
@@ -10,10 +10,10 @@ description: 将 Shaper 网页工程构建、上传预览并提交发布审核
|
|
|
10
10
|
旧版下载包(activity.json.activityId、COLORBOX 指导块或 act-cloudbase 技能)继续原项目流程,本技能停止新版接入;LEGACY_PROJECT_UPGRADE_REQUIRED 不能通过删除标识、link 或旧脚本绕过。升级策略见 shaper-development。
|
|
11
11
|
|
|
12
12
|
1. 用 `shaper_web_deploy` 构建并上传网页代码。它复用 Shaper 版本、内容校验和预览服务。检查操作 `status`、校验结果、`versionId` 与预览信息;上传成功并不代表应用已发布。
|
|
13
|
-
2.
|
|
13
|
+
2. 展示 `result.preview.previewUrl`、`expiresAt` 和二维码;MCP 同时返回二维码图片,CLI 返回 `qrCodePath`。打开云端预览地址验证页面,手机扫描该二维码;本机回环链接不用于手机分享。链接过期、预览生成失败或仅需查看已有版本时,用 `shaper_web_preview(workspace, versionId)` 获取或刷新;省略版本只复用该工程最近一次已确认交付,不选择其他应用或新建版本。若已安装工具缺少此能力,明确提示升级 Toolkit/插件,不用重新上传代替刷新。需要虎扑登录或分享时,在实际 Shaper/虎扑容器中检查对应能力;本地浏览器检查作为独立证据。
|
|
14
14
|
3. 用户要求发布时,调用 `shaper_web_publish`,提供 `versionId` 和说明;可选工程内的 `coverPath`(PNG/JPEG/WebP,最大 2 MiB)。工具保存资料并打开浏览器确认页。用户可在那里补封面、修改应用资料并点击提交审核。
|
|
15
|
-
4. 返回的 operation succeeded 只表示确认页已准备好;`result.status: awaiting_confirmation` 和 `submitted: false` 表示尚未提审。展示确认链接,等待用户在浏览器操作;再调用 `shaper_status(workspace)` 查询 `project.binding.versions` 中同一版本的状态,只有 submitted/in_review/security_review 才报告“已提交审核”,published
|
|
15
|
+
4. 返回的 operation succeeded 只表示确认页已准备好;`result.status: awaiting_confirmation` 和 `submitted: false` 表示尚未提审。展示确认链接,等待用户在浏览器操作;再调用 `shaper_status(workspace)` 查询 `project.binding.versions` 中同一版本的状态,只有 submitted/in_review/security_review 才报告“已提交审核”,published 才报告“该版本已发布”;是否当前线上版本还要核对 `publishedVersionId` 或 `isPublished`。取消或关闭页面不会提交,也不需要新建应用或上传另一个版本。
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
网页上传网络超时、`running` 或 `uncertain` 时,调用 `shaper_status(workspace)` 查看 `project.web` 的原交付结果;状态查询不会重复上传。`succeeded` 后用同一版本获取预览;`not_found` 只表示尚未查到记录,不表示上传已失败。不要为了绕过未确认结果重复创建应用或提交。`uncertain` 需要根据服务端记录核对,不能把它当作失败后自动重发。
|
|
18
18
|
|
|
19
19
|
云函数、数据库和存储属于虎扑云;网页仍走本技能的 Shaper 交付流程。交付包包含构建产物,排除凭证、`.env` 和本地绑定。构建配置决定包内文件,不通过上传整个源仓库绕过构建。
|
package/dist/shared-C4252CVV.js
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import{b as ce}from"./shared-YVV543ON.js";import{a,b as Y,c as _,d as ie,f as ae,h as C,i as O,j as S,k as ne,l as k,q as oe}from"./shared-VUHAWCVD.js";import*as w from"oauth4webapi";import{createHash as Ce}from"node:crypto";import{chmod as de,lstat as he,mkdir as Le,readFile as De,rm as $e,writeFile as Ue}from"node:fs/promises";import{join as Z}from"node:path";import{execFile as Oe}from"node:child_process";import{promisify as xe}from"node:util";import Pe 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(),je=T.object({schemaVersion:T.literal(1),server:T.string(),tokens:pe}).strict(),ue=xe(Oe),x;async function le(n){await Le(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(!x){let{stdout:t}=await ue("whoami.exe",["/user","/fo","csv","/nh"],{windowsHide:!0});if(x=t.match(/S-1-\d+(?:-\d+)+/)?.[0],!x)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",`*${x}:(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(_(n)).digest("hex")}async function fe(n){await le(Y());let e=Z(Y(),n);return await le(e),e}var P=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=je.safeParse(JSON.parse(await De(t,"utf8")));if(!s.success||s.data.server!==_(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:_(e),tokens:pe.parse(t)})}async remove(e){await $e(await this.path(e),{force:!0})}};async function me(n,e,t){let r=Z(await fe("locks"),`${we(n)}-${e}`);await Ue(r,"",{flag:"a",mode:384});try{return await Pe.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 j(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 He 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 He(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",ze=`${X} cloud:read cloud:write`,Ve=(...n)=>[...new Set(n.flatMap(e=>e.split(" ")).filter(Boolean))].join(" "),q=class{constructor(e,t=new P){this.credentials=t;this.server=_(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 j(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?ze: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=>j(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 j(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 H=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;try{u=await i.json()}catch{throw new a("INVALID_API_RESPONSE",`\u670D\u52A1\u8FD4\u56DE\u4E86\u65E0\u6CD5\u89E3\u6790\u7684\u54CD\u5E94\uFF08HTTP ${i.status}\uFF09\u3002\u5199\u64CD\u4F5C\u7ED3\u679C\u5C1A\u672A\u786E\u8BA4\uFF0C\u8BF7\u67E5\u8BE2\u539F\u64CD\u4F5C\uFF0C\u4E0D\u8981\u91CD\u590D\u63D0\u4EA4\u3002`)}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 Me}from"node:module";import{readFile as N,writeFile as ee,mkdir as ye,lstat as J,realpath as z}from"node:fs/promises";import{resolve as A,join as m,relative as D,sep as B,dirname as ge,isAbsolute as Je}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())}),M=n=>Be("sha256").update(n).digest("hex"),Ee=/(?:^|\/)(?:\.env(?:\.[^/]*)?|credentials\.json)$|\.(?:pem|key)$/i;function b(n,e){let t=D(n,e);if(Je(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 L(n,e,t){let r=await z(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 J(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 J(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(M(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 Pt(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(M(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=A(t,e,h);b(t,f);try{throw await J(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=A(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 create\uFF0C\u7531\u7528\u6237\u5728\u7F51\u9875\u786E\u8BA4\u5F00\u901A\uFF0C\u901A\u8FC7 shaper cloud status \u786E\u8BA4\u8D44\u6E90 ready\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 J(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 z(A(t,e));b(t,r);let s=JSON.parse(await L(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 L(t,A(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 L(t,A(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 z(m(r,"vendor",l.archive));if(b(t,g),M(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=A(r,i.entry);await L(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 R=await z(E.path);if(Ee.test(R))throw new a("SECRET_FILE","\u6784\u5EFA\u56FE\u5305\u542B\u51ED\u8BC1\u6587\u4EF6\u3002");R.includes(`${B}node_modules${B}`)||b(t,R)}),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(Me.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=M(te+`
|
|
17
|
-
`+v),U=m(t,".shaper/cloud-build",re);await V(t,U);for(let[g,E]of[["cloud.json",te],["app.cjs",v]]){let R=m(U,g);try{await ee(R,E,{flag:"wx"})}catch(se){if(se.code!=="EEXIST"||await L(t,R,8*1024*1024)!==E)throw se}}return{directory:D(t,r),manifestFile:D(t,m(U,"cloud.json")),bundleFile:D(t,m(U,"app.cjs")),sha256:re,bytes:Buffer.byteLength(v),serverSdk:c.serverSdk,routes:c.routes}}import Ye from"open";import{createHash as Re}from"node:crypto";import{resolve as Ze,relative as Qe,sep as Xe}from"node:path";import{readFile as et,realpath as tt,stat as rt}from"node:fs/promises";var K=class{constructor(e,t=r=>Ye(r,{wait:!1})){this.api=e;this.openBrowser=t}async status(e){return this.api.request(`${(await this.target(e)).url}/status`)}async create(e){let t=await this.api.request(`${(await this.target(e)).url}/create`,{method:"POST",body:{}});if(t.status==="awaiting_confirmation"){let r=new URL(t.confirmationUrl||"",this.api.auth.server);if(r.origin!==new URL(this.api.auth.server).origin||r.pathname!=="/developer/confirm"||!t.confirmationId||r.searchParams.get("requestId")!==t.confirmationId||r.username||r.password)throw new a("INVALID_CONFIRMATION_URL","\u670D\u52A1\u8FD4\u56DE\u7684\u786E\u8BA4\u5730\u5740\u4E0D\u6B63\u786E\u3002");try{await this.openBrowser(r.href)}catch{}return{...t,message:"\u8BF7\u5728\u6D4F\u89C8\u5668\u786E\u8BA4\u5F00\u901A\u4E91\u670D\u52A1\uFF1B\u786E\u8BA4\u540E\u4F7F\u7528 cloud status \u67E5\u770B\u7ED3\u679C\u3002"}}return t}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 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??Re("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 tt(Ze(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 rt(s)).size>r)throw new a("ARTIFACT_TOO_LARGE","\u6587\u4EF6\u8D85\u8FC7\u5141\u8BB8\u5927\u5C0F\u3002");return et(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??Re("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 k(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=Qe(e,t);if(r===".."||r.startsWith(`..${Xe}`))throw new a("INVALID_FILE_PATH","\u5236\u54C1\u6587\u4EF6\u5FC5\u987B\u4F4D\u4E8E\u5DE5\u7A0B\u76EE\u5F55\u5185\u3002")}};import{createHash as st,randomUUID as $}from"node:crypto";import{resolve as W,relative as _e,sep as ke,dirname as it,basename as at}from"node:path";import{readFile as nt,writeFile as ot,realpath as Ae,stat as ct}from"node:fs/promises";var G=class{constructor(e){this.api=e}async base(e,t){let r=await S(e),s=await k(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=st("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=_e(u,c);if(l===".."||l.startsWith(`..${ke}`))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??$()})}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??$()})}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??$()})}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 Ae(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 ct(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 nt(c),key:i??$()})}async getObject(e,t,r,s){let{root:i,url:u}=await this.base(e,t),o=W(await Ae(it(W(i,s))),at(s));this.checkContained(i,o);let c=await this.api.request(`${u}/storage/object?${new URLSearchParams({key:r})}`);return await ot(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??$()})}checkContained(e,t){let r=_e(e,t);if(r===".."||r.startsWith(`..${ke}`))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 H(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 k(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,H as b,Pt as c,Ie as d,K as e,G as f,be as g};
|
package/dist/shared-VUHAWCVD.js
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import{homedir as nt}from"node:os";import{join as b,resolve as rt,dirname as it}from"node:path";import{mkdir as at,readFile as ot,rename as st,writeFile as ct,lstat as pt,rm as dt}from"node:fs/promises";import{randomUUID as ut}from"node:crypto";import{z as T}from"zod";var o=class extends Error{constructor(n,r,i){super(r);this.code=n;this.details=i}},lt=T.object({schemaVersion:T.literal(1),server:T.string().url()}).strict();function z(){return rt(process.env.SHAPER_CONFIG_HOME??b(nt(),".config","shaper"))}function O(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 o("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 I(t,e){await at(it(t),{recursive:!0,mode:448});try{if((await pt(t)).isSymbolicLink())throw new o("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 ct(n,JSON.stringify(e,null,2)+`
|
|
2
|
-
`,{mode:384,flag:"wx"}),await st(n,t)}finally{await dt(n,{force:!0})}}async function y(t){return JSON.parse(await ot(t,"utf8"))}async function Ot(){if(process.env.SHAPER_SERVER)return O(process.env.SHAPER_SERVER);try{return O(lt.parse(await y(b(z(),"config.json"))).server)}catch(t){if(t.code==="ENOENT")return"https://shaper.hupu.com";throw new o("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 bt(t){await I(b(z(),"config.json"),{schemaVersion:1,server:O(t)})}function Pt(t){return{code:t instanceof o?t.code:"OPERATION_FAILED",message:t instanceof Error?t.message:"\u64CD\u4F5C\u672A\u5B8C\u6210",...t instanceof o&&t.details!==void 0?{details:t.details}:{}}}import{realpath as L,mkdir as H,readdir as P,readFile as E,writeFile as S,lstat as U,cp as ft,appendFile as wt}from"node:fs/promises";import{resolve as v,join as f,relative as F,sep as J,dirname as ht,basename as mt,isAbsolute as M}from"node:path";import{fileURLToPath as gt}from"node:url";import{randomUUID as W,createHash as q}from"node:crypto";import{spawn as Et}from"node:child_process";import It from"adm-zip";import yt from"open";import{z as h}from"zod";import Q from"proper-lockfile";var Nt=v(ht(gt(import.meta.url)),".."),vt=h.object({schemaVersion:h.literal(1),devCommand:h.string().min(1).max(500),buildCommand:h.string().min(1).max(500),outputDir:h.string().min(1),workingDirectory:h.string().min(1).default("."),devUrl:h.string().default("http://127.0.0.1:{port}")}).passthrough(),St=h.object({schemaVersion:h.literal(1),appId:h.string().min(1).max(200),server:h.string().url()}).strict();async function N(t){if(!t||!M(t))throw new o("WORKSPACE_REQUIRED","\u8BF7\u6307\u5B9A\u5DE5\u7A0B\u7684\u7EDD\u5BF9\u8DEF\u5F84\u3002");return L(v(t))}async function R(t,e){return E(f(t,e),"utf8").catch(n=>{if(n.code!=="ENOENT")throw n})}async function B(t){let e=new Set;for(let n of[".shaper/project.json","shaper.config.json","shaper.project.json",".shaper/config.json","activity.json"]){let r=await R(t,n);if(r===void 0)continue;let i=JSON.parse(r);for(let a of[i?.appId,i?.applicationId,n==="activity.json"?i?.activityId:void 0])typeof a=="string"&&a&&e.add(a)}return e}function Y(t,e){if(t.size>1||e&&[...t].some(n=>n!==e))throw new o("APP_ID_CONFLICT","\u539F\u9879\u76EE\u5E94\u7528 ID \u4E0E\u76EE\u6807\u4E0D\u4E00\u81F4\uFF1B\u5DF2\u505C\u6B62\uFF0C\u4E0D\u4F1A\u521B\u5EFA\u6216\u5207\u6362\u5E94\u7528\u3002")}async function A(t,e){let n=await R(t,"activity.json"),r=n===void 0?void 0:JSON.parse(n)?.activityId,i=await R(t,"AGENTS.md"),a=await R(t,"skills/act-cloudbase/SKILL.md");if(!(r===void 0&&!i?.includes("<!-- COLORBOX:START -->")&&a===void 0))throw Y(await B(t),e),new o("LEGACY_PROJECT_UPGRADE_REQUIRED","\u8FD9\u662F\u65E7\u7248\u9879\u76EE\uFF0C\u8BF7\u7EE7\u7EED\u4F7F\u7528\u539F\u6709\u6280\u80FD\u548C\u5F00\u53D1\u65B9\u5F0F\u3002\u65B0\u7248\u5DE5\u5177\u672A\u4FEE\u6539\u6B64\u9879\u76EE\uFF0C\u5F53\u524D\u6682\u4E0D\u652F\u6301\u81EA\u52A8\u5347\u7EA7\u3002")}async function j(t){let e=f(t,".shaper");if(await H(e,{recursive:!0,mode:448}),(await U(e)).isSymbolicLink())throw new o("UNSAFE_WORKSPACE",".shaper \u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5\u3002");return e}async function x(t){return await A(t),vt.parse(await y(f(t,"shaper.config.json")))}async function V(t,e){await A(t);let n=St.parse(await y(f(t,".shaper","project.json")));if(n.server!==e)throw new o("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 Z(t,e,n){let r=await j(t);await I(f(r,"project.json"),{schemaVersion:1,appId:e,server:n})}async function Ht(t,e,n={}){if(!e||!M(e))throw new o("WORKSPACE_REQUIRED","\u8BF7\u6307\u5B9A\u5DE5\u7A0B\u7684\u7EDD\u5BF9\u8DEF\u5F84\u3002");await H(e,{recursive:!0});let r=await N(e);await A(r,n.appId);let i=await j(r),a=await Q.lock(i,{retries:0});try{let s;try{s=await V(r,t.auth.server)}catch(w){if(w.code!=="ENOENT")throw w}if(s&&n.appId&&n.appId!==s.appId)throw new o("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 d=(await P(r)).filter(w=>![".git",".shaper",".shaper.lock",".DS_Store"].includes(w));if(!s&&d.length&&n.template)throw new o("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 o("INVALID_TEMPLATE","\u652F\u6301 h5\u3001react\u3001phaser \u6A21\u677F\u3002");let u=await B(r),c=s?.appId??n.appId??[...u][0];Y(u,c);let p=f(i,"init.json"),m=s?void 0:await y(p).catch(w=>{if(w.code!=="ENOENT")throw w});if(!s&&m&&(!m.appId||m.server!==t.auth.server||c&&c!==m.appId))throw new o("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(!c&&!m&&d.length)throw new o("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 l=c??m?.appId??`app_${W().replaceAll("-","").slice(0,10)}`;!m&&!s&&(m={appId:l,server:t.auth.server},await I(p,m));let _;try{_=await t.project(l)}catch(w){if(!(w instanceof o)||!["AUTH_REQUIRED","INVALID_TOKEN","PROJECT_NOT_AUTHORIZED","INSUFFICIENT_SCOPE","NOT_FOUND"].includes(w.code))throw w;let g=await t.auth.start({appId:l,...n.name?{applicationName:n.name}:{},initialize:!s&&u.size===0,reauthorize:!0});if(g.status==="pending"){if(!n.waitForAuthorization)return{root:r,appId:l,...g,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${g.authorizationUrl}
|
|
3
|
-
`),await t.auth.wait(g.flowId)}_=await t.project(l)}let X=_.name;if(s)return n.installDependencies!==!1&&await E(f(i,"install-pending"),"utf8").catch(g=>{if(g.code==="ENOENT")return"";throw g})&&(await k("npm ci",r),await S(f(i,"install-pending"),"")),await C(r),{root:r,...s,alreadyInitialized:!0,...await K(r)};if(d.length===0){let w=n.template??"h5";if(!["h5","react","phaser"].includes(w))throw new o("INVALID_TEMPLATE","\u652F\u6301 h5\u3001react\u3001phaser \u6A21\u677F\u3002");let g=f(Nt,"templates",w);for(let G of(await P(g)).filter(et=>!["node_modules","dist"].includes(et)))await ft(f(g,G),f(r,G),{recursive:!0,force:!1,errorOnExist:!0});n.installDependencies!==!1&&await S(f(i,"install-pending"),`npm ci
|
|
4
|
-
`)}await C(r),await Z(r,l,t.auth.server);let tt=await E(f(i,"install-pending"),"utf8").catch(w=>{if(w.code==="ENOENT")return"";throw w});return n.installDependencies!==!1&&tt&&(await k("npm ci",r),await S(f(i,"install-pending"),"")),{root:r,name:X,appId:l,...await K(r)}}finally{await a()}}async function K(t){try{let e=await x(t);return await $(t,e),{status:"initialized"}}catch(e){if(e.code!=="ENOENT"&&!(e instanceof h.ZodError))throw e;return{status:"configuration_required",next:"\u5E94\u7528\u5DF2\u5173\u8054\u3002\u8BF7\u68C0\u67E5\u5B9E\u9645\u6E90\u7801\u5165\u53E3\u3001\u5305\u7BA1\u7406\u5668\u548C\u6784\u5EFA\u914D\u7F6E\uFF0C\u4FDD\u7559\u539F\u5DE5\u7A0B\uFF0C\u8865\u5145 shaper.config.json \u7684 workingDirectory\u3001devCommand\u3001devUrl\u3001buildCommand\u3001outputDir\uFF1BoutputDir \u76F8\u5BF9\u9879\u76EE\u6839\u76EE\u5F55\u3002\u914D\u7F6E\u540E\u518D\u6B21 init \u5E76\u9A8C\u8BC1\u9884\u89C8\u548C\u6784\u5EFA\u3002"}}}async function $(t,e){let n=await D(t,e.workingDirectory);if(!(await U(n)).isDirectory())throw new o("INVALID_WORKING_DIRECTORY","workingDirectory \u5FC5\u987B\u662F\u5DE5\u7A0B\u5185\u90E8\u76EE\u5F55\u3002");return n}async function Mt(t,e,n){let r=await N(e);await A(r,n);let i=await Q.lock(await j(r),{retries:0});try{let a=await t.project(n);return await Z(r,a.appId,t.auth.server),await C(r),{root:r,appId:a.appId,name:a.name}}finally{await i()}}async function C(t){let e=f(t,".gitignore"),n=await E(e,"utf8").catch(p=>{if(p.code==="ENOENT")return"";throw p}),i=["/.shaper/","/.shaper.lock/","/node_modules/","/dist/","/credentials.json",".env",".env.*","!.env.example"].filter(p=>!n.split(`
|
|
5
|
-
`).includes(p));i.length&&await wt(e,`
|
|
6
|
-
# Shaper local state and generated files
|
|
7
|
-
${i.join(`
|
|
8
|
-
`)}
|
|
9
|
-
`);let a=f(t,"AGENTS.md"),s=await E(a,"utf8").catch(p=>{if(p.code==="ENOENT")return"";throw p}),d="<!-- shaper:project -->",u=`
|
|
10
|
-
${d}
|
|
11
|
-
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.
|
|
12
|
-
<!-- /shaper:project -->
|
|
13
|
-
`,c=s.includes(d)?s.replace(/<!-- shaper:project -->[\s\S]*?<!-- \/shaper:project -->\n?/,u.trimStart()):s+u;c!==s&&await S(a,c)}async function k(t,e){await new Promise((n,r)=>{let i=Et(t,{cwd:e,shell:!0,stdio:["ignore","pipe","pipe"]});i.stdout.on("data",a=>process.stderr.write(a)),i.stderr.on("data",a=>process.stderr.write(a)),i.once("error",r),i.once("exit",a=>a===0?n():r(new o("COMMAND_FAILED",`\u5DE5\u7A0B\u547D\u4EE4\u9000\u51FA\u7801\uFF1A${a??"signal"}`)))})}async function Rt(t){let e=await N(t),n=await x(e);await k(n.buildCommand,await $(e,n));let r=await D(e,n.outputDir);return await E(f(r,"index.html")),{root:e,output:r}}async function D(t,e){let n=await L(v(t,e)),r=F(t,n);if(r===".."||r.startsWith(`..${J}`)||v(t,r)!==n)throw new o("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 L(t),r=new It,i=0,a=0;async function s(d){for(let u of(await P(d,{withFileTypes:!0})).sort((c,p)=>c.name.localeCompare(p.name))){if(/^(\.git|\.shaper|node_modules|\.DS_Store)$/.test(u.name))continue;if(/^(\.env(?:\..*)?|credentials\.json|.*\.(pem|key))$/i.test(u.name))throw new o("SECRET_FILE_IN_PACKAGE",`\u8F93\u51FA\u76EE\u5F55\u5305\u542B\u654F\u611F\u914D\u7F6E\u6587\u4EF6\uFF1A${u.name}`);let c=f(d,u.name);if(u.isSymbolicLink())throw new o("SYMLINK_IN_PACKAGE",`\u4EA4\u4ED8\u5185\u5BB9\u4E2D\u4E0D\u5141\u8BB8\u7B26\u53F7\u94FE\u63A5\uFF1A${u.name}`);if(u.isDirectory()){await s(c);continue}if(!u.isFile())throw new o("INVALID_PACKAGE_FILE","\u4EA4\u4ED8\u76EE\u5F55\u5305\u542B\u975E\u5E38\u89C4\u6587\u4EF6\u3002");let p=await U(c);if(i+=p.size,a++,a>e.files||i>e.bytes)throw new o("PACKAGE_TOO_LARGE","\u4EA4\u4ED8\u5305\u8D85\u8FC7\u6587\u4EF6\u6570\u6216\u5927\u5C0F\u9650\u5236\u3002");r.addFile(F(n,c).split(J).join("/"),await E(c))}}await s(n);for(let d of r.getEntries())d.header.time=new Date(2e3,0,1);return{content:r.toBuffer(),files:a,bytes:i}}async function Wt(t,e,n={}){let r=await N(e),i=await V(r,t.auth.server),a=n.build===!1?await D(r,(await x(r)).outputDir):(await Rt(r)).output,s=await At(a),d=q("sha256").update(s.content).digest("hex"),u=await j(r),c=f(u,"web-deploy.json"),p=W();try{let l=h.object({sha256:h.string(),key:h.string(),appId:h.string(),server:h.string()}).passthrough().parse(await y(c));l.sha256===d&&l.appId===i.appId&&l.server===t.auth.server&&(p=l.key)}catch(l){if(l.code!=="ENOENT")throw l}await I(c,{sha256:d,key:p,appId:i.appId,server:t.auth.server});let m=await t.request(`/api/v1/developer/projects/${encodeURIComponent(i.appId)}/web/deploy`,{method:"POST",file:s.content,key:p});return await I(c,{sha256:d,key:p,appId:i.appId,server:t.auth.server,response:m}),m}async function qt(t,e,n,r,i){let a=await N(e),s=await V(a,t.auth.server),d=i?await E(await D(a,i)):void 0;if(d&&d.length>2*1024*1024)throw new o("INVALID_COVER","\u5C01\u9762\u4E0D\u80FD\u8D85\u8FC7 2 MiB\u3002");let u=d?{filename:mt(i),base64:d.toString("base64")}:void 0,c={versionId:n,description:r,...u?{cover:u}:{}},p=q("sha256").update(JSON.stringify({appId:s.appId,body:c})).digest("hex"),m=await t.request(`/api/v1/developer/projects/${encodeURIComponent(s.appId)}/web/publish`,{method:"POST",body:c,key:p});if(m.result?.confirmationUrl){let l=new URL(m.result.confirmationUrl);if(l.origin!==t.auth.server||l.pathname!=="/applications/create")throw new o("INVALID_CONFIRMATION_URL","\u786E\u8BA4\u9875\u9762\u5730\u5740\u4E0D\u6B63\u786E");try{await yt(l.href,{wait:!1})}catch{}}return{...m,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 Qt(t){let e=await N(t),n=await x(e),r=[];await $(e,n);let i=v(e,n.outputDir),a=F(e,i);return(a===".."||a.startsWith(`..${J}`))&&r.push("outputDir \u8D85\u51FA\u5DE5\u7A0B\u76EE\u5F55"),{root:e,passed:r.length===0,findings:r,checks:["project configuration","command directory","output path"],notRun:["application behavior","build","cloud connectivity"]}}export{o as a,z as b,O as c,I as d,y as e,Ot as f,bt as g,Pt as h,Nt as i,N as j,x as k,V as l,Ht as m,$ as n,Mt as o,Rt as p,At as q,Wt as r,qt as s,Qt as t};
|
package/dist/shared-YVV543ON.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as u,b as p,e as m,i as h,j as d,k as y}from"./shared-VUHAWCVD.js";import{createHash as x,randomUUID as D}from"node:crypto";import{open as k,mkdir as N,readFile as A}from"node:fs/promises";import{join as l}from"node:path";import{spawn as v}from"node:child_process";import{z as i}from"zod";import I from"proper-lockfile";var P=i.object({id:i.string(),root:i.string(),controlUrl:i.string().url(),token:i.string(),url:i.string().url(),startedAt:i.string()}).strict();function g(e){return l(p(),"sessions",x("sha256").update(e).digest("hex"))}async function E(e){let t=P.parse(await m(l(g(e),"session.json")));if(t.root!==e||new URL(t.controlUrl).hostname!=="127.0.0.1")throw new u("INVALID_DEV_SESSION","\u672C\u5730\u5F00\u53D1\u4F1A\u8BDD\u8BB0\u5F55\u4E0D\u6B63\u786E\u3002");return t}async function f(e){let t=await d(e),r;try{r=await E(t)}catch(o){if(o.code==="ENOENT")return{running:!1,root:t};throw o}try{let o=await fetch(`${r.controlUrl}/status`,{headers:{Authorization:`Bearer ${r.token}`},redirect:"error",signal:AbortSignal.timeout(1500)}),n=await o.json();if(!o.ok||n.id!==r.id)throw new Error("Session mismatch");return{root:t,running:n.running,ready:n.ready,url:r.url,sessionId:r.id}}catch{return{root:t,running:!1,url:r.url,sessionId:r.id}}}async function R(e){let t=await d(e);await y(t);let r=g(t);await N(r,{recursive:!0,mode:448});let o=await I.lock(r,{retries:0});try{let n=await f(t);if(n.running)return n;let s=await k(l(r,"dev.log"),"w",384),a=v(process.execPath,[l(h,"dist","dev-runner.js"),t,D()],{cwd:t,detached:!0,stdio:["ignore",s.fd,s.fd],windowsHide:!0});await new Promise((w,c)=>{a.once("spawn",w),a.once("error",c)}),a.unref(),await s.close();for(let w=0;w<120;w++){await new Promise(S=>setTimeout(S,250));let c=await f(t);if(c.running&&c.ready)return c}throw new u("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 o()}}async function V(e){let t=await d(e);if(!(await f(t)).running)return{stopped:!0,alreadyStopped:!0};let o=await E(t);if(!(await fetch(`${o.controlUrl}/stop`,{method:"POST",headers:{Authorization:`Bearer ${o.token}`},redirect:"error",signal:AbortSignal.timeout(1e4)})).ok)throw new u("DEV_STOP_FAILED","\u5F00\u53D1\u4F1A\u8BDD\u672A\u80FD\u505C\u6B62\u3002");for(let s=0;s<30;s++){await new Promise(a=>setTimeout(a,200));try{await fetch(`${o.controlUrl}/status`,{headers:{Authorization:`Bearer ${o.token}`},redirect:"error",signal:AbortSignal.timeout(500)})}catch{return{stopped:!0,sessionId:o.id}}}throw new u("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 L(e){let t=await d(e);try{let r=await A(l(g(t),"dev.log"),"utf8");return{root:t,log:r.slice(-16e3)}}catch(r){if(r.code==="ENOENT")return{root:t,log:"",message:"\u5C1A\u65E0\u672C\u5730\u8FD0\u884C\u65E5\u5FD7"};throw r}}export{g as a,f as b,R as c,V as d,L as e};
|