@powerhousedao/shared 6.2.3-dev.94 → 6.2.3-dev.96

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/clis/args/access-token.mjs +1 -1
  2. package/dist/clis/args/{common-CBLen_yt.mjs → common-DG_SF8fN.mjs} +9 -1
  3. package/dist/clis/args/common-DG_SF8fN.mjs.map +1 -0
  4. package/dist/clis/args/{common-BpLj4peE.d.mts → common-DmerPWXo.d.mts} +5 -1
  5. package/dist/clis/args/common-DmerPWXo.d.mts.map +1 -0
  6. package/dist/clis/args/common.d.mts +1 -1
  7. package/dist/clis/args/common.mjs +1 -1
  8. package/dist/clis/args/connect.mjs +1 -1
  9. package/dist/clis/args/{generate-a36SaAn4.mjs → generate-DoDfK_Wi.mjs} +2 -2
  10. package/dist/clis/args/{generate-a36SaAn4.mjs.map → generate-DoDfK_Wi.mjs.map} +1 -1
  11. package/dist/clis/args/generate.mjs +1 -1
  12. package/dist/clis/args/{help-D_wYe_Fx.mjs → help-DJCRTkC9.mjs} +4 -4
  13. package/dist/clis/args/{help-D_wYe_Fx.mjs.map → help-DJCRTkC9.mjs.map} +1 -1
  14. package/dist/clis/args/help.mjs +1 -1
  15. package/dist/clis/args/index.d.mts +2 -2
  16. package/dist/clis/args/index.mjs +4 -4
  17. package/dist/clis/args/init.mjs +1 -1
  18. package/dist/clis/args/inspect.mjs +1 -1
  19. package/dist/clis/args/install.mjs +1 -1
  20. package/dist/clis/args/keyframes.mjs +1 -1
  21. package/dist/clis/args/list.mjs +1 -1
  22. package/dist/clis/args/login.mjs +1 -1
  23. package/dist/clis/args/mcp.mjs +1 -1
  24. package/dist/clis/args/migrate.mjs +1 -1
  25. package/dist/clis/args/model.d.mts +8 -0
  26. package/dist/clis/args/model.d.mts.map +1 -1
  27. package/dist/clis/args/model.mjs +17 -1
  28. package/dist/clis/args/model.mjs.map +1 -1
  29. package/dist/clis/args/publish.d.mts +4 -0
  30. package/dist/clis/args/publish.mjs +10 -2
  31. package/dist/clis/args/publish.mjs.map +1 -1
  32. package/dist/clis/args/registry.mjs +1 -1
  33. package/dist/clis/args/{service-IZ0Aq58z.d.mts → service-CLCvH3kf.d.mts} +2 -2
  34. package/dist/clis/args/{service-IZ0Aq58z.d.mts.map → service-CLCvH3kf.d.mts.map} +1 -1
  35. package/dist/clis/args/service.d.mts +1 -1
  36. package/dist/clis/args/service.mjs +1 -1
  37. package/dist/clis/args/switchboard.mjs +1 -1
  38. package/dist/clis/args/uninstall.mjs +1 -1
  39. package/dist/clis/args/unpublish.mjs +1 -1
  40. package/dist/clis/args/{vetra-DlAEC_Mv.mjs → vetra-BqjDopAP.mjs} +2 -2
  41. package/dist/clis/args/{vetra-DlAEC_Mv.mjs.map → vetra-BqjDopAP.mjs.map} +1 -1
  42. package/dist/clis/args/vetra.mjs +1 -1
  43. package/dist/clis/build-pieces.d.mts +9 -2
  44. package/dist/clis/build-pieces.d.mts.map +1 -1
  45. package/dist/clis/build-pieces.mjs +61 -16
  46. package/dist/clis/build-pieces.mjs.map +1 -1
  47. package/dist/clis/constants.d.mts +1 -1
  48. package/dist/clis/constants.mjs +4 -1
  49. package/dist/clis/constants.mjs.map +1 -1
  50. package/dist/clis/index.d.mts +11 -0
  51. package/dist/clis/index.d.mts.map +1 -1
  52. package/dist/clis/index.mjs +42 -4
  53. package/dist/clis/index.mjs.map +1 -1
  54. package/dist/clis/{types-B-2NDvpx.d.mts → types-DXqOePw5.d.mts} +4 -1
  55. package/dist/clis/{types-B-2NDvpx.d.mts.map → types-DXqOePw5.d.mts.map} +1 -1
  56. package/dist/registry/index.js.map +1 -1
  57. package/dist/types-cIIv_Rsg.d.ts.map +1 -1
  58. package/package.json +1 -1
  59. package/dist/clis/args/common-BpLj4peE.d.mts.map +0 -1
  60. package/dist/clis/args/common-CBLen_yt.mjs.map +0 -1
@@ -1,4 +1,4 @@
1
- import { o as debugArgs } from "./common-CBLen_yt.mjs";
1
+ import { o as debugArgs } from "./common-DG_SF8fN.mjs";
2
2
  import { boolean, flag, option, optional, positional, rest, string } from "cmd-ts";
3
3
  //#region clis/args/unpublish.ts
4
4
  const unpublishArgs = {
@@ -1,4 +1,4 @@
1
- import { S as getConfig, i as commonServerArgs, r as commonArgs, x as vetraSwitchboardArgs, y as renownNamespace } from "./common-CBLen_yt.mjs";
1
+ import { S as getConfig, i as commonServerArgs, r as commonArgs, x as vetraSwitchboardArgs, y as renownNamespace } from "./common-DG_SF8fN.mjs";
2
2
  import { boolean, flag, number, option, optional, string } from "cmd-ts";
3
3
  import { join } from "node:path";
4
4
  import dotenv from "dotenv";
@@ -139,4 +139,4 @@ const vetraArgs = {
139
139
  //#endregion
140
140
  export { resolveSwitchboardPortDefault as n, vetraArgs as r, resolveConnectPortDefault as t };
141
141
 
142
- //# sourceMappingURL=vetra-DlAEC_Mv.mjs.map
142
+ //# sourceMappingURL=vetra-BqjDopAP.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"vetra-DlAEC_Mv.mjs","names":[],"sources":["../../../clis/project-env.ts","../../../clis/args/vetra.ts"],"sourcesContent":["import dotenv from \"dotenv\";\nimport { join } from \"node:path\";\n\nlet loadedFor: string | undefined;\nlet namesBeforeLoad: ReadonlySet<string> | undefined;\n\n/** `PH_NO_DOTENV=1` (or `true`): no `.env` file is read, so a launcher's\n * explicit environment is the whole environment. */\nexport function isDotenvDisabled(\n env: Record<string, string | undefined> = process.env,\n): boolean {\n const value = env.PH_NO_DOTENV?.trim().toLowerCase();\n return value === \"1\" || value === \"true\";\n}\n\n/**\n * Load the project's `.env.local` and `.env` into `process.env`.\n *\n * `dotenv` never overwrites a variable that is already set, so loading\n * `.env.local` first and `.env` second produces the precedence the CLI\n * documents: a real `process.env` value beats `.env.local`, which beats\n * `.env`. One `process.env` lookup afterwards therefore covers all three\n * sources.\n *\n * Idempotent per directory — CLI argument defaults call it lazily and may\n * call it more than once per process.\n */\nexport function loadProjectEnv(cwd: string = process.cwd()): void {\n if (isDotenvDisabled()) return;\n if (loadedFor === cwd) return;\n loadedFor = cwd;\n namesBeforeLoad ??= new Set(Object.keys(process.env));\n // dotenv 16 logs nothing for a missing file, so no suppression option is\n // needed here (and none exists before dotenv 17).\n dotenv.config({ path: join(cwd, \".env.local\") });\n dotenv.config({ path: join(cwd, \".env\") });\n}\n\n/** The `process.env` names the shell set: those before the first\n * {@link loadProjectEnv}. Undefined while no project `.env` was loaded. */\nexport function envNamesBeforeProjectEnv(): ReadonlySet<string> | undefined {\n return namesBeforeLoad;\n}\n\n/** Test seam: forget which directory has already been loaded. */\nexport function resetProjectEnvForTests(): void {\n loadedFor = undefined;\n namesBeforeLoad = undefined;\n}\n\n/**\n * Read an environment variable as a TCP port.\n *\n * Anything that is not a plain integer in 1-65535 is ignored rather than\n * throwing: a typo in `.env` should fall through to the next source in the\n * precedence chain, not break the CLI.\n */\nexport function readPortEnv(name: string): number | undefined {\n const raw = process.env[name]?.trim();\n if (!raw || !/^\\d+$/.test(raw)) return undefined;\n const port = Number(raw);\n if (port < 1 || port > 65535) return undefined;\n return port;\n}\n","import { boolean, flag, number, option, optional, string } from \"cmd-ts\";\nimport {\n DEFAULT_SWITCHBOARD_PORT,\n DEFAULT_VETRA_CONNECT_PORT,\n} from \"../constants.js\";\nimport { getConfig } from \"../file-system/get-config.js\";\nimport { loadProjectEnv, readPortEnv } from \"../project-env.js\";\nimport {\n commonArgs,\n commonServerArgs,\n renownNamespace,\n vetraSwitchboardArgs,\n} from \"./common.js\";\n\n/**\n * Resolve the Vetra Switchboard port.\n *\n * Precedence: CLI flag (cmd-ts applies that above this function) →\n * `process.env` → `.env.local` → `.env` → `powerhouse.config.json` →\n * constant. `loadProjectEnv` folds the two files into `process.env` without\n * clobbering anything already set, so a single lookup covers the middle three.\n */\nexport function resolveSwitchboardPortDefault(): number {\n loadProjectEnv();\n return (\n readPortEnv(\"PH_SWITCHBOARD_PORT\") ??\n getConfig().reactor?.port ??\n DEFAULT_SWITCHBOARD_PORT\n );\n}\n\n/** Resolve the Vetra Connect port through the same chain. */\nexport function resolveConnectPortDefault(): number {\n loadProjectEnv();\n return (\n readPortEnv(\"PH_VETRA_CONNECT_PORT\") ??\n getConfig().vetra?.connectPort ??\n DEFAULT_VETRA_CONNECT_PORT\n );\n}\n\nexport const vetraArgs = {\n switchboardPort: option({\n type: number,\n long: \"switchboard-port\",\n description: \"port to use for the Vetra Switchboard\",\n defaultValue: resolveSwitchboardPortDefault,\n }),\n connectPort: option({\n type: number,\n long: \"connect-port\",\n // Deliberately not `defaultValueIsSerializable`: the value is now\n // per-project, and cmd-ts prints serializable defaults into `--help`,\n // which would bake one project's port into the help text.\n description: \"port to use for the Vetra Connect\",\n defaultValue: resolveConnectPortDefault,\n }),\n remoteDrive: option({\n type: optional(string),\n long: \"remote-drive\",\n description:\n \"URL of remote drive to connect to (skips switchboard initialization)\",\n defaultValue: () => {\n const baseConfig = getConfig();\n return baseConfig.vetra?.driveUrl;\n },\n }),\n watch: flag({\n type: boolean,\n long: \"watch\",\n short: \"w\",\n description:\n \"Enable dynamic loading for document-models and editors in connect-studio and switchboard\",\n defaultValue: () => false,\n defaultValueIsSerializable: true,\n }),\n verbose: flag({\n type: boolean,\n long: \"logs\",\n description: \"Show additional logs\",\n defaultValue: () => false,\n defaultValueIsSerializable: true,\n }),\n restart: flag({\n type: boolean,\n long: \"restart\",\n description:\n \"Stop this project's running Vetra first (the pid in .ph/vetra-runtime.json), then start\",\n defaultValue: () => false,\n defaultValueIsSerializable: true,\n }),\n disableConnect: flag({\n type: boolean,\n long: \"disable-connect\",\n description:\n \"Skip Connect initialization (only start switchboard and reactor)\",\n defaultValue: () => false,\n defaultValueIsSerializable: true,\n }),\n interactive: flag({\n type: boolean,\n long: \"interactive\",\n description:\n \"Enable interactive mode for code generation (requires user confirmation before generating code)\",\n defaultValue: () => false,\n defaultValueIsSerializable: true,\n }),\n drivesPublicBase: option({\n type: optional(string),\n long: \"drives-public-base\",\n description:\n \"public base URL for the drive URLs advertised to Connect; each drive is exposed as <base>/d/<slug> instead of http://localhost:<switchboard-port>/d/<slug>. Use when the switchboard is reachable through a reverse proxy.\",\n }),\n dbPath: option({\n type: optional(string),\n long: \"db-path\",\n description:\n \"Database path or connection string. Use a `postgres://` URL for Postgres; otherwise treated as a PGlite filesystem path. Leave unset for in-memory PGlite.\",\n }),\n renownNamespace,\n ...commonArgs,\n ...commonServerArgs,\n ...vetraSwitchboardArgs,\n};\n"],"mappings":";;;;;AAGA,IAAI;AACJ,IAAI;;;AAIJ,SAAgB,iBACd,MAA0C,QAAQ,KACzC;CACT,MAAM,QAAQ,IAAI,cAAc,KAAK,CAAC,CAAC,YAAY;CACnD,OAAO,UAAU,OAAO,UAAU;AACpC;;;;;;;;;;;;;AAcA,SAAgB,eAAe,MAAc,QAAQ,IAAI,GAAS;CAChE,IAAI,iBAAiB,GAAG;CACxB,IAAI,cAAc,KAAK;CACvB,YAAY;CACZ,oBAAoB,IAAI,IAAI,OAAO,KAAK,QAAQ,GAAG,CAAC;CAGpD,OAAO,OAAO,EAAE,MAAM,KAAK,KAAK,YAAY,EAAE,CAAC;CAC/C,OAAO,OAAO,EAAE,MAAM,KAAK,KAAK,MAAM,EAAE,CAAC;AAC3C;;;;;;;;AAqBA,SAAgB,YAAY,MAAkC;CAC5D,MAAM,MAAM,QAAQ,IAAI,KAAK,EAAE,KAAK;CACpC,IAAI,CAAC,OAAO,CAAC,QAAQ,KAAK,GAAG,GAAG,OAAO,KAAA;CACvC,MAAM,OAAO,OAAO,GAAG;CACvB,IAAI,OAAO,KAAK,OAAO,OAAO,OAAO,KAAA;CACrC,OAAO;AACT;;;;;;;;;;;ACzCA,SAAgB,gCAAwC;CACtD,eAAe;CACf,OACE,YAAY,qBAAqB,KACjC,UAAU,CAAC,CAAC,SAAS,QAAA;AAGzB;;AAGA,SAAgB,4BAAoC;CAClD,eAAe;CACf,OACE,YAAY,uBAAuB,KACnC,UAAU,CAAC,CAAC,OAAO,eAAA;AAGvB;AAEA,MAAa,YAAY;CACvB,iBAAiB,OAAO;EACtB,MAAM;EACN,MAAM;EACN,aAAa;EACb,cAAc;CAChB,CAAC;CACD,aAAa,OAAO;EAClB,MAAM;EACN,MAAM;EAIN,aAAa;EACb,cAAc;CAChB,CAAC;CACD,aAAa,OAAO;EAClB,MAAM,SAAS,MAAM;EACrB,MAAM;EACN,aACE;EACF,oBAAoB;GAElB,OADmB,UACH,CAAC,CAAC,OAAO;EAC3B;CACF,CAAC;CACD,OAAO,KAAK;EACV,MAAM;EACN,MAAM;EACN,OAAO;EACP,aACE;EACF,oBAAoB;EACpB,4BAA4B;CAC9B,CAAC;CACD,SAAS,KAAK;EACZ,MAAM;EACN,MAAM;EACN,aAAa;EACb,oBAAoB;EACpB,4BAA4B;CAC9B,CAAC;CACD,SAAS,KAAK;EACZ,MAAM;EACN,MAAM;EACN,aACE;EACF,oBAAoB;EACpB,4BAA4B;CAC9B,CAAC;CACD,gBAAgB,KAAK;EACnB,MAAM;EACN,MAAM;EACN,aACE;EACF,oBAAoB;EACpB,4BAA4B;CAC9B,CAAC;CACD,aAAa,KAAK;EAChB,MAAM;EACN,MAAM;EACN,aACE;EACF,oBAAoB;EACpB,4BAA4B;CAC9B,CAAC;CACD,kBAAkB,OAAO;EACvB,MAAM,SAAS,MAAM;EACrB,MAAM;EACN,aACE;CACJ,CAAC;CACD,QAAQ,OAAO;EACb,MAAM,SAAS,MAAM;EACrB,MAAM;EACN,aACE;CACJ,CAAC;CACD;CACA,GAAG;CACH,GAAG;CACH,GAAG;AACL"}
1
+ {"version":3,"file":"vetra-BqjDopAP.mjs","names":[],"sources":["../../../clis/project-env.ts","../../../clis/args/vetra.ts"],"sourcesContent":["import dotenv from \"dotenv\";\nimport { join } from \"node:path\";\n\nlet loadedFor: string | undefined;\nlet namesBeforeLoad: ReadonlySet<string> | undefined;\n\n/** `PH_NO_DOTENV=1` (or `true`): no `.env` file is read, so a launcher's\n * explicit environment is the whole environment. */\nexport function isDotenvDisabled(\n env: Record<string, string | undefined> = process.env,\n): boolean {\n const value = env.PH_NO_DOTENV?.trim().toLowerCase();\n return value === \"1\" || value === \"true\";\n}\n\n/**\n * Load the project's `.env.local` and `.env` into `process.env`.\n *\n * `dotenv` never overwrites a variable that is already set, so loading\n * `.env.local` first and `.env` second produces the precedence the CLI\n * documents: a real `process.env` value beats `.env.local`, which beats\n * `.env`. One `process.env` lookup afterwards therefore covers all three\n * sources.\n *\n * Idempotent per directory — CLI argument defaults call it lazily and may\n * call it more than once per process.\n */\nexport function loadProjectEnv(cwd: string = process.cwd()): void {\n if (isDotenvDisabled()) return;\n if (loadedFor === cwd) return;\n loadedFor = cwd;\n namesBeforeLoad ??= new Set(Object.keys(process.env));\n // dotenv 16 logs nothing for a missing file, so no suppression option is\n // needed here (and none exists before dotenv 17).\n dotenv.config({ path: join(cwd, \".env.local\") });\n dotenv.config({ path: join(cwd, \".env\") });\n}\n\n/** The `process.env` names the shell set: those before the first\n * {@link loadProjectEnv}. Undefined while no project `.env` was loaded. */\nexport function envNamesBeforeProjectEnv(): ReadonlySet<string> | undefined {\n return namesBeforeLoad;\n}\n\n/** Test seam: forget which directory has already been loaded. */\nexport function resetProjectEnvForTests(): void {\n loadedFor = undefined;\n namesBeforeLoad = undefined;\n}\n\n/**\n * Read an environment variable as a TCP port.\n *\n * Anything that is not a plain integer in 1-65535 is ignored rather than\n * throwing: a typo in `.env` should fall through to the next source in the\n * precedence chain, not break the CLI.\n */\nexport function readPortEnv(name: string): number | undefined {\n const raw = process.env[name]?.trim();\n if (!raw || !/^\\d+$/.test(raw)) return undefined;\n const port = Number(raw);\n if (port < 1 || port > 65535) return undefined;\n return port;\n}\n","import { boolean, flag, number, option, optional, string } from \"cmd-ts\";\nimport {\n DEFAULT_SWITCHBOARD_PORT,\n DEFAULT_VETRA_CONNECT_PORT,\n} from \"../constants.js\";\nimport { getConfig } from \"../file-system/get-config.js\";\nimport { loadProjectEnv, readPortEnv } from \"../project-env.js\";\nimport {\n commonArgs,\n commonServerArgs,\n renownNamespace,\n vetraSwitchboardArgs,\n} from \"./common.js\";\n\n/**\n * Resolve the Vetra Switchboard port.\n *\n * Precedence: CLI flag (cmd-ts applies that above this function) →\n * `process.env` → `.env.local` → `.env` → `powerhouse.config.json` →\n * constant. `loadProjectEnv` folds the two files into `process.env` without\n * clobbering anything already set, so a single lookup covers the middle three.\n */\nexport function resolveSwitchboardPortDefault(): number {\n loadProjectEnv();\n return (\n readPortEnv(\"PH_SWITCHBOARD_PORT\") ??\n getConfig().reactor?.port ??\n DEFAULT_SWITCHBOARD_PORT\n );\n}\n\n/** Resolve the Vetra Connect port through the same chain. */\nexport function resolveConnectPortDefault(): number {\n loadProjectEnv();\n return (\n readPortEnv(\"PH_VETRA_CONNECT_PORT\") ??\n getConfig().vetra?.connectPort ??\n DEFAULT_VETRA_CONNECT_PORT\n );\n}\n\nexport const vetraArgs = {\n switchboardPort: option({\n type: number,\n long: \"switchboard-port\",\n description: \"port to use for the Vetra Switchboard\",\n defaultValue: resolveSwitchboardPortDefault,\n }),\n connectPort: option({\n type: number,\n long: \"connect-port\",\n // Deliberately not `defaultValueIsSerializable`: the value is now\n // per-project, and cmd-ts prints serializable defaults into `--help`,\n // which would bake one project's port into the help text.\n description: \"port to use for the Vetra Connect\",\n defaultValue: resolveConnectPortDefault,\n }),\n remoteDrive: option({\n type: optional(string),\n long: \"remote-drive\",\n description:\n \"URL of remote drive to connect to (skips switchboard initialization)\",\n defaultValue: () => {\n const baseConfig = getConfig();\n return baseConfig.vetra?.driveUrl;\n },\n }),\n watch: flag({\n type: boolean,\n long: \"watch\",\n short: \"w\",\n description:\n \"Enable dynamic loading for document-models and editors in connect-studio and switchboard\",\n defaultValue: () => false,\n defaultValueIsSerializable: true,\n }),\n verbose: flag({\n type: boolean,\n long: \"logs\",\n description: \"Show additional logs\",\n defaultValue: () => false,\n defaultValueIsSerializable: true,\n }),\n restart: flag({\n type: boolean,\n long: \"restart\",\n description:\n \"Stop this project's running Vetra first (the pid in .ph/vetra-runtime.json), then start\",\n defaultValue: () => false,\n defaultValueIsSerializable: true,\n }),\n disableConnect: flag({\n type: boolean,\n long: \"disable-connect\",\n description:\n \"Skip Connect initialization (only start switchboard and reactor)\",\n defaultValue: () => false,\n defaultValueIsSerializable: true,\n }),\n interactive: flag({\n type: boolean,\n long: \"interactive\",\n description:\n \"Enable interactive mode for code generation (requires user confirmation before generating code)\",\n defaultValue: () => false,\n defaultValueIsSerializable: true,\n }),\n drivesPublicBase: option({\n type: optional(string),\n long: \"drives-public-base\",\n description:\n \"public base URL for the drive URLs advertised to Connect; each drive is exposed as <base>/d/<slug> instead of http://localhost:<switchboard-port>/d/<slug>. Use when the switchboard is reachable through a reverse proxy.\",\n }),\n dbPath: option({\n type: optional(string),\n long: \"db-path\",\n description:\n \"Database path or connection string. Use a `postgres://` URL for Postgres; otherwise treated as a PGlite filesystem path. Leave unset for in-memory PGlite.\",\n }),\n renownNamespace,\n ...commonArgs,\n ...commonServerArgs,\n ...vetraSwitchboardArgs,\n};\n"],"mappings":";;;;;AAGA,IAAI;AACJ,IAAI;;;AAIJ,SAAgB,iBACd,MAA0C,QAAQ,KACzC;CACT,MAAM,QAAQ,IAAI,cAAc,KAAK,CAAC,CAAC,YAAY;CACnD,OAAO,UAAU,OAAO,UAAU;AACpC;;;;;;;;;;;;;AAcA,SAAgB,eAAe,MAAc,QAAQ,IAAI,GAAS;CAChE,IAAI,iBAAiB,GAAG;CACxB,IAAI,cAAc,KAAK;CACvB,YAAY;CACZ,oBAAoB,IAAI,IAAI,OAAO,KAAK,QAAQ,GAAG,CAAC;CAGpD,OAAO,OAAO,EAAE,MAAM,KAAK,KAAK,YAAY,EAAE,CAAC;CAC/C,OAAO,OAAO,EAAE,MAAM,KAAK,KAAK,MAAM,EAAE,CAAC;AAC3C;;;;;;;;AAqBA,SAAgB,YAAY,MAAkC;CAC5D,MAAM,MAAM,QAAQ,IAAI,KAAK,EAAE,KAAK;CACpC,IAAI,CAAC,OAAO,CAAC,QAAQ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AAM;EACN,aACE;CACJ,CAAC;CACD;CACA,GAAG;CACH,GAAG;CACH,GAAG;AACL"}
@@ -1,2 +1,2 @@
1
- import { n as resolveSwitchboardPortDefault, r as vetraArgs, t as resolveConnectPortDefault } from "./vetra-DlAEC_Mv.mjs";
1
+ import { n as resolveSwitchboardPortDefault, r as vetraArgs, t as resolveConnectPortDefault } from "./vetra-BqjDopAP.mjs";
2
2
  export { resolveConnectPortDefault, resolveSwitchboardPortDefault, vetraArgs };
@@ -1,4 +1,4 @@
1
- import { t as Manifest } from "./types-B-2NDvpx.mjs";
1
+ import { t as Manifest } from "./types-DXqOePw5.mjs";
2
2
  import { t as InlineConfig } from "./index-DnZYG-8g.mjs";
3
3
  //#region clis/external-deps.d.mts
4
4
  /** The files one module needs at run time, and why each was included. */
@@ -67,6 +67,13 @@ export type PiecePlan = {
67
67
  export type PieceBuildTarget = {
68
68
  projectRoot: string;
69
69
  outDir: string;
70
+ /**
71
+ * @experimental Absolute: the directory that stands in for
72
+ * `<projectRoot>/<outDir>` on disk during this build. Every path the build
73
+ * names stays under `outDir`. Experimental while staged builds are
74
+ * introduced.
75
+ */
76
+ writeTo?: string;
70
77
  pieces: PiecePlan[];
71
78
  };
72
79
  export type PackagePiece = {
@@ -119,7 +126,7 @@ export declare function expandEntryGlobs(root: string, globs: string[]): string[
119
126
  export declare function planPieces(projectRoot: string, outDir: string): PiecePlan[];
120
127
  export declare function createJsonReplacer(): (this: unknown, _key: string, value: unknown) => {} | null | undefined;
121
128
  export declare const DESCRIBE_HELPERS = "\nconst isRecord = (value) => typeof value === \"object\" && value !== null;\n\nfunction findPiece(mod) {\n const candidates = [\n ...Object.values(mod),\n ...(isRecord(mod.default) ? Object.values(mod.default) : []),\n mod.default,\n ];\n for (const candidate of candidates) {\n if (isRecord(candidate) && candidate.constructor?.name === \"Piece\") {\n return candidate;\n }\n }\n for (const candidate of candidates) {\n if (\n isRecord(candidate) &&\n typeof candidate.displayName === \"string\" &&\n (isRecord(candidate.actions) ||\n typeof candidate.actions === \"function\" ||\n typeof candidate.getAction === \"function\")\n ) {\n return candidate;\n }\n }\n return undefined;\n}\n\nfunction describePiece(piece) {\n if (typeof piece.metadata === \"function\") return piece.metadata();\n const call = (value) => (typeof value === \"function\" ? value.call(piece) : value);\n return {\n displayName: piece.displayName,\n logoUrl: piece.logoUrl,\n description: piece.description,\n authors: piece.authors,\n categories: piece.categories,\n auth: piece.auth,\n minimumSupportedRelease: piece.minimumSupportedRelease,\n maximumSupportedRelease: piece.maximumSupportedRelease,\n deprecated: piece.deprecated,\n actions: call(piece.actions) ?? {},\n triggers: call(piece.triggers) ?? {},\n };\n}\n\nfunction createJsonReplacer() {\n const ancestors = [];\n return function replace(_key, value) {\n if (typeof value === \"function\" || value === undefined) return undefined;\n if (typeof value === \"bigint\") return value.toString();\n if (typeof value !== \"object\" || value === null) return value;\n while (ancestors.length > 0 && ancestors.at(-1) !== this) ancestors.pop();\n if (ancestors.includes(value)) return undefined;\n ancestors.push(value);\n return value;\n };\n}\n";
122
- export declare const DESCRIBE_SCRIPT = "\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { isAbsolute, join } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nconst job = JSON.parse(readFileSync(process.argv[2], \"utf8\"));\n\nconst isRecord = (value) => typeof value === \"object\" && value !== null;\n\nfunction findPiece(mod) {\n const candidates = [\n ...Object.values(mod),\n ...(isRecord(mod.default) ? Object.values(mod.default) : []),\n mod.default,\n ];\n for (const candidate of candidates) {\n if (isRecord(candidate) && candidate.constructor?.name === \"Piece\") {\n return candidate;\n }\n }\n for (const candidate of candidates) {\n if (\n isRecord(candidate) &&\n typeof candidate.displayName === \"string\" &&\n (isRecord(candidate.actions) ||\n typeof candidate.actions === \"function\" ||\n typeof candidate.getAction === \"function\")\n ) {\n return candidate;\n }\n }\n return undefined;\n}\n\nfunction describePiece(piece) {\n if (typeof piece.metadata === \"function\") return piece.metadata();\n const call = (value) => (typeof value === \"function\" ? value.call(piece) : value);\n return {\n displayName: piece.displayName,\n logoUrl: piece.logoUrl,\n description: piece.description,\n authors: piece.authors,\n categories: piece.categories,\n auth: piece.auth,\n minimumSupportedRelease: piece.minimumSupportedRelease,\n maximumSupportedRelease: piece.maximumSupportedRelease,\n deprecated: piece.deprecated,\n actions: call(piece.actions) ?? {},\n triggers: call(piece.triggers) ?? {},\n };\n}\n\nfunction createJsonReplacer() {\n const ancestors = [];\n return function replace(_key, value) {\n if (typeof value === \"function\" || value === undefined) return undefined;\n if (typeof value === \"bigint\") return value.toString();\n if (typeof value !== \"object\" || value === null) return value;\n while (ancestors.length > 0 && ancestors.at(-1) !== this) ancestors.pop();\n if (ancestors.includes(value)) return undefined;\n ancestors.push(value);\n return value;\n };\n}\n\n// Says why the child gave up in the one place the parent always reads, so a\n// failure reports the cause and never the text of this script.\nfunction fail(message) {\n writeFileSync(job.outFile, JSON.stringify({ fatal: message }));\n process.exit(1);\n}\n\n// The module to load for a list entry; a bundle names its own main.\nfunction entryFile(piece) {\n const declared = piece.entry ?? piece.bundle;\n if (typeof declared !== \"string\") return undefined;\n const path = isAbsolute(declared) ? declared : join(job.projectRoot, declared);\n if (piece.entry) return path;\n const pkgFile = join(path, \"package.json\");\n if (!existsSync(pkgFile)) return undefined;\n const pkg = JSON.parse(readFileSync(pkgFile, \"utf8\"));\n return join(path, typeof pkg.main === \"string\" ? pkg.main : \"index.mjs\");\n}\n\nlet listModule;\ntry {\n listModule = await import(pathToFileURL(job.listPath).href);\n} catch (error) {\n fail(job.listPath + \" threw on import: \" + (error instanceof Error ? error.message : String(error)));\n}\nconst list = listModule.pieces ?? listModule.default;\nif (!Array.isArray(list)) {\n fail(job.listPath + ' exports no \"pieces\" array');\n}\n\nconst out = { list, pieces: [], errors: [] };\nfor (const piece of list) {\n const file = entryFile(piece);\n // A missing file is the parent's to report, with the message it owns.\n if (!file || !existsSync(file)) continue;\n try {\n const mod = await import(pathToFileURL(file).href);\n const found = findPiece(mod);\n if (!found) {\n throw new Error(\n \"no Piece export found in \" + file + \"; exports: \" + Object.keys(mod).join(\", \"),\n );\n }\n const metadata = JSON.parse(JSON.stringify(describePiece(found), createJsonReplacer()));\n out.pieces.push({ name: piece.name, metadata });\n } catch (error) {\n out.errors.push({\n name: piece.name,\n message: error instanceof Error ? error.message : String(error),\n });\n }\n}\nwriteFileSync(job.outFile, JSON.stringify(out, createJsonReplacer()));\n";
129
+ export declare const DESCRIBE_SCRIPT = "\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { isAbsolute, join, relative, sep } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nconst job = JSON.parse(readFileSync(process.argv[2], \"utf8\"));\n\nconst isRecord = (value) => typeof value === \"object\" && value !== null;\n\nfunction findPiece(mod) {\n const candidates = [\n ...Object.values(mod),\n ...(isRecord(mod.default) ? Object.values(mod.default) : []),\n mod.default,\n ];\n for (const candidate of candidates) {\n if (isRecord(candidate) && candidate.constructor?.name === \"Piece\") {\n return candidate;\n }\n }\n for (const candidate of candidates) {\n if (\n isRecord(candidate) &&\n typeof candidate.displayName === \"string\" &&\n (isRecord(candidate.actions) ||\n typeof candidate.actions === \"function\" ||\n typeof candidate.getAction === \"function\")\n ) {\n return candidate;\n }\n }\n return undefined;\n}\n\nfunction describePiece(piece) {\n if (typeof piece.metadata === \"function\") return piece.metadata();\n const call = (value) => (typeof value === \"function\" ? value.call(piece) : value);\n return {\n displayName: piece.displayName,\n logoUrl: piece.logoUrl,\n description: piece.description,\n authors: piece.authors,\n categories: piece.categories,\n auth: piece.auth,\n minimumSupportedRelease: piece.minimumSupportedRelease,\n maximumSupportedRelease: piece.maximumSupportedRelease,\n deprecated: piece.deprecated,\n actions: call(piece.actions) ?? {},\n triggers: call(piece.triggers) ?? {},\n };\n}\n\nfunction createJsonReplacer() {\n const ancestors = [];\n return function replace(_key, value) {\n if (typeof value === \"function\" || value === undefined) return undefined;\n if (typeof value === \"bigint\") return value.toString();\n if (typeof value !== \"object\" || value === null) return value;\n while (ancestors.length > 0 && ancestors.at(-1) !== this) ancestors.pop();\n if (ancestors.includes(value)) return undefined;\n ancestors.push(value);\n return value;\n };\n}\n\n// The parent's onDisk, for the paths a list names under the output directory.\nfunction onDisk(path) {\n if (!job.redirect) return path;\n const inside = relative(job.redirect.from, path);\n const leaves = inside === \"..\" || inside.startsWith(\"..\" + sep) || isAbsolute(inside);\n return leaves ? path : join(job.redirect.to, inside);\n}\n\n// Says why the child gave up in the one place the parent always reads, so a\n// failure reports the cause and never the text of this script.\nfunction fail(message) {\n writeFileSync(job.outFile, JSON.stringify({ fatal: message }));\n process.exit(1);\n}\n\n// The module to load for a list entry; a bundle names its own main.\nfunction entryFile(piece) {\n const declared = piece.entry ?? piece.bundle;\n if (typeof declared !== \"string\") return undefined;\n const path = isAbsolute(declared) ? declared : join(job.projectRoot, declared);\n if (piece.entry) return path;\n const pkgFile = join(onDisk(path), \"package.json\");\n if (!existsSync(pkgFile)) return undefined;\n const pkg = JSON.parse(readFileSync(pkgFile, \"utf8\"));\n return join(path, typeof pkg.main === \"string\" ? pkg.main : \"index.mjs\");\n}\n\nlet listModule;\ntry {\n listModule = await import(pathToFileURL(onDisk(job.listPath)).href);\n} catch (error) {\n fail(job.listPath + \" threw on import: \" + (error instanceof Error ? error.message : String(error)));\n}\nconst list = listModule.pieces ?? listModule.default;\nif (!Array.isArray(list)) {\n fail(job.listPath + ' exports no \"pieces\" array');\n}\n\nconst out = { list, pieces: [], errors: [] };\nfor (const piece of list) {\n const file = entryFile(piece);\n // A missing file is the parent's to report, with the message it owns.\n if (!file || !existsSync(onDisk(file))) continue;\n try {\n const mod = await import(pathToFileURL(onDisk(file)).href);\n const found = findPiece(mod);\n if (!found) {\n throw new Error(\n \"no Piece export found in \" + file + \"; exports: \" + Object.keys(mod).join(\", \"),\n );\n }\n const metadata = JSON.parse(JSON.stringify(describePiece(found), createJsonReplacer()));\n out.pieces.push({ name: piece.name, metadata });\n } catch (error) {\n out.errors.push({\n name: piece.name,\n message: error instanceof Error ? error.message : String(error),\n });\n }\n}\nwriteFileSync(job.outFile, JSON.stringify(out, createJsonReplacer()));\n";
123
130
  export declare function describePieces(projectRoot: string, listPath: string): DescribeResult;
124
131
  export type PieceLocation = {
125
132
  /** The piece directory, absolute. */
@@ -1 +1 @@
1
- {"version":3,"file":"build-pieces.d.mts","names":[],"sources":["../../clis/external-deps.mts","../../clis/build-pieces.mts"],"mappings":";;;;KAQY;;EAEV,UAAU;;EAEV,SAAS;IAAc,SAAS;;;;KAItB,cAAc,iBAAiB,QAAQ;;KAGvC;EAAiB;EAAc;;KAE/B,qBAAqB;EAC/B;EACA;;EAEA;;;KAIU;EACV,OAAO,YAAY,QAAQ;EAC3B,MAAM;;qBAGK,4BAA2B;KAK5B;;EAEV;;EAEA;;EAEA;;EAEA;EACA,QAAQ;;KAGL,SAAS,YAAY;;wBAaV,YAAY,cAAc;;wBAwEpB,iBACpB,eACA,OAAO,YACP,QAAQ,iBACP,QAAQ;;wBAmDK,mBACd,OAAO,YACP,OAAO,YAAY,qBACnB,UAAS,4BACR;;;;;wBA8Da,+BACd,OAAO,SAAS,qBAChB,KAAK,QACH,qEAEE,QAAQ,4BAGX;;wBAUa,2BACd,OAAO,SAAS,sBACf;;;YCjOS;;EAEV;;EAEA;;EAEA;;YAKU;EACV;EACA;EACA,QAAQ;;YAKE;EACV;EACA;EACA;;YAKU,gBAAgB;EAC1B;EACA;EACA,UAAU;EACV,WAAW;;YAGD;EACV;EACA,UAAU;;YAGA;EACV,MAAM;EACN,QAAQ;EACR;IAAU;IAAc;;;YAGd;EACV;EACA;EACA;EACA;;EAEA;;EAEA;;YAGU;EACV;EACA;EACA;;YAGU;;EAEV,SAAS,QAAQ,iBAAiB;;EAElC,QAAQ;EACR,QAAQ;;wBAKM,SAAS,8BAAS;wBAUlB,iBAAiB,cAAc;wBA4B/B,WAAW,qBAAqB,iBAAiB;wBAejD,uBAAkB,eAEK,cAAc;qBAiBxC;qBAiEA;wBAsFG,eACd,qBACA,mBACC;YA0BS;;EAEV;;EAEA;EACA;;wBAKc,qBACd,OAAO,cACP,qBACA,iBACC;wBAmCa,cAAc;EAC5B;EACA;;wBAac,mBAAmB;EACjC;EACA,QAAQ;;wBAWM,mBACd,OAAO,cACP,KAAK;wBAWS,iBAAiB;EAC/B;EACA;EACA;EACA;EACA;EACA,eAAe;IACb;wBAeY,kBACd,aACA,kBACC;wBASa,gBACd,OAAO,cACP,iBACA,UAAU,gBACT;wBAUa,qBACd,UAAU,UACV,OAAO;EACJ,UAAU;EAAU;;wBAkCH,YACpB,QAAQ,kBACR,KAAK,iBACL,SAAS,oBACR,QAAQ;wBAgIK,iBACd,QAAQ,kBACR,OAAO,cACP,uBAAsB"}
1
+ {"version":3,"file":"build-pieces.d.mts","names":[],"sources":["../../clis/external-deps.mts","../../clis/build-pieces.mts"],"mappings":";;;;KAQY;;EAEV,UAAU;;EAEV,SAAS;IAAc,SAAS;;;;KAItB,cAAc,iBAAiB,QAAQ;;KAGvC;EAAiB;EAAc;;KAE/B,qBAAqB;EAC/B;EACA;;EAEA;;;KAIU;EACV,OAAO,YAAY,QAAQ;EAC3B,MAAM;;qBAGK,4BAA2B;KAK5B;;EAEV;;EAEA;;EAEA;;EAEA;EACA,QAAQ;;KAGL,SAAS,YAAY;;wBAaV,YAAY,cAAc;;wBAwEpB,iBACpB,eACA,OAAO,YACP,QAAQ,iBACP,QAAQ;;wBAmDK,mBACd,OAAO,YACP,OAAO,YAAY,qBACnB,UAAS,4BACR;;;;;wBA8Da,+BACd,OAAO,SAAS,qBAChB,KAAK,QACH,qEAEE,QAAQ,4BAGX;;wBAUa,2BACd,OAAO,SAAS,sBACf;;;YChOS;;EAEV;;EAEA;;EAEA;;YAKU;EACV;EACA;;;;;;;EAOA;EACA,QAAQ;;YAKE;EACV;EACA;EACA;;YAKU,gBAAgB;EAC1B;EACA;EACA,UAAU;EACV,WAAW;;YAGD;EACV;EACA,UAAU;;YAGA;EACV,MAAM;EACN,QAAQ;EACR;IAAU;IAAc;;;YAGd;EACV;EACA;EACA;EACA;;EAEA;;EAEA;;YAGU;EACV;EACA;EACA;;YAGU;;EAEV,SAAS,QAAQ,iBAAiB;;EAElC,QAAQ;EACR,QAAQ;;wBAiCM,SAAS,8BAAS;wBAkBlB,iBAAiB,cAAc;wBA4B/B,WAAW,qBAAqB,iBAAiB;wBAejD,uBAAkB,eAEK,cAAc;qBAiBxC;qBAiEA;wBA8FG,eACd,qBACA,mBACC;YAqCS;;EAEV;;EAEA;EACA;;wBAKc,qBACd,OAAO,cACP,qBACA,iBACC;wBAgDa,cAAc;EAC5B;EACA;;wBAac,mBAAmB;EACjC;EACA,QAAQ;;wBAWM,mBACd,OAAO,cACP,KAAK;wBAWS,iBAAiB;EAC/B;EACA;EACA;EACA;EACA;EACA,eAAe;IACb;wBAeY,kBACd,aACA,kBACC;wBASa,gBACd,OAAO,cACP,iBACA,UAAU,gBACT;wBAUa,qBACd,UAAU,UACV,OAAO;EACJ,UAAU;EAAU;;wBAkCH,YACpB,QAAQ,kBACR,KAAK,iBACL,SAAS,oBACR,QAAQ;wBAwIK,iBACd,QAAQ,kBACR,OAAO,cACP,uBAAsB"}
@@ -163,6 +163,21 @@ function externalDependencyVersions(found) {
163
163
  //#endregion
164
164
  //#region clis/build-pieces.mts
165
165
  const toPosix = (p) => p.split(sep).join("/");
166
+ /** `relative(dir, path)` leaves `dir`: `..`, `../…`, or another root. */
167
+ const leaves = (inside) => inside === ".." || inside.startsWith(`..${sep}`) || isAbsolute(inside);
168
+ function onDisk(path, redirect) {
169
+ if (!redirect) return path;
170
+ const inside = relative(redirect.from, path);
171
+ return leaves(inside) ? path : join(redirect.to, inside);
172
+ }
173
+ function toLogical(path, redirect) {
174
+ if (!redirect) return path;
175
+ for (const dir of [redirect.to, redirect.toReal]) {
176
+ const inside = relative(dir, path);
177
+ if (!leaves(inside)) return join(redirect.from, inside);
178
+ }
179
+ return path;
180
+ }
166
181
  function statSafe(p) {
167
182
  try {
168
183
  return statSync(p);
@@ -170,6 +185,13 @@ function statSafe(p) {
170
185
  return null;
171
186
  }
172
187
  }
188
+ function realpathSafe(p) {
189
+ try {
190
+ return realpathSync(p);
191
+ } catch {
192
+ return p;
193
+ }
194
+ }
173
195
  function expandEntryGlobs(root, globs) {
174
196
  const files = /* @__PURE__ */ new Set();
175
197
  for (const pattern of globs) {
@@ -271,11 +293,19 @@ function createJsonReplacer() {
271
293
  `;
272
294
  const DESCRIBE_SCRIPT = `
273
295
  import { existsSync, readFileSync, writeFileSync } from "node:fs";
274
- import { isAbsolute, join } from "node:path";
296
+ import { isAbsolute, join, relative, sep } from "node:path";
275
297
  import { pathToFileURL } from "node:url";
276
298
 
277
299
  const job = JSON.parse(readFileSync(process.argv[2], "utf8"));
278
300
  ${DESCRIBE_HELPERS}
301
+ // The parent's onDisk, for the paths a list names under the output directory.
302
+ function onDisk(path) {
303
+ if (!job.redirect) return path;
304
+ const inside = relative(job.redirect.from, path);
305
+ const leaves = inside === ".." || inside.startsWith(".." + sep) || isAbsolute(inside);
306
+ return leaves ? path : join(job.redirect.to, inside);
307
+ }
308
+
279
309
  // Says why the child gave up in the one place the parent always reads, so a
280
310
  // failure reports the cause and never the text of this script.
281
311
  function fail(message) {
@@ -289,7 +319,7 @@ function entryFile(piece) {
289
319
  if (typeof declared !== "string") return undefined;
290
320
  const path = isAbsolute(declared) ? declared : join(job.projectRoot, declared);
291
321
  if (piece.entry) return path;
292
- const pkgFile = join(path, "package.json");
322
+ const pkgFile = join(onDisk(path), "package.json");
293
323
  if (!existsSync(pkgFile)) return undefined;
294
324
  const pkg = JSON.parse(readFileSync(pkgFile, "utf8"));
295
325
  return join(path, typeof pkg.main === "string" ? pkg.main : "index.mjs");
@@ -297,7 +327,7 @@ function entryFile(piece) {
297
327
 
298
328
  let listModule;
299
329
  try {
300
- listModule = await import(pathToFileURL(job.listPath).href);
330
+ listModule = await import(pathToFileURL(onDisk(job.listPath)).href);
301
331
  } catch (error) {
302
332
  fail(job.listPath + " threw on import: " + (error instanceof Error ? error.message : String(error)));
303
333
  }
@@ -310,9 +340,9 @@ const out = { list, pieces: [], errors: [] };
310
340
  for (const piece of list) {
311
341
  const file = entryFile(piece);
312
342
  // A missing file is the parent's to report, with the message it owns.
313
- if (!file || !existsSync(file)) continue;
343
+ if (!file || !existsSync(onDisk(file))) continue;
314
344
  try {
315
- const mod = await import(pathToFileURL(file).href);
345
+ const mod = await import(pathToFileURL(onDisk(file)).href);
316
346
  const found = findPiece(mod);
317
347
  if (!found) {
318
348
  throw new Error(
@@ -340,6 +370,9 @@ function childFailure(error, outFile) {
340
370
  return `the describe child exited with code ${status ?? "unknown"}`;
341
371
  }
342
372
  function describePieces(projectRoot, listPath) {
373
+ return describePiecesThrough(projectRoot, listPath, void 0);
374
+ }
375
+ function describePiecesThrough(projectRoot, listPath, redirect) {
343
376
  const dir = mkdtempSync(join(tmpdir(), "ph-build-pieces-"));
344
377
  const rel = toPosix(relative(projectRoot, listPath));
345
378
  try {
@@ -350,7 +383,8 @@ function describePieces(projectRoot, listPath) {
350
383
  writeFileSync(jobFile, JSON.stringify({
351
384
  projectRoot,
352
385
  listPath,
353
- outFile
386
+ outFile,
387
+ redirect
354
388
  }));
355
389
  try {
356
390
  execFileSync(process.execPath, [scriptFile, jobFile], {
@@ -369,17 +403,22 @@ function describePieces(projectRoot, listPath) {
369
403
  }
370
404
  }
371
405
  function resolvePieceLocation(piece, projectRoot, outDir) {
406
+ return locatePieceThrough(piece, projectRoot, outDir, void 0);
407
+ }
408
+ function locatePieceThrough(piece, projectRoot, outDir, redirect) {
372
409
  const declared = piece.entry ?? piece.bundle;
373
410
  if (typeof declared !== "string" || declared === "") throw new Error(`pieces: "${piece.name}" declares neither an entry nor a bundle`);
374
- const path = isAbsolute(declared) ? declared : join(projectRoot, declared);
411
+ const shown = isAbsolute(declared) ? toLogical(declared, redirect) : declared;
412
+ const path = isAbsolute(declared) ? shown : join(projectRoot, declared);
375
413
  const form = piece.entry ? "entry" : "bundle";
376
- if (!(form === "entry" ? statSafe(path)?.isFile() : statSafe(join(path, "package.json"))?.isFile())) throw new Error(`pieces: "${piece.name}" declares ${declared}, which is missing`);
414
+ const disk = onDisk(path, redirect);
415
+ if (!(form === "entry" ? statSafe(disk)?.isFile() : statSafe(join(disk, "package.json"))?.isFile())) throw new Error(`pieces: "${piece.name}" declares ${shown}, which is missing`);
377
416
  const dir = form === "entry" ? dirname(path) : path;
378
417
  const piecesRoot = resolve(projectRoot, outDir, "node", "pieces");
379
418
  const inside = relative(piecesRoot, dir);
380
419
  if (inside === "" || inside.startsWith("..") || isAbsolute(inside)) {
381
420
  const expected = toPosix(join(outDir, "node", "pieces"));
382
- throw new Error(`pieces: "${piece.name}" declares ${declared}, which is outside ${expected}/; a piece is built to ${expected}/<dir>/index.mjs and its entry must point there`);
421
+ throw new Error(`pieces: "${piece.name}" declares ${shown}, which is outside ${expected}/; a piece is built to ${expected}/<dir>/index.mjs and its entry must point there`);
383
422
  }
384
423
  return form === "entry" ? {
385
424
  dir,
@@ -459,6 +498,11 @@ const count = (record) => typeof record === "object" && record !== null ? Object
459
498
  async function buildPieces(target, pkg, options) {
460
499
  const { projectRoot, outDir } = target;
461
500
  assertPiecesOutDir(target);
501
+ const redirect = target.writeTo ? {
502
+ from: resolve(projectRoot, outDir),
503
+ to: target.writeTo,
504
+ toReal: realpathSafe(target.writeTo)
505
+ } : void 0;
462
506
  const externalByDir = /* @__PURE__ */ new Map();
463
507
  for (const piece of target.pieces) {
464
508
  console.log(`\n▶ Building piece ${piece.dir}...`);
@@ -466,7 +510,7 @@ async function buildPieces(target, pkg, options) {
466
510
  const external = /* @__PURE__ */ new Map();
467
511
  await options.bundle(buildPieceBuildConfig({
468
512
  entry: resolve(projectRoot, piece.entry),
469
- outDir,
513
+ outDir: onDisk(outDir, redirect),
470
514
  ...options.trace ? { plugins: [externalDepsPlugin(options.trace, external, {
471
515
  root: projectRoot,
472
516
  ...options.cache ? { cache: options.cache } : {}
@@ -476,12 +520,13 @@ async function buildPieces(target, pkg, options) {
476
520
  externalByDir.set(outDir, external);
477
521
  }
478
522
  const listPath = pieceListPath(target);
479
- if (!existsSync(listPath)) throw new Error(`pieces: ${toPosix(relative(projectRoot, listPath))} was not built; pieces/index.ts must export the list of pieces this package ships`);
480
- const described = describePieces(projectRoot, listPath);
523
+ if (!existsSync(onDisk(listPath, redirect))) throw new Error(`pieces: ${toPosix(relative(projectRoot, listPath))} was not built; pieces/index.ts must export the list of pieces this package ships`);
524
+ const described = describePiecesThrough(projectRoot, listPath, redirect);
481
525
  const built = [];
482
526
  const listedDirs = /* @__PURE__ */ new Set();
483
527
  for (const piece of described.list) {
484
- const location = resolvePieceLocation(piece, projectRoot, outDir);
528
+ const location = locatePieceThrough(piece, projectRoot, outDir, redirect);
529
+ const dirOnDisk = onDisk(location.dir, redirect);
485
530
  assertPieceVersion(piece, pkg);
486
531
  const failure = described.errors.find((e) => e.name === piece.name);
487
532
  if (failure) throw new Error(`pieces: "${piece.name}" could not be described: ${failure.message}`);
@@ -490,7 +535,7 @@ async function buildPieces(target, pkg, options) {
490
535
  const metadata = found.metadata;
491
536
  const relDir = toPosix(relative(projectRoot, location.dir));
492
537
  listedDirs.add(relDir);
493
- writeFileSync(join(location.dir, "descriptor.json"), JSON.stringify(pieceDescriptor(piece, pkg.version, metadata), createJsonReplacer(), 2) + "\n");
538
+ writeFileSync(join(dirOnDisk, "descriptor.json"), JSON.stringify(pieceDescriptor(piece, pkg.version, metadata), createJsonReplacer(), 2) + "\n");
494
539
  const piecePackage = location.form === "entry" && location.entryFile ? piecePackageJson({
495
540
  name: piece.name,
496
541
  version: pkg.version,
@@ -498,8 +543,8 @@ async function buildPieces(target, pkg, options) {
498
543
  main: relative(location.dir, location.entryFile),
499
544
  license: pkg.license,
500
545
  dependencies: externalDependencyVersions(externalByDir.get(resolve(location.dir))?.values() ?? [])
501
- }) : bundlePackageJson(location.dir, pkg.version);
502
- writeFileSync(join(location.dir, "package.json"), JSON.stringify(piecePackage, null, 2) + "\n");
546
+ }) : bundlePackageJson(dirOnDisk, pkg.version);
547
+ writeFileSync(join(dirOnDisk, "package.json"), JSON.stringify(piecePackage, null, 2) + "\n");
503
548
  console.log(`piece: ${piece.name}@${pkg.version} -> ${relDir} (${count(metadata.actions)} actions, ${count(metadata.triggers)} triggers)`);
504
549
  built.push({
505
550
  name: piece.name,
@@ -1 +1 @@
1
- {"version":3,"file":"build-pieces.mjs","names":[],"sources":["../../clis/external-deps.mts","../../clis/build-pieces.mts"],"sourcesContent":["// External dependencies: a package whose code needs a native addon or a\n// WebAssembly module cannot be inlined, so it stays a bare import the host installs.\nimport { readdirSync, readFileSync, realpathSync } from \"node:fs\";\nimport { isBuiltin } from \"node:module\";\nimport { isAbsolute, join, relative, sep } from \"node:path\";\nimport type { InlineConfig } from \"tsdown\";\n\n/** The files one module needs at run time, and why each was included. */\nexport type FileTrace = {\n /** Absolute paths. */\n fileList: Set<string>;\n /** Absolute path -> the absolute paths of the files that pulled it in. */\n reasons: Map<string, { parents: Set<string> }>;\n};\n\n/** Traces one file: @vercel/nft's nodeFileTrace, handed in by the CLI. */\nexport type TraceFiles = (file: string) => Promise<FileTrace>;\n\n/** A file the bundle cannot carry: a native addon or a WebAssembly module. */\nexport type RequiredFile = { file: string; kind: \"native\" | \"wasm\" };\n\nexport type ExternalDependency = RequiredFile & {\n name: string;\n version: string;\n /** The first of the package's own files seen importing it. */\n importer?: string;\n};\n\n/** What one `ph build` learns about packages, shared by all of its builds. */\nexport type DetectionCache = {\n files: Map<string, Promise<RequiredFile | undefined>>;\n wasm: Map<string, string | undefined>;\n};\n\nexport const createDetectionCache = (): DetectionCache => ({\n files: new Map(),\n wasm: new Map(),\n});\n\nexport type ExternalDepsPluginOptions = {\n /** The project root the dirs below are relative to. */\n root?: string;\n /** Browser build: a native package fails it; WebAssembly is bundled. */\n browser?: boolean;\n /** Dirs whose imports the bundler handles as usual: code no host runs. */\n ignoreDirs?: string[];\n /** Dirs that may not import a native or WebAssembly package. */\n forbidDirs?: string[];\n cache?: DetectionCache;\n};\n\ntype Plugin = NonNullable<InlineConfig[\"plugins\"]>;\n\ntype PackageJson = {\n name?: string;\n version?: string;\n dependencies?: Record<string, string>;\n optionalDependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n};\n\nconst NODE_MODULES = `${sep}node_modules${sep}`;\n\n/** `file` relative to `root`, with forward slashes on every platform. */\nexport function projectPath(root: string, file: string): string {\n return relative(root, file).split(sep).join(\"/\");\n}\n\n// Windows paths compare case-insensitively, drive letter included.\nconst samePath = (file: string) =>\n process.platform === \"win32\" ? file.toLowerCase() : file;\n\n// \"@scope/name/sub\" -> \"@scope/name\", \"name/sub\" -> \"name\".\nexport function packageNameOf(specifier: string): string | undefined {\n if (specifier.startsWith(\".\") || isAbsolute(specifier)) return undefined;\n const parts = specifier.split(\"/\");\n const name = specifier.startsWith(\"@\")\n ? parts.slice(0, 2).join(\"/\")\n : parts[0];\n return name || undefined;\n}\n\n// The root of the installed package a file belongs to, if it is in one.\nexport function packageRootOf(file: string): string | undefined {\n const at = file.lastIndexOf(NODE_MODULES);\n if (at < 0) return undefined;\n const rest = file.slice(at + NODE_MODULES.length).split(sep);\n const depth = rest[0]?.startsWith(\"@\") ? 2 : 1;\n if (rest.length <= depth) return undefined;\n return join(file.slice(0, at + NODE_MODULES.length), ...rest.slice(0, depth));\n}\n\nfunction readPackageJson(root: string): PackageJson | undefined {\n try {\n return JSON.parse(\n readFileSync(join(root, \"package.json\"), \"utf8\"),\n ) as PackageJson;\n } catch {\n return undefined;\n }\n}\n\n// Only links the importer requires count: an optional peer such as\n// ws -> bufferutil is a speed-up the importer runs without.\nfunction requires(importerRoot: string, importedRoot: string): boolean {\n const importer = readPackageJson(importerRoot);\n const name = readPackageJson(importedRoot)?.name;\n if (!importer || !name) return false;\n return (\n importer.dependencies?.[name] !== undefined ||\n importer.optionalDependencies?.[name] !== undefined\n );\n}\n\n// The first .wasm file in a package's own files. Presence is enough: most\n// packages compute the path or let their caller pass it, so a trace misses it.\nfunction wasmIn(root: string, cache?: DetectionCache): string | undefined {\n if (cache?.wasm.has(root)) return cache.wasm.get(root);\n const found = scanForWasm(root);\n cache?.wasm.set(root, found);\n return found;\n}\n\nfunction scanForWasm(root: string): string | undefined {\n try {\n const found = readdirSync(root, { recursive: true, encoding: \"utf8\" }).find(\n (file) =>\n file.endsWith(\".wasm\") && !file.split(sep).includes(\"node_modules\"),\n );\n return found && join(root, found);\n } catch {\n return undefined;\n }\n}\n\n/** The first file `entry` cannot load without that a bundle cannot carry. */\nexport async function findRequiredFile(\n entry: string,\n trace: TraceFiles,\n cache?: DetectionCache,\n): Promise<RequiredFile | undefined> {\n const { fileList, reasons } = await trace(entry);\n // A tracer reports real paths, and the entry may sit behind a symlink.\n const start = samePath(realpathSync(entry));\n // What to report, and the traced file the walk back to the entry starts at.\n const candidates: (RequiredFile & { from: string })[] = [...fileList]\n .filter((file) => file.endsWith(\".node\"))\n .map((file) => ({ file, kind: \"native\" as const, from: file }));\n {\n const traced = new Map<string, string>();\n for (const file of fileList) {\n const root = packageRootOf(file);\n if (root && !traced.has(root) && /\\.[cm]?js$/.test(file)) {\n traced.set(root, file);\n }\n }\n const tracedWasm = [...fileList].filter((file) => file.endsWith(\".wasm\"));\n for (const [root, from] of traced) {\n const file =\n tracedWasm.find((wasm) => packageRootOf(wasm) === root) ??\n wasmIn(root, cache);\n if (file) candidates.push({ file, kind: \"wasm\", from });\n }\n }\n for (const { from, ...required } of candidates) {\n // Back to the entry, crossing into a parent's package only when that\n // package requires the one being left.\n const seen = new Set([from]);\n const queue = [from];\n while (queue.length > 0) {\n const file = queue.shift()!;\n if (samePath(file) === start) return required;\n for (const parent of reasons.get(file)?.parents ?? []) {\n if (seen.has(parent)) continue;\n const fromRoot = packageRootOf(parent);\n const toRoot = packageRootOf(file);\n if (\n fromRoot !== toRoot &&\n (!fromRoot || !toRoot || !requires(fromRoot, toRoot))\n ) {\n continue;\n }\n seen.add(parent);\n queue.push(parent);\n }\n }\n }\n return undefined;\n}\n\n/** Keeps each package the code imports that needs such a file out of the bundle. */\nexport function externalDepsPlugin(\n trace: TraceFiles,\n found: Map<string, ExternalDependency>,\n options: ExternalDepsPluginOptions = {},\n): Plugin {\n const cache = options.cache ?? createDetectionCache();\n const root = options.root ?? process.cwd();\n const show = (file: string) => projectPath(root, file);\n const inDir = (id: string, dirs: string[] = []) =>\n dirs.some((dir) => show(id).startsWith(`${dir}/`));\n // By resolved file: a package's subpaths can differ in what they load.\n const detect = (id: string) => {\n let verdict = cache.files.get(id);\n if (!verdict) {\n verdict = findRequiredFile(id, trace, cache);\n cache.files.set(id, verdict);\n }\n return verdict;\n };\n return {\n name: \"powerhouse:external-deps\",\n async resolveId(source, importer, extra) {\n // The project's own imports only: whatever a dependency pulls in goes\n // wherever that dependency goes.\n if (!importer || importer.includes(NODE_MODULES)) return null;\n if (isBuiltin(source) || inDir(importer, options.ignoreDirs)) return null;\n const name = packageNameOf(source);\n if (!name) return null;\n const resolved = await this.resolve(source, importer, {\n ...extra,\n skipSelf: true,\n });\n if (!resolved || resolved.external) return null;\n const required = await detect(resolved.id);\n const pkgRoot = packageRootOf(resolved.id);\n const version = pkgRoot ? readPackageJson(pkgRoot)?.version : undefined;\n if (!required || !version) return null;\n const what =\n required.kind === \"native\"\n ? `the native addon ${show(required.file)}`\n : `the WebAssembly module ${show(required.file)}`;\n if (options.browser) {\n if (required.kind === \"wasm\") return null;\n throw new Error(\n `${show(importer)} imports ${name}, which needs ${what}. ` +\n \"Native code cannot run in the browser: import it only from subgraphs, switchboard processors or pieces.\",\n );\n }\n if (inDir(importer, options.forbidDirs)) {\n throw new Error(\n `${show(importer)} imports ${name}, which needs ${what}. ` +\n \"Document models and scalars run in Connect and on every host: use it from a subgraph, processor or piece instead.\",\n );\n }\n if (!found.has(name)) {\n found.set(name, { name, version, ...required, importer });\n }\n return { id: source, external: true };\n },\n };\n}\n\n/**\n * The detected packages `pkg` does not install for its consumers: anything\n * outside dependencies, optionalDependencies and peerDependencies.\n */\nexport function undeclaredExternalDependencies(\n found: Iterable<ExternalDependency>,\n pkg: Partial<\n Record<\n \"dependencies\" | \"optionalDependencies\" | \"peerDependencies\",\n Partial<Record<string, string>>\n >\n >,\n): ExternalDependency[] {\n return [...found].filter(\n (dep) =>\n pkg.dependencies?.[dep.name] === undefined &&\n pkg.optionalDependencies?.[dep.name] === undefined &&\n pkg.peerDependencies?.[dep.name] === undefined,\n );\n}\n\n/** name -> version, sorted by name. */\nexport function externalDependencyVersions(\n found: Iterable<ExternalDependency>,\n): Record<string, string> {\n return Object.fromEntries(\n [...found]\n .sort((a, b) => a.name.localeCompare(b.name))\n .map((dep) => [dep.name, dep.version]),\n );\n}\n","// The pieces half of a package build: find and bundle each piece whole, load\n// it once in a child process to learn what it is, and write what a host reads.\nimport { execFileSync } from \"node:child_process\";\nimport {\n copyFileSync,\n existsSync,\n mkdirSync,\n mkdtempSync,\n readdirSync,\n readFileSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport {\n basename,\n dirname,\n isAbsolute,\n join,\n relative,\n resolve,\n sep,\n} from \"node:path\";\nimport type { InlineConfig } from \"tsdown\";\nimport type { Manifest, PieceModule } from \"../document-model/types.js\";\nimport { buildPieceBuildConfig, PIECE_ENTRY_GLOB } from \"./build-config.mjs\";\nimport {\n externalDependencyVersions,\n externalDepsPlugin,\n projectPath,\n type DetectionCache,\n type ExternalDependency,\n type TraceFiles,\n} from \"./external-deps.mjs\";\n\nexport {\n createDetectionCache,\n projectPath,\n findRequiredFile,\n externalDependencyVersions,\n externalDepsPlugin,\n undeclaredExternalDependencies,\n} from \"./external-deps.mjs\";\nexport type {\n DetectionCache,\n FileTrace,\n ExternalDependency,\n ExternalDepsPluginOptions,\n TraceFiles,\n} from \"./external-deps.mjs\";\n\nexport type PiecePlan = {\n /** The directory under pieces/, and so under <outDir>/node/pieces. */\n dir: string;\n /** Source entry, relative to the project root: pieces/<dir>/index.ts. */\n entry: string;\n /** Where the piece lands, relative to the project root. */\n outDir: string;\n};\n\n// What buildPieces needs to know about the package it works in: where it is,\n// where it builds to, and which pieces the plan found.\nexport type PieceBuildTarget = {\n projectRoot: string;\n outDir: string;\n pieces: PiecePlan[];\n};\n\n// One entry of pieces/index.ts, as @powerhousedao/pieces-framework declares it.\n// Declared here so the build needs no dependency on a package meant for pieces.\nexport type PackagePiece = {\n name: string;\n entry?: string;\n bundle?: string;\n};\n\n// What a piece says about itself, in the framework's PieceMetadata shape.\n// Read from the built piece, so nothing in the build has to know the framework.\nexport type PieceMetadata = Record<string, unknown> & {\n displayName?: string;\n description?: string;\n actions?: Record<string, unknown>;\n triggers?: Record<string, unknown>;\n};\n\nexport type DescribedPiece = {\n name: string;\n metadata: PieceMetadata;\n};\n\nexport type DescribeResult = {\n list: PackagePiece[];\n pieces: DescribedPiece[];\n errors: { name: string; message: string }[];\n};\n\nexport type BuiltPiece = {\n name: string;\n version: string;\n displayName?: string;\n description?: string;\n /** Piece directory, relative to the project root, `/` separated. */\n bundle: string;\n /** The descriptor inside it, relative to the project root, `/` separated. */\n descriptor: string;\n};\n\nexport type PackageIdentity = {\n name: string;\n version: string;\n license?: string;\n};\n\nexport type PieceBuildOptions = {\n /** The bundler: tsdown's `build`, handed in so this module never loads it. */\n bundle: (config: InlineConfig) => Promise<unknown>;\n /** Traces a module's run-time files; without it nothing is kept external. */\n trace?: TraceFiles;\n cache?: DetectionCache;\n};\n\nconst toPosix = (p: string) => p.split(sep).join(\"/\");\n\nexport function statSafe(p: string) {\n try {\n return statSync(p);\n } catch {\n return null;\n }\n}\n\n// Expand entry globs (single-`*` segments only — the shape `browserEntry`\n// uses) against files on disk, resolving against `root`.\nexport function expandEntryGlobs(root: string, globs: string[]): string[] {\n const files = new Set<string>();\n for (const pattern of globs) {\n const segments = pattern.split(\"/\").filter(Boolean);\n let dirs = [root];\n for (const seg of segments) {\n const next: string[] = [];\n for (const d of dirs) {\n if (!statSafe(d)?.isDirectory()) continue;\n if (seg === \"*\") {\n for (const e of readdirSync(d, { withFileTypes: true })) {\n next.push(join(d, e.name));\n }\n } else {\n next.push(join(d, seg));\n }\n }\n dirs = next;\n }\n for (const f of dirs) {\n if (statSafe(f)?.isFile()) files.add(f);\n }\n }\n return [...files];\n}\n\n// The pieces a project holds, one per pieces/<dir>/index.ts, sorted by dir so\n// a build log and a manifest read the same from one run to the next.\nexport function planPieces(projectRoot: string, outDir: string): PiecePlan[] {\n return expandEntryGlobs(projectRoot, [PIECE_ENTRY_GLOB])\n .map((file) => {\n const dir = basename(dirname(file));\n return {\n dir,\n entry: relative(projectRoot, file),\n outDir: join(outDir, \"node\", \"pieces\", dir),\n };\n })\n .sort((a, b) => (a.dir < b.dir ? -1 : a.dir > b.dir ? 1 : 0));\n}\n\n// A JSON.stringify replacer that makes a piece's metadata serializable: props\n// carry resolvers, defaults may be class instances, and a schema may cycle.\nexport function createJsonReplacer() {\n const ancestors: object[] = [];\n return function replace(this: unknown, _key: string, value: unknown) {\n if (typeof value === \"function\" || value === undefined) return undefined;\n if (typeof value === \"bigint\") return value.toString();\n if (typeof value !== \"object\" || value === null) return value;\n // `this` is the holder, so popping back to it leaves the current path.\n while (ancestors.length > 0 && ancestors.at(-1) !== this) ancestors.pop();\n if (ancestors.includes(value)) return undefined;\n ancestors.push(value);\n return value;\n };\n}\n\n// The half of the child script that needs nothing from the job: a test\n// evaluates this text on its own, so neither copy can drift from the other.\n\n// `constructor?.name`: a module may export an Object.create(null), and the\n// real piece is usually beside it in the same module.\nexport const DESCRIBE_HELPERS = `\nconst isRecord = (value) => typeof value === \"object\" && value !== null;\n\nfunction findPiece(mod) {\n const candidates = [\n ...Object.values(mod),\n ...(isRecord(mod.default) ? Object.values(mod.default) : []),\n mod.default,\n ];\n for (const candidate of candidates) {\n if (isRecord(candidate) && candidate.constructor?.name === \"Piece\") {\n return candidate;\n }\n }\n for (const candidate of candidates) {\n if (\n isRecord(candidate) &&\n typeof candidate.displayName === \"string\" &&\n (isRecord(candidate.actions) ||\n typeof candidate.actions === \"function\" ||\n typeof candidate.getAction === \"function\")\n ) {\n return candidate;\n }\n }\n return undefined;\n}\n\nfunction describePiece(piece) {\n if (typeof piece.metadata === \"function\") return piece.metadata();\n const call = (value) => (typeof value === \"function\" ? value.call(piece) : value);\n return {\n displayName: piece.displayName,\n logoUrl: piece.logoUrl,\n description: piece.description,\n authors: piece.authors,\n categories: piece.categories,\n auth: piece.auth,\n minimumSupportedRelease: piece.minimumSupportedRelease,\n maximumSupportedRelease: piece.maximumSupportedRelease,\n deprecated: piece.deprecated,\n actions: call(piece.actions) ?? {},\n triggers: call(piece.triggers) ?? {},\n };\n}\n\nfunction createJsonReplacer() {\n const ancestors = [];\n return function replace(_key, value) {\n if (typeof value === \"function\" || value === undefined) return undefined;\n if (typeof value === \"bigint\") return value.toString();\n if (typeof value !== \"object\" || value === null) return value;\n while (ancestors.length > 0 && ancestors.at(-1) !== this) ancestors.pop();\n if (ancestors.includes(value)) return undefined;\n ancestors.push(value);\n return value;\n };\n}\n`;\n\n// Runs in a child node process: loading a piece runs piece-authored top-level\n// code, and the runtime describes pieces in a worker for the same reason.\n\n// A string so it works from `src` under bun or tsx as well as from `dist`. It\n// answers through a file, leaving both its streams to the piece.\nexport const DESCRIBE_SCRIPT = `\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { isAbsolute, join } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nconst job = JSON.parse(readFileSync(process.argv[2], \"utf8\"));\n${DESCRIBE_HELPERS}\n// Says why the child gave up in the one place the parent always reads, so a\n// failure reports the cause and never the text of this script.\nfunction fail(message) {\n writeFileSync(job.outFile, JSON.stringify({ fatal: message }));\n process.exit(1);\n}\n\n// The module to load for a list entry; a bundle names its own main.\nfunction entryFile(piece) {\n const declared = piece.entry ?? piece.bundle;\n if (typeof declared !== \"string\") return undefined;\n const path = isAbsolute(declared) ? declared : join(job.projectRoot, declared);\n if (piece.entry) return path;\n const pkgFile = join(path, \"package.json\");\n if (!existsSync(pkgFile)) return undefined;\n const pkg = JSON.parse(readFileSync(pkgFile, \"utf8\"));\n return join(path, typeof pkg.main === \"string\" ? pkg.main : \"index.mjs\");\n}\n\nlet listModule;\ntry {\n listModule = await import(pathToFileURL(job.listPath).href);\n} catch (error) {\n fail(job.listPath + \" threw on import: \" + (error instanceof Error ? error.message : String(error)));\n}\nconst list = listModule.pieces ?? listModule.default;\nif (!Array.isArray(list)) {\n fail(job.listPath + ' exports no \"pieces\" array');\n}\n\nconst out = { list, pieces: [], errors: [] };\nfor (const piece of list) {\n const file = entryFile(piece);\n // A missing file is the parent's to report, with the message it owns.\n if (!file || !existsSync(file)) continue;\n try {\n const mod = await import(pathToFileURL(file).href);\n const found = findPiece(mod);\n if (!found) {\n throw new Error(\n \"no Piece export found in \" + file + \"; exports: \" + Object.keys(mod).join(\", \"),\n );\n }\n const metadata = JSON.parse(JSON.stringify(describePiece(found), createJsonReplacer()));\n out.pieces.push({ name: piece.name, metadata });\n } catch (error) {\n out.errors.push({\n name: piece.name,\n message: error instanceof Error ? error.message : String(error),\n });\n }\n}\nwriteFileSync(job.outFile, JSON.stringify(out, createJsonReplacer()));\n`;\n\n// What the child said went wrong, if it got that far, and otherwise how it\n// died: an exit status, never the whole script an `Error.message` carries.\nfunction childFailure(error: unknown, outFile: string): string {\n try {\n const answer = JSON.parse(readFileSync(outFile, \"utf8\")) as {\n fatal?: unknown;\n };\n if (typeof answer.fatal === \"string\") return answer.fatal;\n } catch {\n // no answer on disk: fall through to the exit status\n }\n const { status, signal } = error as {\n status?: number | null;\n signal?: string | null;\n };\n if (signal) return `the describe child was killed by ${signal}`;\n return `the describe child exited with code ${status ?? \"unknown\"}`;\n}\n\n// Load the built list and every piece it names in a child process and return\n// what they say about themselves. Throws when the list itself cannot be read.\n\n// Both of the child's streams are the parent's, so a piece that prints at\n// import time is heard rather than mixed into the answer.\nexport function describePieces(\n projectRoot: string,\n listPath: string,\n): DescribeResult {\n const dir = mkdtempSync(join(tmpdir(), \"ph-build-pieces-\"));\n const rel = toPosix(relative(projectRoot, listPath));\n try {\n const jobFile = join(dir, \"job.json\");\n const scriptFile = join(dir, \"describe.mjs\");\n const outFile = join(dir, \"describe.json\");\n writeFileSync(scriptFile, DESCRIBE_SCRIPT);\n writeFileSync(jobFile, JSON.stringify({ projectRoot, listPath, outFile }));\n try {\n execFileSync(process.execPath, [scriptFile, jobFile], {\n timeout: 60_000,\n stdio: \"inherit\",\n });\n } catch (error) {\n throw new Error(\n `pieces: could not load ${rel}: ${childFailure(error, outFile)}`,\n { cause: error },\n );\n }\n return JSON.parse(readFileSync(outFile, \"utf8\")) as DescribeResult;\n } finally {\n rmSync(dir, { recursive: true, force: true });\n }\n}\n\nexport type PieceLocation = {\n /** The piece directory, absolute. */\n dir: string;\n /** The module file, absolute; unset for a bundle, whose package.json names it. */\n entryFile?: string;\n form: \"entry\" | \"bundle\";\n};\n\n// Where a list entry says its built piece is, checked against the disk: a\n// listed piece nobody built would otherwise fail much later, in a host.\nexport function resolvePieceLocation(\n piece: PackagePiece,\n projectRoot: string,\n outDir: string,\n): PieceLocation {\n const declared = piece.entry ?? piece.bundle;\n if (typeof declared !== \"string\" || declared === \"\") {\n throw new Error(\n `pieces: \"${piece.name}\" declares neither an entry nor a bundle`,\n );\n }\n const path = isAbsolute(declared) ? declared : join(projectRoot, declared);\n const form = piece.entry ? \"entry\" : \"bundle\";\n const present =\n form === \"entry\"\n ? statSafe(path)?.isFile()\n : statSafe(join(path, \"package.json\"))?.isFile();\n if (!present) {\n throw new Error(\n `pieces: \"${piece.name}\" declares ${declared}, which is missing`,\n );\n }\n const dir = form === \"entry\" ? dirname(path) : path;\n // Both forms, not just `entry`: a descriptor.json is written into this\n // directory, and outside outDir that lands in tracked source.\n const piecesRoot = resolve(projectRoot, outDir, \"node\", \"pieces\");\n const inside = relative(piecesRoot, dir);\n if (inside === \"\" || inside.startsWith(\"..\") || isAbsolute(inside)) {\n const expected = toPosix(join(outDir, \"node\", \"pieces\"));\n throw new Error(\n `pieces: \"${piece.name}\" declares ${declared}, which is outside ${expected}/; ` +\n `a piece is built to ${expected}/<dir>/index.mjs and its entry must point there`,\n );\n }\n return form === \"entry\" ? { dir, entryFile: path, form } : { dir, form };\n}\n\n// Where the node build leaves the list of pieces a package ships. Its presence\n// on disk, not a pieces/<dir> in the source, is what says a package has them.\nexport function pieceListPath(target: {\n projectRoot: string;\n outDir: string;\n}): string {\n return resolve(\n target.projectRoot,\n target.outDir,\n \"node\",\n \"pieces\",\n \"index.mjs\",\n );\n}\n\n// `dist` is not a default here but a contract: a host reads a piece from\n// dist/node/pieces/<name>, and a list entry names that path literally.\nexport function assertPiecesOutDir(target: {\n outDir: string;\n pieces: PiecePlan[];\n}): void {\n if (target.pieces.length === 0 || target.outDir === \"dist\") return;\n throw new Error(\n `pieces: --out-dir ${target.outDir} cannot hold pieces; a piece is loaded from ` +\n `dist/node/pieces/<name> by the host, so a package that ships pieces builds to dist`,\n );\n}\n\n// A piece's version is its package's, written by the build; a list entry that\n// declares one is refused, so `name@version` always names one tarball.\nexport function assertPieceVersion(\n piece: PackagePiece,\n pkg: PackageIdentity,\n): void {\n if (\"version\" in piece) {\n throw new Error(\n `pieces: \"${piece.name}\" declares version ${String(piece.version)}; a piece takes its package's version (${pkg.version}), so remove \"version\" from pieces/index.ts`,\n );\n }\n}\n\n// The package.json written beside a piece built from an `entry`, giving the\n// directory npm-bundle shape so a registry can serve it on its own.\nexport function piecePackageJson(options: {\n name: string;\n version: string;\n description?: string;\n main: string;\n license?: string;\n dependencies?: Record<string, string>;\n}): Record<string, unknown> {\n return {\n name: options.name,\n version: options.version,\n description: options.description ?? \"\",\n type: \"module\",\n main: options.main,\n ...(options.license ? { license: options.license } : {}),\n // Only external packages: everything else is inlined, and a host installs\n // what is listed here before it loads the piece.\n dependencies: options.dependencies ?? {},\n };\n}\n\n// A prebuilt bundle's own package.json, restamped with the package's version.\nexport function bundlePackageJson(\n dir: string,\n version: string,\n): Record<string, unknown> {\n const current = JSON.parse(\n readFileSync(join(dir, \"package.json\"), \"utf8\"),\n ) as Record<string, unknown>;\n return { ...current, version };\n}\n\n// The descriptor written beside a piece: the list's name, the package's version,\n// then whatever the piece said about itself, in the framework's PieceMetadata shape.\nexport function pieceDescriptor(\n piece: PackagePiece,\n version: string,\n metadata: PieceMetadata,\n): Record<string, unknown> {\n const { name: _name, version: _version, ...rest } = metadata;\n return { name: piece.name, version, ...rest };\n}\n\n// The manifest's `pieces` with what the build learned: a built piece replaces\n// the source entry with its id in place, or is appended at the end.\n\n// A source entry nothing built is kept as it is and returned as `unbuilt`,\n// for the caller to warn about.\nexport function enrichManifestPieces(\n manifest: Manifest,\n built: BuiltPiece[],\n): { manifest: Manifest; unbuilt: string[] } {\n const byId = new Map(built.map((piece) => [piece.name, piece]));\n const toModule = (piece: BuiltPiece): PieceModule => ({\n id: piece.name,\n name: piece.displayName ?? piece.name,\n version: piece.version,\n ...(piece.description ? { description: piece.description } : {}),\n bundle: piece.bundle,\n descriptor: piece.descriptor,\n });\n const unbuilt: string[] = [];\n const seen = new Set<string>();\n const pieces: PieceModule[] = (manifest.pieces ?? []).map((entry) => {\n const hit = byId.get(entry.id);\n if (!hit) {\n unbuilt.push(entry.id);\n return entry;\n }\n seen.add(entry.id);\n return toModule(hit);\n });\n for (const piece of built) {\n if (!seen.has(piece.name)) pieces.push(toModule(piece));\n }\n return { manifest: { ...manifest, pieces }, unbuilt };\n}\n\nconst count = (record: unknown) =>\n typeof record === \"object\" && record !== null\n ? Object.keys(record).length\n : 0;\n\n// Build every planned piece, then read the built list and describe what it\n// names. Returns what was built, for the manifest.\nexport async function buildPieces(\n target: PieceBuildTarget,\n pkg: PackageIdentity,\n options: PieceBuildOptions,\n): Promise<BuiltPiece[]> {\n const { projectRoot, outDir } = target;\n assertPiecesOutDir(target);\n // resolve, not join: an absolute --out-dir is what the browser and node\n // steps hand tsdown, and joining it onto the project root mangles it.\n const externalByDir = new Map<string, Map<string, ExternalDependency>>();\n for (const piece of target.pieces) {\n console.log(`\\n▶ Building piece ${piece.dir}...`);\n const outDir = resolve(projectRoot, piece.outDir);\n const external = new Map<string, ExternalDependency>();\n await options.bundle(\n buildPieceBuildConfig({\n entry: resolve(projectRoot, piece.entry),\n outDir,\n ...(options.trace\n ? {\n plugins: [\n externalDepsPlugin(options.trace, external, {\n root: projectRoot,\n ...(options.cache ? { cache: options.cache } : {}),\n }),\n ],\n }\n : {}),\n }),\n );\n for (const dep of external.values()) {\n console.log(\n `piece ${piece.dir}: ${dep.name}@${dep.version} stays external, it needs ${projectPath(projectRoot, dep.file)}`,\n );\n }\n externalByDir.set(outDir, external);\n }\n\n // The list is the source of truth for names; a package that\n // built pieces without a list has nothing a host could read.\n const listPath = pieceListPath(target);\n if (!existsSync(listPath)) {\n throw new Error(\n `pieces: ${toPosix(relative(projectRoot, listPath))} was not built; ` +\n `pieces/index.ts must export the list of pieces this package ships`,\n );\n }\n const described = describePieces(projectRoot, listPath);\n\n const built: BuiltPiece[] = [];\n const listedDirs = new Set<string>();\n for (const piece of described.list) {\n const location = resolvePieceLocation(piece, projectRoot, outDir);\n assertPieceVersion(piece, pkg);\n const failure = described.errors.find((e) => e.name === piece.name);\n if (failure) {\n throw new Error(\n `pieces: \"${piece.name}\" could not be described: ${failure.message}`,\n );\n }\n const found = described.pieces.find((p) => p.name === piece.name);\n if (!found) {\n throw new Error(`pieces: \"${piece.name}\" was not described`);\n }\n const metadata = found.metadata;\n const relDir = toPosix(relative(projectRoot, location.dir));\n listedDirs.add(relDir);\n\n writeFileSync(\n join(location.dir, \"descriptor.json\"),\n JSON.stringify(\n pieceDescriptor(piece, pkg.version, metadata),\n createJsonReplacer(),\n 2,\n ) + \"\\n\",\n );\n const piecePackage =\n location.form === \"entry\" && location.entryFile\n ? piecePackageJson({\n name: piece.name,\n version: pkg.version,\n description: metadata.description,\n main: relative(location.dir, location.entryFile),\n license: pkg.license,\n dependencies: externalDependencyVersions(\n externalByDir.get(resolve(location.dir))?.values() ?? [],\n ),\n })\n : bundlePackageJson(location.dir, pkg.version);\n writeFileSync(\n join(location.dir, \"package.json\"),\n JSON.stringify(piecePackage, null, 2) + \"\\n\",\n );\n console.log(\n `piece: ${piece.name}@${pkg.version} -> ${relDir} ` +\n `(${count(metadata.actions)} actions, ${count(metadata.triggers)} triggers)`,\n );\n built.push({\n name: piece.name,\n version: pkg.version,\n displayName: metadata.displayName,\n description: metadata.description,\n bundle: relDir,\n descriptor: `${relDir}/descriptor.json`,\n });\n }\n\n warnUnlistedPieces(target.pieces, listedDirs);\n return built;\n}\n\n// A built piece no list entry points into ships without a host ever finding it.\nfunction warnUnlistedPieces(\n planned: PiecePlan[],\n listedDirs: Set<string>,\n): void {\n for (const piece of planned) {\n if (!listedDirs.has(toPosix(piece.outDir))) {\n console.warn(\n `⚠ pieces: pieces/${piece.dir} was built but pieces/index.ts does not list it; a host will not find it`,\n );\n }\n }\n}\n\n// Make sure the manifest ships under outDir (tsdown copies it only in the\n// browser build) and, when pieces were built, list them in that copy.\n\n// Always copied afresh: only <outDir>/node is cleaned by the builds, so a copy\n// left by the last build would otherwise outlive an edit to the source.\n\n// The source file is never written. Returns the path of the copy, if any.\nexport function syncDistManifest(\n target: PieceBuildTarget,\n built: BuiltPiece[],\n externalDependencies: Record<string, string> = {},\n): string | undefined {\n const { projectRoot, outDir } = target;\n const source = join(projectRoot, \"powerhouse.manifest.json\");\n // resolve, not join: an absolute --out-dir is a location, not a suffix.\n const copy = resolve(projectRoot, outDir, \"powerhouse.manifest.json\");\n // The built list, not the source plan: a package whose pieces are all\n // `bundle:` entries has no pieces/<dir> and still ships pieces.\n const shipsPieces = existsSync(pieceListPath(target));\n const shipsExternal = Object.keys(externalDependencies).length > 0;\n if (!existsSync(source)) {\n if (shipsPieces) {\n console.warn(\"⚠ no powerhouse.manifest.json; pieces will not be listed\");\n }\n if (shipsExternal) {\n console.warn(\n \"⚠ no powerhouse.manifest.json; external dependencies will not be listed\",\n );\n }\n return undefined;\n }\n mkdirSync(dirname(copy), { recursive: true });\n copyFileSync(source, copy);\n if (!shipsPieces && !shipsExternal) return copy;\n\n let manifest = JSON.parse(readFileSync(copy, \"utf8\")) as Manifest;\n if (shipsPieces) {\n const enriched = enrichManifestPieces(manifest, built);\n for (const id of enriched.unbuilt) {\n console.warn(`⚠ manifest lists piece \"${id}\" but nothing built it`);\n }\n manifest = enriched.manifest;\n }\n if (shipsExternal) manifest = { ...manifest, externalDependencies };\n writeFileSync(copy, JSON.stringify(manifest, null, 2) + \"\\n\");\n return copy;\n}\n"],"mappings":";;;;;;;AAkCA,MAAa,8BAA8C;CACzD,uBAAO,IAAI,IAAI;CACf,sBAAM,IAAI,IAAI;AAChB;AAwBA,MAAM,eAAe,GAAG,IAAI,cAAc;;AAG1C,SAAgB,YAAY,MAAc,MAAsB;CAC9D,OAAO,SAAS,MAAM,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG;AACjD;AAGA,MAAM,YAAY,SAChB,QAAQ,aAAa,UAAU,KAAK,YAAY,IAAI;AAGtD,SAAgB,cAAc,WAAuC;CACnE,IAAI,UAAU,WAAW,GAAG,KAAK,WAAW,SAAS,GAAG,OAAO,KAAA;CAC/D,MAAM,QAAQ,UAAU,MAAM,GAAG;CAIjC,QAHa,UAAU,WAAW,GAAG,IACjC,MAAM,MAAM,GAAG,CAAC,CAAC,CAAC,KAAK,GAAG,IAC1B,MAAM,OACK,KAAA;AACjB;AAGA,SAAgB,cAAc,MAAkC;CAC9D,MAAM,KAAK,KAAK,YAAY,YAAY;CACxC,IAAI,KAAK,GAAG,OAAO,KAAA;CACnB,MAAM,OAAO,KAAK,MAAM,KAAK,aAAa,MAAM,CAAC,CAAC,MAAM,GAAG;CAC3D,MAAM,QAAQ,KAAK,EAAE,EAAE,WAAW,GAAG,IAAI,IAAI;CAC7C,IAAI,KAAK,UAAU,OAAO,OAAO,KAAA;CACjC,OAAO,KAAK,KAAK,MAAM,GAAG,KAAK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AAG;EACvB,IAAI,aACF,QAAQ,KAAK,0DAA0D;EAEzE,IAAI,eACF,QAAQ,KACN,yEACF;EAEF;CACF;CACA,UAAU,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;CAC5C,aAAa,QAAQ,IAAI;CACzB,IAAI,CAAC,eAAe,CAAC,eAAe,OAAO;CAE3C,IAAI,WAAW,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC;CACpD,IAAI,aAAa;EACf,MAAM,WAAW,qBAAqB,UAAU,KAAK;EACrD,KAAK,MAAM,MAAM,SAAS,SACxB,QAAQ,KAAK,2BAA2B,GAAG,uBAAuB;EAEpE,WAAW,SAAS;CACtB;CACA,IAAI,eAAe,WAAW;EAAE,GAAG;EAAU;CAAqB;CAClE,cAAc,MAAM,KAAK,UAAU,UAAU,MAAM,CAAC,IAAI,IAAI;CAC5D,OAAO;AACT"}
1
+ {"version":3,"file":"build-pieces.mjs","names":[],"sources":["../../clis/external-deps.mts","../../clis/build-pieces.mts"],"sourcesContent":["// External dependencies: a package whose code needs a native addon or a\n// WebAssembly module cannot be inlined, so it stays a bare import the host installs.\nimport { readdirSync, readFileSync, realpathSync } from \"node:fs\";\nimport { isBuiltin } from \"node:module\";\nimport { isAbsolute, join, relative, sep } from \"node:path\";\nimport type { InlineConfig } from \"tsdown\";\n\n/** The files one module needs at run time, and why each was included. */\nexport type FileTrace = {\n /** Absolute paths. */\n fileList: Set<string>;\n /** Absolute path -> the absolute paths of the files that pulled it in. */\n reasons: Map<string, { parents: Set<string> }>;\n};\n\n/** Traces one file: @vercel/nft's nodeFileTrace, handed in by the CLI. */\nexport type TraceFiles = (file: string) => Promise<FileTrace>;\n\n/** A file the bundle cannot carry: a native addon or a WebAssembly module. */\nexport type RequiredFile = { file: string; kind: \"native\" | \"wasm\" };\n\nexport type ExternalDependency = RequiredFile & {\n name: string;\n version: string;\n /** The first of the package's own files seen importing it. */\n importer?: string;\n};\n\n/** What one `ph build` learns about packages, shared by all of its builds. */\nexport type DetectionCache = {\n files: Map<string, Promise<RequiredFile | undefined>>;\n wasm: Map<string, string | undefined>;\n};\n\nexport const createDetectionCache = (): DetectionCache => ({\n files: new Map(),\n wasm: new Map(),\n});\n\nexport type ExternalDepsPluginOptions = {\n /** The project root the dirs below are relative to. */\n root?: string;\n /** Browser build: a native package fails it; WebAssembly is bundled. */\n browser?: boolean;\n /** Dirs whose imports the bundler handles as usual: code no host runs. */\n ignoreDirs?: string[];\n /** Dirs that may not import a native or WebAssembly package. */\n forbidDirs?: string[];\n cache?: DetectionCache;\n};\n\ntype Plugin = NonNullable<InlineConfig[\"plugins\"]>;\n\ntype PackageJson = {\n name?: string;\n version?: string;\n dependencies?: Record<string, string>;\n optionalDependencies?: Record<string, string>;\n peerDependencies?: Record<string, string>;\n};\n\nconst NODE_MODULES = `${sep}node_modules${sep}`;\n\n/** `file` relative to `root`, with forward slashes on every platform. */\nexport function projectPath(root: string, file: string): string {\n return relative(root, file).split(sep).join(\"/\");\n}\n\n// Windows paths compare case-insensitively, drive letter included.\nconst samePath = (file: string) =>\n process.platform === \"win32\" ? file.toLowerCase() : file;\n\n// \"@scope/name/sub\" -> \"@scope/name\", \"name/sub\" -> \"name\".\nexport function packageNameOf(specifier: string): string | undefined {\n if (specifier.startsWith(\".\") || isAbsolute(specifier)) return undefined;\n const parts = specifier.split(\"/\");\n const name = specifier.startsWith(\"@\")\n ? parts.slice(0, 2).join(\"/\")\n : parts[0];\n return name || undefined;\n}\n\n// The root of the installed package a file belongs to, if it is in one.\nexport function packageRootOf(file: string): string | undefined {\n const at = file.lastIndexOf(NODE_MODULES);\n if (at < 0) return undefined;\n const rest = file.slice(at + NODE_MODULES.length).split(sep);\n const depth = rest[0]?.startsWith(\"@\") ? 2 : 1;\n if (rest.length <= depth) return undefined;\n return join(file.slice(0, at + NODE_MODULES.length), ...rest.slice(0, depth));\n}\n\nfunction readPackageJson(root: string): PackageJson | undefined {\n try {\n return JSON.parse(\n readFileSync(join(root, \"package.json\"), \"utf8\"),\n ) as PackageJson;\n } catch {\n return undefined;\n }\n}\n\n// Only links the importer requires count: an optional peer such as\n// ws -> bufferutil is a speed-up the importer runs without.\nfunction requires(importerRoot: string, importedRoot: string): boolean {\n const importer = readPackageJson(importerRoot);\n const name = readPackageJson(importedRoot)?.name;\n if (!importer || !name) return false;\n return (\n importer.dependencies?.[name] !== undefined ||\n importer.optionalDependencies?.[name] !== undefined\n );\n}\n\n// The first .wasm file in a package's own files. Presence is enough: most\n// packages compute the path or let their caller pass it, so a trace misses it.\nfunction wasmIn(root: string, cache?: DetectionCache): string | undefined {\n if (cache?.wasm.has(root)) return cache.wasm.get(root);\n const found = scanForWasm(root);\n cache?.wasm.set(root, found);\n return found;\n}\n\nfunction scanForWasm(root: string): string | undefined {\n try {\n const found = readdirSync(root, { recursive: true, encoding: \"utf8\" }).find(\n (file) =>\n file.endsWith(\".wasm\") && !file.split(sep).includes(\"node_modules\"),\n );\n return found && join(root, found);\n } catch {\n return undefined;\n }\n}\n\n/** The first file `entry` cannot load without that a bundle cannot carry. */\nexport async function findRequiredFile(\n entry: string,\n trace: TraceFiles,\n cache?: DetectionCache,\n): Promise<RequiredFile | undefined> {\n const { fileList, reasons } = await trace(entry);\n // A tracer reports real paths, and the entry may sit behind a symlink.\n const start = samePath(realpathSync(entry));\n // What to report, and the traced file the walk back to the entry starts at.\n const candidates: (RequiredFile & { from: string })[] = [...fileList]\n .filter((file) => file.endsWith(\".node\"))\n .map((file) => ({ file, kind: \"native\" as const, from: file }));\n {\n const traced = new Map<string, string>();\n for (const file of fileList) {\n const root = packageRootOf(file);\n if (root && !traced.has(root) && /\\.[cm]?js$/.test(file)) {\n traced.set(root, file);\n }\n }\n const tracedWasm = [...fileList].filter((file) => file.endsWith(\".wasm\"));\n for (const [root, from] of traced) {\n const file =\n tracedWasm.find((wasm) => packageRootOf(wasm) === root) ??\n wasmIn(root, cache);\n if (file) candidates.push({ file, kind: \"wasm\", from });\n }\n }\n for (const { from, ...required } of candidates) {\n // Back to the entry, crossing into a parent's package only when that\n // package requires the one being left.\n const seen = new Set([from]);\n const queue = [from];\n while (queue.length > 0) {\n const file = queue.shift()!;\n if (samePath(file) === start) return required;\n for (const parent of reasons.get(file)?.parents ?? []) {\n if (seen.has(parent)) continue;\n const fromRoot = packageRootOf(parent);\n const toRoot = packageRootOf(file);\n if (\n fromRoot !== toRoot &&\n (!fromRoot || !toRoot || !requires(fromRoot, toRoot))\n ) {\n continue;\n }\n seen.add(parent);\n queue.push(parent);\n }\n }\n }\n return undefined;\n}\n\n/** Keeps each package the code imports that needs such a file out of the bundle. */\nexport function externalDepsPlugin(\n trace: TraceFiles,\n found: Map<string, ExternalDependency>,\n options: ExternalDepsPluginOptions = {},\n): Plugin {\n const cache = options.cache ?? createDetectionCache();\n const root = options.root ?? process.cwd();\n const show = (file: string) => projectPath(root, file);\n const inDir = (id: string, dirs: string[] = []) =>\n dirs.some((dir) => show(id).startsWith(`${dir}/`));\n // By resolved file: a package's subpaths can differ in what they load.\n const detect = (id: string) => {\n let verdict = cache.files.get(id);\n if (!verdict) {\n verdict = findRequiredFile(id, trace, cache);\n cache.files.set(id, verdict);\n }\n return verdict;\n };\n return {\n name: \"powerhouse:external-deps\",\n async resolveId(source, importer, extra) {\n // The project's own imports only: whatever a dependency pulls in goes\n // wherever that dependency goes.\n if (!importer || importer.includes(NODE_MODULES)) return null;\n if (isBuiltin(source) || inDir(importer, options.ignoreDirs)) return null;\n const name = packageNameOf(source);\n if (!name) return null;\n const resolved = await this.resolve(source, importer, {\n ...extra,\n skipSelf: true,\n });\n if (!resolved || resolved.external) return null;\n const required = await detect(resolved.id);\n const pkgRoot = packageRootOf(resolved.id);\n const version = pkgRoot ? readPackageJson(pkgRoot)?.version : undefined;\n if (!required || !version) return null;\n const what =\n required.kind === \"native\"\n ? `the native addon ${show(required.file)}`\n : `the WebAssembly module ${show(required.file)}`;\n if (options.browser) {\n if (required.kind === \"wasm\") return null;\n throw new Error(\n `${show(importer)} imports ${name}, which needs ${what}. ` +\n \"Native code cannot run in the browser: import it only from subgraphs, switchboard processors or pieces.\",\n );\n }\n if (inDir(importer, options.forbidDirs)) {\n throw new Error(\n `${show(importer)} imports ${name}, which needs ${what}. ` +\n \"Document models and scalars run in Connect and on every host: use it from a subgraph, processor or piece instead.\",\n );\n }\n if (!found.has(name)) {\n found.set(name, { name, version, ...required, importer });\n }\n return { id: source, external: true };\n },\n };\n}\n\n/**\n * The detected packages `pkg` does not install for its consumers: anything\n * outside dependencies, optionalDependencies and peerDependencies.\n */\nexport function undeclaredExternalDependencies(\n found: Iterable<ExternalDependency>,\n pkg: Partial<\n Record<\n \"dependencies\" | \"optionalDependencies\" | \"peerDependencies\",\n Partial<Record<string, string>>\n >\n >,\n): ExternalDependency[] {\n return [...found].filter(\n (dep) =>\n pkg.dependencies?.[dep.name] === undefined &&\n pkg.optionalDependencies?.[dep.name] === undefined &&\n pkg.peerDependencies?.[dep.name] === undefined,\n );\n}\n\n/** name -> version, sorted by name. */\nexport function externalDependencyVersions(\n found: Iterable<ExternalDependency>,\n): Record<string, string> {\n return Object.fromEntries(\n [...found]\n .sort((a, b) => a.name.localeCompare(b.name))\n .map((dep) => [dep.name, dep.version]),\n );\n}\n","// The pieces half of a package build: find and bundle each piece whole, load\n// it once in a child process to learn what it is, and write what a host reads.\nimport { execFileSync } from \"node:child_process\";\nimport {\n copyFileSync,\n existsSync,\n mkdirSync,\n mkdtempSync,\n readdirSync,\n readFileSync,\n realpathSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport {\n basename,\n dirname,\n isAbsolute,\n join,\n relative,\n resolve,\n sep,\n} from \"node:path\";\nimport type { InlineConfig } from \"tsdown\";\nimport type { Manifest, PieceModule } from \"../document-model/types.js\";\nimport { buildPieceBuildConfig, PIECE_ENTRY_GLOB } from \"./build-config.mjs\";\nimport {\n externalDependencyVersions,\n externalDepsPlugin,\n projectPath,\n type DetectionCache,\n type ExternalDependency,\n type TraceFiles,\n} from \"./external-deps.mjs\";\n\nexport {\n createDetectionCache,\n projectPath,\n findRequiredFile,\n externalDependencyVersions,\n externalDepsPlugin,\n undeclaredExternalDependencies,\n} from \"./external-deps.mjs\";\nexport type {\n DetectionCache,\n FileTrace,\n ExternalDependency,\n ExternalDepsPluginOptions,\n TraceFiles,\n} from \"./external-deps.mjs\";\n\nexport type PiecePlan = {\n /** The directory under pieces/, and so under <outDir>/node/pieces. */\n dir: string;\n /** Source entry, relative to the project root: pieces/<dir>/index.ts. */\n entry: string;\n /** Where the piece lands, relative to the project root. */\n outDir: string;\n};\n\n// What buildPieces needs to know about the package it works in: where it is,\n// where it builds to, and which pieces the plan found.\nexport type PieceBuildTarget = {\n projectRoot: string;\n outDir: string;\n /**\n * @experimental Absolute: the directory that stands in for\n * `<projectRoot>/<outDir>` on disk during this build. Every path the build\n * names stays under `outDir`. Experimental while staged builds are\n * introduced.\n */\n writeTo?: string;\n pieces: PiecePlan[];\n};\n\n// One entry of pieces/index.ts, as @powerhousedao/pieces-framework declares it.\n// Declared here so the build needs no dependency on a package meant for pieces.\nexport type PackagePiece = {\n name: string;\n entry?: string;\n bundle?: string;\n};\n\n// What a piece says about itself, in the framework's PieceMetadata shape.\n// Read from the built piece, so nothing in the build has to know the framework.\nexport type PieceMetadata = Record<string, unknown> & {\n displayName?: string;\n description?: string;\n actions?: Record<string, unknown>;\n triggers?: Record<string, unknown>;\n};\n\nexport type DescribedPiece = {\n name: string;\n metadata: PieceMetadata;\n};\n\nexport type DescribeResult = {\n list: PackagePiece[];\n pieces: DescribedPiece[];\n errors: { name: string; message: string }[];\n};\n\nexport type BuiltPiece = {\n name: string;\n version: string;\n displayName?: string;\n description?: string;\n /** Piece directory, relative to the project root, `/` separated. */\n bundle: string;\n /** The descriptor inside it, relative to the project root, `/` separated. */\n descriptor: string;\n};\n\nexport type PackageIdentity = {\n name: string;\n version: string;\n license?: string;\n};\n\nexport type PieceBuildOptions = {\n /** The bundler: tsdown's `build`, handed in so this module never loads it. */\n bundle: (config: InlineConfig) => Promise<unknown>;\n /** Traces a module's run-time files; without it nothing is kept external. */\n trace?: TraceFiles;\n cache?: DetectionCache;\n};\n\nconst toPosix = (p: string) => p.split(sep).join(\"/\");\n\n/**\n * An output directory, absolute, and the directory written in its place;\n * `toReal` is `to` as `import.meta.url` spells it, through any symlink.\n */\ntype Redirect = { from: string; to: string; toReal: string };\n\n/** `relative(dir, path)` leaves `dir`: `..`, `../…`, or another root. */\nconst leaves = (inside: string) =>\n inside === \"..\" || inside.startsWith(`..${sep}`) || isAbsolute(inside);\n\n// Where a path is on disk: moved to `to` when it lies under `from`.\nfunction onDisk(path: string, redirect: Redirect | undefined): string {\n if (!redirect) return path;\n const inside = relative(redirect.from, path);\n return leaves(inside) ? path : join(redirect.to, inside);\n}\n\n// Where a path in the written directory stands in the output: the inverse of\n// onDisk, for a location a module derived from its own URL.\nfunction toLogical(path: string, redirect: Redirect | undefined): string {\n if (!redirect) return path;\n for (const dir of [redirect.to, redirect.toReal]) {\n const inside = relative(dir, path);\n if (!leaves(inside)) return join(redirect.from, inside);\n }\n return path;\n}\n\nexport function statSafe(p: string) {\n try {\n return statSync(p);\n } catch {\n return null;\n }\n}\n\nfunction realpathSafe(p: string) {\n try {\n return realpathSync(p);\n } catch {\n return p;\n }\n}\n\n// Expand entry globs (single-`*` segments only — the shape `browserEntry`\n// uses) against files on disk, resolving against `root`.\nexport function expandEntryGlobs(root: string, globs: string[]): string[] {\n const files = new Set<string>();\n for (const pattern of globs) {\n const segments = pattern.split(\"/\").filter(Boolean);\n let dirs = [root];\n for (const seg of segments) {\n const next: string[] = [];\n for (const d of dirs) {\n if (!statSafe(d)?.isDirectory()) continue;\n if (seg === \"*\") {\n for (const e of readdirSync(d, { withFileTypes: true })) {\n next.push(join(d, e.name));\n }\n } else {\n next.push(join(d, seg));\n }\n }\n dirs = next;\n }\n for (const f of dirs) {\n if (statSafe(f)?.isFile()) files.add(f);\n }\n }\n return [...files];\n}\n\n// The pieces a project holds, one per pieces/<dir>/index.ts, sorted by dir so\n// a build log and a manifest read the same from one run to the next.\nexport function planPieces(projectRoot: string, outDir: string): PiecePlan[] {\n return expandEntryGlobs(projectRoot, [PIECE_ENTRY_GLOB])\n .map((file) => {\n const dir = basename(dirname(file));\n return {\n dir,\n entry: relative(projectRoot, file),\n outDir: join(outDir, \"node\", \"pieces\", dir),\n };\n })\n .sort((a, b) => (a.dir < b.dir ? -1 : a.dir > b.dir ? 1 : 0));\n}\n\n// A JSON.stringify replacer that makes a piece's metadata serializable: props\n// carry resolvers, defaults may be class instances, and a schema may cycle.\nexport function createJsonReplacer() {\n const ancestors: object[] = [];\n return function replace(this: unknown, _key: string, value: unknown) {\n if (typeof value === \"function\" || value === undefined) return undefined;\n if (typeof value === \"bigint\") return value.toString();\n if (typeof value !== \"object\" || value === null) return value;\n // `this` is the holder, so popping back to it leaves the current path.\n while (ancestors.length > 0 && ancestors.at(-1) !== this) ancestors.pop();\n if (ancestors.includes(value)) return undefined;\n ancestors.push(value);\n return value;\n };\n}\n\n// The half of the child script that needs nothing from the job: a test\n// evaluates this text on its own, so neither copy can drift from the other.\n\n// `constructor?.name`: a module may export an Object.create(null), and the\n// real piece is usually beside it in the same module.\nexport const DESCRIBE_HELPERS = `\nconst isRecord = (value) => typeof value === \"object\" && value !== null;\n\nfunction findPiece(mod) {\n const candidates = [\n ...Object.values(mod),\n ...(isRecord(mod.default) ? Object.values(mod.default) : []),\n mod.default,\n ];\n for (const candidate of candidates) {\n if (isRecord(candidate) && candidate.constructor?.name === \"Piece\") {\n return candidate;\n }\n }\n for (const candidate of candidates) {\n if (\n isRecord(candidate) &&\n typeof candidate.displayName === \"string\" &&\n (isRecord(candidate.actions) ||\n typeof candidate.actions === \"function\" ||\n typeof candidate.getAction === \"function\")\n ) {\n return candidate;\n }\n }\n return undefined;\n}\n\nfunction describePiece(piece) {\n if (typeof piece.metadata === \"function\") return piece.metadata();\n const call = (value) => (typeof value === \"function\" ? value.call(piece) : value);\n return {\n displayName: piece.displayName,\n logoUrl: piece.logoUrl,\n description: piece.description,\n authors: piece.authors,\n categories: piece.categories,\n auth: piece.auth,\n minimumSupportedRelease: piece.minimumSupportedRelease,\n maximumSupportedRelease: piece.maximumSupportedRelease,\n deprecated: piece.deprecated,\n actions: call(piece.actions) ?? {},\n triggers: call(piece.triggers) ?? {},\n };\n}\n\nfunction createJsonReplacer() {\n const ancestors = [];\n return function replace(_key, value) {\n if (typeof value === \"function\" || value === undefined) return undefined;\n if (typeof value === \"bigint\") return value.toString();\n if (typeof value !== \"object\" || value === null) return value;\n while (ancestors.length > 0 && ancestors.at(-1) !== this) ancestors.pop();\n if (ancestors.includes(value)) return undefined;\n ancestors.push(value);\n return value;\n };\n}\n`;\n\n// Runs in a child node process: loading a piece runs piece-authored top-level\n// code, and the runtime describes pieces in a worker for the same reason.\n\n// A string so it works from `src` under bun or tsx as well as from `dist`. It\n// answers through a file, leaving both its streams to the piece.\nexport const DESCRIBE_SCRIPT = `\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { isAbsolute, join, relative, sep } from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\n\nconst job = JSON.parse(readFileSync(process.argv[2], \"utf8\"));\n${DESCRIBE_HELPERS}\n// The parent's onDisk, for the paths a list names under the output directory.\nfunction onDisk(path) {\n if (!job.redirect) return path;\n const inside = relative(job.redirect.from, path);\n const leaves = inside === \"..\" || inside.startsWith(\"..\" + sep) || isAbsolute(inside);\n return leaves ? path : join(job.redirect.to, inside);\n}\n\n// Says why the child gave up in the one place the parent always reads, so a\n// failure reports the cause and never the text of this script.\nfunction fail(message) {\n writeFileSync(job.outFile, JSON.stringify({ fatal: message }));\n process.exit(1);\n}\n\n// The module to load for a list entry; a bundle names its own main.\nfunction entryFile(piece) {\n const declared = piece.entry ?? piece.bundle;\n if (typeof declared !== \"string\") return undefined;\n const path = isAbsolute(declared) ? declared : join(job.projectRoot, declared);\n if (piece.entry) return path;\n const pkgFile = join(onDisk(path), \"package.json\");\n if (!existsSync(pkgFile)) return undefined;\n const pkg = JSON.parse(readFileSync(pkgFile, \"utf8\"));\n return join(path, typeof pkg.main === \"string\" ? pkg.main : \"index.mjs\");\n}\n\nlet listModule;\ntry {\n listModule = await import(pathToFileURL(onDisk(job.listPath)).href);\n} catch (error) {\n fail(job.listPath + \" threw on import: \" + (error instanceof Error ? error.message : String(error)));\n}\nconst list = listModule.pieces ?? listModule.default;\nif (!Array.isArray(list)) {\n fail(job.listPath + ' exports no \"pieces\" array');\n}\n\nconst out = { list, pieces: [], errors: [] };\nfor (const piece of list) {\n const file = entryFile(piece);\n // A missing file is the parent's to report, with the message it owns.\n if (!file || !existsSync(onDisk(file))) continue;\n try {\n const mod = await import(pathToFileURL(onDisk(file)).href);\n const found = findPiece(mod);\n if (!found) {\n throw new Error(\n \"no Piece export found in \" + file + \"; exports: \" + Object.keys(mod).join(\", \"),\n );\n }\n const metadata = JSON.parse(JSON.stringify(describePiece(found), createJsonReplacer()));\n out.pieces.push({ name: piece.name, metadata });\n } catch (error) {\n out.errors.push({\n name: piece.name,\n message: error instanceof Error ? error.message : String(error),\n });\n }\n}\nwriteFileSync(job.outFile, JSON.stringify(out, createJsonReplacer()));\n`;\n\n// What the child said went wrong, if it got that far, and otherwise how it\n// died: an exit status, never the whole script an `Error.message` carries.\nfunction childFailure(error: unknown, outFile: string): string {\n try {\n const answer = JSON.parse(readFileSync(outFile, \"utf8\")) as {\n fatal?: unknown;\n };\n if (typeof answer.fatal === \"string\") return answer.fatal;\n } catch {\n // no answer on disk: fall through to the exit status\n }\n const { status, signal } = error as {\n status?: number | null;\n signal?: string | null;\n };\n if (signal) return `the describe child was killed by ${signal}`;\n return `the describe child exited with code ${status ?? \"unknown\"}`;\n}\n\n// Load the built list and every piece it names in a child process and return\n// what they say about themselves. Throws when the list itself cannot be read.\n\n// Both of the child's streams are the parent's, so a piece that prints at\n// import time is heard rather than mixed into the answer.\nexport function describePieces(\n projectRoot: string,\n listPath: string,\n): DescribeResult {\n return describePiecesThrough(projectRoot, listPath, undefined);\n}\n\nfunction describePiecesThrough(\n projectRoot: string,\n listPath: string,\n redirect: Redirect | undefined,\n): DescribeResult {\n const dir = mkdtempSync(join(tmpdir(), \"ph-build-pieces-\"));\n const rel = toPosix(relative(projectRoot, listPath));\n try {\n const jobFile = join(dir, \"job.json\");\n const scriptFile = join(dir, \"describe.mjs\");\n const outFile = join(dir, \"describe.json\");\n writeFileSync(scriptFile, DESCRIBE_SCRIPT);\n writeFileSync(\n jobFile,\n JSON.stringify({ projectRoot, listPath, outFile, redirect }),\n );\n try {\n execFileSync(process.execPath, [scriptFile, jobFile], {\n timeout: 60_000,\n stdio: \"inherit\",\n });\n } catch (error) {\n throw new Error(\n `pieces: could not load ${rel}: ${childFailure(error, outFile)}`,\n { cause: error },\n );\n }\n return JSON.parse(readFileSync(outFile, \"utf8\")) as DescribeResult;\n } finally {\n rmSync(dir, { recursive: true, force: true });\n }\n}\n\nexport type PieceLocation = {\n /** The piece directory, absolute. */\n dir: string;\n /** The module file, absolute; unset for a bundle, whose package.json names it. */\n entryFile?: string;\n form: \"entry\" | \"bundle\";\n};\n\n// Where a list entry says its built piece is, checked against the disk: a\n// listed piece nobody built would otherwise fail much later, in a host.\nexport function resolvePieceLocation(\n piece: PackagePiece,\n projectRoot: string,\n outDir: string,\n): PieceLocation {\n return locatePieceThrough(piece, projectRoot, outDir, undefined);\n}\n\nfunction locatePieceThrough(\n piece: PackagePiece,\n projectRoot: string,\n outDir: string,\n redirect: Redirect | undefined,\n): PieceLocation {\n const declared = piece.entry ?? piece.bundle;\n if (typeof declared !== \"string\" || declared === \"\") {\n throw new Error(\n `pieces: \"${piece.name}\" declares neither an entry nor a bundle`,\n );\n }\n // A list may derive a location from import.meta.url, which names the\n // written directory: it is read as the output it stands in for.\n const shown = isAbsolute(declared) ? toLogical(declared, redirect) : declared;\n const path = isAbsolute(declared) ? shown : join(projectRoot, declared);\n const form = piece.entry ? \"entry\" : \"bundle\";\n const disk = onDisk(path, redirect);\n const present =\n form === \"entry\"\n ? statSafe(disk)?.isFile()\n : statSafe(join(disk, \"package.json\"))?.isFile();\n if (!present) {\n throw new Error(\n `pieces: \"${piece.name}\" declares ${shown}, which is missing`,\n );\n }\n const dir = form === \"entry\" ? dirname(path) : path;\n // Both forms, not just `entry`: a descriptor.json is written into this\n // directory, and outside outDir that lands in tracked source.\n const piecesRoot = resolve(projectRoot, outDir, \"node\", \"pieces\");\n const inside = relative(piecesRoot, dir);\n if (inside === \"\" || inside.startsWith(\"..\") || isAbsolute(inside)) {\n const expected = toPosix(join(outDir, \"node\", \"pieces\"));\n throw new Error(\n `pieces: \"${piece.name}\" declares ${shown}, which is outside ${expected}/; ` +\n `a piece is built to ${expected}/<dir>/index.mjs and its entry must point there`,\n );\n }\n return form === \"entry\" ? { dir, entryFile: path, form } : { dir, form };\n}\n\n// Where the node build leaves the list of pieces a package ships. Its presence\n// on disk, not a pieces/<dir> in the source, is what says a package has them.\nexport function pieceListPath(target: {\n projectRoot: string;\n outDir: string;\n}): string {\n return resolve(\n target.projectRoot,\n target.outDir,\n \"node\",\n \"pieces\",\n \"index.mjs\",\n );\n}\n\n// `dist` is not a default here but a contract: a host reads a piece from\n// dist/node/pieces/<name>, and a list entry names that path literally.\nexport function assertPiecesOutDir(target: {\n outDir: string;\n pieces: PiecePlan[];\n}): void {\n if (target.pieces.length === 0 || target.outDir === \"dist\") return;\n throw new Error(\n `pieces: --out-dir ${target.outDir} cannot hold pieces; a piece is loaded from ` +\n `dist/node/pieces/<name> by the host, so a package that ships pieces builds to dist`,\n );\n}\n\n// A piece's version is its package's, written by the build; a list entry that\n// declares one is refused, so `name@version` always names one tarball.\nexport function assertPieceVersion(\n piece: PackagePiece,\n pkg: PackageIdentity,\n): void {\n if (\"version\" in piece) {\n throw new Error(\n `pieces: \"${piece.name}\" declares version ${String(piece.version)}; a piece takes its package's version (${pkg.version}), so remove \"version\" from pieces/index.ts`,\n );\n }\n}\n\n// The package.json written beside a piece built from an `entry`, giving the\n// directory npm-bundle shape so a registry can serve it on its own.\nexport function piecePackageJson(options: {\n name: string;\n version: string;\n description?: string;\n main: string;\n license?: string;\n dependencies?: Record<string, string>;\n}): Record<string, unknown> {\n return {\n name: options.name,\n version: options.version,\n description: options.description ?? \"\",\n type: \"module\",\n main: options.main,\n ...(options.license ? { license: options.license } : {}),\n // Only external packages: everything else is inlined, and a host installs\n // what is listed here before it loads the piece.\n dependencies: options.dependencies ?? {},\n };\n}\n\n// A prebuilt bundle's own package.json, restamped with the package's version.\nexport function bundlePackageJson(\n dir: string,\n version: string,\n): Record<string, unknown> {\n const current = JSON.parse(\n readFileSync(join(dir, \"package.json\"), \"utf8\"),\n ) as Record<string, unknown>;\n return { ...current, version };\n}\n\n// The descriptor written beside a piece: the list's name, the package's version,\n// then whatever the piece said about itself, in the framework's PieceMetadata shape.\nexport function pieceDescriptor(\n piece: PackagePiece,\n version: string,\n metadata: PieceMetadata,\n): Record<string, unknown> {\n const { name: _name, version: _version, ...rest } = metadata;\n return { name: piece.name, version, ...rest };\n}\n\n// The manifest's `pieces` with what the build learned: a built piece replaces\n// the source entry with its id in place, or is appended at the end.\n\n// A source entry nothing built is kept as it is and returned as `unbuilt`,\n// for the caller to warn about.\nexport function enrichManifestPieces(\n manifest: Manifest,\n built: BuiltPiece[],\n): { manifest: Manifest; unbuilt: string[] } {\n const byId = new Map(built.map((piece) => [piece.name, piece]));\n const toModule = (piece: BuiltPiece): PieceModule => ({\n id: piece.name,\n name: piece.displayName ?? piece.name,\n version: piece.version,\n ...(piece.description ? { description: piece.description } : {}),\n bundle: piece.bundle,\n descriptor: piece.descriptor,\n });\n const unbuilt: string[] = [];\n const seen = new Set<string>();\n const pieces: PieceModule[] = (manifest.pieces ?? []).map((entry) => {\n const hit = byId.get(entry.id);\n if (!hit) {\n unbuilt.push(entry.id);\n return entry;\n }\n seen.add(entry.id);\n return toModule(hit);\n });\n for (const piece of built) {\n if (!seen.has(piece.name)) pieces.push(toModule(piece));\n }\n return { manifest: { ...manifest, pieces }, unbuilt };\n}\n\nconst count = (record: unknown) =>\n typeof record === \"object\" && record !== null\n ? Object.keys(record).length\n : 0;\n\n// Build every planned piece, then read the built list and describe what it\n// names. Returns what was built, for the manifest.\nexport async function buildPieces(\n target: PieceBuildTarget,\n pkg: PackageIdentity,\n options: PieceBuildOptions,\n): Promise<BuiltPiece[]> {\n const { projectRoot, outDir } = target;\n assertPiecesOutDir(target);\n const redirect = target.writeTo\n ? {\n from: resolve(projectRoot, outDir),\n to: target.writeTo,\n toReal: realpathSafe(target.writeTo),\n }\n : undefined;\n // resolve, not join: an absolute --out-dir is what the browser and node\n // steps hand tsdown, and joining it onto the project root mangles it.\n const externalByDir = new Map<string, Map<string, ExternalDependency>>();\n for (const piece of target.pieces) {\n console.log(`\\n▶ Building piece ${piece.dir}...`);\n const outDir = resolve(projectRoot, piece.outDir);\n const external = new Map<string, ExternalDependency>();\n await options.bundle(\n buildPieceBuildConfig({\n entry: resolve(projectRoot, piece.entry),\n outDir: onDisk(outDir, redirect),\n ...(options.trace\n ? {\n plugins: [\n externalDepsPlugin(options.trace, external, {\n root: projectRoot,\n ...(options.cache ? { cache: options.cache } : {}),\n }),\n ],\n }\n : {}),\n }),\n );\n for (const dep of external.values()) {\n console.log(\n `piece ${piece.dir}: ${dep.name}@${dep.version} stays external, it needs ${projectPath(projectRoot, dep.file)}`,\n );\n }\n externalByDir.set(outDir, external);\n }\n\n // The list is the source of truth for names; a package that\n // built pieces without a list has nothing a host could read.\n const listPath = pieceListPath(target);\n if (!existsSync(onDisk(listPath, redirect))) {\n throw new Error(\n `pieces: ${toPosix(relative(projectRoot, listPath))} was not built; ` +\n `pieces/index.ts must export the list of pieces this package ships`,\n );\n }\n const described = describePiecesThrough(projectRoot, listPath, redirect);\n\n const built: BuiltPiece[] = [];\n const listedDirs = new Set<string>();\n for (const piece of described.list) {\n const location = locatePieceThrough(piece, projectRoot, outDir, redirect);\n const dirOnDisk = onDisk(location.dir, redirect);\n assertPieceVersion(piece, pkg);\n const failure = described.errors.find((e) => e.name === piece.name);\n if (failure) {\n throw new Error(\n `pieces: \"${piece.name}\" could not be described: ${failure.message}`,\n );\n }\n const found = described.pieces.find((p) => p.name === piece.name);\n if (!found) {\n throw new Error(`pieces: \"${piece.name}\" was not described`);\n }\n const metadata = found.metadata;\n const relDir = toPosix(relative(projectRoot, location.dir));\n listedDirs.add(relDir);\n\n writeFileSync(\n join(dirOnDisk, \"descriptor.json\"),\n JSON.stringify(\n pieceDescriptor(piece, pkg.version, metadata),\n createJsonReplacer(),\n 2,\n ) + \"\\n\",\n );\n const piecePackage =\n location.form === \"entry\" && location.entryFile\n ? piecePackageJson({\n name: piece.name,\n version: pkg.version,\n description: metadata.description,\n main: relative(location.dir, location.entryFile),\n license: pkg.license,\n dependencies: externalDependencyVersions(\n externalByDir.get(resolve(location.dir))?.values() ?? [],\n ),\n })\n : bundlePackageJson(dirOnDisk, pkg.version);\n writeFileSync(\n join(dirOnDisk, \"package.json\"),\n JSON.stringify(piecePackage, null, 2) + \"\\n\",\n );\n console.log(\n `piece: ${piece.name}@${pkg.version} -> ${relDir} ` +\n `(${count(metadata.actions)} actions, ${count(metadata.triggers)} triggers)`,\n );\n built.push({\n name: piece.name,\n version: pkg.version,\n displayName: metadata.displayName,\n description: metadata.description,\n bundle: relDir,\n descriptor: `${relDir}/descriptor.json`,\n });\n }\n\n warnUnlistedPieces(target.pieces, listedDirs);\n return built;\n}\n\n// A built piece no list entry points into ships without a host ever finding it.\nfunction warnUnlistedPieces(\n planned: PiecePlan[],\n listedDirs: Set<string>,\n): void {\n for (const piece of planned) {\n if (!listedDirs.has(toPosix(piece.outDir))) {\n console.warn(\n `⚠ pieces: pieces/${piece.dir} was built but pieces/index.ts does not list it; a host will not find it`,\n );\n }\n }\n}\n\n// Make sure the manifest ships under outDir (tsdown copies it only in the\n// browser build) and, when pieces were built, list them in that copy.\n\n// Always copied afresh: only <outDir>/node is cleaned by the builds, so a copy\n// left by the last build would otherwise outlive an edit to the source.\n\n// The source file is never written. Returns the path of the copy, if any.\nexport function syncDistManifest(\n target: PieceBuildTarget,\n built: BuiltPiece[],\n externalDependencies: Record<string, string> = {},\n): string | undefined {\n const { projectRoot, outDir } = target;\n const source = join(projectRoot, \"powerhouse.manifest.json\");\n // resolve, not join: an absolute --out-dir is a location, not a suffix.\n const copy = resolve(projectRoot, outDir, \"powerhouse.manifest.json\");\n // The built list, not the source plan: a package whose pieces are all\n // `bundle:` entries has no pieces/<dir> and still ships pieces.\n const shipsPieces = existsSync(pieceListPath(target));\n const shipsExternal = Object.keys(externalDependencies).length > 0;\n if (!existsSync(source)) {\n if (shipsPieces) {\n console.warn(\"⚠ no powerhouse.manifest.json; pieces will not be listed\");\n }\n if (shipsExternal) {\n console.warn(\n \"⚠ no powerhouse.manifest.json; external dependencies will not be listed\",\n );\n }\n return undefined;\n }\n mkdirSync(dirname(copy), { recursive: true });\n copyFileSync(source, copy);\n if (!shipsPieces && !shipsExternal) return copy;\n\n let manifest = JSON.parse(readFileSync(copy, \"utf8\")) as Manifest;\n if (shipsPieces) {\n const enriched = enrichManifestPieces(manifest, built);\n for (const id of enriched.unbuilt) {\n console.warn(`⚠ manifest lists piece \"${id}\" but nothing built it`);\n }\n manifest = enriched.manifest;\n }\n if (shipsExternal) manifest = { ...manifest, externalDependencies };\n writeFileSync(copy, JSON.stringify(manifest, null, 2) + \"\\n\");\n return copy;\n}\n"],"mappings":";;;;;;;AAkCA,MAAa,8BAA8C;CACzD,uBAAO,IAAI,IAAI;CACf,sBAAM,IAAI,IAAI;AAChB;AAwBA,MAAM,eAAe,GAAG,IAAI,cAAc;;AAG1C,SAAgB,YAAY,MAAc,MAAsB;CAC9D,OAAO,SAAS,MAAM,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG;AACjD;AAGA,MAAM,YAAY,SAChB,QAAQ,aAAa,UAAU,KAAK,YAAY,IAAI;AAGtD,SAAgB,cAAc,W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AM,SAAS,SAClB,IAAI,CAAC,WAAW,IAAI,QAAQ,MAAM,MAAM,CAAC,GACvC,QAAQ,KACN,oBAAoB,MAAM,IAAI,yEAChC;AAGN;AASA,SAAgB,iBACd,QACA,OACA,uBAA+C,CAAC,GAC5B;CACpB,MAAM,EAAE,aAAa,WAAW;CAChC,MAAM,SAAS,KAAK,aAAa,0BAA0B;CAE3D,MAAM,OAAO,QAAQ,aAAa,QAAQ,0BAA0B;CAGpE,MAAM,cAAc,WAAW,cAAc,MAAM,CAAC;CACpD,MAAM,gBAAgB,OAAO,KAAK,oBAAoB,CAAC,CAAC,SAAS;CACjE,IAAI,CAAC,WAAW,MAAM,GAAG;EACvB,IAAI,aACF,QAAQ,KAAK,0DAA0D;EAEzE,IAAI,eACF,QAAQ,KACN,yEACF;EAEF;CACF;CACA,UAAU,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;CAC5C,aAAa,QAAQ,IAAI;CACzB,IAAI,CAAC,eAAe,CAAC,eAAe,OAAO;CAE3C,IAAI,WAAW,KAAK,MAAM,aAAa,MAAM,MAAM,CAAC;CACpD,IAAI,aAAa;EACf,MAAM,WAAW,qBAAqB,UAAU,KAAK;EACrD,KAAK,MAAM,MAAM,SAAS,SACxB,QAAQ,KAAK,2BAA2B,GAAG,uBAAuB;EAEpE,WAAW,SAAS;CACtB;CACA,IAAI,eAAe,WAAW;EAAE,GAAG;EAAU;CAAqB;CAClE,cAAc,MAAM,KAAK,UAAU,UAAU,MAAM,CAAC,IAAI,IAAI;CAC5D,OAAO;AACT"}
@@ -1,3 +1,3 @@
1
- import { A as PH_GLOBAL_DIR_NAME, B as RELATIONAL_DB_PROCESSOR_CLASS, C as KYSELY_PACKAGE, D as MINIMUM_NODE_VERSION, E as LOG_LEVELS, F as PROJECT_PORT_BAND_SIZE, G as VERSIONED_PEER_DEPENDENCIES, H as SERVICE_ACTIONS, I as PROJECT_PORT_BAND_STUDIO, J as externalDevDependencies, K as defaultManifest, L as PROJECT_PORT_BAND_SWITCHBOARD, M as PIECES_FRAMEWORK_PACKAGE, N as POWERHOUSE_CONFIG_FILE, O as PEER_EXTERNAL_DEPENDENCIES, P as POWERHOUSE_GLOBAL_DIR, R as PROJECT_PORT_BAND_VETRA_CONNECT, S as HOME_DIR, T as LEGACY_LINT_FORMAT_FILES, U as VERSIONED_DEPENDENCIES, V as SECONDS_IN_DAY, W as VERSIONED_DEV_DEPENDENCIES, X as packageScripts, Y as packageJsonExports, _ as DEFAULT_VETRA_DRIVE_ID, a as DEFAULT_CONFIG, b as GRAPHQL_PACKAGE, c as DEFAULT_CONNECT_STUDIO_PORT, d as DEFAULT_EXPIRY_SECONDS, f as DEFAULT_REGISTRY_URL, g as DEFAULT_VETRA_CONNECT_PORT, h as DEFAULT_TIMEOUT, i as BOILERPLATE_DEPENDENCY_OVERRIDES, j as PH_GLOBAL_PROJECT_NAME, k as PH_BIN, l as DEFAULT_DRIVE_ICON, m as DEFAULT_SWITCHBOARD_PORT, n as ANALYTICS_ENGINE_CORE_PACKAGE, o as DEFAULT_CONNECT_OUTDIR, p as DEFAULT_RENOWN_URL, q as externalDependencies, r as BOILERPLATE_ALLOWED_BUILDS, s as DEFAULT_CONNECT_PREVIEW_PORT, u as DEFAULT_EXPIRY_DAYS, v as DRIVES_PRESERVE_STRATEGIES, w as LEGACY_LINT_FORMAT_DEPENDENCIES, x as GRAPHQL_TAG_PACKAGE, y as FEATURE_DEPENDENCIES, z as REACTOR_API_PACKAGE } from "./types-B-2NDvpx.mjs";
1
+ import { A as PH_GLOBAL_DIR_NAME, B as RELATIONAL_DB_PROCESSOR_CLASS, C as KYSELY_PACKAGE, D as MINIMUM_NODE_VERSION, E as LOG_LEVELS, F as PROJECT_PORT_BAND_SIZE, G as VERSIONED_PEER_DEPENDENCIES, H as SERVICE_ACTIONS, I as PROJECT_PORT_BAND_STUDIO, J as externalDevDependencies, K as defaultManifest, L as PROJECT_PORT_BAND_SWITCHBOARD, M as PIECES_FRAMEWORK_PACKAGE, N as POWERHOUSE_CONFIG_FILE, O as PEER_EXTERNAL_DEPENDENCIES, P as POWERHOUSE_GLOBAL_DIR, R as PROJECT_PORT_BAND_VETRA_CONNECT, S as HOME_DIR, T as LEGACY_LINT_FORMAT_FILES, U as VERSIONED_DEPENDENCIES, V as SECONDS_IN_DAY, W as VERSIONED_DEV_DEPENDENCIES, X as packageScripts, Y as packageJsonExports, _ as DEFAULT_VETRA_DRIVE_ID, a as DEFAULT_CONFIG, b as GRAPHQL_PACKAGE, c as DEFAULT_CONNECT_STUDIO_PORT, d as DEFAULT_EXPIRY_SECONDS, f as DEFAULT_REGISTRY_URL, g as DEFAULT_VETRA_CONNECT_PORT, h as DEFAULT_TIMEOUT, i as BOILERPLATE_DEPENDENCY_OVERRIDES, j as PH_GLOBAL_PROJECT_NAME, k as PH_BIN, l as DEFAULT_DRIVE_ICON, m as DEFAULT_SWITCHBOARD_PORT, n as ANALYTICS_ENGINE_CORE_PACKAGE, o as DEFAULT_CONNECT_OUTDIR, p as DEFAULT_RENOWN_URL, q as externalDependencies, r as BOILERPLATE_ALLOWED_BUILDS, s as DEFAULT_CONNECT_PREVIEW_PORT, u as DEFAULT_EXPIRY_DAYS, v as DRIVES_PRESERVE_STRATEGIES, w as LEGACY_LINT_FORMAT_DEPENDENCIES, x as GRAPHQL_TAG_PACKAGE, y as FEATURE_DEPENDENCIES, z as REACTOR_API_PACKAGE } from "./types-DXqOePw5.mjs";
2
2
  export { ANALYTICS_ENGINE_CORE_PACKAGE, BOILERPLATE_ALLOWED_BUILDS, BOILERPLATE_DEPENDENCY_OVERRIDES, DEFAULT_CONFIG, DEFAULT_CONNECT_OUTDIR, DEFAULT_CONNECT_PREVIEW_PORT, DEFAULT_CONNECT_STUDIO_PORT, DEFAULT_DRIVE_ICON, DEFAULT_EXPIRY_DAYS, DEFAULT_EXPIRY_SECONDS, DEFAULT_REGISTRY_URL, DEFAULT_RENOWN_URL, DEFAULT_SWITCHBOARD_PORT, DEFAULT_TIMEOUT, DEFAULT_VETRA_CONNECT_PORT, DEFAULT_VETRA_DRIVE_ID, DRIVES_PRESERVE_STRATEGIES, FEATURE_DEPENDENCIES, GRAPHQL_PACKAGE, GRAPHQL_TAG_PACKAGE, HOME_DIR, KYSELY_PACKAGE, LEGACY_LINT_FORMAT_DEPENDENCIES, LEGACY_LINT_FORMAT_FILES, LOG_LEVELS, MINIMUM_NODE_VERSION, PEER_EXTERNAL_DEPENDENCIES, PH_BIN, PH_GLOBAL_DIR_NAME, PH_GLOBAL_PROJECT_NAME, PIECES_FRAMEWORK_PACKAGE, POWERHOUSE_CONFIG_FILE, POWERHOUSE_GLOBAL_DIR, PROJECT_PORT_BAND_SIZE, PROJECT_PORT_BAND_STUDIO, PROJECT_PORT_BAND_SWITCHBOARD, PROJECT_PORT_BAND_VETRA_CONNECT, REACTOR_API_PACKAGE, RELATIONAL_DB_PROCESSOR_CLASS, SECONDS_IN_DAY, SERVICE_ACTIONS, VERSIONED_DEPENDENCIES, VERSIONED_DEV_DEPENDENCIES, VERSIONED_PEER_DEPENDENCIES, defaultManifest, externalDependencies, externalDevDependencies, packageJsonExports, packageScripts };
3
3
  export {};
@@ -133,7 +133,10 @@ const BOILERPLATE_ALLOWED_BUILDS = [
133
133
  const BOILERPLATE_DEPENDENCY_OVERRIDES = {
134
134
  "date-fns": "4.3.0",
135
135
  vite: "8.0.14",
136
- rolldown: "1.0.2"
136
+ rolldown: "1.0.2",
137
+ "@solana/kit": "5.5.1",
138
+ "@solana-program/system": "0.10.0",
139
+ "@solana-program/token": "0.9.0"
137
140
  };
138
141
  const VERSIONED_DEV_DEPENDENCIES = [
139
142
  "@powerhousedao/ph-cli",