@powerhousedao/ph-cli 6.4.0-next.2 → 6.4.0-next.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -5
- package/dist/{build-C7RBpPwa.mjs → build-B-rPwjM8.mjs} +6 -6
- package/dist/{build-C7RBpPwa.mjs.map → build-B-rPwjM8.mjs.map} +1 -1
- package/dist/build-DuwAPWMY.mjs +4 -0
- package/dist/{check-1Hfe0lVO.mjs → check-B7C3Vi_b.mjs} +4 -4
- package/dist/{check-1Hfe0lVO.mjs.map → check-B7C3Vi_b.mjs.map} +1 -1
- package/dist/{check-MBdw9Lbm.mjs → check-DM7UdFTK.mjs} +4 -4
- package/dist/{check-MBdw9Lbm.mjs.map → check-DM7UdFTK.mjs.map} +1 -1
- package/dist/{check-ClxYRer4.mjs → check-DeUTd514.mjs} +3 -3
- package/dist/{cli-connect-override-DsuuectH.mjs → cli-connect-override-Bx_g3-ZE.mjs} +4 -4
- package/dist/{cli-connect-override-DsuuectH.mjs.map → cli-connect-override-Bx_g3-ZE.mjs.map} +1 -1
- package/dist/cli.mjs +8 -8
- package/dist/cli.mjs.map +1 -1
- package/dist/{compound-Q9sZSEZF-zZWzQ7VC.mjs → compound-Q9sZSEZF-DQvtoigb.mjs} +4 -4
- package/dist/{compound-Q9sZSEZF-zZWzQ7VC.mjs.map → compound-Q9sZSEZF-DQvtoigb.mjs.map} +1 -1
- package/dist/{connect-build-DAnGPSF5.mjs → connect-build-CaTxdYcc.mjs} +5 -5
- package/dist/{connect-build-DAnGPSF5.mjs.map → connect-build-CaTxdYcc.mjs.map} +1 -1
- package/dist/{connect-config-C0QZ7zTf.mjs → connect-config-A-U83U8U.mjs} +4 -4
- package/dist/{connect-config-C0QZ7zTf.mjs.map → connect-config-A-U83U8U.mjs.map} +1 -1
- package/dist/{connect-studio-BUth3UYP.mjs → connect-studio-B2gugCJU.mjs} +4 -4
- package/dist/{connect-studio-BUth3UYP.mjs.map → connect-studio-B2gugCJU.mjs.map} +1 -1
- package/dist/definitions-worker.mjs +1 -1
- package/dist/dev-host-RhWeATKB.mjs +19 -0
- package/dist/dev-host-RhWeATKB.mjs.map +1 -0
- package/dist/{dist-CRR5Anp2.mjs → dist-D_UjZsgt.mjs} +4 -4
- package/dist/{dist-CRR5Anp2.mjs.map → dist-D_UjZsgt.mjs.map} +1 -1
- package/dist/{explain-BfOC7Ngv.mjs → explain-DbbHpa61.mjs} +5 -5
- package/dist/{explain-BfOC7Ngv.mjs.map → explain-DbbHpa61.mjs.map} +1 -1
- package/dist/{export-CdTqYviH.mjs → export-FduYVQEM.mjs} +4 -4
- package/dist/{export-CdTqYviH.mjs.map → export-FduYVQEM.mjs.map} +1 -1
- package/dist/{files-D6_euBBn.mjs → files-DEHg350R.mjs} +4 -4
- package/dist/{files-D6_euBBn.mjs.map → files-DEHg350R.mjs.map} +1 -1
- package/dist/{generate-all-HujZHqCG.mjs → generate-all-BE8UmbJv.mjs} +6 -21
- package/dist/generate-all-BE8UmbJv.mjs.map +1 -0
- package/dist/{generate-app-hm6CJ_4O.mjs → generate-app-C7n0j8Ak.mjs} +5 -18
- package/dist/generate-app-C7n0j8Ak.mjs.map +1 -0
- package/dist/{generate-document-model-BiD6ovXc.mjs → generate-document-model-DSYPTMZg.mjs} +9 -31
- package/dist/generate-document-model-DSYPTMZg.mjs.map +1 -0
- package/dist/{generate-editor-DBj_Pxwa.mjs → generate-editor-DKuRUeIt.mjs} +5 -18
- package/dist/generate-editor-DKuRUeIt.mjs.map +1 -0
- package/dist/{generate-processor-BVjOsfjJ.mjs → generate-processor-CwJvJDpd.mjs} +5 -18
- package/dist/generate-processor-CwJvJDpd.mjs.map +1 -0
- package/dist/{generate-subgraph-DJZCr0Tk.mjs → generate-subgraph-EQ2ZjMp9.mjs} +6 -25
- package/dist/generate-subgraph-EQ2ZjMp9.mjs.map +1 -0
- package/dist/{get-version-DAYhm6MX.mjs → get-version-7oKMD8Gt.mjs} +4 -4
- package/dist/{get-version-DAYhm6MX.mjs.map → get-version-7oKMD8Gt.mjs.map} +1 -1
- package/dist/{mcp-rtMGg307.mjs → mcp-CcZT9zT9.mjs} +8 -8
- package/dist/mcp-CcZT9zT9.mjs.map +1 -0
- package/dist/{migrate-CWCJP19Q.mjs → migrate-Ddr7YAtM.mjs} +4 -4
- package/dist/{migrate-CWCJP19Q.mjs.map → migrate-Ddr7YAtM.mjs.map} +1 -1
- package/dist/{migrate-document-models-DTxM7D7p.mjs → migrate-document-models-X_mVTljj.mjs} +4 -4
- package/dist/{migrate-document-models-DTxM7D7p.mjs.map → migrate-document-models-X_mVTljj.mjs.map} +1 -1
- package/dist/migrate-subgraphs-DEqWkLoh.mjs +4 -0
- package/dist/{migrate-subgraphs-_yRnF7xt.mjs → migrate-subgraphs-Ffwwm7Oy.mjs} +5 -5
- package/dist/{migrate-subgraphs-_yRnF7xt.mjs.map → migrate-subgraphs-Ffwwm7Oy.mjs.map} +1 -1
- package/dist/{ph-cli-commands-FLZClR4x.mjs → ph-cli-commands-D4Z6YSwd.mjs} +39 -104
- package/dist/ph-cli-commands-D4Z6YSwd.mjs.map +1 -0
- package/dist/ph-cli-commands-p9cO6MsE.mjs +4 -0
- package/dist/{run-sugar-DUiDFl_T.mjs → run-sugar-CkuGJuPg.mjs} +16 -8
- package/dist/run-sugar-CkuGJuPg.mjs.map +1 -0
- package/dist/{run-sugar-YDxw0iV9.mjs → run-sugar-Dd_Mu058.mjs} +3 -3
- package/dist/runners/connect.mjs +2 -2
- package/dist/runners/switchboard.mjs +3 -3
- package/dist/{sugar-checks-BFu3sfFJ.mjs → sugar-checks-CAtgUIem.mjs} +16 -15
- package/dist/sugar-checks-CAtgUIem.mjs.map +1 -0
- package/dist/{verify-Dkb6K1fc.mjs → verify-DXrs0JUp.mjs} +5 -5
- package/dist/{verify-Dkb6K1fc.mjs.map → verify-DXrs0JUp.mjs.map} +1 -1
- package/dist/{vetra-gateway-BMzq0mqX.mjs → vetra-gateway-BHuz7pvS.mjs} +5 -5
- package/dist/{vetra-gateway-BMzq0mqX.mjs.map → vetra-gateway-BHuz7pvS.mjs.map} +1 -1
- package/dist/vetra-gateway-ag33E_Ta.mjs +4 -0
- package/dist/{vetra-host-C37IGwBM.mjs → vetra-host-CYdbd3J3.mjs} +28 -11
- package/dist/vetra-host-CYdbd3J3.mjs.map +1 -0
- package/dist/{vetra-launcher-Dq0tWyNW.mjs → vetra-launcher-B5L3yXPo.mjs} +16 -13
- package/dist/vetra-launcher-B5L3yXPo.mjs.map +1 -0
- package/dist/vetra-launcher-BUO9e74r.mjs +4 -0
- package/dist/{vetra-instance-CLUzbtbh.mjs → vetra-runtime-Bk6CW-BE.mjs} +6 -24
- package/dist/vetra-runtime-Bk6CW-BE.mjs.map +1 -0
- package/dist/warn-subgraph-type-conflicts-BZ4NwLx5.mjs +131 -0
- package/dist/warn-subgraph-type-conflicts-BZ4NwLx5.mjs.map +1 -0
- package/package.json +15 -16
- package/dist/build-BUpe1j4m.mjs +0 -4
- package/dist/generate-all-HujZHqCG.mjs.map +0 -1
- package/dist/generate-app-hm6CJ_4O.mjs.map +0 -1
- package/dist/generate-document-model-BiD6ovXc.mjs.map +0 -1
- package/dist/generate-editor-DBj_Pxwa.mjs.map +0 -1
- package/dist/generate-processor-BVjOsfjJ.mjs.map +0 -1
- package/dist/generate-subgraph-DJZCr0Tk.mjs.map +0 -1
- package/dist/mcp-rtMGg307.mjs.map +0 -1
- package/dist/migrate-subgraphs-DcJjLMFd.mjs +0 -4
- package/dist/ph-cli-commands-CRwA1aVX.mjs +0 -4
- package/dist/ph-cli-commands-FLZClR4x.mjs.map +0 -1
- package/dist/run-sugar-DUiDFl_T.mjs.map +0 -1
- package/dist/sugar-checks-BFu3sfFJ.mjs.map +0 -1
- package/dist/vetra-gateway-BP6Catg4.mjs +0 -4
- package/dist/vetra-host-C37IGwBM.mjs.map +0 -1
- package/dist/vetra-instance-CLUzbtbh.mjs.map +0 -1
- package/dist/vetra-launcher-CJ01qmS1.mjs +0 -4
- package/dist/vetra-launcher-Dq0tWyNW.mjs.map +0 -1
- package/dist/warn-subgraph-type-conflicts-BOHBmThq.mjs +0 -19
- package/dist/warn-subgraph-type-conflicts-BOHBmThq.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"files-D6_euBBn.mjs","sources":["../src/services/build-control.ts","../src/services/release/revision.ts","../src/services/release/approval.ts","../src/services/release/pack.ts","../src/services/release/files.ts"],"sourcesContent":["import { basename, join, posix, sep } from \"node:path\";\n\n/** Scratch space of `ph build`, per package. */\nexport const BUILD_DIRECTORY = join(\".ph\", \"build\");\nexport const LOCK_FILE = join(BUILD_DIRECTORY, \"lock\");\n\nexport const takeoverPrefix = (lockName: string) => `${lockName}.takeover-`;\nexport const pendingPrefix = (fileName: string) => `.${fileName}.`;\n\nexport function isBuildLockFile(path: string): boolean {\n const lockName = basename(LOCK_FILE);\n const name = posix.basename(path);\n return (\n posix.dirname(path) === BUILD_DIRECTORY.split(sep).join(\"/\") &&\n (name === lockName ||\n name.startsWith(takeoverPrefix(lockName)) ||\n name.startsWith(pendingPrefix(lockName)))\n );\n}\n","import { createHash } from \"node:crypto\";\n\nexport type Sha256 = `sha256:${string}`;\n\n/** One file, by its POSIX path relative to the package root, and the hex sha256 of its bytes. */\nexport type FileDigest = { readonly path: string; readonly sha256: string };\n\n/**\n * The package revision: one digest over its files, sorted by path, bound to\n * the given values (the ph-cli version), so the same files under another\n * ph-cli are another revision.\n */\nexport function packageRevision(\n files: readonly FileDigest[],\n bindings: Readonly<Record<string, string>>,\n): Sha256 {\n const hash = createHash(\"sha256\");\n for (const { path, sha256 } of [...files].sort(byPath)) {\n hash.update(`${path}\\0${sha256}\\n`);\n }\n for (const key of Object.keys(bindings).sort()) {\n hash.update(`binding:${key}\\0${bindings[key]}\\n`);\n }\n return `sha256:${hash.digest(\"hex\")}`;\n}\n\nexport function byPath(left: FileDigest, right: FileDigest): number {\n return left.path < right.path ? -1 : left.path > right.path ? 1 : 0;\n}\n\n/** Paths added, removed or with other bytes in `after`, sorted. */\nexport function changedPaths(\n before: readonly FileDigest[],\n after: readonly FileDigest[],\n): string[] {\n const was = new Map(before.map(({ path, sha256 }) => [path, sha256]));\n const now = new Map(after.map(({ path, sha256 }) => [path, sha256]));\n return [...new Set([...was.keys(), ...now.keys()])]\n .filter((path) => was.get(path) !== now.get(path))\n .sort();\n}\n","import { z } from \"zod\";\nimport { type FileDigest, packageRevision } from \"./revision.js\";\n\n/** Where `ph build --release` records its approval, relative to the package root. */\nexport const RELEASE_APPROVAL_PATH = \".ph/build/release-approval.json\";\n\n/** The binding key of the ph-cli version in the package revision. */\nexport const PH_CLI_BINDING = \"ph-cli\";\n\nconst fileDigest = z.object({\n path: z.string(),\n sha256: z.string().regex(/^[0-9a-f]{64}$/),\n});\n\nconst hostFinding = z.looseObject({\n kind: z.enum([\n \"scalar-unbound\",\n \"scalar-mismatch\",\n \"scalar-uncomparable\",\n \"definition-invalid\",\n \"definition-mismatch\",\n ]),\n documentType: z.string(),\n scalar: z.string().optional(),\n});\n\nconst approvalSchema = z.object({\n kind: z.literal(\"powerhouse.release-approval\"),\n formatVersion: z.literal(1),\n phCliVersion: z.string(),\n /** POSIX, relative to the package root: the output directory the build replaced. */\n outDir: z.string(),\n packageRevision: z.object({\n digest: z.templateLiteral([\"sha256:\", z.string()]),\n /** Compiler outputs left out besides the fixed exclusions, POSIX and package relative. */\n excluded: z.array(z.string()).readonly(),\n }),\n /** What `npm pack` publishes, sorted by path. */\n publishedFiles: z.array(fileDigest).readonly(),\n report: z.object({\n profile: z.literal(\"release\"),\n status: z.enum([\"ok\", \"invalid\", \"failed\", \"skipped\"]),\n definitions: z\n .array(z.looseObject({ kind: z.string(), key: z.string() }))\n .readonly(),\n }),\n scalars: z\n .array(\n z.object({\n scalar: z.string(),\n packageName: z.string(),\n version: z.string().nullable(),\n }),\n )\n .readonly(),\n hostValidation: z.discriminatedUnion(\"completed\", [\n z.object({\n completed: z.literal(true),\n findings: z.array(hostFinding).readonly(),\n }),\n z.object({\n completed: z.literal(false),\n reason: z.string(),\n findings: z.array(hostFinding).readonly(),\n }),\n ]),\n});\n\n/** `.ph/build/release-approval.json`: what a successful `ph build --release` checked and built. */\nexport type ReleaseApproval = z.infer<typeof approvalSchema>;\n\n/** One scalar the package's models use, and the package and version that provide it. */\nexport type ScalarBinding = ReleaseApproval[\"scalars\"][number];\n\nexport type ApprovalRead =\n | { readonly kind: \"missing\" }\n | { readonly kind: \"unreadable\"; readonly reason: string }\n | { readonly kind: \"found\"; readonly approval: ReleaseApproval };\n\n/** Parses an approval file's text. */\nexport function parseReleaseApproval(\n text: string,\n): Exclude<ApprovalRead, { kind: \"missing\" }> {\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch {\n return { kind: \"unreadable\", reason: \"it is not JSON\" };\n }\n const parsed = approvalSchema.safeParse(json);\n if (parsed.success) return { kind: \"found\", approval: parsed.data };\n const [issue] = parsed.error.issues;\n const at = issue.path.length > 0 ? ` at ${issue.path.join(\".\")}` : \"\";\n return {\n kind: \"unreadable\",\n reason: `it is not an approval this ph-cli reads (${issue.message}${at})`,\n };\n}\n\n/** The package as it is now, read with the approval's output directory and exclusions. */\nexport type CurrentRelease = {\n readonly phCliVersion: string;\n /** The files the package revision reads. */\n readonly files: readonly FileDigest[];\n readonly publishedFiles: readonly FileDigest[];\n};\n\ntype Reasons = readonly [string, ...string[]];\n\n/** Whether the package may be published as the approval describes it, and why not. */\nexport type ReleaseDecision =\n | { readonly decision: \"approved\"; readonly reasons: readonly [] }\n | {\n readonly decision: \"missing\" | \"unreadable\" | \"stale\" | \"refused\";\n readonly reasons: Reasons;\n };\n\n/** The decision when there is no approval to compare. */\nexport function decisionWithoutApproval(\n read: Exclude<ApprovalRead, { kind: \"found\" }>,\n): ReleaseDecision {\n return read.kind === \"missing\"\n ? {\n decision: \"missing\",\n reasons: [\n `there is no release approval (${RELEASE_APPROVAL_PATH}); ph build --release writes one`,\n ],\n }\n : {\n decision: \"unreadable\",\n reasons: [\n `the release approval (${RELEASE_APPROVAL_PATH}) cannot be read: ${read.reason}`,\n ],\n };\n}\n\nconst LISTED = 5;\n\n/** Up to five items, then how many more. */\nexport function listed(items: readonly string[]): string {\n const shown = items.slice(0, LISTED).join(\", \");\n return items.length > LISTED\n ? `${shown} and ${items.length - LISTED} more`\n : shown;\n}\n\nconst plural = (count: number, one: string, many: string) =>\n `${count} ${count === 1 ? one : many}`;\n\nfunction describeFinding(\n finding: ReleaseApproval[\"hostValidation\"][\"findings\"][number],\n): string {\n return finding.scalar === undefined\n ? `${finding.kind} in ${finding.documentType}`\n : `${finding.kind} ${finding.scalar} in ${finding.documentType}`;\n}\n\nfunction refusalReasons(approval: ReleaseApproval): string[] {\n const { report, hostValidation } = approval;\n const reasons: string[] = [];\n if (report.status === \"invalid\" || report.status === \"failed\") {\n reasons.push(`its release check reported ${report.status}`);\n }\n if (!hostValidation.completed) {\n reasons.push(`host validation did not complete: ${hostValidation.reason}`);\n }\n if (hostValidation.findings.length > 0) {\n reasons.push(\n `host validation found ${plural(hostValidation.findings.length, \"problem\", \"problems\")}: ${listed(hostValidation.findings.map(describeFinding))}`,\n );\n }\n return reasons;\n}\n\nfunction staleReasons(\n approval: ReleaseApproval,\n current: CurrentRelease,\n): string[] {\n const reasons: string[] = [];\n if (approval.phCliVersion !== current.phCliVersion) {\n reasons.push(\n `it was made by ph-cli ${approval.phCliVersion}, and this is ph-cli ${current.phCliVersion}`,\n );\n }\n // Under the approval's own binding, so a new ph-cli alone does not read as edited files.\n const revision = packageRevision(current.files, {\n [PH_CLI_BINDING]: approval.phCliVersion,\n });\n if (revision !== approval.packageRevision.digest) {\n reasons.push(\"the package's files changed since the approval was made\");\n }\n const approved = new Map(\n approval.publishedFiles.map(({ path, sha256 }) => [path, sha256]),\n );\n const now = new Map(\n current.publishedFiles.map(({ path, sha256 }) => [path, sha256]),\n );\n const added = [...now.keys()].filter((path) => !approved.has(path));\n const removed = [...approved.keys()].filter((path) => !now.has(path));\n const changed = [...now].filter(\n ([path, sha256]) => approved.has(path) && approved.get(path) !== sha256,\n );\n const files = (paths: readonly string[], what: string) =>\n `${plural(paths.length, \"published file\", \"published files\")} ${what} since the approval was made: ${listed(paths)}`;\n if (added.length > 0) reasons.push(files(added, \"added\"));\n if (removed.length > 0) reasons.push(files(removed, \"removed\"));\n if (changed.length > 0) {\n reasons.push(\n files(\n changed.map(([path]) => path),\n \"changed\",\n ),\n );\n }\n return reasons;\n}\n\nfunction decided(\n decision: \"stale\" | \"refused\",\n reasons: readonly string[],\n): ReleaseDecision | undefined {\n if (reasons.length === 0) return undefined;\n const [first, ...rest] = reasons;\n return { decision, reasons: [first, ...rest] };\n}\n\n/**\n * Whether the package as it is now is the one the approval checked. Refused\n * when the approval records a failed check; stale when ph-cli, the package's\n * files or the published files changed since.\n */\nexport function verifyReleaseApproval(\n approval: ReleaseApproval,\n current: CurrentRelease,\n): ReleaseDecision {\n return (\n decided(\"refused\", refusalReasons(approval)) ??\n decided(\"stale\", staleReasons(approval, current)) ?? {\n decision: \"approved\",\n reasons: [],\n }\n );\n}\n","import { spawnSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport {\n mkdtempSync,\n readdirSync,\n readFileSync,\n realpathSync,\n rmSync,\n} from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join, posix } from \"node:path\";\nimport { gunzipSync } from \"node:zlib\";\nimport { z } from \"zod\";\nimport { isBuildLockFile } from \"../build-control.js\";\nimport { RELEASE_APPROVAL_PATH } from \"./approval.js\";\nimport { byPath, type FileDigest } from \"./revision.js\";\n\nexport type PackedRelease = {\n readonly directory: string;\n readonly tarball: string;\n readonly manifest: PackedManifest;\n readonly files: ReadonlyMap<string, Buffer>;\n readonly dispose: () => void;\n};\n\nconst manifestSchema = z.looseObject({\n name: z.string(),\n version: z.string(),\n main: z.string().optional(),\n exports: z.unknown().optional(),\n dependencies: z.record(z.string(), z.string()).optional(),\n optionalDependencies: z.record(z.string(), z.string()).optional(),\n peerDependencies: z.record(z.string(), z.string()).optional(),\n});\n\nexport type PackedManifest = z.infer<typeof manifestSchema>;\n\nconst packListing = z.array(\n z.object({ name: z.string(), version: z.string(), filename: z.string() }),\n);\n\n/** npm refuses `--workspaces=false` while its configuration selects one. */\nconst SELECTS_WORKSPACE = /--no-workspaces and --workspace/;\n\nexport const selectsAnotherPackage = (packageRoot: string) =>\n `npm's configuration (a workspace setting in the environment or an .npmrc) selects a package other than the one in ${packageRoot}; the release approval covers that package only.`;\n\nconst BLOCK = 512;\n\nfunction field(header: Buffer, start: number, length: number): string {\n const bytes = header.subarray(start, start + length);\n const end = bytes.indexOf(0);\n return bytes.subarray(0, end === -1 ? length : end).toString(\"utf8\");\n}\n\nfunction paxPath(body: Buffer): string | undefined {\n for (let offset = 0; offset < body.length;) {\n const space = body.indexOf(0x20, offset);\n const length = Number(body.subarray(offset, space).toString(\"ascii\"));\n if (space === -1 || !(length > 0)) return undefined;\n const record = body\n .subarray(space + 1, offset + length - 1)\n .toString(\"utf8\");\n if (record.startsWith(\"path=\")) return record.slice(\"path=\".length);\n offset += length;\n }\n return undefined;\n}\n\nexport function readTarball(tarball: string): Map<string, Buffer> {\n const tar = gunzipSync(readFileSync(tarball));\n const files = new Map<string, Buffer>();\n let longPath: string | undefined;\n for (let offset = 0; offset + BLOCK <= tar.length;) {\n const header = tar.subarray(offset, offset + BLOCK);\n if (header.every((byte) => byte === 0)) break;\n const size = parseInt(field(header, 124, 12).trim() || \"0\", 8);\n const type = String.fromCharCode(header[156] || 48);\n const body = tar.subarray(offset + BLOCK, offset + BLOCK + size);\n offset += BLOCK + Math.ceil(size / BLOCK) * BLOCK;\n if (type === \"x\") {\n longPath = paxPath(body) ?? longPath;\n continue;\n }\n if (type === \"L\") {\n longPath = field(body, 0, body.length);\n continue;\n }\n if (type === \"g\") continue;\n const prefix = field(header, 345, 155);\n const name = field(header, 0, 100);\n const path = longPath ?? (prefix === \"\" ? name : `${prefix}/${name}`);\n longPath = undefined;\n if (type === \"5\") continue;\n const inside = posix.normalize(path.split(\"/\").slice(1).join(\"/\"));\n if (\n inside === \".\" ||\n inside.startsWith(\"../\") ||\n posix.isAbsolute(inside)\n ) {\n throw new Error(`the tarball has an entry outside the package: ${path}`);\n }\n const bytes =\n type === \"1\" || type === \"2\"\n ? Buffer.from(field(header, 157, 100))\n : Buffer.from(body);\n files.set(inside, bytes);\n }\n return files;\n}\n\nexport function packRelease(packageRoot: string): PackedRelease {\n const directory = realpathSync.native(\n mkdtempSync(join(tmpdir(), \"ph-release-\")),\n );\n const dispose = () => rmSync(directory, { recursive: true, force: true });\n try {\n const packed = spawnSync(\n \"npm\",\n [\n \"pack\",\n \"--json\",\n \"--ignore-scripts\",\n \"--workspaces=false\",\n \"--pack-destination\",\n // cmd.exe splits an unquoted path at its spaces.\n process.platform === \"win32\" ? `\"${directory}\"` : directory,\n ],\n {\n cwd: packageRoot,\n encoding: \"utf8\",\n maxBuffer: 256 * 1024 * 1024,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n shell: process.platform === \"win32\",\n },\n );\n if (packed.status !== 0) {\n if (SELECTS_WORKSPACE.test(`${packed.stdout}${packed.stderr}`)) {\n throw new Error(selectsAnotherPackage(packageRoot));\n }\n throw new Error(\n `npm pack could not pack the package: ${(packed.stderr || packed.error?.message || packed.stdout).trim()}`,\n );\n }\n const listings = packListing.parse(JSON.parse(packed.stdout));\n const root = z\n .object({ name: z.string(), version: z.string() })\n .parse(\n JSON.parse(readFileSync(join(packageRoot, \"package.json\"), \"utf8\")),\n );\n const [listing] = listings;\n const tarballs = readdirSync(directory);\n if (\n listings.length !== 1 ||\n listing.name !== root.name ||\n listing.version !== root.version ||\n tarballs.length !== 1\n ) {\n const packs = listings.map(({ name, version }) => `${name}@${version}`);\n throw new Error(\n `npm pack packs ${packs.join(\", \") || \"no package\"}, not ${root.name}@${root.version}: ${selectsAnotherPackage(packageRoot)}`,\n );\n }\n const tarball = join(directory, tarballs[0]);\n const files = readTarball(tarball);\n const manifestBytes = files.get(\"package.json\");\n if (manifestBytes === undefined) {\n throw new Error(\"npm pack wrote a tarball without a package.json\");\n }\n const manifest = manifestSchema.parse(\n JSON.parse(manifestBytes.toString(\"utf8\")),\n );\n return { directory, tarball, manifest, files, dispose };\n } catch (error) {\n dispose();\n throw error;\n }\n}\n\nexport function packedDigests(packed: PackedRelease): FileDigest[] {\n return [...packed.files]\n .filter(\n ([path]) => path !== RELEASE_APPROVAL_PATH && !isBuildLockFile(path),\n )\n .map(([path, bytes]) => ({\n path,\n sha256: createHash(\"sha256\").update(bytes).digest(\"hex\"),\n }))\n .sort(byPath);\n}\n","import { spawnSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport {\n type Dirent,\n existsSync,\n lstatSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n readlinkSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname, join, relative, resolve, sep } from \"node:path\";\nimport {\n type ApprovalRead,\n parseReleaseApproval,\n RELEASE_APPROVAL_PATH,\n type ReleaseApproval,\n} from \"./approval.js\";\nimport { packedDigests, packRelease } from \"./pack.js\";\nimport { byPath, type FileDigest } from \"./revision.js\";\n\nconst ALWAYS_EXCLUDED = new Set([\"node_modules\", \".git\", \".ph\"]);\n// A build's stage and retired tree, beside its output while it runs.\nconst BUILD_SCRATCH = /^\\..+\\.ph-(stage|old)-/;\n\nconst toPosix = (path: string) => path.split(sep).join(\"/\");\n\n/** `path` relative to the package root, in POSIX form. */\nexport function packagePath(packageRoot: string, path: string): string {\n return toPosix(relative(packageRoot, resolve(packageRoot, path)));\n}\n\nfunction sha256(bytes: string | Buffer): string {\n return createHash(\"sha256\").update(bytes).digest(\"hex\");\n}\n\n/** A file's digest; a symlink's is its target text, which is not followed. */\nfunction digestOf(packageRoot: string, path: string): FileDigest | undefined {\n const absolute = join(packageRoot, ...path.split(\"/\"));\n const stat = lstatSync(absolute, { throwIfNoEntry: false });\n if (stat?.isSymbolicLink()) {\n return { path, sha256: sha256(toPosix(readlinkSync(absolute))) };\n }\n return stat?.isFile()\n ? { path, sha256: sha256(readFileSync(absolute)) }\n : undefined;\n}\n\nfunction insideWorkTree(packageRoot: string): boolean {\n const probe = spawnSync(\"git\", [\"rev-parse\", \"--is-inside-work-tree\"], {\n cwd: packageRoot,\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n });\n return probe.status === 0 && probe.stdout.trim() === \"true\";\n}\n\n/** Tracked and untracked files git does not ignore, relative to the package root. */\nfunction gitFiles(packageRoot: string): string[] {\n const listed = spawnSync(\n \"git\",\n [\"ls-files\", \"-co\", \"--exclude-standard\", \"-z\"],\n {\n cwd: packageRoot,\n encoding: \"utf8\",\n maxBuffer: 256 * 1024 * 1024,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n },\n );\n if (listed.status !== 0) {\n throw new Error(\n `git ls-files could not list the package's files: ${listed.stderr || listed.error?.message}`,\n );\n }\n return [...new Set(listed.stdout.split(\"\\0\").filter(Boolean))];\n}\n\n/**\n * Every file under the package root, by POSIX path, without entering a\n * directory `included` rejects. Throws when a directory cannot be read.\n */\nfunction walkedFiles(\n packageRoot: string,\n included: (path: string) => boolean,\n): string[] {\n const files: string[] = [];\n const visit = (directory: string, prefix: string) => {\n let entries: Dirent[];\n try {\n entries = readdirSync(directory, { withFileTypes: true });\n } catch (error) {\n throw new Error(\n `the package directory ${prefix || \".\"} cannot be read: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n for (const entry of entries) {\n const path = prefix === \"\" ? entry.name : `${prefix}/${entry.name}`;\n if (!included(path)) continue;\n if (entry.isDirectory()) {\n visit(join(directory, entry.name), path);\n } else {\n files.push(path);\n }\n }\n };\n visit(packageRoot, \"\");\n return files;\n}\n\n/**\n * The files the package revision reads, with their digests: what git tracks\n * or would track inside a work tree, every file otherwise. Leaves out\n * node_modules, .git, .ph, a build's stage, and each excluded path (the\n * output directory, compiler outputs) with what is under it.\n */\nexport function revisionFiles(\n packageRoot: string,\n excluded: readonly string[],\n): FileDigest[] {\n const included = (path: string) =>\n !path\n .split(\"/\")\n .some(\n (segment) =>\n ALWAYS_EXCLUDED.has(segment) || BUILD_SCRATCH.test(segment),\n ) &&\n !excluded.some(\n (exclusion) => path === exclusion || path.startsWith(`${exclusion}/`),\n );\n const paths = insideWorkTree(packageRoot)\n ? gitFiles(packageRoot)\n : walkedFiles(packageRoot, included);\n return paths\n .filter(included)\n .flatMap((path) => digestOf(packageRoot, path) ?? [])\n .sort(byPath);\n}\n\n/**\n * What `npm pack` publishes from the package root, with digests read from the\n * packed tarball. Workspaces are off, so npm packs the root package or\n * refuses; a tarball of another package than the root's package.json names\n * throws as well.\n */\nexport function publishedFiles(packageRoot: string): FileDigest[] {\n const packed = packRelease(packageRoot);\n try {\n return packedDigests(packed);\n } finally {\n packed.dispose();\n }\n}\n\nconst approvalFile = (packageRoot: string) =>\n join(packageRoot, ...RELEASE_APPROVAL_PATH.split(\"/\"));\n\nexport function readReleaseApproval(packageRoot: string): ApprovalRead {\n const file = approvalFile(packageRoot);\n if (!existsSync(file)) return { kind: \"missing\" };\n let text: string;\n try {\n text = readFileSync(file, \"utf8\");\n } catch (error) {\n return {\n kind: \"unreadable\",\n reason: error instanceof Error ? error.message : String(error),\n };\n }\n return parseReleaseApproval(text);\n}\n\n/** Replaces the approval in one rename, so a reader never sees half of one. */\nexport function writeReleaseApproval(\n packageRoot: string,\n approval: ReleaseApproval,\n): void {\n const file = approvalFile(packageRoot);\n mkdirSync(dirname(file), { recursive: true });\n const temporary = `${file}.${process.pid}.tmp`;\n try {\n writeFileSync(temporary, `${JSON.stringify(approval, null, 2)}\\n`);\n renameSync(temporary, file);\n } finally {\n rmSync(temporary, { force: true });\n }\n}\n"],"names":["z.object","z.string","z.looseObject","z.enum","z.literal","z.templateLiteral","z.array","z\n .array","z\n .array","z.discriminatedUnion","z.looseObject","z.string","z.unknown","z.record","z.array","z.object","z\n .object"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AG,OAAO,EAAE,MAAM,UAAU;CAChD,IAAI;CACJ,IAAI;EACF,OAAO,aAAa,MAAM,MAAM;CAClC,SAAS,OAAO;EACd,OAAO;GACL,MAAM;GACN,QAAQ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAC/D;CACF;CACA,OAAO,qBAAqB,IAAI;AAClC;;AAGA,SAAgB,qBACd,aACA,UACM;CACN,MAAM,OAAO,aAAa,WAAW;CACrC,UAAU,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;CAC5C,MAAM,YAAY,GAAG,KAAK,GAAG,QAAQ,IAAI;CACzC,IAAI;EACF,cAAc,WAAW,GAAG,KAAK,UAAU,UAAU,MAAM,CAAC,EAAE,GAAG;EACjE,WAAW,WAAW,IAAI;CAC5B,UAAU;EACR,OAAO,WAAW,EAAE,OAAO,KAAK,CAAC;CACnC;AACF","debug_id":"fe8bf27c-1748-57ef-aec3-baf7d689bdaa"}
|
|
1
|
+
{"version":3,"file":"files-DEHg350R.mjs","sources":["../src/services/build-control.ts","../src/services/release/revision.ts","../src/services/release/approval.ts","../src/services/release/pack.ts","../src/services/release/files.ts"],"sourcesContent":["import { basename, join, posix, sep } from \"node:path\";\n\n/** Scratch space of `ph build`, per package. */\nexport const BUILD_DIRECTORY = join(\".ph\", \"build\");\nexport const LOCK_FILE = join(BUILD_DIRECTORY, \"lock\");\n\nexport const takeoverPrefix = (lockName: string) => `${lockName}.takeover-`;\nexport const pendingPrefix = (fileName: string) => `.${fileName}.`;\n\nexport function isBuildLockFile(path: string): boolean {\n const lockName = basename(LOCK_FILE);\n const name = posix.basename(path);\n return (\n posix.dirname(path) === BUILD_DIRECTORY.split(sep).join(\"/\") &&\n (name === lockName ||\n name.startsWith(takeoverPrefix(lockName)) ||\n name.startsWith(pendingPrefix(lockName)))\n );\n}\n","import { createHash } from \"node:crypto\";\n\nexport type Sha256 = `sha256:${string}`;\n\n/** One file, by its POSIX path relative to the package root, and the hex sha256 of its bytes. */\nexport type FileDigest = { readonly path: string; readonly sha256: string };\n\n/**\n * The package revision: one digest over its files, sorted by path, bound to\n * the given values (the ph-cli version), so the same files under another\n * ph-cli are another revision.\n */\nexport function packageRevision(\n files: readonly FileDigest[],\n bindings: Readonly<Record<string, string>>,\n): Sha256 {\n const hash = createHash(\"sha256\");\n for (const { path, sha256 } of [...files].sort(byPath)) {\n hash.update(`${path}\\0${sha256}\\n`);\n }\n for (const key of Object.keys(bindings).sort()) {\n hash.update(`binding:${key}\\0${bindings[key]}\\n`);\n }\n return `sha256:${hash.digest(\"hex\")}`;\n}\n\nexport function byPath(left: FileDigest, right: FileDigest): number {\n return left.path < right.path ? -1 : left.path > right.path ? 1 : 0;\n}\n\n/** Paths added, removed or with other bytes in `after`, sorted. */\nexport function changedPaths(\n before: readonly FileDigest[],\n after: readonly FileDigest[],\n): string[] {\n const was = new Map(before.map(({ path, sha256 }) => [path, sha256]));\n const now = new Map(after.map(({ path, sha256 }) => [path, sha256]));\n return [...new Set([...was.keys(), ...now.keys()])]\n .filter((path) => was.get(path) !== now.get(path))\n .sort();\n}\n","import { z } from \"zod\";\nimport { type FileDigest, packageRevision } from \"./revision.js\";\n\n/** Where `ph build --release` records its approval, relative to the package root. */\nexport const RELEASE_APPROVAL_PATH = \".ph/build/release-approval.json\";\n\n/** The binding key of the ph-cli version in the package revision. */\nexport const PH_CLI_BINDING = \"ph-cli\";\n\nconst fileDigest = z.object({\n path: z.string(),\n sha256: z.string().regex(/^[0-9a-f]{64}$/),\n});\n\nconst hostFinding = z.looseObject({\n kind: z.enum([\n \"scalar-unbound\",\n \"scalar-mismatch\",\n \"scalar-uncomparable\",\n \"definition-invalid\",\n \"definition-mismatch\",\n ]),\n documentType: z.string(),\n scalar: z.string().optional(),\n});\n\nconst approvalSchema = z.object({\n kind: z.literal(\"powerhouse.release-approval\"),\n formatVersion: z.literal(1),\n phCliVersion: z.string(),\n /** POSIX, relative to the package root: the output directory the build replaced. */\n outDir: z.string(),\n packageRevision: z.object({\n digest: z.templateLiteral([\"sha256:\", z.string()]),\n /** Compiler outputs left out besides the fixed exclusions, POSIX and package relative. */\n excluded: z.array(z.string()).readonly(),\n }),\n /** What `npm pack` publishes, sorted by path. */\n publishedFiles: z.array(fileDigest).readonly(),\n report: z.object({\n profile: z.literal(\"release\"),\n status: z.enum([\"ok\", \"invalid\", \"failed\", \"skipped\"]),\n definitions: z\n .array(z.looseObject({ kind: z.string(), key: z.string() }))\n .readonly(),\n }),\n scalars: z\n .array(\n z.object({\n scalar: z.string(),\n packageName: z.string(),\n version: z.string().nullable(),\n }),\n )\n .readonly(),\n hostValidation: z.discriminatedUnion(\"completed\", [\n z.object({\n completed: z.literal(true),\n findings: z.array(hostFinding).readonly(),\n }),\n z.object({\n completed: z.literal(false),\n reason: z.string(),\n findings: z.array(hostFinding).readonly(),\n }),\n ]),\n});\n\n/** `.ph/build/release-approval.json`: what a successful `ph build --release` checked and built. */\nexport type ReleaseApproval = z.infer<typeof approvalSchema>;\n\n/** One scalar the package's models use, and the package and version that provide it. */\nexport type ScalarBinding = ReleaseApproval[\"scalars\"][number];\n\nexport type ApprovalRead =\n | { readonly kind: \"missing\" }\n | { readonly kind: \"unreadable\"; readonly reason: string }\n | { readonly kind: \"found\"; readonly approval: ReleaseApproval };\n\n/** Parses an approval file's text. */\nexport function parseReleaseApproval(\n text: string,\n): Exclude<ApprovalRead, { kind: \"missing\" }> {\n let json: unknown;\n try {\n json = JSON.parse(text);\n } catch {\n return { kind: \"unreadable\", reason: \"it is not JSON\" };\n }\n const parsed = approvalSchema.safeParse(json);\n if (parsed.success) return { kind: \"found\", approval: parsed.data };\n const [issue] = parsed.error.issues;\n const at = issue.path.length > 0 ? ` at ${issue.path.join(\".\")}` : \"\";\n return {\n kind: \"unreadable\",\n reason: `it is not an approval this ph-cli reads (${issue.message}${at})`,\n };\n}\n\n/** The package as it is now, read with the approval's output directory and exclusions. */\nexport type CurrentRelease = {\n readonly phCliVersion: string;\n /** The files the package revision reads. */\n readonly files: readonly FileDigest[];\n readonly publishedFiles: readonly FileDigest[];\n};\n\ntype Reasons = readonly [string, ...string[]];\n\n/** Whether the package may be published as the approval describes it, and why not. */\nexport type ReleaseDecision =\n | { readonly decision: \"approved\"; readonly reasons: readonly [] }\n | {\n readonly decision: \"missing\" | \"unreadable\" | \"stale\" | \"refused\";\n readonly reasons: Reasons;\n };\n\n/** The decision when there is no approval to compare. */\nexport function decisionWithoutApproval(\n read: Exclude<ApprovalRead, { kind: \"found\" }>,\n): ReleaseDecision {\n return read.kind === \"missing\"\n ? {\n decision: \"missing\",\n reasons: [\n `there is no release approval (${RELEASE_APPROVAL_PATH}); ph build --release writes one`,\n ],\n }\n : {\n decision: \"unreadable\",\n reasons: [\n `the release approval (${RELEASE_APPROVAL_PATH}) cannot be read: ${read.reason}`,\n ],\n };\n}\n\nconst LISTED = 5;\n\n/** Up to five items, then how many more. */\nexport function listed(items: readonly string[]): string {\n const shown = items.slice(0, LISTED).join(\", \");\n return items.length > LISTED\n ? `${shown} and ${items.length - LISTED} more`\n : shown;\n}\n\nconst plural = (count: number, one: string, many: string) =>\n `${count} ${count === 1 ? one : many}`;\n\nfunction describeFinding(\n finding: ReleaseApproval[\"hostValidation\"][\"findings\"][number],\n): string {\n return finding.scalar === undefined\n ? `${finding.kind} in ${finding.documentType}`\n : `${finding.kind} ${finding.scalar} in ${finding.documentType}`;\n}\n\nfunction refusalReasons(approval: ReleaseApproval): string[] {\n const { report, hostValidation } = approval;\n const reasons: string[] = [];\n if (report.status === \"invalid\" || report.status === \"failed\") {\n reasons.push(`its release check reported ${report.status}`);\n }\n if (!hostValidation.completed) {\n reasons.push(`host validation did not complete: ${hostValidation.reason}`);\n }\n if (hostValidation.findings.length > 0) {\n reasons.push(\n `host validation found ${plural(hostValidation.findings.length, \"problem\", \"problems\")}: ${listed(hostValidation.findings.map(describeFinding))}`,\n );\n }\n return reasons;\n}\n\nfunction staleReasons(\n approval: ReleaseApproval,\n current: CurrentRelease,\n): string[] {\n const reasons: string[] = [];\n if (approval.phCliVersion !== current.phCliVersion) {\n reasons.push(\n `it was made by ph-cli ${approval.phCliVersion}, and this is ph-cli ${current.phCliVersion}`,\n );\n }\n // Under the approval's own binding, so a new ph-cli alone does not read as edited files.\n const revision = packageRevision(current.files, {\n [PH_CLI_BINDING]: approval.phCliVersion,\n });\n if (revision !== approval.packageRevision.digest) {\n reasons.push(\"the package's files changed since the approval was made\");\n }\n const approved = new Map(\n approval.publishedFiles.map(({ path, sha256 }) => [path, sha256]),\n );\n const now = new Map(\n current.publishedFiles.map(({ path, sha256 }) => [path, sha256]),\n );\n const added = [...now.keys()].filter((path) => !approved.has(path));\n const removed = [...approved.keys()].filter((path) => !now.has(path));\n const changed = [...now].filter(\n ([path, sha256]) => approved.has(path) && approved.get(path) !== sha256,\n );\n const files = (paths: readonly string[], what: string) =>\n `${plural(paths.length, \"published file\", \"published files\")} ${what} since the approval was made: ${listed(paths)}`;\n if (added.length > 0) reasons.push(files(added, \"added\"));\n if (removed.length > 0) reasons.push(files(removed, \"removed\"));\n if (changed.length > 0) {\n reasons.push(\n files(\n changed.map(([path]) => path),\n \"changed\",\n ),\n );\n }\n return reasons;\n}\n\nfunction decided(\n decision: \"stale\" | \"refused\",\n reasons: readonly string[],\n): ReleaseDecision | undefined {\n if (reasons.length === 0) return undefined;\n const [first, ...rest] = reasons;\n return { decision, reasons: [first, ...rest] };\n}\n\n/**\n * Whether the package as it is now is the one the approval checked. Refused\n * when the approval records a failed check; stale when ph-cli, the package's\n * files or the published files changed since.\n */\nexport function verifyReleaseApproval(\n approval: ReleaseApproval,\n current: CurrentRelease,\n): ReleaseDecision {\n return (\n decided(\"refused\", refusalReasons(approval)) ??\n decided(\"stale\", staleReasons(approval, current)) ?? {\n decision: \"approved\",\n reasons: [],\n }\n );\n}\n","import { spawnSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport {\n mkdtempSync,\n readdirSync,\n readFileSync,\n realpathSync,\n rmSync,\n} from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { join, posix } from \"node:path\";\nimport { gunzipSync } from \"node:zlib\";\nimport { z } from \"zod\";\nimport { isBuildLockFile } from \"../build-control.js\";\nimport { RELEASE_APPROVAL_PATH } from \"./approval.js\";\nimport { byPath, type FileDigest } from \"./revision.js\";\n\nexport type PackedRelease = {\n readonly directory: string;\n readonly tarball: string;\n readonly manifest: PackedManifest;\n readonly files: ReadonlyMap<string, Buffer>;\n readonly dispose: () => void;\n};\n\nconst manifestSchema = z.looseObject({\n name: z.string(),\n version: z.string(),\n main: z.string().optional(),\n exports: z.unknown().optional(),\n dependencies: z.record(z.string(), z.string()).optional(),\n optionalDependencies: z.record(z.string(), z.string()).optional(),\n peerDependencies: z.record(z.string(), z.string()).optional(),\n});\n\nexport type PackedManifest = z.infer<typeof manifestSchema>;\n\nconst packListing = z.array(\n z.object({ name: z.string(), version: z.string(), filename: z.string() }),\n);\n\n/** npm refuses `--workspaces=false` while its configuration selects one. */\nconst SELECTS_WORKSPACE = /--no-workspaces and --workspace/;\n\nexport const selectsAnotherPackage = (packageRoot: string) =>\n `npm's configuration (a workspace setting in the environment or an .npmrc) selects a package other than the one in ${packageRoot}; the release approval covers that package only.`;\n\nconst BLOCK = 512;\n\nfunction field(header: Buffer, start: number, length: number): string {\n const bytes = header.subarray(start, start + length);\n const end = bytes.indexOf(0);\n return bytes.subarray(0, end === -1 ? length : end).toString(\"utf8\");\n}\n\nfunction paxPath(body: Buffer): string | undefined {\n for (let offset = 0; offset < body.length;) {\n const space = body.indexOf(0x20, offset);\n const length = Number(body.subarray(offset, space).toString(\"ascii\"));\n if (space === -1 || !(length > 0)) return undefined;\n const record = body\n .subarray(space + 1, offset + length - 1)\n .toString(\"utf8\");\n if (record.startsWith(\"path=\")) return record.slice(\"path=\".length);\n offset += length;\n }\n return undefined;\n}\n\nexport function readTarball(tarball: string): Map<string, Buffer> {\n const tar = gunzipSync(readFileSync(tarball));\n const files = new Map<string, Buffer>();\n let longPath: string | undefined;\n for (let offset = 0; offset + BLOCK <= tar.length;) {\n const header = tar.subarray(offset, offset + BLOCK);\n if (header.every((byte) => byte === 0)) break;\n const size = parseInt(field(header, 124, 12).trim() || \"0\", 8);\n const type = String.fromCharCode(header[156] || 48);\n const body = tar.subarray(offset + BLOCK, offset + BLOCK + size);\n offset += BLOCK + Math.ceil(size / BLOCK) * BLOCK;\n if (type === \"x\") {\n longPath = paxPath(body) ?? longPath;\n continue;\n }\n if (type === \"L\") {\n longPath = field(body, 0, body.length);\n continue;\n }\n if (type === \"g\") continue;\n const prefix = field(header, 345, 155);\n const name = field(header, 0, 100);\n const path = longPath ?? (prefix === \"\" ? name : `${prefix}/${name}`);\n longPath = undefined;\n if (type === \"5\") continue;\n const inside = posix.normalize(path.split(\"/\").slice(1).join(\"/\"));\n if (\n inside === \".\" ||\n inside.startsWith(\"../\") ||\n posix.isAbsolute(inside)\n ) {\n throw new Error(`the tarball has an entry outside the package: ${path}`);\n }\n const bytes =\n type === \"1\" || type === \"2\"\n ? Buffer.from(field(header, 157, 100))\n : Buffer.from(body);\n files.set(inside, bytes);\n }\n return files;\n}\n\nexport function packRelease(packageRoot: string): PackedRelease {\n const directory = realpathSync.native(\n mkdtempSync(join(tmpdir(), \"ph-release-\")),\n );\n const dispose = () => rmSync(directory, { recursive: true, force: true });\n try {\n const packed = spawnSync(\n \"npm\",\n [\n \"pack\",\n \"--json\",\n \"--ignore-scripts\",\n \"--workspaces=false\",\n \"--pack-destination\",\n // cmd.exe splits an unquoted path at its spaces.\n process.platform === \"win32\" ? `\"${directory}\"` : directory,\n ],\n {\n cwd: packageRoot,\n encoding: \"utf8\",\n maxBuffer: 256 * 1024 * 1024,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n shell: process.platform === \"win32\",\n },\n );\n if (packed.status !== 0) {\n if (SELECTS_WORKSPACE.test(`${packed.stdout}${packed.stderr}`)) {\n throw new Error(selectsAnotherPackage(packageRoot));\n }\n throw new Error(\n `npm pack could not pack the package: ${(packed.stderr || packed.error?.message || packed.stdout).trim()}`,\n );\n }\n const listings = packListing.parse(JSON.parse(packed.stdout));\n const root = z\n .object({ name: z.string(), version: z.string() })\n .parse(\n JSON.parse(readFileSync(join(packageRoot, \"package.json\"), \"utf8\")),\n );\n const [listing] = listings;\n const tarballs = readdirSync(directory);\n if (\n listings.length !== 1 ||\n listing.name !== root.name ||\n listing.version !== root.version ||\n tarballs.length !== 1\n ) {\n const packs = listings.map(({ name, version }) => `${name}@${version}`);\n throw new Error(\n `npm pack packs ${packs.join(\", \") || \"no package\"}, not ${root.name}@${root.version}: ${selectsAnotherPackage(packageRoot)}`,\n );\n }\n const tarball = join(directory, tarballs[0]);\n const files = readTarball(tarball);\n const manifestBytes = files.get(\"package.json\");\n if (manifestBytes === undefined) {\n throw new Error(\"npm pack wrote a tarball without a package.json\");\n }\n const manifest = manifestSchema.parse(\n JSON.parse(manifestBytes.toString(\"utf8\")),\n );\n return { directory, tarball, manifest, files, dispose };\n } catch (error) {\n dispose();\n throw error;\n }\n}\n\nexport function packedDigests(packed: PackedRelease): FileDigest[] {\n return [...packed.files]\n .filter(\n ([path]) => path !== RELEASE_APPROVAL_PATH && !isBuildLockFile(path),\n )\n .map(([path, bytes]) => ({\n path,\n sha256: createHash(\"sha256\").update(bytes).digest(\"hex\"),\n }))\n .sort(byPath);\n}\n","import { spawnSync } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport {\n type Dirent,\n existsSync,\n lstatSync,\n mkdirSync,\n readdirSync,\n readFileSync,\n readlinkSync,\n renameSync,\n rmSync,\n writeFileSync,\n} from \"node:fs\";\nimport { dirname, join, relative, resolve, sep } from \"node:path\";\nimport {\n type ApprovalRead,\n parseReleaseApproval,\n RELEASE_APPROVAL_PATH,\n type ReleaseApproval,\n} from \"./approval.js\";\nimport { packedDigests, packRelease } from \"./pack.js\";\nimport { byPath, type FileDigest } from \"./revision.js\";\n\nconst ALWAYS_EXCLUDED = new Set([\"node_modules\", \".git\", \".ph\"]);\n// A build's stage and retired tree, beside its output while it runs.\nconst BUILD_SCRATCH = /^\\..+\\.ph-(stage|old)-/;\n\nconst toPosix = (path: string) => path.split(sep).join(\"/\");\n\n/** `path` relative to the package root, in POSIX form. */\nexport function packagePath(packageRoot: string, path: string): string {\n return toPosix(relative(packageRoot, resolve(packageRoot, path)));\n}\n\nfunction sha256(bytes: string | Buffer): string {\n return createHash(\"sha256\").update(bytes).digest(\"hex\");\n}\n\n/** A file's digest; a symlink's is its target text, which is not followed. */\nfunction digestOf(packageRoot: string, path: string): FileDigest | undefined {\n const absolute = join(packageRoot, ...path.split(\"/\"));\n const stat = lstatSync(absolute, { throwIfNoEntry: false });\n if (stat?.isSymbolicLink()) {\n return { path, sha256: sha256(toPosix(readlinkSync(absolute))) };\n }\n return stat?.isFile()\n ? { path, sha256: sha256(readFileSync(absolute)) }\n : undefined;\n}\n\nfunction insideWorkTree(packageRoot: string): boolean {\n const probe = spawnSync(\"git\", [\"rev-parse\", \"--is-inside-work-tree\"], {\n cwd: packageRoot,\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n });\n return probe.status === 0 && probe.stdout.trim() === \"true\";\n}\n\n/** Tracked and untracked files git does not ignore, relative to the package root. */\nfunction gitFiles(packageRoot: string): string[] {\n const listed = spawnSync(\n \"git\",\n [\"ls-files\", \"-co\", \"--exclude-standard\", \"-z\"],\n {\n cwd: packageRoot,\n encoding: \"utf8\",\n maxBuffer: 256 * 1024 * 1024,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n },\n );\n if (listed.status !== 0) {\n throw new Error(\n `git ls-files could not list the package's files: ${listed.stderr || listed.error?.message}`,\n );\n }\n return [...new Set(listed.stdout.split(\"\\0\").filter(Boolean))];\n}\n\n/**\n * Every file under the package root, by POSIX path, without entering a\n * directory `included` rejects. Throws when a directory cannot be read.\n */\nfunction walkedFiles(\n packageRoot: string,\n included: (path: string) => boolean,\n): string[] {\n const files: string[] = [];\n const visit = (directory: string, prefix: string) => {\n let entries: Dirent[];\n try {\n entries = readdirSync(directory, { withFileTypes: true });\n } catch (error) {\n throw new Error(\n `the package directory ${prefix || \".\"} cannot be read: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n for (const entry of entries) {\n const path = prefix === \"\" ? entry.name : `${prefix}/${entry.name}`;\n if (!included(path)) continue;\n if (entry.isDirectory()) {\n visit(join(directory, entry.name), path);\n } else {\n files.push(path);\n }\n }\n };\n visit(packageRoot, \"\");\n return files;\n}\n\n/**\n * The files the package revision reads, with their digests: what git tracks\n * or would track inside a work tree, every file otherwise. Leaves out\n * node_modules, .git, .ph, a build's stage, and each excluded path (the\n * output directory, compiler outputs) with what is under it.\n */\nexport function revisionFiles(\n packageRoot: string,\n excluded: readonly string[],\n): FileDigest[] {\n const included = (path: string) =>\n !path\n .split(\"/\")\n .some(\n (segment) =>\n ALWAYS_EXCLUDED.has(segment) || BUILD_SCRATCH.test(segment),\n ) &&\n !excluded.some(\n (exclusion) => path === exclusion || path.startsWith(`${exclusion}/`),\n );\n const paths = insideWorkTree(packageRoot)\n ? gitFiles(packageRoot)\n : walkedFiles(packageRoot, included);\n return paths\n .filter(included)\n .flatMap((path) => digestOf(packageRoot, path) ?? [])\n .sort(byPath);\n}\n\n/**\n * What `npm pack` publishes from the package root, with digests read from the\n * packed tarball. Workspaces are off, so npm packs the root package or\n * refuses; a tarball of another package than the root's package.json names\n * throws as well.\n */\nexport function publishedFiles(packageRoot: string): FileDigest[] {\n const packed = packRelease(packageRoot);\n try {\n return packedDigests(packed);\n } finally {\n packed.dispose();\n }\n}\n\nconst approvalFile = (packageRoot: string) =>\n join(packageRoot, ...RELEASE_APPROVAL_PATH.split(\"/\"));\n\nexport function readReleaseApproval(packageRoot: string): ApprovalRead {\n const file = approvalFile(packageRoot);\n if (!existsSync(file)) return { kind: \"missing\" };\n let text: string;\n try {\n text = readFileSync(file, \"utf8\");\n } catch (error) {\n return {\n kind: \"unreadable\",\n reason: error instanceof Error ? error.message : String(error),\n };\n }\n return parseReleaseApproval(text);\n}\n\n/** Replaces the approval in one rename, so a reader never sees half of one. */\nexport function writeReleaseApproval(\n packageRoot: string,\n approval: ReleaseApproval,\n): void {\n const file = approvalFile(packageRoot);\n mkdirSync(dirname(file), { recursive: true });\n const temporary = `${file}.${process.pid}.tmp`;\n try {\n writeFileSync(temporary, `${JSON.stringify(approval, null, 2)}\\n`);\n renameSync(temporary, file);\n } finally {\n rmSync(temporary, { force: true });\n }\n}\n"],"names":["z.object","z.string","z.looseObject","z.enum","z.literal","z.templateLiteral","z.array","z\n .array","z\n .array","z.discriminatedUnion","z.looseObject","z.string","z.unknown","z.record","z.array","z.object","z\n .object"],"mappings":";;;;;;;;;;;AAGA,MAAa,kBAAkB,KAAK,OAAO,OAAO;AAClD,MAAa,YAAY,KAAK,iBAAiB,MAAM;AAErD,MAAa,kBAAkB,aAAqB,GAAG,SAAS;AAChE,MAAa,iBAAiB,aAAqB,IAAI,SAAS;AAEhE,SAAgB,gBAAgB,MAAuB;CACrD,MAAM,WAAW,SAAS,SAAS;CACnC,MAAM,OAAO,MAAM,SAAS,IAAI;CAChC,OACE,MAAM,QAAQ,IAAI,MAAM,gBAAgB,MAAM,GAAG,CAAC,CAAC,KAAK,GAAG,MAC1D,SAAS,YACR,KAAK,WAAW,eAAe,QAAQ,CAAC,KACxC,KAAK,WAAW,cAAc,QAAQ,CAAC;AAE7C;;;;;;;;ACNA,SAAgB,gBACd,OACA,UACQ;CACR,MAAM,OAAO,WAAW,QAAQ;CAChC,KAAK,MAAM,EAAE,MAAM,YAAY,CAAC,GAAG,KAAK,CAAC,CAAC,KAAK,MAAM,GACnD,KAAK,OAAO,GAAG,KAAK,IAAI,OAAO,GAAG;CAEpC,KAAK,MAAM,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,KAAK,GAC3C,KAAK,OAAO,WAAW,IAAI,IAAI,SAAS,KAAK,GAAG;CAElD,OAAO,UAAU,KAAK,OAAO,KAAK;AACpC;AAEA,SAA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AAA,CAElC,OAAO,QAAQ,CAAC,CAChB,SAAS,SAAS,SAAS,aAAa,IAAI,KAAK,CAAC,CAAC,CAAC,CACpD,KAAK,MAAM;AAChB;;;;;;;AAQA,SAAgB,eAAe,aAAmC;CAChE,MAAM,SAAS,YAAY,WAAW;CACtC,IAAI;EACF,OAAO,cAAc,MAAM;CAC7B,UAAU;EACR,OAAO,QAAQ;CACjB;AACF;AAEA,MAAM,gBAAgB,gBACpB,KAAK,aAAa,GAAG,sBAAsB,MAAM,GAAG,CAAC;AAEvD,SAAgB,oBAAoB,aAAmC;CACrE,MAAM,OAAO,aAAa,WAAW;CACrC,IAAI,CAAC,WAAW,IAAI,GAAG,OAAO,EAAE,MAAM,UAAU;CAChD,IAAI;CACJ,IAAI;EACF,OAAO,aAAa,MAAM,MAAM;CAClC,SAAS,OAAO;EACd,OAAO;GACL,MAAM;GACN,QAAQ,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAC/D;CACF;CACA,OAAO,qBAAqB,IAAI;AAClC;;AAGA,SAAgB,qBACd,aACA,UACM;CACN,MAAM,OAAO,aAAa,WAAW;CACrC,UAAU,QAAQ,IAAI,GAAG,EAAE,WAAW,KAAK,CAAC;CAC5C,MAAM,YAAY,GAAG,KAAK,GAAG,QAAQ,IAAI;CACzC,IAAI;EACF,cAAc,WAAW,GAAG,KAAK,UAAU,UAAU,MAAM,CAAC,EAAE,GAAG;EACjE,WAAW,WAAW,IAAI;CAC5B,UAAU;EACR,OAAO,WAAW,EAAE,OAAO,KAAK,CAAC;CACnC;AACF","debug_id":"f99e2579-f543-5f1e-a61e-983f65051040"}
|
|
@@ -1,28 +1,13 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
3
|
-
import { U as probeHostsFolder } from "./compound-Q9sZSEZF-
|
|
4
|
-
import { t as warnSubgraphTypeConflicts } from "./warn-subgraph-type-conflicts-
|
|
2
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="83b0362d-9ad4-573f-86b3-534dd80d8e6b")}catch(e){}}();
|
|
3
|
+
import { U as probeHostsFolder } from "./compound-Q9sZSEZF-DQvtoigb.mjs";
|
|
4
|
+
import { t as warnSubgraphTypeConflicts } from "./warn-subgraph-type-conflicts-BZ4NwLx5.mjs";
|
|
5
5
|
import { t as startGenerateHosts } from "./generate-hosts-BFmPIW2X.mjs";
|
|
6
6
|
import { modelGeneration } from "@powerhousedao/codegen";
|
|
7
7
|
import { buildTsMorphProject } from "@powerhousedao/codegen/utils";
|
|
8
|
-
import { extractAllDocuments, saveSpec } from "@powerhousedao/vetra/codegen";
|
|
9
8
|
//#region src/services/generate-all.ts
|
|
10
|
-
async function startGenerateAll(
|
|
9
|
+
async function startGenerateAll(projectDir) {
|
|
11
10
|
const project = buildTsMorphProject(projectDir);
|
|
12
|
-
if (args.extract) {
|
|
13
|
-
const all = extractAllDocuments(project);
|
|
14
|
-
for (const doc of [
|
|
15
|
-
...all.documentModels,
|
|
16
|
-
...all.editors,
|
|
17
|
-
...all.processors,
|
|
18
|
-
...all.subgraphs,
|
|
19
|
-
...all.apps
|
|
20
|
-
]) {
|
|
21
|
-
const path = await saveSpec(doc, projectDir);
|
|
22
|
-
console.log(`Wrote ${path}`);
|
|
23
|
-
}
|
|
24
|
-
return;
|
|
25
|
-
}
|
|
26
11
|
await modelGeneration.generateAll(project);
|
|
27
12
|
await project.save();
|
|
28
13
|
await warnSubgraphTypeConflicts(projectDir);
|
|
@@ -31,5 +16,5 @@ async function startGenerateAll(args, projectDir) {
|
|
|
31
16
|
//#endregion
|
|
32
17
|
export { startGenerateAll };
|
|
33
18
|
|
|
34
|
-
//# sourceMappingURL=generate-all-
|
|
35
|
-
//# debugId=
|
|
19
|
+
//# sourceMappingURL=generate-all-BE8UmbJv.mjs.map
|
|
20
|
+
//# debugId=83b0362d-9ad4-573f-86b3-534dd80d8e6b
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generate-all-BE8UmbJv.mjs","sources":["../src/services/generate-all.ts"],"sourcesContent":["import { modelGeneration } from \"@powerhousedao/codegen\";\nimport { buildTsMorphProject } from \"@powerhousedao/codegen/utils\";\nimport { probeHostsFolder } from \"@powerhousedao/host-core\";\nimport { warnSubgraphTypeConflicts } from \"../utils/warn-subgraph-type-conflicts.js\";\nimport { startGenerateHosts } from \"./generate-hosts.js\";\n\nexport async function startGenerateAll(projectDir: string) {\n const project = buildTsMorphProject(projectDir);\n await modelGeneration.generateAll(project);\n await project.save();\n await warnSubgraphTypeConflicts(projectDir);\n if (\n probeHostsFolder(projectDir).kind === \"present\" &&\n !(await startGenerateHosts(projectDir))\n ) {\n process.exitCode = 1;\n }\n}\n"],"names":[],"mappings":";;;;;;;;AAMA,eAAsB,iBAAiB,YAAoB;CACzD,MAAM,UAAU,oBAAoB,UAAU;CAC9C,MAAM,gBAAgB,YAAY,OAAO;CACzC,MAAM,QAAQ,KAAK;CACnB,MAAM,0BAA0B,UAAU;CAC1C,IACE,iBAAiB,UAAU,CAAC,CAAC,SAAS,aACtC,CAAE,MAAM,mBAAmB,UAAU,GAErC,QAAQ,WAAW;AAEvB","debug_id":"83b0362d-9ad4-573f-86b3-534dd80d8e6b"}
|
|
@@ -1,26 +1,16 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
2
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b86b085e-d6be-53cb-bc30-7a4457d62ae3")}catch(e){}}();
|
|
3
3
|
import { t as resolveModuleDirName } from "./module-dir-1avCXsBi.mjs";
|
|
4
4
|
import { existsSync } from "node:fs";
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
import { generateAllApps, generateApp } from "@powerhousedao/codegen";
|
|
7
7
|
import { buildTsMorphProject, getAppMetadata, getEditorMetadata } from "@powerhousedao/codegen/utils";
|
|
8
|
-
import { extractAppDocuments, generateAppFromDocument, getDocument, saveSpec } from "@powerhousedao/vetra/codegen";
|
|
9
8
|
//#region src/services/generate-app.ts
|
|
10
9
|
const MODULE_FILE_EXPECTATION = "an EditorModule with string literals for config.id, config.name and documentTypes";
|
|
11
10
|
async function startGenerateApp(args, projectDir) {
|
|
12
|
-
const { name, allowedDocumentTypes = [], disableDragAndDrop,
|
|
11
|
+
const { name, allowedDocumentTypes = [], disableDragAndDrop, dir, all, debug } = args;
|
|
13
12
|
if (debug) console.log({ args });
|
|
14
13
|
const project = buildTsMorphProject(projectDir);
|
|
15
|
-
if (extract) {
|
|
16
|
-
const docs = extractAppDocuments(project);
|
|
17
|
-
if (docs.length === 0) console.log("No drive apps found in editors/.");
|
|
18
|
-
for (const doc of docs) {
|
|
19
|
-
const path = await saveSpec(doc, projectDir);
|
|
20
|
-
console.log(`Wrote ${path}`);
|
|
21
|
-
}
|
|
22
|
-
return;
|
|
23
|
-
}
|
|
24
14
|
if (all) {
|
|
25
15
|
const { apps, unreadableDirs } = await generateAllApps(project);
|
|
26
16
|
await project.save();
|
|
@@ -28,9 +18,6 @@ async function startGenerateApp(args, projectDir) {
|
|
|
28
18
|
for (const app of apps) console.log(`Regenerated app "${app.name}" in editors/${app.dirName}`);
|
|
29
19
|
for (const dirName of unreadableDirs) console.warn(`Skipped editors/${dirName}: expected its module.ts to export ${MODULE_FILE_EXPECTATION}. Kept the manifest's apps.`);
|
|
30
20
|
return;
|
|
31
|
-
} else if (document) {
|
|
32
|
-
const doc = await getDocument(document);
|
|
33
|
-
await generateAppFromDocument(doc, project);
|
|
34
21
|
} else if (name) await generateApp({
|
|
35
22
|
appName: name,
|
|
36
23
|
allowedDocumentTypes,
|
|
@@ -51,7 +38,7 @@ async function startGenerateApp(args, projectDir) {
|
|
|
51
38
|
console.log(`Regenerated app "${appName}" in editors/${appDirName}`);
|
|
52
39
|
return;
|
|
53
40
|
} else {
|
|
54
|
-
console.log("Please specify one of `name`, `
|
|
41
|
+
console.log("Please specify one of `name`, `dir`, or `all`.");
|
|
55
42
|
return;
|
|
56
43
|
}
|
|
57
44
|
await project.save();
|
|
@@ -68,5 +55,5 @@ function resolveAppDirName(project, projectDir, dir) {
|
|
|
68
55
|
//#endregion
|
|
69
56
|
export { startGenerateApp };
|
|
70
57
|
|
|
71
|
-
//# sourceMappingURL=generate-app-
|
|
72
|
-
//# debugId=
|
|
58
|
+
//# sourceMappingURL=generate-app-C7n0j8Ak.mjs.map
|
|
59
|
+
//# debugId=b86b085e-d6be-53cb-bc30-7a4457d62ae3
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generate-app-C7n0j8Ak.mjs","sources":["../src/services/generate-app.ts"],"sourcesContent":["import { generateAllApps, generateApp } from \"@powerhousedao/codegen\";\nimport {\n buildTsMorphProject,\n getAppMetadata,\n getEditorMetadata,\n} from \"@powerhousedao/codegen/utils\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { GenerateAppArgs } from \"../types.js\";\nimport { resolveModuleDirName } from \"../utils/module-dir.js\";\n\nconst MODULE_FILE_EXPECTATION =\n \"an EditorModule with string literals for config.id, config.name and documentTypes\";\n\nexport async function startGenerateApp(\n args: GenerateAppArgs,\n projectDir: string,\n) {\n const {\n name,\n allowedDocumentTypes = [],\n disableDragAndDrop,\n dir,\n all,\n debug,\n } = args;\n if (debug) {\n console.log({ args });\n }\n const project = buildTsMorphProject(projectDir);\n if (all) {\n const { apps, unreadableDirs } = await generateAllApps(project);\n await project.save();\n if (apps.length === 0 && unreadableDirs.length === 0) {\n console.log(\"No drive apps found in editors/.\");\n }\n for (const app of apps) {\n console.log(`Regenerated app \"${app.name}\" in editors/${app.dirName}`);\n }\n for (const dirName of unreadableDirs) {\n console.warn(\n `Skipped editors/${dirName}: expected its module.ts to export ${MODULE_FILE_EXPECTATION}. Kept the manifest's apps.`,\n );\n }\n return;\n } else if (name) {\n await generateApp(\n {\n appName: name,\n allowedDocumentTypes,\n isDragAndDropEnabled: !disableDragAndDrop,\n },\n project,\n );\n } else if (dir) {\n const appMetadata = getAppMetadata(\n project,\n resolveAppDirName(project, projectDir, dir),\n );\n if (!appMetadata) {\n throw new Error(`Failed to get data for app in dir \"${dir}\"`);\n }\n const {\n name: appName,\n id: appId,\n dirName: appDirName,\n allowedDocumentTypes,\n isDragAndDropEnabled,\n } = appMetadata;\n\n await generateApp(\n {\n appName,\n appId,\n appDirName,\n allowedDocumentTypes,\n isDragAndDropEnabled,\n },\n project,\n );\n await project.save();\n console.log(`Regenerated app \"${appName}\" in editors/${appDirName}`);\n return;\n } else {\n console.log(\"Please specify one of `name`, `dir`, or `all`.\");\n return;\n }\n await project.save();\n}\n\n/** The app directory that `--dir` names, checked to hold a drive app's module.ts */\nfunction resolveAppDirName(\n project: ReturnType<typeof buildTsMorphProject>,\n projectDir: string,\n dir: string,\n) {\n const dirName = resolveModuleDirName(projectDir, \"editors\", dir, \"my-app\");\n if (!existsSync(join(projectDir, \"editors\", dirName, \"module.ts\"))) {\n throw new Error(`editors/${dirName} has no module.ts.`);\n }\n const editorMetadata = getEditorMetadata(project, dirName);\n if (!editorMetadata) {\n throw new Error(\n `Could not read editors/${dirName}/module.ts: expected ${MODULE_FILE_EXPECTATION}.`,\n );\n }\n if (!editorMetadata.documentTypes.includes(\"powerhouse/document-drive\")) {\n throw new Error(\n `editors/${dirName} is a document editor, not a drive app: its documentTypes don't include \"powerhouse/document-drive\". Use \\`ph-cli generate editor --dir ${dirName}\\` instead.`,\n );\n }\n return dirName;\n}\n"],"names":[],"mappings":";;;;;;;;AAWA,MAAM,0BACJ;AAEF,eAAsB,iBACpB,MACA,YACA;CACA,MAAM,EACJ,MACA,uBAAuB,CAAC,GACxB,oBACA,KACA,KACA,UACE;CACJ,IAAI,OACF,QAAQ,IAAI,EAAE,KAAK,CAAC;CAEtB,MAAM,UAAU,oBAAoB,UAAU;CAC9C,IAAI,KAAK;EACP,MAAM,EAAE,MAAM,mBAAmB,MAAM,gBAAgB,OAAO;EAC9D,MAAM,QAAQ,KAAK;EACnB,IAAI,KAAK,WAAW,KAAK,eAAe,WAAW,GACjD,QAAQ,IAAI,kCAAkC;EAEhD,KAAK,MAAM,OAAO,MAChB,QAAQ,IAAI,oBAAoB,IAAI,KAAK,eAAe,IAAI,SAAS;EAEvE,KAAK,MAAM,WAAW,gBACpB,QAAQ,KACN,mBAAmB,QAAQ,qCAAqC,wBAAwB,4BAC1F;EAEF;CACF,OAAO,IAAI,MACT,MAAM,YACJ;EACE,SAAS;EACT;EACA,sBAAsB,CAAC;CACzB,GACA,OACF;MACK,IAAI,KAAK;EACd,MAAM,cAAc,eAClB,SACA,kBAAkB,SAAS,YAAY,GAAG,CAC5C;EACA,IAAI,CAAC,aACH,MAAM,IAAI,MAAM,sCAAsC,IAAI,EAAE;EAE9D,MAAM,EACJ,MAAM,SACN,IAAI,OACJ,SAAS,YACT,sBACA,yBACE;EAEJ,MAAM,YACJ;GACE;GACA;GACA;GACA;GACA;EACF,GACA,OACF;EACA,MAAM,QAAQ,KAAK;EACnB,QAAQ,IAAI,oBAAoB,QAAQ,eAAe,YAAY;EACnE;CACF,OAAO;EACL,QAAQ,IAAI,gDAAgD;EAC5D;CACF;CACA,MAAM,QAAQ,KAAK;AACrB;;AAGA,SAAS,kBACP,SACA,YACA,KACA;CACA,MAAM,UAAU,qBAAqB,YAAY,WAAW,KAAK,QAAQ;CACzE,IAAI,CAAC,WAAW,KAAK,YAAY,WAAW,SAAS,WAAW,CAAC,GAC/D,MAAM,IAAI,MAAM,WAAW,QAAQ,mBAAmB;CAExD,MAAM,iBAAiB,kBAAkB,SAAS,OAAO;CACzD,IAAI,CAAC,gBACH,MAAM,IAAI,MACR,0BAA0B,QAAQ,uBAAuB,wBAAwB,EACnF;CAEF,IAAI,CAAC,eAAe,cAAc,SAAS,2BAA2B,GACpE,MAAM,IAAI,MACR,WAAW,QAAQ,0IAA0I,QAAQ,YACvK;CAEF,OAAO;AACT","debug_id":"b86b085e-d6be-53cb-bc30-7a4457d62ae3"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
3
|
-
import { t as warnSubgraphTypeConflicts } from "./warn-subgraph-type-conflicts-
|
|
2
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="20df4d67-b636-5349-964d-d9245a565596")}catch(e){}}();
|
|
3
|
+
import { t as warnSubgraphTypeConflicts } from "./warn-subgraph-type-conflicts-BZ4NwLx5.mjs";
|
|
4
4
|
import { t as resolveModuleDirName } from "./module-dir-1avCXsBi.mjs";
|
|
5
5
|
import { existsSync } from "node:fs";
|
|
6
6
|
import { join, relative } from "node:path";
|
|
@@ -8,7 +8,6 @@ import { loadDocumentModel, modelGeneration } from "@powerhousedao/codegen";
|
|
|
8
8
|
import { handleMutuallyExclusiveOptions } from "@powerhousedao/shared/clis";
|
|
9
9
|
import { buildTsMorphProject, documentModelsDirOf } from "@powerhousedao/codegen/utils";
|
|
10
10
|
import { readPackage } from "read-pkg";
|
|
11
|
-
import { extractDocumentModelDocuments, getDocument, saveSpec } from "@powerhousedao/vetra/codegen";
|
|
12
11
|
import { capitalCase, kebabCase } from "change-case";
|
|
13
12
|
//#region src/services/definitions/code-first-scaffold.ts
|
|
14
13
|
async function scaffoldCodeFirstDocumentModel(generation, name, projectDir, project) {
|
|
@@ -52,7 +51,7 @@ function modelsDirOf(projectDir) {
|
|
|
52
51
|
return relative(projectDir, documentModelsDirOf(projectDir).path).replaceAll("\\", "/");
|
|
53
52
|
}
|
|
54
53
|
async function startGenerateDocumentModel(args, projectDir) {
|
|
55
|
-
const {
|
|
54
|
+
const { dir, all, name, codeFirst, debug } = args;
|
|
56
55
|
if (debug) console.log({ args });
|
|
57
56
|
if (name !== void 0 && !codeFirst) throw new Error("--name creates a code-first document model. Pass --code-first.");
|
|
58
57
|
if (codeFirst && name === void 0) throw new Error("--code-first only chooses how --name creates a model. Existing models of both styles are discovered without it; drop --code-first. To convert a schema-first model, run ph migrate --document-model <dir>.");
|
|
@@ -60,22 +59,12 @@ async function startGenerateDocumentModel(args, projectDir) {
|
|
|
60
59
|
if (name !== void 0) {
|
|
61
60
|
handleMutuallyExclusiveOptions({
|
|
62
61
|
"--name": name,
|
|
63
|
-
"--document": document,
|
|
64
62
|
"--dir": dir,
|
|
65
|
-
"--all": all || void 0
|
|
66
|
-
"--extract": extract || void 0
|
|
63
|
+
"--all": all || void 0
|
|
67
64
|
}, "generation mode");
|
|
68
65
|
await scaffoldCodeFirstDocumentModel(modelGeneration, name, projectDir, project);
|
|
69
66
|
return;
|
|
70
67
|
}
|
|
71
|
-
if (extract) {
|
|
72
|
-
const docs = extractDocumentModelDocuments(project);
|
|
73
|
-
for (const doc of docs) {
|
|
74
|
-
const path = await saveSpec(doc, projectDir);
|
|
75
|
-
console.log(`Wrote ${path}`);
|
|
76
|
-
}
|
|
77
|
-
return;
|
|
78
|
-
}
|
|
79
68
|
if (all) {
|
|
80
69
|
const { documentModels, unreadableDirs, codeFirstDocumentModels } = await modelGeneration.generateAllDocumentModels(project);
|
|
81
70
|
await project.save();
|
|
@@ -85,15 +74,8 @@ async function startGenerateDocumentModel(args, projectDir) {
|
|
|
85
74
|
for (const dirName of unreadableDirs) console.warn(`Skipped ${modelsDirOf(projectDir)}/${dirName}: it has no readable ${dirName}.json, and no index.ts in it exports a code-first model. Kept the manifest's document models.`);
|
|
86
75
|
await warnSubgraphTypeConflicts(projectDir);
|
|
87
76
|
return;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
const doc = await getDocument(document);
|
|
91
|
-
await modelGeneration.generateDocumentModel(doc.state.global, project);
|
|
92
|
-
} else {
|
|
93
|
-
const state = await loadDocumentModel(document);
|
|
94
|
-
await modelGeneration.generateDocumentModel(state, project);
|
|
95
|
-
}
|
|
96
|
-
} else if (dir) {
|
|
77
|
+
}
|
|
78
|
+
if (dir) {
|
|
97
79
|
const modelsDir = modelsDirOf(projectDir);
|
|
98
80
|
const dirName = resolveModuleDirName(projectDir, modelsDir, dir, "my-document-model");
|
|
99
81
|
const specPath = join(projectDir, modelsDir, dirName, `${dirName}.json`);
|
|
@@ -104,15 +86,11 @@ async function startGenerateDocumentModel(args, projectDir) {
|
|
|
104
86
|
console.log(`Regenerated document model "${state.name}" in ${modelsDir}/${dirName}`);
|
|
105
87
|
await warnSubgraphTypeConflicts(projectDir);
|
|
106
88
|
return;
|
|
107
|
-
} else {
|
|
108
|
-
console.log("Please specify one of `document`, `dir`, `all`, or `extract`.");
|
|
109
|
-
return;
|
|
110
89
|
}
|
|
111
|
-
|
|
112
|
-
await warnSubgraphTypeConflicts(projectDir);
|
|
90
|
+
console.log("Please specify one of `name`, `dir`, or `all`.");
|
|
113
91
|
}
|
|
114
92
|
//#endregion
|
|
115
93
|
export { startGenerateDocumentModel };
|
|
116
94
|
|
|
117
|
-
//# sourceMappingURL=generate-document-model-
|
|
118
|
-
//# debugId=
|
|
95
|
+
//# sourceMappingURL=generate-document-model-DSYPTMZg.mjs.map
|
|
96
|
+
//# debugId=20df4d67-b636-5349-964d-d9245a565596
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generate-document-model-DSYPTMZg.mjs","sources":["../src/services/definitions/code-first-scaffold.ts","../src/services/generate-document-model.ts"],"sourcesContent":["import type { ModelGeneration } from \"@powerhousedao/codegen\";\nimport { capitalCase, kebabCase } from \"change-case\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { readPackage } from \"read-pkg\";\nimport type { Project } from \"ts-morph\";\n\nexport async function scaffoldCodeFirstDocumentModel(\n generation: ModelGeneration,\n name: string,\n projectDir: string,\n project: Project,\n) {\n const modelName = name.trim();\n if (modelName === \"\") {\n throw new Error(\"--name needs a document model name.\");\n }\n const namespace = await documentTypeNamespace(projectDir);\n const documentType = `${namespace}/${kebabCase(modelName)}`;\n const editorName = `${capitalCase(modelName)} Editor`;\n const editorDirName = kebabCase(editorName);\n if (existsSync(join(projectDir, \"editors\", editorDirName))) {\n throw new Error(\n `editors/${editorDirName} already exists. Choose another --name, or move that editor first.`,\n );\n }\n\n const result = await generation.scaffoldDocumentModel(\n {\n name: modelName,\n documentType,\n author: { name: namespace, website: null },\n },\n project,\n );\n for (const path of result.written) {\n console.log(`Wrote ${path}`);\n }\n\n await generation.generateEditor(\n {\n editorName,\n documentTypes: [documentType],\n editorId: editorDirName,\n editorDirName,\n },\n project,\n );\n await project.save();\n console.log(`Generated editor \"${editorName}\" in editors/${editorDirName}`);\n}\n\nasync function documentTypeNamespace(projectDir: string) {\n const { name } = await readPackage({ cwd: projectDir, normalize: false });\n if (!name) {\n throw new Error(\n \"--name puts the document type under the package name. Add a name to package.json.\",\n );\n }\n return name.replace(/^@/, \"\").replaceAll(\"/\", \"-\");\n}\n","import { loadDocumentModel, modelGeneration } from \"@powerhousedao/codegen\";\nimport {\n buildTsMorphProject,\n documentModelsDirOf,\n} from \"@powerhousedao/codegen/utils\";\nimport { handleMutuallyExclusiveOptions } from \"@powerhousedao/shared/clis\";\nimport { existsSync } from \"node:fs\";\nimport { join, relative } from \"node:path\";\nimport type { GenerateDocumentModelArgs } from \"../types.js\";\nimport { resolveModuleDirName } from \"../utils/module-dir.js\";\nimport { warnSubgraphTypeConflicts } from \"../utils/warn-subgraph-type-conflicts.js\";\nimport { scaffoldCodeFirstDocumentModel } from \"./definitions/code-first-scaffold.js\";\n\n/** The configured documentModelsDir, package-relative, for messages and paths. */\nfunction modelsDirOf(projectDir: string) {\n return relative(projectDir, documentModelsDirOf(projectDir).path).replaceAll(\n \"\\\\\",\n \"/\",\n );\n}\n\nexport async function startGenerateDocumentModel(\n args: GenerateDocumentModelArgs,\n projectDir: string,\n) {\n const { dir, all, name, codeFirst, debug } = args;\n if (debug) {\n console.log({ args });\n }\n if (name !== undefined && !codeFirst) {\n throw new Error(\n \"--name creates a code-first document model. Pass --code-first.\",\n );\n }\n if (codeFirst && name === undefined) {\n throw new Error(\n \"--code-first only chooses how --name creates a model. Existing models of both styles are discovered without it; drop --code-first. To convert a schema-first model, run ph migrate --document-model <dir>.\",\n );\n }\n const project = buildTsMorphProject(projectDir);\n if (name !== undefined) {\n handleMutuallyExclusiveOptions(\n {\n \"--name\": name,\n \"--dir\": dir,\n \"--all\": all || undefined,\n },\n \"generation mode\",\n );\n await scaffoldCodeFirstDocumentModel(\n modelGeneration,\n name,\n projectDir,\n project,\n );\n return;\n }\n if (all) {\n const { documentModels, unreadableDirs, codeFirstDocumentModels } =\n await modelGeneration.generateAllDocumentModels(project);\n await project.save();\n if (\n documentModels.length === 0 &&\n unreadableDirs.length === 0 &&\n codeFirstDocumentModels.length === 0\n ) {\n console.log(`No document models found in ${modelsDirOf(projectDir)}/.`);\n }\n for (const { name } of documentModels) {\n console.log(`Regenerated document model \"${name}\"`);\n }\n for (const { name } of codeFirstDocumentModels) {\n console.log(`Updated the exports of code-first document model \"${name}\"`);\n }\n for (const dirName of unreadableDirs) {\n console.warn(\n `Skipped ${modelsDirOf(projectDir)}/${dirName}: it has no readable ${dirName}.json, and no index.ts in it exports a code-first model. Kept the manifest's document models.`,\n );\n }\n await warnSubgraphTypeConflicts(projectDir);\n return;\n }\n if (dir) {\n const modelsDir = modelsDirOf(projectDir);\n const dirName = resolveModuleDirName(\n projectDir,\n modelsDir,\n dir,\n \"my-document-model\",\n );\n const specPath = join(projectDir, modelsDir, dirName, `${dirName}.json`);\n if (!existsSync(specPath)) {\n throw new Error(`${modelsDir}/${dirName} has no ${dirName}.json.`);\n }\n const state = await loadDocumentModel(specPath);\n await modelGeneration.generateDocumentModel(state, project);\n await project.save();\n console.log(\n `Regenerated document model \"${state.name}\" in ${modelsDir}/${dirName}`,\n );\n await warnSubgraphTypeConflicts(projectDir);\n return;\n }\n console.log(\"Please specify one of `name`, `dir`, or `all`.\");\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAOA,eAAsB,+BACpB,YACA,MACA,YACA,SACA;CACA,MAAM,YAAY,KAAK,KAAK;CAC5B,IAAI,cAAc,IAChB,MAAM,IAAI,MAAM,qCAAqC;CAEvD,MAAM,YAAY,MAAM,sBAAsB,UAAU;CACxD,MAAM,eAAe,GAAG,UAAU,GAAG,UAAU,SAAS;CACxD,MAAM,aAAa,GAAG,YAAY,SAAS,EAAE;CAC7C,MAAM,gBAAgB,UAAU,UAAU;CAC1C,IAAI,WAAW,KAAK,YAAY,WAAW,aAAa,CAAC,GACvD,MAAM,IAAI,MACR,WAAW,cAAc,mEAC3B;CAGF,MAAM,SAAS,MAAM,WAAW,sBAC9B;EACE,MAAM;EACN;EACA,QAAQ;GAAE,MAAM;GAAW,SAAS;EAAK;CAC3C,GACA,OACF;CACA,KAAK,MAAM,QAAQ,OAAO,SACxB,QAAQ,IAAI,SAAS,MAAM;CAG7B,MAAM,WAAW,eACf;EACE;EACA,eAAe,CAAC,YAAY;EAC5B,UAAU;EACV;CACF,GACA,OACF;CACA,MAAM,QAAQ,KAAK;CACnB,QAAQ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,WAAW,YAAY,UAAU,EAAE,GAAG,QAAQ,uBAAuB,QAAQ,8FAC/E;EAEF,MAAM,0BAA0B,UAAU;EAC1C;CACF;CACA,IAAI,KAAK;EACP,MAAM,YAAY,YAAY,UAAU;EACxC,MAAM,UAAU,qBACd,YACA,WACA,KACA,mBACF;EACA,MAAM,WAAW,KAAK,YAAY,WAAW,SAAS,GAAG,QAAQ,MAAM;EACvE,IAAI,CAAC,WAAW,QAAQ,GACtB,MAAM,IAAI,MAAM,GAAG,UAAU,GAAG,QAAQ,UAAU,QAAQ,OAAO;EAEnE,MAAM,QAAQ,MAAM,kBAAkB,QAAQ;EAC9C,MAAM,gBAAgB,sBAAsB,OAAO,OAAO;EAC1D,MAAM,QAAQ,KAAK;EACnB,QAAQ,IACN,+BAA+B,MAAM,KAAK,OAAO,UAAU,GAAG,SAChE;EACA,MAAM,0BAA0B,UAAU;EAC1C;CACF;CACA,QAAQ,IAAI,gDAAgD;AAC9D","debug_id":"20df4d67-b636-5349-964d-d9245a565596"}
|
|
@@ -1,35 +1,22 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
2
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="7a309a30-d5b4-555b-a827-2872f00f888f")}catch(e){}}();
|
|
3
3
|
import { t as resolveModuleDirName } from "./module-dir-1avCXsBi.mjs";
|
|
4
4
|
import { existsSync } from "node:fs";
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
import { modelGeneration } from "@powerhousedao/codegen";
|
|
7
7
|
import { buildTsMorphProject, getEditorMetadata } from "@powerhousedao/codegen/utils";
|
|
8
|
-
import { extractEditorDocuments, generateEditorFromDocument, getDocument, saveSpec } from "@powerhousedao/vetra/codegen";
|
|
9
8
|
//#region src/services/generate-editor.ts
|
|
10
9
|
const MODULE_FILE_EXPECTATION = "an EditorModule with string literals for config.id, config.name and documentTypes";
|
|
11
10
|
async function startGenerateEditor(args, projectDir) {
|
|
12
|
-
const { name, documentType,
|
|
11
|
+
const { name, documentType, dir, all, debug } = args;
|
|
13
12
|
if (debug) console.log({ args });
|
|
14
13
|
const project = buildTsMorphProject(projectDir);
|
|
15
|
-
if (extract) {
|
|
16
|
-
const docs = extractEditorDocuments(project);
|
|
17
|
-
if (docs.length === 0) console.log("No document editors found in editors/.");
|
|
18
|
-
for (const doc of docs) {
|
|
19
|
-
const path = await saveSpec(doc, projectDir);
|
|
20
|
-
console.log(`Wrote ${path}`);
|
|
21
|
-
}
|
|
22
|
-
return;
|
|
23
|
-
}
|
|
24
14
|
const report = [];
|
|
25
15
|
if (all) {
|
|
26
16
|
const { editors, unreadableDirs } = await modelGeneration.generateAllEditors(project);
|
|
27
17
|
if (editors.length === 0 && unreadableDirs.length === 0) report.push("No document editors found in editors/.");
|
|
28
18
|
for (const editor of editors) report.push(`Regenerated editor "${editor.name}" in editors/${editor.dirName}`);
|
|
29
19
|
for (const dirName of unreadableDirs) console.warn(`Skipped editors/${dirName}: expected its module.ts to export ${MODULE_FILE_EXPECTATION}. Kept the manifest's editors.`);
|
|
30
|
-
} else if (document) {
|
|
31
|
-
const doc = await getDocument(document);
|
|
32
|
-
await generateEditorFromDocument(doc, project);
|
|
33
20
|
} else if (name) {
|
|
34
21
|
if (!documentType) throw new Error("Please specify a document type for the new editor to generate.");
|
|
35
22
|
await modelGeneration.generateEditor({
|
|
@@ -51,7 +38,7 @@ async function startGenerateEditor(args, projectDir) {
|
|
|
51
38
|
}, project);
|
|
52
39
|
report.push(`Regenerated editor "${editorName}" in editors/${editorDirName}`);
|
|
53
40
|
} else {
|
|
54
|
-
console.log("Please specify one of `name`, `
|
|
41
|
+
console.log("Please specify one of `name`, `dir`, or `all`.");
|
|
55
42
|
return;
|
|
56
43
|
}
|
|
57
44
|
await project.save();
|
|
@@ -60,5 +47,5 @@ async function startGenerateEditor(args, projectDir) {
|
|
|
60
47
|
//#endregion
|
|
61
48
|
export { startGenerateEditor };
|
|
62
49
|
|
|
63
|
-
//# sourceMappingURL=generate-editor-
|
|
64
|
-
//# debugId=
|
|
50
|
+
//# sourceMappingURL=generate-editor-DKuRUeIt.mjs.map
|
|
51
|
+
//# debugId=7a309a30-d5b4-555b-a827-2872f00f888f
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generate-editor-DKuRUeIt.mjs","sources":["../src/services/generate-editor.ts"],"sourcesContent":["import { modelGeneration } from \"@powerhousedao/codegen\";\nimport {\n buildTsMorphProject,\n getEditorMetadata,\n} from \"@powerhousedao/codegen/utils\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { GenerateEditorArgs } from \"../types.js\";\nimport { resolveModuleDirName } from \"../utils/module-dir.js\";\n\nconst MODULE_FILE_EXPECTATION =\n \"an EditorModule with string literals for config.id, config.name and documentTypes\";\n\nexport async function startGenerateEditor(\n args: GenerateEditorArgs,\n projectDir: string,\n) {\n const { name, documentType, dir, all, debug } = args;\n if (debug) {\n console.log({ args });\n }\n const project = buildTsMorphProject(projectDir);\n const report: string[] = [];\n if (all) {\n const { editors, unreadableDirs } =\n await modelGeneration.generateAllEditors(project);\n if (editors.length === 0 && unreadableDirs.length === 0) {\n report.push(\"No document editors found in editors/.\");\n }\n for (const editor of editors) {\n report.push(\n `Regenerated editor \"${editor.name}\" in editors/${editor.dirName}`,\n );\n }\n for (const dirName of unreadableDirs) {\n console.warn(\n `Skipped editors/${dirName}: expected its module.ts to export ${MODULE_FILE_EXPECTATION}. Kept the manifest's editors.`,\n );\n }\n } else if (name) {\n if (!documentType) {\n throw new Error(\n \"Please specify a document type for the new editor to generate.\",\n );\n }\n await modelGeneration.generateEditor(\n { editorName: name, documentTypes: [documentType] },\n project,\n );\n } else if (dir) {\n const dirName = resolveModuleDirName(\n projectDir,\n \"editors\",\n dir,\n \"my-editor\",\n );\n if (!existsSync(join(projectDir, \"editors\", dirName, \"module.ts\"))) {\n throw new Error(`editors/${dirName} has no module.ts.`);\n }\n const editorArgs = getEditorMetadata(project, dirName);\n if (!editorArgs) {\n throw new Error(\n `Could not read editors/${dirName}/module.ts: expected ${MODULE_FILE_EXPECTATION}.`,\n );\n }\n if (editorArgs.documentTypes.includes(\"powerhouse/document-drive\")) {\n throw new Error(\n `editors/${dirName} is a drive app, not a document editor. Use \\`ph-cli generate app --dir ${dirName}\\` instead.`,\n );\n }\n const {\n name: editorName,\n id: editorId,\n dirName: editorDirName,\n documentTypes,\n } = editorArgs;\n await modelGeneration.generateEditor(\n {\n editorName,\n editorId,\n editorDirName,\n documentTypes,\n },\n project,\n );\n report.push(\n `Regenerated editor \"${editorName}\" in editors/${editorDirName}`,\n );\n } else {\n console.log(\"Please specify one of `name`, `dir`, or `all`.\");\n return;\n }\n await project.save();\n for (const line of report) {\n console.log(line);\n }\n}\n"],"names":[],"mappings":";;;;;;;;AAUA,MAAM,0BACJ;AAEF,eAAsB,oBACpB,MACA,YACA;CACA,MAAM,EAAE,MAAM,cAAc,KAAK,KAAK,UAAU;CAChD,IAAI,OACF,QAAQ,IAAI,EAAE,KAAK,CAAC;CAEtB,MAAM,UAAU,oBAAoB,UAAU;CAC9C,MAAM,SAAmB,CAAC;CAC1B,IAAI,KAAK;EACP,MAAM,EAAE,SAAS,mBACf,MAAM,gBAAgB,mBAAmB,OAAO;EAClD,IAAI,QAAQ,WAAW,KAAK,eAAe,WAAW,GACpD,OAAO,KAAK,wCAAwC;EAEtD,KAAK,MAAM,UAAU,SACnB,OAAO,KACL,uBAAuB,OAAO,KAAK,eAAe,OAAO,SAC3D;EAEF,KAAK,MAAM,WAAW,gBACpB,QAAQ,KACN,mBAAmB,QAAQ,qCAAqC,wBAAwB,+BAC1F;CAEJ,OAAO,IAAI,MAAM;EACf,IAAI,CAAC,cACH,MAAM,IAAI,MACR,gEACF;EAEF,MAAM,gBAAgB,eACpB;GAAE,YAAY;GAAM,eAAe,CAAC,YAAY;EAAE,GAClD,OACF;CACF,OAAO,IAAI,KAAK;EACd,MAAM,UAAU,qBACd,YACA,WACA,KACA,WACF;EACA,IAAI,CAAC,WAAW,KAAK,YAAY,WAAW,SAAS,WAAW,CAAC,GAC/D,MAAM,IAAI,MAAM,WAAW,QAAQ,mBAAmB;EAExD,MAAM,aAAa,kBAAkB,SAAS,OAAO;EACrD,IAAI,CAAC,YACH,MAAM,IAAI,MACR,0BAA0B,QAAQ,uBAAuB,wBAAwB,EACnF;EAEF,IAAI,WAAW,cAAc,SAAS,2BAA2B,GAC/D,MAAM,IAAI,MACR,WAAW,QAAQ,0EAA0E,QAAQ,YACvG;EAEF,MAAM,EACJ,MAAM,YACN,IAAI,UACJ,SAAS,eACT,kBACE;EACJ,MAAM,gBAAgB,eACpB;GACE;GACA;GACA;GACA;EACF,GACA,OACF;EACA,OAAO,KACL,uBAAuB,WAAW,eAAe,eACnD;CACF,OAAO;EACL,QAAQ,IAAI,gDAAgD;EAC5D;CACF;CACA,MAAM,QAAQ,KAAK;CACnB,KAAK,MAAM,QAAQ,QACjB,QAAQ,IAAI,IAAI;AAEpB","debug_id":"7a309a30-d5b4-555b-a827-2872f00f888f"}
|
|
@@ -1,34 +1,21 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
2
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="88ec1831-447a-539d-bae5-93d4d91db5af")}catch(e){}}();
|
|
3
3
|
import { t as installAddedDependencies$1 } from "./install-added-dependencies-DnZFR3aE.mjs";
|
|
4
4
|
import { t as resolveModuleDirName } from "./module-dir-1avCXsBi.mjs";
|
|
5
5
|
import { existsSync } from "node:fs";
|
|
6
6
|
import { join } from "node:path";
|
|
7
7
|
import { detectFeatures, generateAllProcessors, generateProcessor, syncFeatureDependencies } from "@powerhousedao/codegen";
|
|
8
8
|
import { buildTsMorphProject, getProcessorMetadata } from "@powerhousedao/codegen/utils";
|
|
9
|
-
import { extractProcessorDocuments, generateProcessorFromDocument, getDocument, saveSpec } from "@powerhousedao/vetra/codegen";
|
|
10
9
|
//#region src/services/generate-processor.ts
|
|
11
10
|
async function startGenerateProcessor(args, projectDir) {
|
|
12
|
-
const { name: processorName, type: processorType, apps: processorApps, documentTypes,
|
|
11
|
+
const { name: processorName, type: processorType, apps: processorApps, documentTypes, dir, all, debug } = args;
|
|
13
12
|
if (debug) console.log({ args });
|
|
14
13
|
const project = buildTsMorphProject(projectDir);
|
|
15
|
-
if (extract) {
|
|
16
|
-
const docs = extractProcessorDocuments(project);
|
|
17
|
-
if (docs.length === 0) console.log("No processors found in processors/.");
|
|
18
|
-
for (const doc of docs) {
|
|
19
|
-
const path = await saveSpec(doc, projectDir);
|
|
20
|
-
console.log(`Wrote ${path}`);
|
|
21
|
-
}
|
|
22
|
-
return;
|
|
23
|
-
}
|
|
24
14
|
const report = [];
|
|
25
15
|
if (all) {
|
|
26
16
|
const processors = await generateAllProcessors(project);
|
|
27
17
|
if (processors.length === 0) report.push("No processors found in processors/.");
|
|
28
18
|
for (const { processorName } of processors) report.push(`Regenerated processor in processors/${processorName}`);
|
|
29
|
-
} else if (document) {
|
|
30
|
-
const doc = await getDocument(document);
|
|
31
|
-
await generateProcessorFromDocument(doc, project);
|
|
32
19
|
} else if (processorName) await generateProcessor({
|
|
33
20
|
processorName,
|
|
34
21
|
processorApps,
|
|
@@ -43,7 +30,7 @@ async function startGenerateProcessor(args, projectDir) {
|
|
|
43
30
|
await generateProcessor(processorArgs, project);
|
|
44
31
|
report.push(`Regenerated processor in processors/${processorDirName}`);
|
|
45
32
|
} else {
|
|
46
|
-
console.log("Please specify one of `name`, `
|
|
33
|
+
console.log("Please specify one of `name`, `dir`, or `all`.");
|
|
47
34
|
return;
|
|
48
35
|
}
|
|
49
36
|
await project.save();
|
|
@@ -54,5 +41,5 @@ async function startGenerateProcessor(args, projectDir) {
|
|
|
54
41
|
//#endregion
|
|
55
42
|
export { startGenerateProcessor };
|
|
56
43
|
|
|
57
|
-
//# sourceMappingURL=generate-processor-
|
|
58
|
-
//# debugId=
|
|
44
|
+
//# sourceMappingURL=generate-processor-CwJvJDpd.mjs.map
|
|
45
|
+
//# debugId=88ec1831-447a-539d-bae5-93d4d91db5af
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"generate-processor-CwJvJDpd.mjs","sources":["../src/services/generate-processor.ts"],"sourcesContent":["import {\n detectFeatures,\n generateAllProcessors,\n generateProcessor,\n syncFeatureDependencies,\n} from \"@powerhousedao/codegen\";\nimport {\n buildTsMorphProject,\n getProcessorMetadata,\n} from \"@powerhousedao/codegen/utils\";\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { GenerateProcessorArgs } from \"../types.js\";\nimport { installAddedDependencies } from \"../utils/install-added-dependencies.js\";\nimport { resolveModuleDirName } from \"../utils/module-dir.js\";\n\nexport async function startGenerateProcessor(\n args: GenerateProcessorArgs,\n projectDir: string,\n) {\n const {\n name: processorName,\n type: processorType,\n apps: processorApps,\n documentTypes,\n dir,\n all,\n debug,\n } = args;\n if (debug) {\n console.log({ args });\n }\n const project = buildTsMorphProject(projectDir);\n const report: string[] = [];\n if (all) {\n const processors = await generateAllProcessors(project);\n if (processors.length === 0) {\n report.push(\"No processors found in processors/.\");\n }\n for (const { processorName } of processors) {\n report.push(`Regenerated processor in processors/${processorName}`);\n }\n } else if (processorName) {\n await generateProcessor(\n {\n processorName,\n processorApps,\n processorType,\n documentTypes,\n },\n project,\n );\n } else if (dir) {\n const processorDirName = resolveModuleDirName(\n projectDir,\n \"processors\",\n dir,\n \"my-processor\",\n );\n const processorDir = join(projectDir, \"processors\", processorDirName);\n if (\n ![\"processor.ts\", \"index.ts\"].some((file) =>\n existsSync(join(processorDir, file)),\n )\n ) {\n throw new Error(\n `processors/${processorDirName} has no processor.ts or index.ts.`,\n );\n }\n const processorArgs = getProcessorMetadata(project, processorDirName);\n await generateProcessor(processorArgs, project);\n report.push(`Regenerated processor in processors/${processorDirName}`);\n } else {\n console.log(\"Please specify one of `name`, `dir`, or `all`.\");\n return;\n }\n await project.save();\n for (const line of report) {\n console.log(line);\n }\n const added = await syncFeatureDependencies(\n detectFeatures(projectDir),\n projectDir,\n );\n await installAddedDependencies(added, projectDir, args.skipInstall);\n}\n"],"names":["installAddedDependencies"],"mappings":";;;;;;;;;AAgBA,eAAsB,uBACpB,MACA,YACA;CACA,MAAM,EACJ,MAAM,eACN,MAAM,eACN,MAAM,eACN,eACA,KACA,KACA,UACE;CACJ,IAAI,OACF,QAAQ,IAAI,EAAE,KAAK,CAAC;CAEtB,MAAM,UAAU,oBAAoB,UAAU;CAC9C,MAAM,SAAmB,CAAC;CAC1B,IAAI,KAAK;EACP,MAAM,aAAa,MAAM,sBAAsB,OAAO;EACtD,IAAI,WAAW,WAAW,GACxB,OAAO,KAAK,qCAAqC;EAEnD,KAAK,MAAM,EAAE,mBAAmB,YAC9B,OAAO,KAAK,uCAAuC,eAAe;CAEtE,OAAO,IAAI,eACT,MAAM,kBACJ;EACE;EACA;EACA;EACA;CACF,GACA,OACF;MACK,IAAI,KAAK;EACd,MAAM,mBAAmB,qBACvB,YACA,cACA,KACA,cACF;EACA,MAAM,eAAe,KAAK,YAAY,cAAc,gBAAgB;EACpE,IACE,CAAC,CAAC,gBAAgB,UAAU,CAAC,CAAC,MAAM,SAClC,WAAW,KAAK,cAAc,IAAI,CAAC,CACrC,GAEA,MAAM,IAAI,MACR,cAAc,iBAAiB,kCACjC;EAEF,MAAM,gBAAgB,qBAAqB,SAAS,gBAAgB;EACpE,MAAM,kBAAkB,eAAe,OAAO;EAC9C,OAAO,KAAK,uCAAuC,kBAAkB;CACvE,OAAO;EACL,QAAQ,IAAI,gDAAgD;EAC5D;CACF;CACA,MAAM,QAAQ,KAAK;CACnB,KAAK,MAAM,QAAQ,QACjB,QAAQ,IAAI,IAAI;CAElB,MAAM,QAAQ,MAAM,wBAClB,eAAe,UAAU,GACzB,UACF;CACA,MAAMA,2BAAyB,OAAO,YAAY,KAAK,WAAW;AACpE","debug_id":"88ec1831-447a-539d-bae5-93d4d91db5af"}
|
|
@@ -1,13 +1,12 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
2
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="6106c53a-29b0-5d26-8dde-d0627343082d")}catch(e){}}();
|
|
3
3
|
import { t as installAddedDependencies$1 } from "./install-added-dependencies-DnZFR3aE.mjs";
|
|
4
|
-
import { t as warnSubgraphTypeConflicts } from "./warn-subgraph-type-conflicts-
|
|
4
|
+
import { n as findSubgraphNameConflict, t as warnSubgraphTypeConflicts } from "./warn-subgraph-type-conflicts-BZ4NwLx5.mjs";
|
|
5
5
|
import { t as resolveModuleDirName } from "./module-dir-1avCXsBi.mjs";
|
|
6
6
|
import { existsSync } from "node:fs";
|
|
7
7
|
import { join } from "node:path";
|
|
8
8
|
import { detectFeatures, generateAllSubgraphs, generateSubgraph, generateSubgraphDir, syncFeatureDependencies } from "@powerhousedao/codegen";
|
|
9
9
|
import { buildTsMorphProject, subgraphDirStyle } from "@powerhousedao/codegen/utils";
|
|
10
|
-
import { extractSubgraphDocuments, findSubgraphNameConflict, generateSubgraphFromDocument, getDocument, saveSpec } from "@powerhousedao/vetra/codegen";
|
|
11
10
|
import { kebabCase } from "change-case";
|
|
12
11
|
//#region src/services/generate-subgraph.ts
|
|
13
12
|
const INDEX_FILE_EXPECTATION = {
|
|
@@ -28,33 +27,15 @@ function codeFirstOnSchemaFirst(args, projectDir, name) {
|
|
|
28
27
|
return `subgraphs/${dirName} is schema-first; --code-first only applies to new subgraphs. To convert it, run ph migrate --subgraph ${dirName}.`;
|
|
29
28
|
}
|
|
30
29
|
async function startGenerateSubgraph(args, projectDir) {
|
|
31
|
-
const { name,
|
|
30
|
+
const { name, dir, all, debug } = args;
|
|
32
31
|
if (debug) console.log({ args });
|
|
33
32
|
const project = buildTsMorphProject(projectDir);
|
|
34
|
-
if (extract) {
|
|
35
|
-
const docs = extractSubgraphDocuments(project);
|
|
36
|
-
if (docs.length === 0) console.log("No subgraphs found in subgraphs/.");
|
|
37
|
-
for (const doc of docs) {
|
|
38
|
-
const path = await saveSpec(doc, projectDir);
|
|
39
|
-
console.log(`Wrote ${path}`);
|
|
40
|
-
}
|
|
41
|
-
return;
|
|
42
|
-
}
|
|
43
33
|
const report = [];
|
|
44
34
|
if (all) {
|
|
45
35
|
const { subgraphNames, unreadableDirs } = await generateAllSubgraphs(project);
|
|
46
36
|
if (subgraphNames.length === 0 && unreadableDirs.length === 0) report.push("No subgraphs found in subgraphs/.");
|
|
47
37
|
for (const subgraphName of subgraphNames) report.push(`Regenerated subgraph "${subgraphName}"`);
|
|
48
38
|
for (const dirName of unreadableDirs) console.warn(`Skipped subgraphs/${dirName}: expected its index.ts to export ${INDEX_FILE_EXPECTATION[subgraphDirStyle(join(projectDir, "subgraphs"), dirName)]}. Kept the manifest's subgraphs.`);
|
|
49
|
-
} else if (document) {
|
|
50
|
-
const doc = await getDocument(document);
|
|
51
|
-
const notice = codeFirstOnSchemaFirst(args, projectDir, doc.state.global.name);
|
|
52
|
-
if (notice) {
|
|
53
|
-
console.log(notice);
|
|
54
|
-
return;
|
|
55
|
-
}
|
|
56
|
-
await assertSubgraphNameFree(projectDir, doc.state.global.name);
|
|
57
|
-
await generateSubgraphFromDocument(doc, project, { codeFirst: args.codeFirst });
|
|
58
39
|
} else if (name) {
|
|
59
40
|
const notice = codeFirstOnSchemaFirst(args, projectDir, name);
|
|
60
41
|
if (notice) {
|
|
@@ -70,7 +51,7 @@ async function startGenerateSubgraph(args, projectDir) {
|
|
|
70
51
|
if (!subgraphName) throw new Error(`Could not read subgraphs/${dirName}/index.ts: expected ${INDEX_FILE_EXPECTATION[style]}.`);
|
|
71
52
|
report.push(`Regenerated subgraph "${subgraphName}"`);
|
|
72
53
|
} else {
|
|
73
|
-
console.log("Please specify one of `name`, `
|
|
54
|
+
console.log("Please specify one of `name`, `dir`, or `all`.");
|
|
74
55
|
return;
|
|
75
56
|
}
|
|
76
57
|
await project.save();
|
|
@@ -82,5 +63,5 @@ async function startGenerateSubgraph(args, projectDir) {
|
|
|
82
63
|
//#endregion
|
|
83
64
|
export { startGenerateSubgraph };
|
|
84
65
|
|
|
85
|
-
//# sourceMappingURL=generate-subgraph-
|
|
86
|
-
//# debugId=
|
|
66
|
+
//# sourceMappingURL=generate-subgraph-EQ2ZjMp9.mjs.map
|
|
67
|
+
//# debugId=6106c53a-29b0-5d26-8dde-d0627343082d
|