@dashai/cli 0.8.0 → 0.9.0
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 +83 -22
- package/dist/bin.js +2209 -337
- package/dist/bin.js.map +1 -1
- package/package.json +2 -2
package/dist/bin.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/config.ts","../src/lib/api-client.ts","../src/lib/manifest-io.ts","../src/lib/output.ts","../src/lib/scaffold.ts","../src/lib/workspaces.ts","../src/commands/module/init.ts","../src/lib/schema-command-context.ts","../src/commands/module/destroy-dev-install.ts","../src/commands/module/reset-dev-install.ts","../src/lib/field-spec.ts","../src/commands/table/create.ts","../src/commands/table/delete.ts","../src/commands/field/add.ts","../src/commands/field/remove.ts","../src/commands/field/set-type.ts","../src/commands/dev.ts","../src/lib/manifest-poll.ts","../src/commands/login.ts","../src/commands/logout.ts","../src/commands/profile.ts","../src/commands/workspace.ts","../src/commands/module/clone.ts","../src/commands/module/connect-git.ts","../src/commands/module/convert.ts","../src/commands/module/export.ts","../src/commands/module/register.ts","../src/commands/module/generate.ts","../src/commands/module/dev.ts","../src/commands/module/diff.ts","../src/bin.ts","../src/commands/module/list.ts","../src/commands/module/publish.ts","../src/lib/tarball.ts","../src/commands/module/pull-data.ts","../src/commands/module/validate.ts","../src/commands/deps/add.ts","../src/commands/deps/check.ts","../src/commands/deps/list.ts","../src/commands/deps/remove.ts","../src/commands/pull.ts","../src/commands/api-keys.ts","../src/commands/env-export.ts","../src/commands/query.ts","../src/commands/module/query-log.ts","../src/commands/module/action-log.ts"],"names":["c","out","code","join","existsSync","readFileSync","writeFileSync","select","isCancel","intro","resolve","readdirSync","mkdirSync","outro","workspace","resolvePath","manifestPath","exitCode","text","walk","statSync","deriveSlug","basename","rmSync","dirname","fsWatch","relative","formatBytes","pathResolve","sleep","POLL_INTERVAL_MS","runTail","runOnce","msg","destroyDevInstallCommand","resetDevInstallCommand","table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AAY,EAAE,GAAA,EAAK,OAAA,CAAQ,GAAA,EAAI,GAAI;AAAC;AAC1D,KACF;AAAA,EACF;AACF,CAAA;AAAA,CAGD,YAAY;AACX,EAAA,IAAI;AACF,IAAA,MAAM,OAAA,CAAQ,UAAA,CAAW,OAAA,CAAQ,IAAI,CAAA;AAAA,EACvC,SAAS,GAAA,EAAK;AACZ,IAAA,IAAA,CAAK,oBAAqB,GAAA,CAAc,OAAA,IAAW,MAAA,CAAO,GAAG,CAAC,CAAA,CAAE,CAAA;AAChE,IAAA,IAAI,OAAA,CAAQ,IAAI,cAAA,EAAgB;AAI9B,MAAA,OAAA,CAAQ,MAAM,GAAG,CAAA;AAAA,IACnB;AACA,IAAA,OAAA,CAAQ,QAAA,GAAW,CAAA;AAAA,EACrB;AACF,CAAA,GAAG;AAQH,SAAS,UAAA,GAAqB;AAC5B,EAAA,OAAO,OAAA;AACT;AAGA,SAAS,eAAe,KAAA,EAAuB;AAC7C,EAAA,MAAM,CAAA,GAAI,MAAA,CAAO,QAAA,CAAS,KAAA,EAAO,EAAE,CAAA;AACnC,EAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,CAAC,CAAA,EAAG;AACvB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,0BAAA,EAA6B,KAAK,CAAA,CAAA,CAAG,CAAA;AAAA,EACvD;AACA,EAAA,OAAO,CAAA;AACT;AAUA,SAAS,eAAA,CAAgB,OAAe,QAAA,EAA8B;AACpE,EAAA,OAAO,CAAC,GAAG,QAAA,EAAU,KAAK,CAAA;AAC5B","file":"bin.js","sourcesContent":["/**\n * Local CLI configuration — persisted to\n * `$XDG_CONFIG_HOME/dashwise/auth.json` (defaults to\n * `~/.config/dashwise/auth.json` on Linux/macOS and the equivalent\n * `%APPDATA%\\dashwise\\auth.json` on Windows).\n *\n * Contents:\n * - `apiUrl` — backend root, e.g. `http://localhost:3000`\n * - `token` — raw `dwc_*` CLI token (the secret)\n * - `tokenId` — DB id of the `cli_tokens` row (so `dashwise\n * logout` can call DELETE precisely)\n * - `user` — cached profile for fast `dashwise profile`\n * (refreshed on `dashwise login` + on demand)\n * - `workspaceSlug` — default workspace selected via\n * `dashwise workspace use <slug>`\n *\n * Permissions: chmod 0600 on write — the file holds a long-lived\n * bearer credential. Best-effort on Windows (the API tolerates\n * `EPERM` on the chmod call there).\n */\n\nimport {\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from 'node:fs';\nimport { homedir, platform } from 'node:os';\nimport { join } from 'node:path';\n\nexport interface CliConfig {\n /** Backend base URL — e.g. `http://localhost:3000`. */\n apiUrl: string;\n /** Raw CLI token (`dwc_<...>`). */\n token: string;\n /** DB id of the matching `cli_tokens` row. Used by `logout`. */\n tokenId: number;\n /** Cached user identity. */\n user: {\n id: number;\n email: string;\n username: string;\n firstName: string;\n lastName: string;\n };\n /** Optional default workspace slug. */\n workspaceSlug?: string;\n /**\n * HH-CC-LDI-6 — per-module local-dev install metadata, keyed by\n * the module's slug (matches `module.json#module.slug`).\n *\n * Written by `dashwise init` after `POST /api/installations/dev`\n * returns a runtime token. Read by `@dashai/sdk`'s\n * `createDevClient({ moduleSlug })` to authenticate against the\n * local-dev install. Each entry is independent — entries for\n * other modules survive any single module's destroy / re-init.\n *\n * Field semantics:\n * - `runtimeToken` — JWT bearer the SDK sends on every data\n * request. Long-lived (default 90d). Replaced on rotation\n * (LDI-9 `dashwise module rotate-token`).\n * - `installationId` — numeric install id the token binds to.\n * Useful for surfacing to the user in `dashwise module status`\n * output and for the future LDI-9 destroy command.\n * - `expiresAt` — ISO timestamp; informational only. The CLI\n * can warn when the token is nearing expiry, but expiry is\n * enforced server-side via the JWT's `exp` claim.\n */\n modules?: Record<string, CliConfigModuleEntry>;\n}\n\n/** Per-module entry within `CliConfig.modules`. See `modules` field above. */\nexport interface CliConfigModuleEntry {\n runtimeToken: string;\n installationId: number;\n expiresAt: string;\n}\n\nconst FILE_NAME = 'auth.json';\nconst DIR_NAME = 'dashwise';\n\n/**\n * Resolve the config directory using XDG conventions.\n *\n * 1. `$XDG_CONFIG_HOME/dashwise/` if set\n * 2. `~/.config/dashwise/` on Linux/macOS\n * 3. `%APPDATA%\\dashwise\\` on Windows (via env)\n *\n * Mirrors `dashwise` projects on common platforms; matches what\n * users would expect from other CLIs (gh, npm, etc.).\n */\nexport function configDir(): string {\n if (process.env.XDG_CONFIG_HOME) {\n return join(process.env.XDG_CONFIG_HOME, DIR_NAME);\n }\n if (platform() === 'win32' && process.env.APPDATA) {\n return join(process.env.APPDATA, DIR_NAME);\n }\n return join(homedir(), '.config', DIR_NAME);\n}\n\nexport function configPath(): string {\n return join(configDir(), FILE_NAME);\n}\n\n/**\n * Read the saved config, or `null` if no file exists. Throws if the\n * file exists but is malformed JSON — the caller decides whether to\n * surface as \"run `dashwise login` again\" or as a hard error.\n */\nexport function readConfig(): CliConfig | null {\n const path = configPath();\n if (!existsSync(path)) return null;\n const raw = readFileSync(path, 'utf-8');\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n throw new Error(\n `Failed to parse ${path}: ${(err as Error).message}. Run \\`dashwise login\\` to recreate it.`,\n );\n }\n if (!isPlausibleConfig(parsed)) {\n throw new Error(\n `Config at ${path} is missing required fields. Run \\`dashwise login\\` to recreate it.`,\n );\n }\n return parsed;\n}\n\n/**\n * Write the config atomically (via temp + rename) with 0600 perms.\n * Creates the parent dir if missing.\n */\nexport function writeConfig(config: CliConfig): void {\n const dir = configDir();\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n const path = configPath();\n const tmp = `${path}.tmp.${process.pid}`;\n writeFileSync(tmp, JSON.stringify(config, null, 2) + '\\n', 'utf-8');\n try {\n chmodSync(tmp, 0o600);\n } catch {\n // Windows + some FUSE FS don't support chmod; best-effort.\n }\n // Atomic rename — readers see either the old config or the new\n // one, never a partial write.\n renameSync(tmp, path);\n}\n\n/**\n * Remove the config file (`dashwise logout`). Idempotent — no error\n * if the file already doesn't exist.\n */\nexport function deleteConfig(): void {\n const path = configPath();\n if (!existsSync(path)) return;\n rmSync(path);\n}\n\n/**\n * Resolve the API URL the CLI should talk to.\n * Priority: explicit `DASHWISE_API_URL` env → saved config → default.\n */\nexport function resolveApiUrl(): string {\n const fromEnv = process.env.DASHWISE_API_URL?.trim();\n if (fromEnv) return fromEnv.replace(/\\/+$/, '');\n const cfg = safeReadConfig();\n if (cfg?.apiUrl) return cfg.apiUrl.replace(/\\/+$/, '');\n return 'http://localhost:3000';\n}\n\n/**\n * Convenience: read the saved token if the file exists + is valid.\n * Returns `null` if the user isn't logged in.\n */\nexport function readSavedToken(): string | null {\n const cfg = safeReadConfig();\n return cfg?.token ?? null;\n}\n\nfunction safeReadConfig(): CliConfig | null {\n try {\n return readConfig();\n } catch {\n return null;\n }\n}\n\nfunction isPlausibleConfig(v: unknown): v is CliConfig {\n if (!v || typeof v !== 'object') return false;\n const c = v as Record<string, unknown>;\n if (typeof c.apiUrl !== 'string') return false;\n if (typeof c.token !== 'string') return false;\n if (typeof c.tokenId !== 'number') return false;\n if (!c.user || typeof c.user !== 'object') return false;\n const u = c.user as Record<string, unknown>;\n if (typeof u.id !== 'number') return false;\n if (typeof u.email !== 'string') return false;\n // HH-CC-LDI-6: `modules` is optional and forgiving — entries with\n // wrong shape are silently ignored at read time, mirroring the\n // SDK's reader. Strict per-entry validation would force CLI\n // crashes on partial writes (e.g. interrupt mid-init).\n if (c.modules !== undefined) {\n if (typeof c.modules !== 'object' || c.modules === null) return false;\n }\n return true;\n}\n\n/**\n * HH-CC-LDI-6 — record a module's local-dev install in `auth.json`.\n *\n * Atomic: reads, mutates, writes. If `dashwise init` is interrupted\n * after the API call but before this returns, the install row exists\n * server-side without local persistence — the user has to re-init or\n * use the future `dashwise module recover-dev-install` command (LDI-9).\n *\n * Throws if there's no saved config (the user isn't logged in).\n * Callers should check `isLoggedIn()` first and surface a clear\n * \"run `dashwise login` first\" error.\n */\nexport function upsertModuleEntry(\n slug: string,\n entry: CliConfigModuleEntry,\n): void {\n const cfg = readConfig();\n if (!cfg) {\n throw new Error(\n 'No CLI config file. Run `dashwise login` first to create one.',\n );\n }\n const next: CliConfig = {\n ...cfg,\n modules: {\n ...(cfg.modules ?? {}),\n [slug]: entry,\n },\n };\n writeConfig(next);\n}\n\n/**\n * HH-CC-LDI-6 — read a module's local-dev entry, or `null` if none\n * has been provisioned. Returns `null` when the user isn't logged in.\n */\nexport function readModuleEntry(slug: string): CliConfigModuleEntry | null {\n const cfg = safeReadConfig();\n if (!cfg?.modules) return null;\n return cfg.modules[slug] ?? null;\n}\n\n/**\n * HH-CC-LDI-6 — remove a module's entry (used by future LDI-9\n * `dashwise module destroy-dev-install`). Idempotent — no-op when\n * the entry doesn't exist or the user isn't logged in.\n */\nexport function removeModuleEntry(slug: string): void {\n const cfg = safeReadConfig();\n if (!cfg?.modules || !(slug in cfg.modules)) return;\n const { [slug]: _removed, ...rest } = cfg.modules;\n void _removed;\n const next: CliConfig = {\n ...cfg,\n modules: Object.keys(rest).length > 0 ? rest : undefined,\n };\n writeConfig(next);\n}\n\n/**\n * Return current file mode bits (for diagnostics). Returns `null`\n * on any failure (file missing, permission denied, etc.).\n */\nexport function configFileMode(): number | null {\n try {\n const s = statSync(configPath());\n return s.mode & 0o777;\n } catch {\n return null;\n }\n}\n\n/** Confirm a saved config exists (for `whoami` short-circuit). */\nexport function isLoggedIn(): boolean {\n return readSavedToken() !== null;\n}\n\n/** Convenience helper used by tests + diagnostic commands. */\nexport function configSummary(): {\n path: string;\n exists: boolean;\n mode: number | null;\n} {\n return {\n path: configPath(),\n exists: existsSync(configPath()),\n mode: configFileMode(),\n };\n}\n\n// Helpers above intentionally exported individually — no default\n// export so tree-shake at the `bin.ts` level remains effective.\n","/**\n * Thin HTTP client for the DashWise backend, tailored for the CLI's\n * call patterns.\n *\n * Three shapes of authenticated request emerge in the CLI:\n * 1. **Public** — `dashwise login` device-code start/poll (no token yet)\n * 2. **CLI token (`Bearer dwc_*`)** — every command after login\n * 3. **One-off Bearer** — internal use during the login flow\n * (we don't have a saved token while polling)\n *\n * The class is intentionally small + dependency-free (uses\n * `globalThis.fetch`). Error envelopes from the backend\n * (`{ code, message, retriable, context }`) are surfaced as typed\n * `ApiError`s so command code can branch on `err.code`.\n */\n\nimport { resolveApiUrl, readSavedToken } from './config.js';\n\nexport interface ApiErrorEnvelope {\n code?: string;\n message?: string;\n retriable?: boolean;\n context?: Record<string, unknown>;\n}\n\nexport class ApiError extends Error {\n readonly status: number;\n readonly code: string;\n readonly context: Record<string, unknown> | undefined;\n readonly retriable: boolean;\n\n constructor(status: number, envelope: ApiErrorEnvelope | null, fallbackMessage: string) {\n const code = envelope?.code ?? codeFromStatus(status);\n const message = envelope?.message ?? fallbackMessage;\n super(message);\n this.name = 'ApiError';\n this.status = status;\n this.code = code;\n this.context = envelope?.context;\n this.retriable = envelope?.retriable ?? status >= 500;\n }\n}\n\nexport interface RequestOptions {\n /**\n * Auth mode:\n * - `'auto'` (default) — `Bearer <saved-token>` if one exists,\n * else no header.\n * - `'public'` — no Authorization header (used by the device-code\n * endpoints which authenticate via the device_code itself).\n * - `{ token: 'dwc_...' }` — explicit token (used during login\n * polling before we save the file).\n */\n auth?: 'auto' | 'public' | { token: string };\n\n /** Override the base URL (testing / `--api-url` flag). */\n baseUrl?: string;\n\n /** Extra request headers (rare — diagnostic plumbing). */\n headers?: Record<string, string>;\n}\n\n/**\n * Make a JSON request. Returns the parsed body (`T`) or throws an\n * `ApiError`. 204 responses return `undefined`.\n */\nexport async function apiRequest<T = unknown>(\n method: string,\n path: string,\n body?: unknown,\n options: RequestOptions = {},\n): Promise<T> {\n const baseUrl = (options.baseUrl ?? resolveApiUrl()).replace(/\\/+$/, '');\n const url = `${baseUrl}${path.startsWith('/') ? path : `/${path}`}`;\n\n const headers: Record<string, string> = {\n Accept: 'application/json',\n ...(options.headers ?? {}),\n };\n if (body !== undefined) {\n headers['Content-Type'] = 'application/json';\n }\n const authMode = options.auth ?? 'auto';\n if (authMode === 'auto') {\n const saved = readSavedToken();\n if (saved) headers['Authorization'] = `Bearer ${saved}`;\n } else if (typeof authMode === 'object' && authMode.token) {\n headers['Authorization'] = `Bearer ${authMode.token}`;\n }\n\n let res: Response;\n try {\n res = await fetch(url, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n } catch (err) {\n // Network-level failure — DNS, ECONNREFUSED, TLS, etc. Surface\n // as an ApiError with a stable code so callers can branch.\n throw new ApiError(0, { code: 'NETWORK_ERROR', message: (err as Error).message }, 'Network error');\n }\n\n if (res.status === 204) {\n return undefined as T;\n }\n\n const contentType = res.headers.get('content-type') ?? '';\n let parsed: unknown = null;\n if (contentType.includes('application/json')) {\n try {\n parsed = await res.json();\n } catch {\n parsed = null;\n }\n } else if (res.status >= 400) {\n // Non-JSON error body — still want a stable error shape.\n try {\n parsed = { message: await res.text() };\n } catch {\n parsed = null;\n }\n }\n\n if (!res.ok) {\n throw new ApiError(res.status, asEnvelope(parsed), `HTTP ${res.status}`);\n }\n return parsed as T;\n}\n\nfunction asEnvelope(v: unknown): ApiErrorEnvelope | null {\n if (!v || typeof v !== 'object') return null;\n const env = v as Record<string, unknown>;\n const out: ApiErrorEnvelope = {};\n if (typeof env.code === 'string') out.code = env.code;\n if (typeof env.message === 'string') out.message = env.message;\n if (typeof env.retriable === 'boolean') out.retriable = env.retriable;\n if (env.context && typeof env.context === 'object') {\n out.context = env.context as Record<string, unknown>;\n }\n return out;\n}\n\nfunction codeFromStatus(status: number): string {\n if (status === 401) return 'UNAUTHENTICATED';\n if (status === 403) return 'FORBIDDEN';\n if (status === 404) return 'NOT_FOUND';\n if (status === 0) return 'NETWORK_ERROR';\n if (status >= 500) return 'INTERNAL_ERROR';\n return 'HTTP_ERROR';\n}\n\n// ── HH-CC-LDI-6: typed wrapper for POST /api/installations/dev ────────\n\n/**\n * Shape returned by `POST /api/installations/dev` — matches the\n * backend's `DevInstallationController.createDevInstallation` envelope.\n * See `dashwise-backend/src/modules/modules/installation/dev-installation.controller.ts`.\n */\nexport interface DevInstallationResponse {\n installation: {\n id: number;\n kind: 'sandbox' | 'local' | 'production';\n workspace_id: number;\n module_id: number;\n module_version_id: number;\n application_id: number;\n installed_on: string;\n };\n module: {\n id: number;\n slug: string;\n name: string;\n };\n runtime_token: string;\n runtime_token_expires_at: string;\n}\n\n/**\n * Create a local-dev module installation + mint a runtime token.\n *\n * Called by `dashwise init` after the user picks a workspace + slug\n * + name. The returned `runtime_token` is persisted into\n * `auth.json#modules[<slug>]` via `upsertModuleEntry`; the SDK's\n * `createDevClient({ moduleSlug })` reads from there on every dev\n * server boot.\n *\n * Errors (surfaced as `ApiError` with the backend's `code` field):\n * - 403 — caller is not a member of the target workspace.\n * - 409 SLUG_ALREADY_EXISTS — a module with this slug exists. The\n * user should pick a different slug or run `dashwise module\n * destroy-dev-install` first (LDI-9).\n * - 503 RUNTIME_DATA_API_DISABLED — `BUILDER_SESSION_TOKEN_SECRET`\n * unset on the backend. Operator-side issue, not a user issue.\n */\nexport async function createDevInstallation(\n body: {\n slug: string;\n name: string;\n description?: string;\n workspaceId: number;\n /**\n * HH-CC-FUP-2 — `module_kind` from the scaffold's `module.json`.\n * Without forwarding it the backend's draft manifest gets no\n * `module_kind`, `SchemaProposeService.getManifest()` falls back\n * to `'ai_builder'`, and that wrong value rewrites the local\n * module.json on the first watcher tick.\n */\n moduleKind?: 'ai_builder' | 'hand_authored' | 'custom';\n },\n options: RequestOptions = {},\n): Promise<DevInstallationResponse> {\n return apiRequest<DevInstallationResponse>(\n 'POST',\n '/api/installations/dev',\n body,\n options,\n );\n}\n\n/**\n * HH-CC-LDI-9 — destroy a local-dev installation.\n *\n * Maps to `DELETE /api/installations/dev/:installationId`. The\n * backend (`DevInstallationService.destroy`) tears down the install\n * row + its application tile, and conditionally drops the module\n * if it was a dev-only artifact (no other installs, never published).\n *\n * Returns `{ installation_id, module_id, module_also_dropped }`.\n *\n * Errors (`ApiError`):\n * - 404 `INSTALLATION_NOT_FOUND` — install id doesn't exist.\n * - 403 `INSTALLATION_KIND_NOT_LOCAL` — refuses non-local installs.\n * - 403 `NOT_WORKSPACE_MEMBER` — caller isn't in the install's workspace.\n */\nexport interface DestroyDevInstallationResponse {\n installation_id: number;\n module_id: number;\n module_also_dropped: boolean;\n}\n\nexport async function destroyDevInstallation(\n installationId: number,\n options: RequestOptions = {},\n): Promise<DestroyDevInstallationResponse> {\n return apiRequest<DestroyDevInstallationResponse>(\n 'DELETE',\n `/api/installations/dev/${installationId}`,\n undefined,\n options,\n );\n}\n\n// ── HH-CC-P1-C1/C4: per-installation API keys ─────────────────────────\n\n/**\n * Shape returned by the API-keys endpoints. Mirrors `ApiKeyPublic`\n * from the backend controller. NEVER contains the hash or raw key\n * (those are POST-time-only).\n */\nexport interface ApiKeyPublic {\n id: number;\n installation_id: number;\n module_id: number;\n name: string;\n key_prefix: string;\n scopes: string[];\n created_by_user_id: number;\n created_at: string;\n last_used_at: string | null;\n expires_at: string | null;\n revoked_at: string | null;\n}\n\n/** Response from `POST /api/installations/:id/api-keys`. */\nexport interface CreateApiKeyResponse {\n api_key: ApiKeyPublic;\n /** Plaintext key. Backend returns this ONCE; never stored. */\n raw_key: string;\n}\n\nexport async function createApiKey(\n installationId: number,\n body: { name: string; scopes?: string[]; expires_at?: string },\n options: RequestOptions = {},\n): Promise<CreateApiKeyResponse> {\n return apiRequest<CreateApiKeyResponse>(\n 'POST',\n `/api/installations/${installationId}/api-keys`,\n body,\n options,\n );\n}\n\nexport async function listApiKeys(\n installationId: number,\n options: RequestOptions = {},\n): Promise<{ api_keys: ApiKeyPublic[] }> {\n return apiRequest<{ api_keys: ApiKeyPublic[] }>(\n 'GET',\n `/api/installations/${installationId}/api-keys`,\n undefined,\n options,\n );\n}\n\nexport async function revokeApiKey(\n installationId: number,\n keyId: number,\n options: RequestOptions = {},\n): Promise<{ api_key: ApiKeyPublic }> {\n return apiRequest<{ api_key: ApiKeyPublic }>(\n 'DELETE',\n `/api/installations/${installationId}/api-keys/${keyId}`,\n undefined,\n options,\n );\n}\n\n// ── HH-CC-LDI-8: schema-mutation endpoints (mirrors LDI-4 controller) ──\n\n/** FieldDef body shape — open enough to carry `options`, `target`, etc. */\nexport interface FieldDefBody {\n slug: string;\n type: string;\n required?: boolean;\n options?: string[];\n target?: string;\n default?: unknown;\n}\n\n/**\n * Common response shape from `propose_*` endpoints — the LDI-4\n * controller strips the in-memory `sdk` blob, so the wire payload is\n * just the operation result + sdk_regen metadata.\n */\nexport interface SchemaOpResponse {\n table_slug: string;\n physical_table_id: number;\n manifest_version: number;\n sdk_regen: { hash: string; ms: number };\n /** Present on proposeField responses (add / update / remove). */\n operation_applied?: 'add' | 'update' | 'remove';\n}\n\nexport interface DropTableResponse {\n table_slug: string;\n dropped: boolean;\n manifest_version: number;\n sdk_regen: { hash: string; ms: number };\n}\n\n/** `POST /api/installations/:id/schema/tables` — create a table. */\nexport async function createTable(\n installationId: number,\n body: {\n slug: string;\n fields: FieldDefBody[];\n indexes?: Array<{ fields: string[]; unique?: boolean }>;\n },\n options: RequestOptions = {},\n): Promise<SchemaOpResponse> {\n return apiRequest<SchemaOpResponse>(\n 'POST',\n `/api/installations/${installationId}/schema/tables`,\n body,\n options,\n );\n}\n\n/** `DELETE /api/installations/:id/schema/tables/:tableSlug` — drop a table. */\nexport async function dropTable(\n installationId: number,\n tableSlug: string,\n options: RequestOptions = {},\n): Promise<DropTableResponse> {\n return apiRequest<DropTableResponse>(\n 'DELETE',\n `/api/installations/${installationId}/schema/tables/${tableSlug}`,\n undefined,\n options,\n );\n}\n\n/** `POST /api/installations/:id/schema/fields` — add a field. */\nexport async function addField(\n installationId: number,\n body: { table_slug: string; field: FieldDefBody },\n options: RequestOptions = {},\n): Promise<SchemaOpResponse> {\n return apiRequest<SchemaOpResponse>(\n 'POST',\n `/api/installations/${installationId}/schema/fields`,\n body,\n options,\n );\n}\n\n/** `PATCH /api/installations/:id/schema/fields/:tableSlug/:fieldSlug` — update. */\nexport async function updateField(\n installationId: number,\n tableSlug: string,\n fieldSlug: string,\n body: Omit<FieldDefBody, 'slug'>,\n options: RequestOptions = {},\n): Promise<SchemaOpResponse> {\n return apiRequest<SchemaOpResponse>(\n 'PATCH',\n `/api/installations/${installationId}/schema/fields/${tableSlug}/${fieldSlug}`,\n body,\n options,\n );\n}\n\n/**\n * `GET /api/installations/:id/schema` — read the current draft\n * manifest. Used post-mutation to write the new state back to local\n * `module.json` (HH-CC-LDI-8 REST-first / write-back-from-GET model).\n */\nexport async function getInstallationSchema(\n installationId: number,\n options: RequestOptions = {},\n): Promise<{ manifest: Record<string, unknown> }> {\n return apiRequest<{ manifest: Record<string, unknown> }>(\n 'GET',\n `/api/installations/${installationId}/schema`,\n undefined,\n options,\n );\n}\n\n/** `DELETE /api/installations/:id/schema/fields/:tableSlug/:fieldSlug` — remove. */\nexport async function removeField(\n installationId: number,\n tableSlug: string,\n fieldSlug: string,\n options: RequestOptions = {},\n): Promise<SchemaOpResponse> {\n return apiRequest<SchemaOpResponse>(\n 'DELETE',\n `/api/installations/${installationId}/schema/fields/${tableSlug}/${fieldSlug}`,\n undefined,\n options,\n );\n}\n","/**\n * Shared `module.json` I/O for CLI commands.\n *\n * Several commands need to read + mutate the local manifest\n * (`connect-git`, `deps add / remove`, future `module fields add`,\n * etc.). Inlining the read/write/JSON-parse dance in every command\n * leaks formatting choices (2-space indent, trailing newline) and\n * makes file-level invariants harder to enforce. This helper is the\n * single chokepoint.\n *\n * Properties:\n * - Tolerates an absent file with a typed null return.\n * - Throws a typed error (with file path) on parse failure.\n * - Writes are atomic-ish: same write pattern as the rest of the\n * CLI (one `writeFileSync`, no temp file — manifest is small +\n * local; partial writes only matter for ~256-byte regions and\n * fsync ordering on local disk).\n * - Preserves 2-space indent + trailing newline so `git diff` after\n * a CLI mutation shows only the actual change.\n * - Generic over the manifest shape — callers cast to their needed\n * shape since the manifest schema is owned by the backend.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\n\n/**\n * Reasonably-permissive shape covering what CLI commands care about.\n * The backend validator owns the full schema; we only narrow what we\n * need to read/write here.\n */\nexport interface ManifestShape {\n schema_version?: number;\n module?: {\n slug?: string;\n name?: string;\n version?: string;\n [k: string]: unknown;\n };\n module_kind?: string;\n owns?: { tables?: Array<{ slug?: string; [k: string]: unknown }> };\n dependencies?: ManifestDependency[];\n exposes?: Array<Record<string, unknown>>;\n repository?: Record<string, unknown>;\n [k: string]: unknown;\n}\n\nexport interface ManifestDependency {\n module: string;\n version: string;\n reads: Array<{ table: string; fields: string[] }>;\n writes?: Array<{ table: string; fields: string[]; operations: string[] }>;\n purpose: string;\n}\n\n/**\n * Resolve the manifest path inside `dir` (defaults to `process.cwd()`).\n * Pure path math — does not touch the filesystem.\n */\nexport function manifestPath(dir?: string): string {\n return join(resolve(dir ?? process.cwd()), 'module.json');\n}\n\n/**\n * Read + parse `module.json` from `dir`. Returns `null` when the file\n * doesn't exist (so callers can branch on \"not a module directory\" vs\n * \"broken manifest\"). Throws with a clear message on parse failure.\n */\nexport function readManifest<T extends ManifestShape = ManifestShape>(dir?: string): T | null {\n const path = manifestPath(dir);\n if (!existsSync(path)) return null;\n const raw = readFileSync(path, 'utf-8');\n try {\n return JSON.parse(raw) as T;\n } catch (err) {\n throw new Error(\n `Failed to parse ${path}: ${(err as Error).message}. Fix or delete the file and re-run.`,\n );\n }\n}\n\n/**\n * Write `manifest` back to `module.json` in `dir`. Uses the canonical\n * 2-space indent + trailing newline so subsequent commits show only\n * the intended diff. Caller is responsible for any structural\n * validation — this helper is a dumb serializer.\n */\nexport function writeManifest(manifest: ManifestShape, dir?: string): void {\n const path = manifestPath(dir);\n writeFileSync(path, JSON.stringify(manifest, null, 2) + '\\n', 'utf-8');\n}\n\n/**\n * Convenience: read the manifest or throw a CLI-friendly error if\n * either the file is missing or unparseable. Use from commands that\n * REQUIRE a manifest to function (most of them).\n */\nexport function readManifestOrThrow<T extends ManifestShape = ManifestShape>(dir?: string): T {\n const manifest = readManifest<T>(dir);\n if (!manifest) {\n throw new Error(\n `No module.json found in ${resolve(dir ?? process.cwd())}. Run \\`dashwise module init\\` first or pass \\`--dir <path>\\`.`,\n );\n }\n return manifest;\n}\n","/**\n * Output formatting helpers — colors via picocolors (zero deps,\n * tiny). All output goes through these so the CLI has a consistent\n * voice + we can later add `--no-color` / `--json` modes by editing\n * one file.\n */\n\nimport pc from 'picocolors';\n\nexport function success(msg: string): void {\n process.stderr.write(`${pc.green('✓')} ${msg}\\n`);\n}\n\nexport function info(msg: string): void {\n process.stderr.write(`${pc.cyan('ℹ')} ${msg}\\n`);\n}\n\nexport function warn(msg: string): void {\n process.stderr.write(`${pc.yellow('⚠')} ${msg}\\n`);\n}\n\nexport function fail(msg: string): void {\n process.stderr.write(`${pc.red('✗')} ${msg}\\n`);\n}\n\n/** Plain text to stdout — for command output that should be pipe-able. */\nexport function out(msg: string): void {\n process.stdout.write(`${msg}\\n`);\n}\n\n/** Print a `key: value` pair, key bold and right-padded. */\nexport function kv(key: string, value: string, padTo = 14): void {\n const padded = key.padEnd(padTo);\n process.stdout.write(`${pc.bold(padded)} ${value}\\n`);\n}\n\n/** Highlight CLI commands or paths in inline text. */\nexport function code(s: string): string {\n return pc.cyan(s);\n}\n\n/** Dim secondary info (timestamps, helper hints). */\nexport function dim(s: string): string {\n return pc.dim(s);\n}\n\nexport { pc };\n","/**\n * Inline scaffold for `dashwise module init`. Each function returns\n * the file content for a single file in the target project tree.\n *\n * Kept inline (no template-files dir) because the scaffold is small\n * + benefits from having the runtime values (slug, name) interpolated\n * in TS rather than via a separate templating engine. When the\n * scaffold grows beyond ~10 files OR starts to differ meaningfully\n * between AI-built / hand-authored / custom flavors, splitting to\n * `templates/<flavor>/` becomes worth it.\n */\n\nexport type ScaffoldKind = 'hand_authored' | 'custom';\n\n/**\n * HH-CC-P1-D2 — supported `--deploy-target` values. When set, the\n * scaffold emits the matching platform config file (`railway.json`,\n * `vercel.json`, or `fly.toml`) so the project lands as a one-shot\n * deploy-ready repo. Default (omitted) writes no platform file —\n * the repo stays clean and the user can add one later by hand.\n */\nexport const DEPLOY_TARGETS = ['railway', 'vercel', 'fly'] as const;\nexport type DeployTarget = (typeof DEPLOY_TARGETS)[number];\n\nexport function isDeployTarget(value: string): value is DeployTarget {\n return (DEPLOY_TARGETS as readonly string[]).includes(value);\n}\n\nexport interface ScaffoldOptions {\n slug: string;\n name: string;\n /** Module flavor — `hand_authored` (simple isolate-runtime) or `custom` (full Next.js + machine runtime). */\n kind?: ScaffoldKind;\n /** Optional Git repository URL — populates `module.json#repository.url`. */\n repositoryUrl?: string;\n}\n\nexport function manifestJson(opts: ScaffoldOptions): string {\n const kind = opts.kind ?? 'hand_authored';\n // HH-CC-FUP-5: `owns.tables` starts empty. Earlier versions seeded\n // a default `items` table with one `title` field as a \"starter\n // example\" — but dogfood feedback was that this is confusing\n // (authors think \"I didn't create that, why is it there?\") and\n // worse, the seeded slug + field never make it into the actual DB\n // (provisioning creates an empty draft on the backend, and the local\n // module.json doesn't sync into the manifest until something like\n // `dashwise table create` runs). Empty tables array is honest. The\n // first `dashwise table create` populates it.\n const manifest: Record<string, unknown> = {\n schema_version: 2,\n module: {\n slug: opts.slug,\n name: opts.name,\n version: '0.0.1',\n },\n module_kind: kind,\n owns: {\n tables: [],\n },\n };\n if (kind === 'custom') {\n manifest.runtime = {\n type: 'nextjs',\n kind: 'machine',\n machine_size: 'shared-cpu-1x',\n server_actions: true,\n };\n }\n if (opts.repositoryUrl) {\n manifest.repository = { type: 'git', url: opts.repositoryUrl };\n }\n return JSON.stringify(manifest, null, 2) + '\\n';\n}\n\nexport function packageJson(opts: ScaffoldOptions): string {\n return (\n JSON.stringify(\n {\n name: opts.slug,\n version: '0.0.1',\n private: true,\n type: 'module',\n scripts: {\n dev: 'dashwise module dev',\n 'dev:next': 'next dev',\n 'dashwise:generate': 'dashwise module generate',\n build: 'next build',\n start: 'next start',\n },\n dependencies: {\n '@dashai/sdk': '^0.8.0',\n next: '^15.0.0',\n react: '^19.0.0',\n 'react-dom': '^19.0.0',\n },\n devDependencies: {\n '@types/node': '^22.0.0',\n '@types/react': '^19.0.0',\n '@types/react-dom': '^19.0.0',\n typescript: '^5.5.0',\n },\n },\n null,\n 2,\n ) + '\\n'\n );\n}\n\nexport function tsconfigJson(): string {\n return (\n JSON.stringify(\n {\n compilerOptions: {\n target: 'ES2022',\n lib: ['dom', 'dom.iterable', 'ES2022'],\n module: 'ESNext',\n moduleResolution: 'Bundler',\n jsx: 'preserve',\n strict: true,\n skipLibCheck: true,\n resolveJsonModule: true,\n esModuleInterop: true,\n isolatedModules: true,\n allowJs: false,\n noEmit: true,\n incremental: true,\n plugins: [{ name: 'next' }],\n paths: { '@/*': ['./*'] },\n },\n include: ['next-env.d.ts', '**/*.ts', '**/*.tsx', '.next/types/**/*.ts'],\n exclude: ['node_modules'],\n },\n null,\n 2,\n ) + '\\n'\n );\n}\n\nexport function nextConfig(): string {\n return `/** @type {import(\"next\").NextConfig} */\nconst nextConfig = {\n typescript: { ignoreBuildErrors: true },\n eslint: { ignoreDuringBuilds: true },\n};\nexport default nextConfig;\n`;\n}\n\nexport function nextEnvDts(): string {\n return `/// <reference types=\"next\" />\n/// <reference types=\"next/image-types/global\" />\n`;\n}\n\nexport function gitignore(): string {\n return [\n '# Dependencies',\n '/node_modules',\n '',\n '# Generated by Next.js',\n '/.next',\n '/out',\n '',\n '# Production',\n '/build',\n '',\n '# Misc',\n '.DS_Store',\n '*.log',\n '',\n '# Env',\n '.env',\n '.env.local',\n '.env.*.local',\n '',\n '# Editor',\n '.vscode/',\n '.idea/',\n '',\n '# DashWise-generated SDK output is regenerable from module.json',\n '# (run `dashwise module generate`); keep it out of source control.',\n '/node_modules/@dashai/generated/',\n '',\n ].join('\\n');\n}\n\n/**\n * HH-CC-FUP-5: `apiUrl` accepts the CLI's saved API URL so a scaffold\n * created after `dashwise login https://api.dashwise.net` doesn't lie\n * about where it expects the backend to be. Falls back to localhost:3000\n * for offline scaffolds (no login yet).\n */\nconst SCAFFOLD_DEFAULT_API_URL = 'http://localhost:3000';\n\nexport function envLocalExample(apiUrl: string = SCAFFOLD_DEFAULT_API_URL): string {\n return [\n '# Copy to .env.local + fill in real values.',\n '# These vars are auto-injected by `dashwise dev` (the unified dev loop)',\n '# from ~/.config/dashwise/auth.json — you only need to edit this file if',\n '# you want to point at a non-default backend or run `next dev` standalone.',\n `DASHWISE_API_URL=${apiUrl}`,\n '# Client-side mirror — Next.js inlines NEXT_PUBLIC_* into the browser',\n '# bundle so the SDK\\'s <AuthProvider> can hit `/api/auth/sessions/me`',\n '# on the right origin. Should match DASHWISE_API_URL above.',\n `NEXT_PUBLIC_DASHWISE_API_URL=${apiUrl}`,\n 'DASHWISE_API_TOKEN=',\n 'DASHWISE_INSTALLATION_ID=local',\n '',\n ].join('\\n');\n}\n\nexport function envLocal(apiUrl: string = SCAFFOLD_DEFAULT_API_URL): string {\n return [\n '# Local dev config — auto-generated by `dashwise module init`.',\n `# Backend URL pinned to your logged-in CLI config (${apiUrl}). Gitignored;`,\n '# safe to edit. `dashwise dev` (the unified loop) auto-injects',\n '# DASHWISE_API_TOKEN from ~/.config/dashwise/auth.json AND',\n '# DASHWISE_DEV_SESSION_ID from the dev session it registers — so',\n '# you typically don\\'t need to set either here. Change DASHWISE_API_URL',\n '# (and NEXT_PUBLIC_DASHWISE_API_URL to match) to point at a different',\n '# backend.',\n '#',\n '# DASHWISE_INSTALLATION_ID is only needed AFTER you publish + install',\n '# the module in a workspace; until then dev mode (DASHWISE_DEV_SESSION_ID,',\n '# auto-set by `dashwise dev`) is the auth path.',\n `DASHWISE_API_URL=${apiUrl}`,\n '# Client-side mirror (must match DASHWISE_API_URL). Next.js inlines',\n '# NEXT_PUBLIC_* into the browser bundle so the SDK\\'s AuthProvider can',\n '# call /api/auth/sessions/me on the right origin instead of bouncing',\n '# off the local module server with a 404.',\n `NEXT_PUBLIC_DASHWISE_API_URL=${apiUrl}`,\n 'DASHWISE_API_TOKEN=',\n 'DASHWISE_INSTALLATION_ID=',\n '',\n ].join('\\n');\n}\n\nexport function appLayoutTsx(opts: ScaffoldOptions): string {\n return `export const metadata = {\n title: ${JSON.stringify(opts.name)},\n description: ${JSON.stringify(`DashWise module: ${opts.slug}`)},\n};\n\nexport default function RootLayout({ children }: { children: React.ReactNode }) {\n return (\n <html lang=\"en\">\n <body style={{ margin: 0, fontFamily: 'system-ui, sans-serif' }}>{children}</body>\n </html>\n );\n}\n`;\n}\n\nexport function appPageTsx(opts: ScaffoldOptions): string {\n return `export default function Page() {\n return (\n <main style={{ minHeight: '100dvh', display: 'grid', placeItems: 'center', padding: 32 }}>\n <div style={{ maxWidth: 560, textAlign: 'center' }}>\n <h1 style={{ fontSize: 28, marginBottom: 8 }}>${escapeHtml(opts.name)}</h1>\n <p style={{ color: '#475569' }}>\n Module slug: <code>${escapeHtml(opts.slug)}</code>\n </p>\n <p style={{ marginTop: 24, color: '#64748b', fontSize: 14 }}>\n Run <code>dashwise module dev</code> to start the watch loop.\n <br />\n Edit <code>module.json</code> to add tables; regenerated types\n land in <code>@dashai/generated</code>.\n </p>\n </div>\n </main>\n );\n}\n`;\n}\n\nexport function readme(opts: ScaffoldOptions): string {\n const kind = opts.kind ?? 'hand_authored';\n if (kind === 'custom') {\n return readmeCustom(opts);\n }\n return readmeHandAuthored(opts);\n}\n\nfunction readmeHandAuthored(opts: ScaffoldOptions): string {\n return `# ${opts.name}\n\nA DashWise module (hand-authored). Slug: \\`${opts.slug}\\`.\n\n## Get started\n\n\\`\\`\\`bash\nnpm install\ndashwise dev # one command: watcher + Next.js dev together,\n # auth env vars auto-injected from your CLI config\n\\`\\`\\`\n\nIf you'd rather run the two halves in separate terminals (e.g. to attach a\ndebugger to Next), use the legacy two-terminal flow:\n\n\\`\\`\\`bash\ndashwise module generate # produces node_modules/@dashai/generated/\ndashwise module dev # watch module.json + auto-regenerate\nnpm run dev:next # plain Next.js dev server (in another terminal)\n\\`\\`\\`\n\n## Project layout\n\n| Path | What |\n| --- | --- |\n| \\`module.json\\` | Manifest. Declares tables, dependencies, runtime config. |\n| \\`app/\\` | Next.js App Router. Edit freely. |\n| \\`node_modules/@dashai/generated/\\` | Auto-generated typed wrappers. **Do not edit by hand** — regenerated by \\`dashwise module generate\\`. |\n\n## Imports\n\n\\`\\`\\`ts\nimport { db } from '@dashai/generated';\nimport type { ItemsRow } from '@dashai/generated';\n\n// runtime types + errors\nimport { createClient, type Where } from '@dashai/sdk';\n\\`\\`\\`\n`;\n}\n\nfunction readmeCustom(opts: ScaffoldOptions): string {\n return `# ${opts.name}\n\nA **custom DashWise module** — a full Next.js App Router app that\nruns in a per-installation Fly Machine (P7 substrate). Authenticated\nvia the DashWise NestJS backend through \\`@dashai/sdk/auth\\`.\n\nSlug: \\`${opts.slug}\\`.\n\n## Get started\n\n\\`\\`\\`bash\nnpm install\ndashwise dev # one command: watcher + Next.js dev together,\n # auth env vars auto-injected from your CLI config\n\\`\\`\\`\n\nIf you'd rather run the two halves in separate terminals (e.g. to attach a\ndebugger to Next), use the legacy two-terminal flow:\n\n\\`\\`\\`bash\ndashwise module generate # produces node_modules/@dashai/generated/\ndashwise module dev # watch + regen on module.json save (terminal 1)\nnpm run dev:next # next dev on :3000 (terminal 2)\n\\`\\`\\`\n\n## Architecture\n\n- **\\`module.json\\`** — manifest (\\`module_kind: 'custom'\\`, \\`runtime.kind: 'machine'\\`).\n- **\\`middleware.ts\\`** — \\`withAuth\\` from \\`@dashai/sdk/auth/middleware\\`. Redirects unauthenticated requests through the DashWise SSO flow.\n- **\\`app/layout.tsx\\`** — wraps the tree in \\`<AuthProvider>\\` from \\`@dashai/sdk/auth/client\\`.\n- **\\`app/page.tsx\\`** — public landing (allowlisted in \\`middleware.ts\\`).\n- **\\`app/dashboard/page.tsx\\`** — Server Component requiring a valid session via \\`getServerSession()\\`.\n- **\\`app/api/auth/callback/route.ts\\`** — exchanges the SSO one-time code for a session cookie (uses \\`exchangeCode()\\` from the SDK).\n- **\\`app/api/auth/sign-in/route.ts\\`** — entry point that redirects to the backend's \\`/sso/start\\` with the right \\`return_to\\` + \\`client_id\\`.\n- **\\`app/api/auth/sign-out/route.ts\\`** — clears the session cookie + tells the backend to revoke.\n\n## Imports\n\n\\`\\`\\`ts\n// Data:\nimport { db } from '@dashai/generated';\n\n// Auth (server, e.g. inside a Server Component or route handler):\nimport { getServerSession, exchangeCode, signOut } from '@dashai/sdk/auth/server';\n\n// Auth (client, inside a Client Component):\n'use client';\nimport { useSession, SignOutButton, AuthProvider } from '@dashai/sdk/auth/client';\n\n// Runtime types + errors:\nimport { type Where, RowNotFoundError } from '@dashai/sdk';\n\\`\\`\\`\n\n## Publish\n\n\\`\\`\\`bash\ndashwise module validate # local lint\ndashwise module publish --bump patch\n\\`\\`\\`\n\n## Adding UI blocks\n\nThe scaffold pre-installs two shadcn/ui primitives (\\`Button\\`, \\`Card\\`) plus the\ncanonical Tailwind 4 + theme-tokens setup. To add more components:\n\n\\`\\`\\`bash\n# shadcn/ui base (free):\nnpx shadcn@latest add input badge dialog dropdown-menu\n\n# shadcn-studio blocks (free at https://shadcnstudio.com):\nnpx shadcn@latest add @shadcn-studio/hero-section-01\n\n# shadcn-studio Pro blocks (requires \\$EMAIL + \\$LICENSE_KEY env vars):\nnpx shadcn@latest add @ss-components/dashboard-shell-01\n\\`\\`\\`\n\nIf you're using Claude Code or another IDE that supports the shadcn-studio MCP,\ntrigger \\`/cui\\` (create new UI) or \\`/rui\\` (refine existing UI) to walk through\nthe canonical block-discovery flow.\n\n## Deploying elsewhere (custom domain)\n\nThe scaffolded SSO flow is wired for DashWise's own infrastructure\n(\\`m-<id>.dashwise.net\\`). If you want to host this module on your own\ndomain (e.g. \\`mymodule.example.com\\`), there are two options:\n\n1. **Wait for custom-domain support (in design).** A future \\`--callback-origin\\`\n flag on \\`dashwise module init\\` plus a \\`module_oauth_clients\\` allowlist will\n let modules run at arbitrary domains while still using DashWise SSO. Tracked\n in [\\`modules-author-experience-v1.md\\`](https://github.com/sharmaintuize/dashwise-devops-docs/blob/main/plans/modules-author-experience-v1.md) §3.\n2. **Bypass SSO + use a Workspace API Token today.** Replace the SSO middleware\n with a token-check middleware that reads \\`Authorization: Token <key>\\` from\n each request. Tokens are created at \\`<dashwise-dashboard>/settings/tokens\\`\n and scoped to a workspace. The SDK accepts these via the standard\n \\`DASHWISE_API_TOKEN\\` env var. You'll lose the per-user session model\n (every request runs as the token's owner) but gain the freedom to deploy\n anywhere.\n\nThe CLI's \\`dashwise dev\\` command auto-injects the developer's CLI token (also\na bearer token) into local dev — so local development works regardless of\nwhich path you pick for production.\n`;\n}\n\n// ── Custom-flavor templates ──────────────────────────────────────────\n\nexport function middlewareTs(): string {\n return `// Next.js middleware — gates every route on the DashWise session cookie.\n// Public routes (and /api/auth/*) bypass the redirect; everything else\n// 302s through the SSO flow when no \\`dashwise.session\\` cookie is set.\nimport { withAuth } from '@dashai/sdk/auth/middleware';\n\nexport default withAuth({\n // \\`/sign-in-error\\` is public so unauthenticated visitors can actually\n // see the polished SSO error page — otherwise a sign-in failure would\n // redirect-loop trying to re-authenticate.\n publicPaths: ['/', '/about', '/sign-in-error'],\n loginPath: '/api/auth/sign-in',\n});\n\nexport const config = {\n matcher: ['/((?!_next/static|_next/image|favicon.ico|public/).*)'],\n};\n`;\n}\n\nexport function appLayoutCustomTsx(opts: ScaffoldOptions): string {\n return `import './globals.css';\nimport { AuthProvider } from '@dashai/sdk/auth/client';\nimport { ThemeProvider } from '@/components/theme-provider';\n\nexport const metadata = {\n title: ${JSON.stringify(opts.name)},\n description: ${JSON.stringify(`DashWise custom module: ${opts.slug}`)},\n};\n\nexport default function RootLayout({ children }: { children: React.ReactNode }) {\n return (\n <html lang=\"en\" suppressHydrationWarning>\n <body className=\"antialiased\">\n <ThemeProvider\n attribute=\"class\"\n defaultTheme=\"system\"\n enableSystem\n disableTransitionOnChange\n >\n <AuthProvider>{children}</AuthProvider>\n </ThemeProvider>\n </body>\n </html>\n );\n}\n`;\n}\n\nexport function appPageCustomTsx(opts: ScaffoldOptions): string {\n return `// Public landing page — listed in middleware.ts publicPaths.\n//\n// First-run experience for unauthenticated visitors: hero with the\n// module name + tagline, a \"Sign in with DashWise\" button that kicks\n// off the SSO flow (via /api/auth/sign-in), and a feature card\n// describing what the module does. After signing in, the user lands\n// on /dashboard (Server Component, session-validated).\n//\n// Styling: shadcn/ui primitives (\\`<Button>\\`, \\`<Card>\\`) on Tailwind 4\n// theme tokens. Add more blocks via \\`npx shadcn add @shadcn-studio/...\\`\n// (see README's \"Adding UI blocks\" section).\nimport Link from 'next/link';\nimport { LogIn, LayoutDashboard } from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from '@/components/ui/card';\n\nexport default function Page() {\n return (\n <main className=\"flex min-h-dvh flex-col items-center justify-center gap-12 px-6 py-16\">\n <section className=\"flex max-w-2xl flex-col items-center gap-6 text-center\">\n <h1 className=\"text-balance text-4xl font-semibold tracking-tight sm:text-5xl\">\n ${escapeHtml(opts.name)}\n </h1>\n <p className=\"text-balance text-lg text-muted-foreground\">\n A DashWise module. Sign in with your DashWise account to access the\n dashboard and start using the workspace's data through the typed SDK.\n </p>\n <div className=\"flex flex-wrap items-center justify-center gap-3\">\n <Button asChild size=\"lg\">\n <Link href=\"/api/auth/sign-in?return_to=/dashboard\">\n <LogIn aria-hidden=\"true\" />\n Sign in with DashWise\n </Link>\n </Button>\n <Button asChild variant=\"ghost\" size=\"lg\">\n <Link href=\"/dashboard\">\n <LayoutDashboard aria-hidden=\"true\" />\n Go to dashboard\n </Link>\n </Button>\n </div>\n </section>\n\n <Card className=\"w-full max-w-2xl\">\n <CardHeader>\n <CardTitle>What you can do here</CardTitle>\n <CardDescription>\n This is a custom DashWise module — a full Next.js app authenticated\n against the DashWise SSO. Edit \\`app/page.tsx\\` to replace this\n landing page; everything else is yours to customize.\n </CardDescription>\n </CardHeader>\n <CardContent className=\"text-sm text-muted-foreground\">\n <ul className=\"space-y-2\">\n <li>\n Edit <code className=\"rounded bg-muted px-1.5 py-0.5\">module.json</code>\n {' '}to declare tables, dependencies, and runtime config.\n </li>\n <li>\n Run <code className=\"rounded bg-muted px-1.5 py-0.5\">dashwise dev</code>\n {' '}for a one-command local loop with auth env vars auto-injected.\n </li>\n <li>\n Import typed table clients from{' '}\n <code className=\"rounded bg-muted px-1.5 py-0.5\">@dashai/generated</code>\n {' '}— the SDK regenerates on every manifest save.\n </li>\n </ul>\n </CardContent>\n </Card>\n </main>\n );\n}\n`;\n}\n\nexport function appDashboardPageTsx(): string {\n return `import { getServerSession } from '@dashai/sdk/auth/server';\nimport { redirect } from 'next/navigation';\nimport { LogOut, ShieldCheck } from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from '@/components/ui/card';\n\n/**\n * Auth-gated Server Component. The middleware ensures the user has\n * a session cookie before this page renders; \\`getServerSession()\\`\n * validates the cookie against the backend's \\`/api/auth/sessions/me\\`\n * endpoint, returning the decoded \\`Session\\` (or \\`null\\` if stale).\n *\n * On a successful render, this is the polished session card — replace\n * the contents with whatever your module actually needs to show.\n */\nexport default async function Dashboard() {\n const session = await getServerSession();\n if (!session) {\n redirect('/api/auth/sign-in?return_to=/dashboard');\n }\n return (\n <main className=\"mx-auto flex min-h-dvh max-w-3xl flex-col gap-6 px-6 py-12\">\n <header className=\"flex items-start justify-between gap-4\">\n <div>\n <h1 className=\"text-2xl font-semibold tracking-tight\">Dashboard</h1>\n <p className=\"text-sm text-muted-foreground\">\n You're signed in. This page is rendered as a Server Component and\n validates the session cookie on every request.\n </p>\n </div>\n <form action=\"/api/auth/sign-out\" method=\"POST\">\n <Button variant=\"outline\" size=\"sm\" type=\"submit\">\n <LogOut aria-hidden=\"true\" />\n Sign out\n </Button>\n </form>\n </header>\n\n <Card>\n <CardHeader>\n <CardTitle className=\"flex items-center gap-2\">\n <ShieldCheck className=\"size-5 text-primary\" aria-hidden=\"true\" />\n Session\n </CardTitle>\n <CardDescription>\n Decoded from the \\`dashwise.session\\` cookie via{' '}\n <code className=\"rounded bg-muted px-1.5 py-0.5\">getServerSession()</code>.\n </CardDescription>\n </CardHeader>\n <CardContent className=\"space-y-3 text-sm\">\n <Row label=\"Email\" value={session.user.email} />\n <Row label=\"User ID\" value={String(session.user.id)} />\n <Row label=\"Workspace\" value={String(session.workspaceId)} />\n <Row label=\"Role\" value={session.role} />\n {session.installationId !== undefined && (\n <Row\n label=\"Installation\"\n value={\n session.moduleSlug\n ? \\`\\${session.installationId} (\\${session.moduleSlug})\\`\n : String(session.installationId)\n }\n />\n )}\n </CardContent>\n </Card>\n\n <Card>\n <CardHeader>\n <CardTitle>Next steps</CardTitle>\n <CardDescription>\n Replace this dashboard with your module's actual UI.\n </CardDescription>\n </CardHeader>\n <CardContent className=\"space-y-2 text-sm text-muted-foreground\">\n <p>\n <strong className=\"text-foreground\">1.</strong> Edit{' '}\n <code className=\"rounded bg-muted px-1.5 py-0.5\">module.json</code>{' '}\n to add tables, dependencies, and exposed actions.\n </p>\n <p>\n <strong className=\"text-foreground\">2.</strong> Import typed clients\n from{' '}\n <code className=\"rounded bg-muted px-1.5 py-0.5\">@dashai/generated</code>{' '}\n (regenerated on every manifest save).\n </p>\n <p>\n <strong className=\"text-foreground\">3.</strong> Run{' '}\n <code className=\"rounded bg-muted px-1.5 py-0.5\">dashwise module publish --bump patch</code>{' '}\n when you're ready to ship.\n </p>\n </CardContent>\n </Card>\n </main>\n );\n}\n\nfunction Row({ label, value }: { label: string; value: string }) {\n return (\n <div className=\"flex items-baseline justify-between gap-4 border-b border-border/50 pb-2 last:border-0 last:pb-0\">\n <span className=\"text-muted-foreground\">{label}</span>\n <span className=\"font-mono text-sm\">{value}</span>\n </div>\n );\n}\n`;\n}\n\nexport function appApiAuthSignInTs(): string {\n return `// /api/auth/sign-in — kick off the SSO flow.\n//\n// Reads \\`?return_to=\\` from the caller (defaults to '/'). Branches\n// on env:\n//\n// - DASHWISE_DEV_SESSION_ID set (set automatically by\n// \\`dashwise dev\\`): hits /api/auth/dev/sso/start with the dev\n// session id. No installation_id required — the module isn't\n// installed in a workspace yet.\n//\n// - DASHWISE_INSTALLATION_ID set (production / installed-module\n// path): hits /api/auth/sso/start with the installation id.\n//\n// In both cases the backend mints an exchange code + 302s back to\n// \\`/api/auth/callback?code=...\\` where we set the session cookie.\n//\n// Unauthenticated browser hits to either backend endpoint 302 to\n// the DashWise FE \\`/login?return_to=...\\` automatically — you don't\n// need to handle the \"user not logged in\" case here.\nimport { NextResponse } from 'next/server';\nimport { getPublicOrigin } from '@/lib/request-origin';\n\nexport function GET(request: Request) {\n const url = new URL(request.url);\n const returnTo = url.searchParams.get('return_to') ?? '/';\n const apiBaseUrl = process.env.DASHWISE_API_URL;\n const installationId = process.env.DASHWISE_INSTALLATION_ID;\n const devSessionId = process.env.DASHWISE_DEV_SESSION_ID;\n\n if (!apiBaseUrl) {\n return new NextResponse(\n 'DASHWISE_API_URL must be set in .env.local',\n { status: 500 },\n );\n }\n if (!installationId && !devSessionId) {\n return new NextResponse(\n 'Either DASHWISE_INSTALLATION_ID (installed module) or DASHWISE_DEV_SESSION_ID ' +\n '(local dev via \\`dashwise dev\\`) must be set. Run \\`dashwise dev\\` to register ' +\n 'a dev session, or set DASHWISE_INSTALLATION_ID after publishing your module.',\n { status: 500 },\n );\n }\n\n // Absolute URL for return_to so the backend knows which host to\n // bounce back to (the callback path is fixed at /api/auth/callback\n // by SDK convention). \\`getPublicOrigin\\` reads \\`X-Forwarded-Host\\`\n // when present so the redirect URL points at the public domain,\n // not the internal Node origin behind reverse proxies.\n const moduleOrigin = getPublicOrigin(request);\n const absoluteReturnTo = \\`\\${moduleOrigin}\\${returnTo}\\`;\n\n let ssoStart;\n if (devSessionId) {\n // Dev mode wins when both are set — \\`dashwise dev\\` injects\n // DASHWISE_DEV_SESSION_ID into the child env, which overrides\n // whatever was in .env.local. The dev session id keys back to\n // the dev's workspace + callback origin allowlist.\n ssoStart = new URL('/api/auth/dev/sso/start', apiBaseUrl);\n ssoStart.searchParams.set('return_to', absoluteReturnTo);\n ssoStart.searchParams.set('dev_session_id', devSessionId);\n } else {\n ssoStart = new URL('/api/auth/sso/start', apiBaseUrl);\n ssoStart.searchParams.set('return_to', absoluteReturnTo);\n ssoStart.searchParams.set('client_id', installationId);\n }\n return NextResponse.redirect(ssoStart);\n}\n`;\n}\n\nexport function appApiAuthCallbackTs(): string {\n return `// /api/auth/callback — receives \\`?code=&return_to=\\` from the\n// DashWise SSO start endpoint OR \\`?error=&error_description=\\` if the\n// SSO flow failed. Two paths:\n//\n// 1. Success path: exchange \\`?code\\` for a session cookie via\n// \\`exchangeCode()\\`, then redirect to \\`return_to\\`.\n// 2. Error path: SSO returned \\`?error=\\` — redirect to the polished\n// sign-in-error page so the user sees a real error UI instead of\n// a raw 4xx page. The error code maps to known SSO error codes\n// (e.g. \\`access_denied\\`, \\`server_error\\`, \\`invalid_request\\`).\nimport { NextResponse } from 'next/server';\nimport { exchangeCode } from '@dashai/sdk/auth/server';\nimport { getPublicOrigin } from '@/lib/request-origin';\n\nexport async function GET(request: Request) {\n const url = new URL(request.url);\n // Resolve the public origin once — all redirects below are\n // back to this module, and behind a reverse proxy url.origin is\n // the internal Node origin (localhost:<PORT>), not the public host.\n const publicOrigin = getPublicOrigin(request);\n const error = url.searchParams.get('error');\n if (error) {\n const target = new URL('/sign-in-error', publicOrigin);\n target.searchParams.set('code', error);\n const description = url.searchParams.get('error_description');\n if (description) target.searchParams.set('description', description);\n return NextResponse.redirect(target);\n }\n const code = url.searchParams.get('code');\n const returnTo = url.searchParams.get('return_to') ?? '/';\n if (!code) {\n const target = new URL('/sign-in-error', publicOrigin);\n target.searchParams.set('code', 'missing_code');\n return NextResponse.redirect(target);\n }\n try {\n await exchangeCode(code); // sets the dashwise.session cookie\n } catch (err) {\n const target = new URL('/sign-in-error', publicOrigin);\n target.searchParams.set('code', 'exchange_failed');\n target.searchParams.set('description', (err as Error).message);\n return NextResponse.redirect(target);\n }\n return NextResponse.redirect(new URL(returnTo, publicOrigin));\n}\n`;\n}\n\nexport function appApiAuthSignOutTs(): string {\n return `// /api/auth/sign-out — best-effort backend revoke + cookie clear,\n// then redirect to / so the browser actually navigates somewhere\n// after the form POST. A 204 here would leave the user staring at\n// /dashboard with stale-rendered HTML — the cookie WAS cleared but\n// they'd think nothing happened. 303 See Other forces the browser\n// to follow with GET (not re-POST), landing on the public '/' page.\nimport { NextResponse } from 'next/server';\nimport { signOut } from '@dashai/sdk/auth/server';\nimport { getPublicOrigin } from '@/lib/request-origin';\n\nexport async function POST(request: Request) {\n await signOut();\n // Build the redirect against the public origin so we don't land\n // the user on \\`http://localhost:<PORT>/\\` when running behind a\n // reverse proxy (Railway/Vercel/Fly).\n return NextResponse.redirect(new URL('/', getPublicOrigin(request)), 303);\n}\n`;\n}\n\nexport function packageJsonCustom(opts: ScaffoldOptions): string {\n return (\n JSON.stringify(\n {\n name: opts.slug,\n version: '0.0.1',\n private: true,\n type: 'module',\n scripts: {\n dev: 'dashwise module dev',\n 'dev:next': 'next dev',\n 'dashwise:generate': 'dashwise module generate',\n build: 'next build',\n start: 'next start',\n },\n dependencies: {\n '@dashai/sdk': '^0.8.0',\n next: '^15.0.0',\n react: '^19.0.0',\n 'react-dom': '^19.0.0',\n // Styling system — same shadcn + Tailwind 4 stack as the\n // main DashWise frontend, so look-and-feel stays consistent\n // and module authors can add more blocks via the\n // shadcn-studio MCP (`npx shadcn add @shadcn-studio/...`).\n tailwindcss: '^4',\n '@tailwindcss/postcss': '^4',\n 'tw-animate-css': '^1.4.0',\n shadcn: '^4.0.8',\n 'radix-ui': '^1.4.3',\n 'class-variance-authority': '^0.7.1',\n clsx: '^2.1.1',\n 'tailwind-merge': '^3.5.0',\n 'lucide-react': '^0.577.0',\n 'next-themes': '^0.4.6',\n },\n devDependencies: {\n '@types/node': '^22.0.0',\n '@types/react': '^19.0.0',\n '@types/react-dom': '^19.0.0',\n typescript: '^5.5.0',\n },\n },\n null,\n 2,\n ) + '\\n'\n );\n}\n\n// ── shadcn + Tailwind 4 stack (custom scaffold) ──────────────────────\n//\n// These templates mirror the configuration the main `dashwise-frontend`\n// uses, so visual + UX consistency is preserved across the dashboard\n// and scaffolded modules. The stack: Tailwind 4 (no config file —\n// config lives in `globals.css` via `@import \"tailwindcss\"`), shadcn\n// New York style, oklch theme tokens, lucide icons, next-themes for\n// the dark-mode toggle.\n//\n// Module authors who want more blocks add them via the shadcn-studio\n// MCP workflow: `/cui` for new blocks, `/rui` for refines (see the\n// scaffold's README for the canonical pointer).\n\n/**\n * `components.json` — shadcn config. Pins the style + base color so\n * `npx shadcn add` produces the same look as the rest of the DashWise\n * ecosystem. The two registries (`@shadcn-studio` free + `@ss-components`\n * Pro) are declared so module authors can pull blocks from either\n * without re-running init.\n */\nexport function componentsJson(): string {\n return (\n JSON.stringify(\n {\n $schema: 'https://ui.shadcn.com/schema.json',\n style: 'new-york',\n rsc: true,\n tsx: true,\n tailwind: {\n config: '',\n css: 'app/globals.css',\n baseColor: 'neutral',\n cssVariables: true,\n prefix: '',\n },\n iconLibrary: 'lucide',\n rtl: false,\n aliases: {\n components: '@/components',\n utils: '@/lib/utils',\n ui: '@/components/ui',\n lib: '@/lib',\n hooks: '@/hooks',\n },\n registries: {\n '@shadcn-studio': 'https://shadcnstudio.com/r/{name}.json',\n '@ss-components': {\n url: 'https://shadcnstudio.com/r/components/{name}.json',\n params: {\n email: '${EMAIL}',\n license_key: '${LICENSE_KEY}',\n },\n },\n },\n },\n null,\n 2,\n ) + '\\n'\n );\n}\n\n/**\n * `postcss.config.mjs` — Tailwind 4's PostCSS plugin entry. No other\n * plugins needed; the rest of the build is Next.js's defaults.\n */\nexport function postcssConfigMjs(): string {\n return `const config = {\n plugins: {\n \"@tailwindcss/postcss\": {},\n },\n};\n\nexport default config;\n`;\n}\n\n/**\n * `app/globals.css` — Tailwind 4 entry + oklch theme tokens.\n *\n * Tailwind 4 has no `tailwind.config.ts`; config lives here via the\n * `@import \"tailwindcss\"` directive + CSS custom properties. The\n * `:root` block defines the light theme; `.dark` overrides it. Tokens\n * are copied verbatim from the main dashwise-frontend so module authors\n * who later read the frontend code see the same names.\n */\nexport function globalsCss(): string {\n return `@import \"tailwindcss\";\n@import \"tw-animate-css\";\n@import \"shadcn/tailwind.css\";\n\n@custom-variant dark (&:is(.dark *));\n\n:root {\n --background: oklch(1 0 0);\n --foreground: oklch(0.14 0 0);\n --card: oklch(1 0 0);\n --card-foreground: oklch(0.14 0 0);\n --popover: oklch(1 0 0);\n --popover-foreground: oklch(0.14 0 0);\n --primary: oklch(0.2 0 0);\n --primary-foreground: oklch(0.99 0 0);\n --secondary: oklch(0.97 0 0);\n --secondary-foreground: oklch(0.2 0 0);\n --muted: oklch(0.97 0 0);\n --muted-foreground: oklch(0.56 0 0);\n --accent: oklch(0.97 0 0);\n --accent-foreground: oklch(0.2 0 0);\n --destructive: oklch(0.58 0.24 28.48);\n --border: oklch(0.92 0 0);\n --input: oklch(0.92 0 0);\n --ring: oklch(0.71 0 0);\n --radius: 0.625rem;\n\n --font-sans:\n ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,\n \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif;\n --font-mono:\n ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,\n \"Liberation Mono\", \"Courier New\", monospace;\n}\n\n.dark {\n --background: oklch(0.14 0 0);\n --foreground: oklch(0.99 0 0);\n --card: oklch(0.2 0 0);\n --card-foreground: oklch(0.99 0 0);\n --popover: oklch(0.2 0 0);\n --popover-foreground: oklch(0.99 0 0);\n --primary: oklch(0.92 0 0);\n --primary-foreground: oklch(0.2 0 0);\n --secondary: oklch(0.27 0 0);\n --secondary-foreground: oklch(0.99 0 0);\n --muted: oklch(0.27 0 0);\n --muted-foreground: oklch(0.71 0 0);\n --accent: oklch(0.27 0 0);\n --accent-foreground: oklch(0.99 0 0);\n --destructive: oklch(0.7 0.19 22.23);\n --border: oklch(0.27 0 0);\n --input: oklch(0.27 0 0);\n --ring: oklch(0.56 0 0);\n}\n\n* {\n border-color: var(--border);\n}\n\nbody {\n background-color: var(--background);\n color: var(--foreground);\n font-family: var(--font-sans);\n}\n`;\n}\n\n/**\n * `lib/utils.ts` — the canonical \\`cn()\\` helper that shadcn components\n * import. Combines \\`clsx\\` (conditional class composition) with\n * \\`tailwind-merge\\` (resolves conflicting Tailwind utilities, e.g.\n * \\`px-2 px-4\\` → \\`px-4\\`).\n */\nexport function libUtilsTs(): string {\n return `import { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n`;\n}\n\n/**\n * \\`lib/request-origin.ts\\` — resolve the **public** origin of an\n * incoming request, respecting reverse-proxy headers.\n *\n * Used by the three \\`/api/auth/*\\` route handlers when building\n * redirect URLs. Behind a reverse proxy (Railway, Vercel, Fly,\n * Cloudflare, an nginx in front of a Node container, etc.)\n * \\`new URL(request.url).origin\\` reports the *internal* origin the\n * Node process is bound to — usually \\`http://localhost:<PORT>\\` —\n * not the public host the browser actually hit. Building the SSO\n * \\`return_to\\` against that internal origin sends the browser to\n * localhost after the round-trip and breaks sign-in entirely.\n */\nexport function libRequestOriginTs(): string {\n return `/**\n * Resolve the **public** origin of an incoming request.\n *\n * Behind a reverse proxy (Railway, Vercel, Fly, Cloudflare, an\n * nginx in front of a Node container, etc.) \\`new URL(request.url)\\`\n * reports the *internal* origin the Node process is bound to —\n * usually \\`http://localhost:<PORT>\\` — not the public URL the\n * browser hit. The proxy preserves the public origin in\n * \\`X-Forwarded-*\\` headers; we read those first.\n *\n * Falls back to \\`new URL(request.url).origin\\` for local dev where\n * there's no proxy in front of Next.js.\n *\n * Both \\`x-forwarded-proto\\` and \\`x-forwarded-host\\` can be\n * comma-separated when multiple proxies chain; the leftmost entry\n * is the original client-facing one per RFC 7239 conventions.\n */\nexport function getPublicOrigin(request: Request): string {\n const forwardedProto = request.headers.get('x-forwarded-proto');\n const forwardedHost = request.headers.get('x-forwarded-host');\n if (forwardedProto && forwardedHost) {\n const proto = forwardedProto.split(',')[0].trim();\n const host = forwardedHost.split(',')[0].trim();\n return \\`\\${proto}://\\${host}\\`;\n }\n return new URL(request.url).origin;\n}\n`;\n}\n\n/**\n * \\`components/ui/button.tsx\\` — vendored from the dashwise-frontend's\n * canonical button (which itself came from shadcn New York). Vendored\n * (vs running \\`npx shadcn add\\` in a post-install) so the scaffold\n * doesn't need network access at install time.\n */\nexport function componentsUiButtonTsx(): string {\n return `import * as React from \"react\";\nimport { cva, type VariantProps } from \"class-variance-authority\";\nimport { Slot } from \"radix-ui\";\n\nimport { cn } from \"@/lib/utils\";\n\nconst buttonVariants = cva(\n \"inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n {\n variants: {\n variant: {\n default: \"bg-primary text-primary-foreground hover:bg-primary/90\",\n destructive:\n \"bg-destructive text-white hover:bg-destructive/90\",\n outline:\n \"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground\",\n secondary:\n \"bg-secondary text-secondary-foreground hover:bg-secondary/80\",\n ghost:\n \"hover:bg-accent hover:text-accent-foreground\",\n link: \"text-primary underline-offset-4 hover:underline\",\n },\n size: {\n default: \"h-9 px-4 py-2 has-[>svg]:px-3\",\n sm: \"h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5\",\n lg: \"h-10 rounded-md px-6 has-[>svg]:px-4\",\n icon: \"size-9\",\n },\n },\n defaultVariants: {\n variant: \"default\",\n size: \"default\",\n },\n },\n);\n\nfunction Button({\n className,\n variant = \"default\",\n size = \"default\",\n asChild = false,\n ...props\n}: React.ComponentProps<\"button\"> &\n VariantProps<typeof buttonVariants> & {\n asChild?: boolean;\n }) {\n const Comp = asChild ? Slot.Root : \"button\";\n return (\n <Comp\n data-slot=\"button\"\n className={cn(buttonVariants({ variant, size, className }))}\n {...props}\n />\n );\n}\n\nexport { Button, buttonVariants };\n`;\n}\n\n/**\n * \\`components/ui/card.tsx\\` — vendored from the dashwise-frontend. Same\n * rationale as button.tsx.\n */\nexport function componentsUiCardTsx(): string {\n return `import * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\nfunction Card({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card\"\n className={cn(\n \"flex flex-col gap-6 rounded-xl border bg-card py-6 text-card-foreground shadow-sm\",\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction CardHeader({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-header\"\n className={cn(\n \"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6\",\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction CardTitle({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-title\"\n className={cn(\"leading-none font-semibold\", className)}\n {...props}\n />\n );\n}\n\nfunction CardDescription({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-description\"\n className={cn(\"text-sm text-muted-foreground\", className)}\n {...props}\n />\n );\n}\n\nfunction CardContent({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-content\"\n className={cn(\"px-6\", className)}\n {...props}\n />\n );\n}\n\nfunction CardFooter({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-footer\"\n className={cn(\"flex items-center px-6\", className)}\n {...props}\n />\n );\n}\n\nexport { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };\n`;\n}\n\n/**\n * \\`components/theme-provider.tsx\\` — thin re-export of the next-themes\n * provider, marked \\`\"use client\"\\`. Layout wraps in this so the\n * \\`.dark\\` class can be applied to \\`<html>\\` based on system preference\n * or explicit user toggle.\n */\nexport function componentsThemeProviderTsx(): string {\n return `\"use client\";\n\nimport { ThemeProvider as NextThemesProvider } from \"next-themes\";\n\nexport function ThemeProvider({\n children,\n ...props\n}: React.ComponentProps<typeof NextThemesProvider>) {\n return <NextThemesProvider {...props}>{children}</NextThemesProvider>;\n}\n`;\n}\n\n/**\n * \\`app/sign-in-error/page.tsx\\` — the SSO error landing.\n *\n * Reached via redirect from /api/auth/callback when the SSO flow\n * returns \\`?error=\\` or when code exchange fails. Renders a polished\n * error UI with the SSO error code (plain-English when known) + a\n * \"Try again\" button that retries the sign-in flow.\n *\n * Listed in middleware.ts publicPaths so unauthenticated visitors can\n * actually reach the error page (otherwise the redirect would loop).\n */\nexport function appSignInErrorPageTsx(): string {\n return `import Link from 'next/link';\nimport { AlertTriangle, RefreshCw } from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from '@/components/ui/card';\n\nconst ERROR_MESSAGES: Record<string, string> = {\n access_denied:\n \"You declined the sign-in request. To use this module, you'll need to authorize it on the DashWise sign-in page.\",\n server_error:\n 'The DashWise sign-in server returned an internal error. This is usually transient — try again in a moment.',\n invalid_request:\n 'The sign-in request was malformed. This is almost always a configuration bug — check that DASHWISE_API_URL and DASHWISE_INSTALLATION_ID are set correctly.',\n missing_code:\n 'The callback URL was missing the expected exchange code. This usually means the SSO flow was interrupted.',\n exchange_failed:\n \"The exchange code couldn't be redeemed for a session. The code may have expired (they're single-use and short-lived) — try signing in again.\",\n};\n\ninterface SignInErrorPageProps {\n searchParams: Promise<{ code?: string; description?: string }>;\n}\n\nexport default async function SignInErrorPage({ searchParams }: SignInErrorPageProps) {\n const params = await searchParams;\n const errorCode = params.code ?? 'unknown';\n const friendlyMessage = ERROR_MESSAGES[errorCode];\n return (\n <main className=\"flex min-h-dvh items-center justify-center px-6 py-12\">\n <Card className=\"w-full max-w-lg\">\n <CardHeader>\n <div className=\"flex items-start gap-3\">\n <div className=\"rounded-full bg-destructive/10 p-2\">\n <AlertTriangle className=\"size-5 text-destructive\" aria-hidden=\"true\" />\n </div>\n <div className=\"flex-1\">\n <CardTitle>Sign-in failed</CardTitle>\n <CardDescription>\n The DashWise SSO flow couldn't complete.\n </CardDescription>\n </div>\n </div>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <div className=\"space-y-1\">\n <div className=\"text-xs uppercase tracking-wide text-muted-foreground\">\n Error code\n </div>\n <code className=\"block rounded bg-muted px-2 py-1 text-sm\">\n {errorCode}\n </code>\n </div>\n {friendlyMessage && (\n <p className=\"text-sm text-muted-foreground\">{friendlyMessage}</p>\n )}\n {params.description && (\n <div className=\"space-y-1\">\n <div className=\"text-xs uppercase tracking-wide text-muted-foreground\">\n Detail\n </div>\n <p className=\"text-sm text-muted-foreground\">{params.description}</p>\n </div>\n )}\n <div className=\"flex flex-wrap gap-2 pt-2\">\n <Button asChild>\n <Link href=\"/api/auth/sign-in?return_to=/dashboard\">\n <RefreshCw aria-hidden=\"true\" />\n Try again\n </Link>\n </Button>\n <Button asChild variant=\"ghost\">\n <Link href=\"/\">Back to landing</Link>\n </Button>\n </div>\n </CardContent>\n </Card>\n </main>\n );\n}\n`;\n}\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"');\n}\n\n/** Slug validation matching the manifest schema's regex. */\nexport function isValidSlug(slug: string): boolean {\n return /^[a-z][a-z0-9_-]*$/.test(slug);\n}\n\n// ── HH-CC-FUP-5: agent-facing scaffold docs ───────────────────────────\n//\n// CLAUDE.md + spec.md + agent-log.md ship with every scaffold so AI\n// coding agents (Claude Code, Cursor, etc.) inherit the spec-first +\n// log-every-change discipline used in the dashwise-backend codebase\n// without the author having to write any of it themselves. The bodies\n// are kept short on purpose — pointers to the canonical docs\n// (`building-modules.md`, manifest schema) instead of duplicating\n// content that drifts.\n\nexport function claudeMd(opts: ScaffoldOptions): string {\n const isCustom = (opts.kind ?? 'hand_authored') === 'custom';\n return `# CLAUDE.md — ${opts.name}\n\nInstructions for AI coding agents (Claude Code, Cursor, etc.) working\nin this DashWise module. Read this before making changes.\n\n## What this module is\n\nA DashWise ${isCustom ? '**custom Next.js** module (full app runtime, machine-class)' : '**hand-authored simple** module (isolate runtime)'} authored against \\`@dashai/sdk\\`.\nModule slug: \\`${opts.slug}\\`.\n\nDashWise calls apps \"modules\". A module is a Next.js app + a\nmanifest (\\`module.json\\`) declaring the tables it owns, modules it\ndepends on, and actions it exposes. The DashWise backend hosts the\ndata plane + auth; this module ships UI + business logic.\n\n## Spec-first, log-every-change\n\nThis scaffold mirrors the dashwise-backend convention:\n\n- **\\`spec.md\\`** is the source of truth for what this module does —\n tables, fields, API contracts, business rules, error cases. Update\n it BEFORE writing code that changes behavior. If a behavior isn't\n in \\`spec.md\\`, it isn't real yet.\n- **\\`agent-log.md\\`** is an append-only log of every meaningful\n change. Every commit that touches \\`module.json\\`, \\`spec.md\\`, a\n schema mutation, or a public surface MUST add an entry. Format:\n\n \\`\\`\\`\n ## YYYY-MM-DD HH:MM — <author or agent name>\n\n **Change:** one-line summary\n **Files:** comma-separated list of files\n **Reason:** why this change was necessary\n **Spec impact:** none | updated spec.md §<section>\n \\`\\`\\`\n\n Reverse chronological (newest first).\n\n## Schema changes go through the CLI, not by hand\n\n\\`module.json\\` is the manifest. The backend has its own copy that\nthe runtime data plane uses. To keep them in sync, mutate via the\nCLI — \\`dashwise table create\\`, \\`dashwise field add\\`, etc. —\nwhich calls the schema endpoints and rewrites the local\n\\`module.json\\` from the backend's response. Hand-edits to\n\\`module.json\\` won't sync until the next CLI mutation picks them up.\n\nCommon commands:\n\n\\`\\`\\`\ndashwise table create <slug> --field <slug:type[:required]>\ndashwise table delete <slug>\ndashwise field add <table> <slug:type[:required]>\ndashwise field remove <table> <slug>\ndashwise field set-type <table> <slug> <type>\n\\`\\`\\`\n\nAllowed field types: \\`text\\`, \\`long_text\\`, \\`number\\`, \\`boolean\\`,\n\\`date\\`, \\`datetime\\`, \\`single_select\\`, \\`multi_select\\`,\n\\`link_row\\`, \\`file\\`, \\`multi_file\\`, \\`email\\`, \\`url\\`,\n\\`phone\\`, \\`formula\\`, \\`ai\\`.\n\n## Read + write data via the generated SDK\n\nThe CLI's watcher regenerates typed clients into\n\\`node_modules/@dashai/generated/\\` every time \\`module.json\\` changes.\nImport from there:\n\n\\`\\`\\`ts\nimport { db, qb } from '@dashai/generated';\n\n// Simple CRUD\nconst rows = await db.<table>.list();\nawait db.<table>.create({ /* fields */ });\n\n// Query builder (joins, aggregates)\nconst stats = await qb.from('<table>').where({ /* ... */ }).execute();\n\\`\\`\\`\n\nThe data plane authenticates via the per-module runtime token cached\nin \\`~/.config/dashwise/auth.json#modules[${opts.slug}]\\` after\n\\`dashwise init\\` provisions the dev install. \\`dashwise dev\\` injects\nthis token into the Next.js child env automatically.\n\n## Auth in dev mode\n\n\\`dashwise dev\\` registers a dev-mode SSO session with the backend\nand injects \\`DASHWISE_DEV_SESSION_ID\\` so workspace members can sign\ninto the locally-running module via DashWise SSO — no installed\n\\`installation_id\\` required.\n\nIn Server Components: \\`await getServerSession()\\` (from\n\\`@dashai/sdk/auth/server\\`).\nIn Client Components: \\`useSession()\\` (from\n\\`@dashai/sdk/auth/client\\`), wrapped in \\`<AuthProvider>\\` (already\nin \\`app/layout.tsx\\`).\n\n## Local dev lifecycle\n\n\\`\\`\\`\ndashwise login # one-time, opens browser\ndashwise init [slug] # scaffold + provision dev install\ndashwise dev # watcher + next dev, auth env auto-injected\ndashwise module destroy-dev-install # tear down when done (cleans backend + auth.json)\n\\`\\`\\`\n\n## Engineering bar\n\n- **No hacks, shortcuts, or temporary \"quick fixes\" as final\n implementations.** If something needs work, leave it as a stub and\n open an issue / TODO with a clear name — don't bury a workaround.\n- **No silent error swallowing.** Catch what you can handle; surface\n what you can't. Tests should assert error codes, not just status.\n- **No untyped \\`any\\`.** The generated SDK gives you types — use\n them. If you need an escape hatch, add a \\`@ts-expect-error\\` with\n a comment explaining why.\n- **No secrets in code or env files.** Use \\`runtime.secrets[]\\` in\n \\`module.json\\`; values are encrypted at rest and resolved at\n runtime.\n\n## Pointers\n\n- Full walkthrough — \\`@dashai/cli\\`'s [building-modules.md](https://github.com/Intuize/dashwise-cli/blob/main/docs/building-modules.md).\n- Manifest schema — \\`@dashai/sdk/dist/manifest/schema.d.ts\\` (generated from the backend Zod source of truth).\n- Query plane reference — same docs, \\`Query AST v1 wire format\\` section.\n`;\n}\n\nexport function specMd(opts: ScaffoldOptions): string {\n return `# ${opts.name} — Spec\n\n> Living document. Source of truth for what this module does. Update\n> this BEFORE changing code that changes behavior — see CLAUDE.md.\n\n## Notion\n\n(link to ticket / design doc here, or remove this section)\n\n## Overview\n\nOne-sentence description of what this module does, who uses it, and\nwhat tables it owns.\n\n## Database schema\n\n| Table | Columns | Notes |\n|---|---|---|\n| (none yet) | run \\`dashwise table create <slug> --field <slug:type>\\` to add one | |\n\n## API / contract\n\n| Method | Path | Auth | Purpose |\n|---|---|---|---|\n| (none yet) | | | |\n\n## Business rules\n\n- (RBAC, validation, domain logic.)\n\n## Dependencies\n\nModules this module reads from + which tables/actions:\n\n- (none yet — declare in \\`module.json#dependencies[]\\`)\n\n## Exposed tables + actions\n\nTables or server-actions this module makes available to other\nmodules:\n\n- (none yet)\n\n## Error cases\n\n- (what can go wrong + how it's handled)\n\n## Decisions\n\n- (architectural choices + the trade-offs that drove them)\n\n## Open questions\n\n- (anything blocking implementation)\n`;\n}\n\nexport function agentLogMd(opts: ScaffoldOptions): string {\n return `# Agent Log — ${opts.name}\n\nAppend-only log of meaningful changes to this module. Every commit\nthat touches \\`module.json\\`, \\`spec.md\\`, a schema, or a public\nsurface MUST add an entry here in the same change.\n\nFormat (reverse chronological, newest first):\n\n\\`\\`\\`\n## YYYY-MM-DD HH:MM — <author or agent name>\n\n**Change:** one-line summary\n**Files:** comma-separated list of files\n**Reason:** why this change was necessary\n**Spec impact:** none | updated spec.md §<section>\n\n(optional: longer context, verification steps, decisions deferred)\n\\`\\`\\`\n\n---\n\n## ${new Date().toISOString().slice(0, 10)} — dashwise module init\n\n**Change:** Scaffolded module \\`${opts.slug}\\` via \\`dashwise module init\\`.\n**Files:** entire scaffold (\\`module.json\\`, \\`app/\\`, \\`components/\\`, ...).\n**Reason:** initial scaffold.\n**Spec impact:** seeded \\`spec.md\\` template — fill in before first\nschema mutation.\n`;\n}\n\n// ── HH-CC-P1-D2: deploy-target platform config templates ──────────────\n//\n// When `dashwise init` is run with `--deploy-target <platform>`, the\n// scaffold emits a single platform config file. These templates are\n// intentionally minimal — they cover the build/start contract and\n// reasonable defaults for a Next.js custom module; the operator still\n// pushes env vars via `dashwise env export --format <platform> | sh`\n// (P1-D1). Default (no flag) emits no file — the repo stays clean.\n//\n// Templates are deliberately copy-paste-able for the simple module\n// flavor too, since all three platforms can host plain Node services.\n\n/**\n * Railway picks up `railway.json` for build/deploy config. The schema\n * is documented at <https://docs.railway.com/reference/config-as-code>.\n * Nixpacks is Railway's default builder for Node — it autodetects\n * Next.js from `package.json` so we don't need to spell out build/start\n * commands; the `restartPolicyType` line is the one tweak worth making\n * since the default is `ALWAYS`, which masks crash loops.\n *\n * Env vars are NOT set here — Railway reads them from its dashboard or\n * via `railway variables set` (which is what `dashwise env export\n * --format railway` produces).\n */\nexport function railwayJson(_opts: ScaffoldOptions): string {\n return (\n JSON.stringify(\n {\n $schema: 'https://railway.com/railway.schema.json',\n build: {\n builder: 'NIXPACKS',\n },\n deploy: {\n restartPolicyType: 'ON_FAILURE',\n restartPolicyMaxRetries: 3,\n },\n },\n null,\n 2,\n ) + '\\n'\n );\n}\n\n/**\n * Vercel auto-detects Next.js from `package.json` and doesn't strictly\n * need a `vercel.json` — but emitting one declares \"this repo is\n * Vercel-ready\" and gives the author a hook for future overrides\n * (rewrites, headers, regions, etc.) without a second commit later.\n *\n * Env vars are NOT inlined here — Vercel reads them from its dashboard\n * or via `vercel env add` (which is what `dashwise env export --format\n * vercel` produces).\n */\nexport function vercelJson(_opts: ScaffoldOptions): string {\n return (\n JSON.stringify(\n {\n $schema: 'https://openapi.vercel.sh/vercel.json',\n framework: 'nextjs',\n },\n null,\n 2,\n ) + '\\n'\n );\n}\n\n/**\n * Fly's `fly.toml` is more involved — it carries the app name + region\n * + machine sizing. We seed `app = \"<slug>\"` from the module slug; if\n * the slug is already taken globally on fly.io, the author will hit a\n * clear \"name taken\" error from `fly launch` and can edit this file.\n *\n * `primary_region = \"iad\"` is Fly's recommended default for US-East\n * latency; reasonable for the typical DashWise install (api.dashwise.net\n * is also US-East). Authors targeting other regions should edit this.\n *\n * `auto_stop_machines = \"stop\"` + `min_machines_running = 0` keeps cost\n * down for low-traffic modules — Fly will spin up on first request.\n * Authors who want always-on can flip `min_machines_running = 1`.\n *\n * Env vars (DASHWISE_API_KEY etc.) are NOT inlined here — they go in\n * Fly secrets via `fly secrets set` (`dashwise env export --format\n * fly` produces those).\n */\nexport function flyToml(opts: ScaffoldOptions): string {\n return `# fly.toml — generated by \\`dashwise init --deploy-target fly\\`.\n# Run \\`fly launch --no-deploy --copy-config\\` to register this app with\n# Fly; the launcher will read this file and prompt for anything missing.\n#\n# Edit \\`app\\` if the slug is already taken globally on fly.io.\n# Edit \\`primary_region\\` for non-US-East deploys (https://fly.io/docs/reference/regions/).\n\napp = \"${opts.slug}\"\nprimary_region = \"iad\"\n\n[build]\n\n[http_service]\n internal_port = 3000\n force_https = true\n auto_stop_machines = \"stop\"\n auto_start_machines = true\n min_machines_running = 0\n processes = [\"app\"]\n\n[[vm]]\n cpu_kind = \"shared\"\n cpus = 1\n memory_mb = 256\n`;\n}\n","/**\n * HH-CC-LDI-6 — workspace selection helpers used across commands\n * that need to scope an operation to one workspace (`dashwise init`,\n * `dashwise dev`, future `dashwise module status`, etc.).\n *\n * Two resolution paths emerge from the existing CLI:\n *\n * - **Non-interactive** (CI, scripted) — caller passes `--workspace\n * <slug-or-id>`. We validate against the user's accessible\n * workspaces; throw on miss. Auto-pick if the user has exactly\n * one workspace.\n *\n * - **Interactive** (TTY, no `--workspace` flag) — when the user\n * has multiple workspaces and `interactive: true` is passed, we\n * prompt with @clack's `select`. Otherwise we throw with the\n * same \"re-run with --workspace\" error as the non-interactive\n * path.\n *\n * The split exists because `dashwise dev` was designed for\n * scripting (errors loudly with a re-run hint) and `dashwise init`\n * is designed for interactive onboarding (asks the user to pick).\n * One function, two policies via the `interactive` flag.\n */\n\nimport { isCancel, select } from '@clack/prompts';\nimport { apiRequest } from './api-client.js';\n\nexport interface WorkspaceSummary {\n id: number;\n name: string;\n slug: string;\n}\n\n/**\n * Resolve which workspace an operation should target.\n *\n * Resolution order:\n * 1. If `flag` is set → match it against the user's workspaces by\n * slug (preferred) or numeric id; throw if no match.\n * 2. Else if the user has exactly one workspace → auto-pick it.\n * 3. Else if `interactive` and we're in a TTY → prompt with @clack.\n * 4. Else → throw with a \"re-run with --workspace\" hint.\n *\n * `apiToken` is taken explicitly (not from saved config) so callers\n * can pass an in-memory token during the login flow or a per-call\n * override token. Most callers pass `readSavedToken()`.\n */\nexport async function selectWorkspace(opts: {\n apiUrl: string;\n apiToken: string;\n flag?: string;\n interactive: boolean;\n}): Promise<WorkspaceSummary> {\n const workspaces = await apiRequest<WorkspaceSummary[]>(\n 'GET',\n '/api/workspaces',\n undefined,\n { baseUrl: opts.apiUrl, auth: { token: opts.apiToken } },\n );\n if (workspaces.length === 0) {\n throw new Error(\n 'No workspaces found for your account. Create a workspace at the DashWise dashboard first.',\n );\n }\n\n // Flag path — caller provided a slug or id.\n if (opts.flag !== undefined) {\n return matchWorkspaceOrThrow(workspaces, opts.flag);\n }\n\n // Single workspace — auto-pick. Same behavior in both modes.\n if (workspaces.length === 1) {\n return workspaces[0]!;\n }\n\n // Multiple workspaces — interactive prompt OR throw.\n if (opts.interactive && process.stdout.isTTY) {\n const choice = await select({\n message: 'Which workspace should this module live in?',\n options: workspaces.map((w) => ({\n value: w.slug,\n label: w.name,\n hint: `slug=${w.slug}, id=${w.id}`,\n })),\n });\n if (isCancel(choice)) {\n throw new Error('Aborted.');\n }\n const picked = workspaces.find((w) => w.slug === choice);\n if (!picked) {\n // Shouldn't happen — @clack returns one of the options we\n // gave it — but defensive guard so a TS narrowing failure\n // doesn't surface as a stack trace.\n throw new Error(`Internal error: selection \"${String(choice)}\" did not match any workspace.`);\n }\n return picked;\n }\n\n // Non-interactive multi-workspace case — throw with the re-run hint.\n const list = workspaces\n .map((w) => ` - ${w.slug} (id=${w.id}, name=\"${w.name}\")`)\n .join('\\n');\n throw new Error(\n `You have ${workspaces.length} workspaces. Re-run with --workspace <slug-or-id> to pick one:\\n${list}`,\n );\n}\n\n/**\n * Match a `--workspace` flag value against the workspace list.\n *\n * Accepts either a slug (preferred) or a numeric id as a string.\n * Throws if there's no match — surfacing the list helps users\n * notice typos.\n *\n * Exported for tests; not part of the typical command surface.\n */\nexport function matchWorkspaceOrThrow(\n workspaces: WorkspaceSummary[],\n flag: string,\n): WorkspaceSummary {\n const asNumber = Number.parseInt(flag, 10);\n const isNumeric = !Number.isNaN(asNumber) && String(asNumber) === flag;\n const match = isNumeric\n ? workspaces.find((w) => w.id === asNumber)\n : workspaces.find((w) => w.slug === flag);\n if (!match) {\n const list = workspaces.map((w) => ` - ${w.slug} (id=${w.id})`).join('\\n');\n throw new Error(`No workspace matching --workspace=${flag}. Available:\\n${list}`);\n }\n return match;\n}\n","/**\n * `dashwise module init <slug>` — scaffold a new DashWise module\n * project in a fresh directory.\n *\n * As of 2026-05-18, the DEFAULT scaffold is the full Next.js custom-\n * module scaffold — a real Next.js 16 app with `middleware.ts`,\n * `/api/auth/*` routes, an `<AuthProvider>` wrap, and a protected\n * `app/dashboard/page.tsx` example. Authentication + workspace\n * context are wired against the DashWise NestJS backend out of the\n * box (per the v1 plan in\n * `dashwise-devops-docs/plans/module-authoring-platform.md`).\n *\n * Files emitted by the default (`custom` kind):\n *\n * module.json — manifest (schema_version 2)\n * package.json — deps on @dashai/sdk + next + react\n * tsconfig.json\n * next.config.mjs\n * next-env.d.ts\n * .gitignore — ignores node_modules + .next + .dashwise/\n * .env.local.example — DASHWISE_* var template\n * middleware.ts — uses withAuth() from @dashai/sdk/auth/middleware\n * app/layout.tsx — wraps {children} in <AuthProvider>\n * app/page.tsx — public landing\n * app/dashboard/page.tsx — protected route using getServerSession()\n * app/api/auth/sign-in/route.ts — kicks off DashWise SSO redirect\n * app/api/auth/callback/route.ts — exchanges one-time code for cookie\n * app/api/auth/sign-out/route.ts — clears cookie + tells backend\n * README.md — getting-started + auth flow explainer\n *\n * For the legacy minimal scaffold (no Next.js auth wiring — purely\n * hand-authored simple-module runtime), pass `--simple`:\n *\n * dashwise module init my-mod --simple\n *\n * This emits 9 files (no middleware, no /api/auth/*, no dashboard).\n * The `--simple` flag is permanent — some module use cases (public\n * data viewers, demo modules) genuinely don't need auth.\n *\n * `--custom` is kept as a back-compat alias for the default and is\n * silently deprecated. New code should not pass either flag for the\n * full scaffold — just `dashwise module init <slug>`.\n *\n * Refuses to overwrite an existing non-empty directory unless\n * `--force` is passed. Does NOT run `npm install` automatically —\n * surfaces the next-step commands at the end of the run.\n */\n\nimport { existsSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { intro, isCancel, outro, text } from '@clack/prompts';\nimport {\n appApiAuthCallbackTs,\n appApiAuthSignInTs,\n agentLogMd,\n appApiAuthSignOutTs,\n appDashboardPageTsx,\n appLayoutCustomTsx,\n appLayoutTsx,\n appPageCustomTsx,\n appPageTsx,\n appSignInErrorPageTsx,\n claudeMd,\n componentsJson,\n componentsThemeProviderTsx,\n componentsUiButtonTsx,\n componentsUiCardTsx,\n DEPLOY_TARGETS,\n type DeployTarget,\n envLocal,\n envLocalExample,\n flyToml,\n gitignore,\n globalsCss,\n isDeployTarget,\n isValidSlug,\n libRequestOriginTs,\n libUtilsTs,\n manifestJson,\n middlewareTs,\n nextConfig,\n nextEnvDts,\n packageJson,\n packageJsonCustom,\n postcssConfigMjs,\n railwayJson,\n readme,\n specMd,\n type ScaffoldKind,\n tsconfigJson,\n vercelJson,\n} from '../../lib/scaffold.js';\nimport { code, dim, fail, info, success, warn } from '../../lib/output.js';\nimport {\n ApiError,\n createDevInstallation,\n type DevInstallationResponse,\n} from '../../lib/api-client.js';\nimport {\n isLoggedIn,\n readConfig,\n resolveApiUrl,\n upsertModuleEntry,\n} from '../../lib/config.js';\nimport { selectWorkspace } from '../../lib/workspaces.js';\n\nexport interface InitOptions {\n /** Override the target directory (defaults to `./<slug>`). */\n dir?: string;\n /** Overwrite an existing non-empty directory. */\n force?: boolean;\n /** Human-readable module name (default: derive from slug). */\n name?: string;\n /**\n * Use the legacy minimal scaffold (hand-authored simple module —\n * no Next.js auth wiring). Default before 2026-05-18; opt-in now.\n * Mutually exclusive with `custom`; if both are passed, an error\n * is raised before any files are written.\n */\n simple?: boolean;\n /**\n * @deprecated Back-compat alias for the default (full Next.js +\n * auth wiring). New code should call `init` without flags.\n *\n * Kept for back-compat across the v0.x.y series. Will be removed\n * in a future major version. When passed alongside `--simple`,\n * raises an error (mutually exclusive).\n */\n custom?: boolean;\n /** Optional Git repository URL to write into module.json#repository. */\n git?: string;\n /**\n * HH-CC-LDI-6 — skip the provisioning phase (no `POST /api/installations/dev`\n * call, no `auth.json#modules[slug]` write). The local scaffold is\n * created as before; the resulting module has no dev install backing it,\n * so `dashwise dev` / SDK data-plane calls will fail with\n * `UnauthenticatedError` until you run a future\n * `dashwise module provision-dev-install` (LDI-9) or re-run\n * `dashwise init --force`.\n *\n * Commander maps the CLI flag `--no-provision` to `provision: false`;\n * this option is therefore typed as `provision?: boolean` with\n * `undefined` (default) meaning \"provision if logged in\".\n */\n provision?: boolean;\n /**\n * HH-CC-LDI-6 — target workspace slug or numeric id. When omitted +\n * interactive (TTY), the CLI prompts; when omitted + non-interactive\n * (CI), throws if the user has more than one workspace.\n */\n workspace?: string;\n /**\n * HH-CC-LDI-6 — module description forwarded to the backend's\n * `POST /api/installations/dev` request. No effect when\n * `--no-provision`. Defaults to undefined.\n */\n description?: string;\n /**\n * HH-CC-P1-D2 — when set, the scaffold emits the matching platform\n * config file (`railway.json` / `vercel.json` / `fly.toml`) alongside\n * the rest of the scaffold so the project lands as a one-shot\n * deploy-ready repo. Default (undefined) writes no platform file.\n *\n * Validated at the top of `moduleInitCommand` before any files are\n * written; an invalid value fails fast with exit code 1.\n */\n deployTarget?: DeployTarget;\n}\n\nexport async function moduleInitCommand(\n slugArg: string | undefined,\n options: InitOptions,\n): Promise<number> {\n intro('Scaffolding a new DashWise module');\n\n // Resolve slug — prompt if not provided.\n let slug = slugArg;\n if (!slug && process.stdout.isTTY) {\n const answer = await text({\n message: 'Module slug?',\n placeholder: 'tasks',\n validate: (v) =>\n isValidSlug(v) ? undefined : 'Slug must match /^[a-z][a-z0-9_-]*$/',\n });\n if (isCancel(answer)) {\n fail('Aborted.');\n return 130;\n }\n slug = answer;\n }\n if (!slug) {\n fail('Usage: `dashwise module init <slug>`');\n return 1;\n }\n if (!isValidSlug(slug)) {\n fail(`Invalid slug ${code(slug)} — must match /^[a-z][a-z0-9_-]*$/`);\n return 1;\n }\n\n // Derive a default human name from the slug if --name wasn't given.\n const name = options.name ?? humanizeSlug(slug);\n const dir = resolve(options.dir ?? slug);\n\n if (existsSync(dir)) {\n const entries = readdirSync(dir);\n if (entries.length > 0 && !options.force) {\n fail(\n `Directory ${code(dir)} is not empty. Pass ${code('--force')} to scaffold anyway (existing files will be overwritten).`,\n );\n return 1;\n }\n }\n\n // Resolve scaffold kind. As of 2026-05-18 the default is `'custom'`\n // (the full Next.js + auth scaffold); `--simple` opts back to the\n // legacy minimal scaffold; `--custom` is a back-compat no-op alias.\n //\n // Mutually-exclusive flags are caught here before any files are\n // written so the user gets a clean failure instead of \"scaffolded\n // simple but you also passed --custom, which one wins?\".\n if (options.simple && options.custom) {\n fail(\n `Cannot pass both ${code('--simple')} and ${code('--custom')} — they're mutually exclusive. ${code('--simple')} selects the legacy minimal scaffold; the default (no flag) is the full Next.js scaffold (formerly ${code('--custom')}).`,\n );\n return 1;\n }\n\n // HH-CC-P1-D2: validate --deploy-target before any files are written.\n // Commander's `.choices(...)` already enforces the allowlist at the\n // CLI boundary, but the library entry (moduleInitCommand) is reached\n // from tests + future callers without commander, so we re-check here\n // to keep the contract honest.\n if (\n options.deployTarget !== undefined &&\n !isDeployTarget(options.deployTarget)\n ) {\n fail(\n `Invalid --deploy-target ${code(options.deployTarget)} — must be one of ${DEPLOY_TARGETS.map((t) => code(t)).join(', ')}.`,\n );\n return 1;\n }\n\n const kind: ScaffoldKind = options.simple ? 'hand_authored' : 'custom';\n const scaffoldOpts = {\n slug,\n name,\n kind,\n ...(options.git !== undefined ? { repositoryUrl: options.git } : {}),\n };\n\n // HH-CC-FUP-5: pin the scaffold's .env.local to whatever backend\n // the CLI is currently pointed at (from saved login config or\n // $DASHWISE_API_URL or --api-url). Pre-FUP-5 every scaffold got\n // a hard-coded `http://localhost:3000`, which was wrong for anyone\n // running against api.dashwise.net (the common case once login\n // shipped). `resolveApiUrl()` falls back to `http://localhost:3000`\n // if nothing is set, preserving the old behavior for offline\n // scaffolds.\n const scaffoldApiUrl = resolveApiUrl();\n\n // Common files (both flavors).\n const files: Array<[string, string]> = [\n ['module.json', manifestJson(scaffoldOpts)],\n ['tsconfig.json', tsconfigJson()],\n ['next.config.mjs', nextConfig()],\n ['next-env.d.ts', nextEnvDts()],\n ['.gitignore', gitignore()],\n ['.env.local.example', envLocalExample(scaffoldApiUrl)],\n ['.env.local', envLocal(scaffoldApiUrl)],\n ['README.md', readme(scaffoldOpts)],\n // HH-CC-FUP-5: agent-facing docs ship with every scaffold so AI\n // coding agents (Claude Code, Cursor, etc.) have the spec + log\n // discipline + SDK pointers loaded into context from byte one.\n ['CLAUDE.md', claudeMd(scaffoldOpts)],\n ['spec.md', specMd(scaffoldOpts)],\n ['agent-log.md', agentLogMd(scaffoldOpts)],\n ];\n\n // Flavor-specific files.\n if (kind === 'custom') {\n // Custom Next.js app with auth wiring + shadcn/Tailwind 4 stack.\n // The shadcn config + base primitives (button, card) are vendored\n // rather than installed via `npx shadcn add` so the scaffold has\n // no network dependency at first run.\n files.push(\n ['package.json', packageJsonCustom(scaffoldOpts)],\n ['middleware.ts', middlewareTs()],\n ['components.json', componentsJson()],\n ['postcss.config.mjs', postcssConfigMjs()],\n ['app/globals.css', globalsCss()],\n ['lib/utils.ts', libUtilsTs()],\n ['lib/request-origin.ts', libRequestOriginTs()],\n ['components/theme-provider.tsx', componentsThemeProviderTsx()],\n ['components/ui/button.tsx', componentsUiButtonTsx()],\n ['components/ui/card.tsx', componentsUiCardTsx()],\n ['app/layout.tsx', appLayoutCustomTsx(scaffoldOpts)],\n ['app/page.tsx', appPageCustomTsx(scaffoldOpts)],\n ['app/dashboard/page.tsx', appDashboardPageTsx()],\n ['app/sign-in-error/page.tsx', appSignInErrorPageTsx()],\n ['app/api/auth/sign-in/route.ts', appApiAuthSignInTs()],\n ['app/api/auth/callback/route.ts', appApiAuthCallbackTs()],\n ['app/api/auth/sign-out/route.ts', appApiAuthSignOutTs()],\n );\n } else {\n // Hand-authored simple module (isolate runtime).\n files.push(\n ['package.json', packageJson(scaffoldOpts)],\n ['app/layout.tsx', appLayoutTsx(scaffoldOpts)],\n ['app/page.tsx', appPageTsx(scaffoldOpts)],\n );\n }\n\n // HH-CC-P1-D2: optional platform config file. Default (no\n // --deploy-target) writes nothing — the repo stays clean and the\n // author can add a platform file later by hand. When set, the file\n // is written alongside the rest of the scaffold; pairs with\n // `dashwise env export --format <platform>` (P1-D1) for the full\n // deploy loop.\n if (options.deployTarget !== undefined) {\n switch (options.deployTarget) {\n case 'railway':\n files.push(['railway.json', railwayJson(scaffoldOpts)]);\n break;\n case 'vercel':\n files.push(['vercel.json', vercelJson(scaffoldOpts)]);\n break;\n case 'fly':\n files.push(['fly.toml', flyToml(scaffoldOpts)]);\n break;\n }\n }\n\n // We intentionally don't run `npm install` here — the user might\n // want to inspect what we wrote first OR run it in their own shell\n // with their preferred package manager.\n for (const [relPath, content] of files) {\n const absPath = join(dir, relPath);\n const parentDir = join(absPath, '..');\n if (!existsSync(parentDir)) {\n mkdirSync(parentDir, { recursive: true });\n }\n writeFileSync(absPath, content, 'utf-8');\n }\n\n success(\n `Scaffolded ${code(slug)} (${kind === 'custom' ? 'custom Next.js' : 'simple module'}) in ${code(dir)}`,\n );\n\n // HH-CC-LDI-6: provisioning phase. After the scaffold lands, talk\n // to the backend to create a real local-dev install + mint a\n // runtime token. Cache the token in `auth.json#modules[slug]` so\n // `dashwise dev` + `@dashai/sdk`'s `createDevClient({ moduleSlug })`\n // can pick it up. Failures here DON'T roll back the scaffold —\n // the user can re-run `dashwise init --force` later (or, once\n // LDI-9 ships, `dashwise module provision-dev-install`).\n let devInstall: DevInstallationResponse | null = null;\n const wantsProvision = options.provision !== false; // default = true\n if (wantsProvision) {\n // FUP-2: forward the scaffold's module_kind so the backend stamps\n // it on the draft manifest at provision time. `kind` here is the\n // ScaffoldKind we just resolved above (custom | hand_authored).\n devInstall = await tryProvisionDevInstall({\n slug,\n name,\n description: options.description,\n workspaceFlag: options.workspace,\n moduleKind: kind,\n });\n } else {\n info(\n `Skipping provisioning (${code('--no-provision')}). ${dim(\"Run with provisioning later to enable `dashwise dev` data-plane.\")}`,\n );\n }\n\n info(`Next steps:`);\n process.stdout.write(`\n ${dim('1.')} ${code(`cd ${dir}`)}\n ${dim('2.')} ${code('npm install')}\n ${dim('3.')} ${code('dashwise dev')} ${dim('# one command: watcher + next dev, auth auto-injected')}\n\n ${dim(' (or, for the two-terminal flow:')}\n ${dim(' dashwise module generate')} ${dim('# materialize typed wrappers')}\n ${dim(' dashwise module dev')} ${dim('# watch + auto-regenerate')}\n ${dim(' npm run dev:next # next dev on :3000)')}\n${\n devInstall\n ? `\n ${dim(`Dev installation id=${devInstall.installation.id}; runtime token expires ${devInstall.runtime_token_expires_at}.`)}\n`\n : ''\n}`);\n outro('Happy authoring.');\n return 0;\n}\n\n/**\n * HH-CC-LDI-6 — provisioning sub-flow for `dashwise init`.\n *\n * Returns the API response on success, or `null` on a recoverable\n * failure (not logged in, network error, backend down). All failures\n * are surfaced to the user with `warn(...)` so they know what to fix;\n * the parent caller continues with a successful scaffold.\n *\n * Errors that should be unrecoverable (slug conflict, kind mismatch,\n * any 4xx from the backend) are surfaced as warnings too — the user\n * can re-init with a different slug or destroy the conflicting\n * install (LDI-9) without losing their local scaffold.\n *\n * Exported as an internal because the integration is hard to unit-\n * test through `moduleInitCommand` (intro/outro/text prompts +\n * filesystem). Tests that need to exercise this path can call this\n * function directly.\n */\nasync function tryProvisionDevInstall(args: {\n slug: string;\n name: string;\n description?: string;\n workspaceFlag?: string;\n /**\n * FUP-2: scaffold's `module_kind`. Stamped on the backend's draft\n * manifest at create time so the first getManifest() read returns\n * this value instead of falling back to `'ai_builder'`.\n */\n moduleKind?: 'ai_builder' | 'hand_authored' | 'custom';\n}): Promise<DevInstallationResponse | null> {\n if (!isLoggedIn()) {\n warn(\n `Not logged in — skipping dev-install provisioning. Run ${code('dashwise login')} then ${code(`dashwise init ${args.slug} --force`)} to retry.`,\n );\n return null;\n }\n const cfg = readConfig();\n if (!cfg) {\n // Defense — isLoggedIn() returned true so cfg should exist; if\n // it doesn't, the file got removed between the two reads. Treat\n // as not-logged-in.\n warn('CLI config disappeared mid-init. Skipping provisioning.');\n return null;\n }\n\n let workspace;\n try {\n workspace = await selectWorkspace({\n apiUrl: resolveApiUrl(),\n apiToken: cfg.token,\n flag: args.workspaceFlag,\n interactive: true,\n });\n } catch (err) {\n warn(`Workspace selection failed: ${(err as Error).message}`);\n return null;\n }\n info(\n `Provisioning dev install in workspace ${code(workspace.slug)} (id=${workspace.id})…`,\n );\n\n let response: DevInstallationResponse;\n try {\n response = await createDevInstallation(\n {\n slug: args.slug,\n name: args.name,\n ...(args.description !== undefined ? { description: args.description } : {}),\n workspaceId: workspace.id,\n ...(args.moduleKind !== undefined ? { moduleKind: args.moduleKind } : {}),\n },\n { baseUrl: resolveApiUrl(), auth: { token: cfg.token } },\n );\n } catch (err) {\n if (err instanceof ApiError) {\n surfaceProvisionApiError(err, args.slug);\n return null;\n }\n warn(`Provisioning failed: ${(err as Error).message}`);\n return null;\n }\n\n // Persist the runtime token. If THIS step fails (disk full,\n // permissions, etc.) we MUST tell the user the token so they can\n // recover manually — the server-side install was created and\n // there's no point in re-creating it.\n try {\n upsertModuleEntry(args.slug, {\n runtimeToken: response.runtime_token,\n installationId: response.installation.id,\n expiresAt: response.runtime_token_expires_at,\n });\n } catch (err) {\n warn(\n `Provisioned successfully (installation id=${response.installation.id}) but failed to cache the runtime token: ${(err as Error).message}\\n` +\n ` Runtime token (save this manually): ${response.runtime_token}\\n` +\n ` Token expires: ${response.runtime_token_expires_at}`,\n );\n return response;\n }\n\n success(\n `Provisioned dev install id=${response.installation.id}. Runtime token cached in your CLI config.`,\n );\n return response;\n}\n\n/**\n * Map a known `ApiError.code` to a user-friendly recovery hint.\n * Anything unmapped falls back to printing the raw envelope.\n */\nfunction surfaceProvisionApiError(err: ApiError, slug: string): void {\n switch (err.code) {\n case 'UNAUTHENTICATED':\n warn(\n `Auth rejected by backend. Your CLI token may be stale — run ${code('dashwise login')} then ${code(`dashwise init ${slug} --force`)}.`,\n );\n return;\n case 'FORBIDDEN':\n warn(\n `Not authorized to create a module in that workspace. Confirm you're a member at the DashWise dashboard.`,\n );\n return;\n case 'SLUG_ALREADY_EXISTS':\n // The backend's POST /api/installations/dev maps the upstream\n // createDraft 409 ConflictException to this code; the user\n // either picks a different slug or, once LDI-9 ships,\n // destroys the existing install.\n warn(\n `A module with slug ${code(slug)} already exists. Pick a different slug, or destroy the existing dev install (LDI-9 coming soon) and re-run.`,\n );\n return;\n case 'RUNTIME_DATA_API_DISABLED':\n warn(\n `Backend has the local-dev API turned off (BUILDER_SESSION_TOKEN_SECRET unset). Contact the operator.`,\n );\n return;\n default:\n warn(\n `Provisioning failed (${err.code} ${err.status}): ${err.message}`,\n );\n }\n}\n\n/** Convert `tasks-app` → `Tasks app` for a friendly default name. */\nfunction humanizeSlug(slug: string): string {\n const words = slug.replace(/[-_]/g, ' ').split(/\\s+/).filter(Boolean);\n if (words.length === 0) return slug;\n const first = words[0];\n const cap = first.charAt(0).toUpperCase() + first.slice(1);\n return [cap, ...words.slice(1)].join(' ');\n}\n","/**\n * HH-CC-LDI-8 — shared setup for `dashwise table` / `dashwise field`\n * commands.\n *\n * Each schema-mutation command needs the same six things:\n *\n * 1. The project root (containing `module.json`)\n * 2. The current manifest (parsed) + the raw bytes (for rollback)\n * 3. The module's slug\n * 4. The CLI's saved config (apiUrl + bearer + ...)\n * 5. The per-module dev install entry (`auth.json#modules[slug]`)\n * — runtime token + installation id\n * 6. A `RequestOptions` ready to pass to the api-client helpers\n *\n * `loadSchemaCommandContext()` centralises that — commands stay\n * focused on the operation itself instead of repeating the setup\n * boilerplate.\n *\n * Errors at any step throw a user-readable `Error` (no stack trace\n * surface area); commands catch + `fail(err.message)` + return 1.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { join, resolve as resolvePath } from 'node:path';\nimport type { RequestOptions } from './api-client.js';\nimport {\n readConfig,\n readModuleEntry,\n resolveApiUrl,\n type CliConfig,\n type CliConfigModuleEntry,\n} from './config.js';\nimport {\n readManifestOrThrow,\n type ManifestShape,\n} from './manifest-io.js';\n\nexport interface SchemaCommandContext {\n projectRoot: string;\n manifestPath: string;\n manifest: ManifestShape;\n /** Verbatim file bytes — preserved so commands that want to do\n * edit-first-with-rollback have something to restore from. */\n manifestRawBytes: string;\n slug: string;\n cfg: CliConfig;\n entry: CliConfigModuleEntry;\n /**\n * Pre-built RequestOptions targeting the per-module runtime token.\n * Pass directly to api-client helpers (createTable, addField, etc.).\n * Uses the bound install's runtime token, NOT the CLI bearer —\n * the REST endpoints require a kind=local runtime token.\n */\n requestOptions: RequestOptions;\n}\n\n/**\n * Load + validate the four prerequisites for any schema-mutation\n * command. Throws on any missing piece with a clear \"how to fix\"\n * error message.\n */\nexport function loadSchemaCommandContext(opts: {\n dir?: string;\n}): SchemaCommandContext {\n const projectRoot = resolvePath(opts.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n\n // Use readManifestOrThrow for a typed \"doesn't exist / unreadable\"\n // failure mode; capture the raw bytes for potential rollback paths.\n const manifest = readManifestOrThrow<ManifestShape>(projectRoot);\n const manifestRawBytes = readFileSync(manifestPath, 'utf-8');\n\n const slug = manifest.module?.slug;\n if (!slug) {\n throw new Error(\n `module.json at ${manifestPath} has no module.slug — the manifest is malformed.`,\n );\n }\n\n const cfg = readConfig();\n if (!cfg) {\n throw new Error('Not logged in. Run `dashwise login` first.');\n }\n\n const entry = readModuleEntry(slug);\n if (!entry) {\n throw new Error(\n `No dev install cached for module \"${slug}\". Run \\`dashwise init ${slug} --force\\` to provision one.`,\n );\n }\n\n return {\n projectRoot,\n manifestPath,\n manifest,\n manifestRawBytes,\n slug,\n cfg,\n entry,\n requestOptions: {\n baseUrl: resolveApiUrl(),\n auth: { token: entry.runtimeToken },\n },\n };\n}\n","/**\n * `dashwise module destroy-dev-install [--module <slug>]`\n *\n * HH-CC-LDI-9 — tear down the local-dev install for a module. Reads\n * the current module's slug from `module.json` by default; pass\n * `--module <slug>` to target a different one (useful when the\n * project directory's manifest is gone but the auth.json entry\n * still lingers).\n *\n * Sequence:\n * 1. Resolve slug + install id from auth.json#modules[slug].\n * 2. DELETE /api/installations/dev/:id (audited as\n * DESTROY_DEV_INSTALLATION on the backend).\n * 3. Remove the auth.json#modules[slug] entry.\n *\n * If the backend returns 404 INSTALLATION_NOT_FOUND, we still clean\n * up the local auth.json entry — the install is gone on the server\n * already, no point in leaving a dangling token client-side.\n */\n\nimport { isCancel, confirm } from '@clack/prompts';\nimport { resolve as resolvePath } from 'node:path';\nimport {\n ApiError,\n destroyDevInstallation,\n} from '../../lib/api-client.js';\nimport {\n readConfig,\n readModuleEntry,\n removeModuleEntry,\n resolveApiUrl,\n} from '../../lib/config.js';\nimport { readManifest } from '../../lib/manifest-io.js';\nimport { code, fail, info, success, warn } from '../../lib/output.js';\n\nexport interface DestroyDevInstallOptions {\n dir?: string;\n /** Override the module slug (default: read from local module.json). */\n module?: string;\n /** Skip the confirmation prompt — for CI. */\n yes?: boolean;\n}\n\nexport async function destroyDevInstallCommand(\n options: DestroyDevInstallOptions,\n): Promise<number> {\n // ── 1. Resolve slug ────────────────────────────────────────────────\n let slug = options.module;\n if (!slug) {\n const projectRoot = resolvePath(options.dir ?? process.cwd());\n const manifest = (() => {\n try {\n return readManifest(projectRoot);\n } catch {\n return null;\n }\n })();\n slug = manifest?.module?.slug;\n if (!slug) {\n fail(\n `No module slug — pass ${code('--module <slug>')} or run from a directory with a valid module.json.`,\n );\n return 1;\n }\n }\n\n // ── 2. Find the cached install id ──────────────────────────────────\n const cfg = readConfig();\n if (!cfg) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n const entry = readModuleEntry(slug);\n if (!entry) {\n warn(\n `No cached dev install for ${code(slug)} in auth.json. Nothing to do.`,\n );\n return 0;\n }\n\n // ── 3. Confirm (skipped with --yes) ────────────────────────────────\n if (!options.yes && process.stdout.isTTY) {\n const choice = await confirm({\n message: `Destroy dev install ${code(`${slug} (id=${entry.installationId})`)}? Tables and rows will be soft-deleted (recoverable for 30 days via dashboard trash).`,\n });\n if (isCancel(choice) || !choice) {\n info('Aborted.');\n return 130;\n }\n }\n\n // ── 4. DELETE on backend ───────────────────────────────────────────\n let backendCleaned = false;\n try {\n const response = await destroyDevInstallation(entry.installationId, {\n baseUrl: resolveApiUrl(),\n auth: { token: cfg.token },\n });\n backendCleaned = true;\n success(\n `Destroyed dev install ${code(`${slug} (id=${response.installation_id})`)}${\n response.module_also_dropped\n ? ' — module also dropped (no other installs, unpublished).'\n : ' (module kept — other installs reference it or it has a published version).'\n }`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.code === 'INSTALLATION_NOT_FOUND') {\n // Already gone server-side; clean up the local entry anyway.\n warn(\n `Install ${entry.installationId} not found on the backend — already destroyed elsewhere. Cleaning up local cache.`,\n );\n backendCleaned = true;\n } else {\n return surfaceDestroyError(err);\n }\n }\n\n // ── 5. Clean up auth.json ──────────────────────────────────────────\n if (backendCleaned) {\n try {\n removeModuleEntry(slug);\n info(`Removed ${code(slug)} entry from auth.json.`);\n } catch (err) {\n warn(\n `Backend cleanup succeeded but failed to update auth.json: ${(err as Error).message}. Edit ${code('~/.config/dashwise/auth.json')} manually to remove the ${code(`modules[\"${slug}\"]`)} entry.`,\n );\n }\n }\n\n return 0;\n}\n\nfunction surfaceDestroyError(err: unknown): number {\n if (err instanceof ApiError) {\n switch (err.code) {\n case 'INSTALLATION_KIND_NOT_LOCAL':\n fail(\n `Refusing to destroy: the install isn't kind=local (it may have been promoted to production). Use the dashboard's uninstall flow instead.`,\n );\n break;\n case 'NOT_WORKSPACE_MEMBER':\n fail(\n `You're not a member of the install's workspace. Contact a workspace admin.`,\n );\n break;\n case 'UNAUTHENTICATED':\n fail(\n `Auth rejected by backend — your CLI bearer may be stale. Re-run ${code('dashwise login')} and try again.`,\n );\n break;\n default:\n fail(`Backend rejected: ${err.code} ${err.status} — ${err.message}`);\n }\n return 1;\n }\n fail(`Unexpected error: ${(err as Error).message}`);\n return 1;\n}\n","/**\n * `dashwise module reset-dev-install`\n *\n * HH-CC-LDI-9 — destroy + re-create the local-dev install for the\n * current module. Useful when:\n * - Test data has accumulated and you want a clean slate\n * - The cached runtime token has been compromised + you want a\n * fresh one without the LDI-9.x rotate-token endpoint\n * - Schema is in a wedged state and you want to start over from\n * the local module.json\n *\n * Implementation: composes `destroyDevInstallCommand` +\n * `moduleInitCommand({ provision: true, force: true })`. Both phases\n * are interactive in a TTY (with `--yes` to skip prompts).\n *\n * If destroy fails the reset bails — we don't want to provision a\n * second install while a stale one still exists (the backend would\n * 409 SLUG_ALREADY_EXISTS anyway).\n */\n\nimport { resolve as resolvePath } from 'node:path';\nimport { destroyDevInstallCommand } from './destroy-dev-install.js';\nimport { moduleInitCommand } from './init.js';\nimport { readManifest } from '../../lib/manifest-io.js';\nimport { code, fail, info } from '../../lib/output.js';\n\nexport interface ResetDevInstallOptions {\n dir?: string;\n /** Override the module slug (default: from local module.json). */\n module?: string;\n /** Target workspace for re-provisioning (passed to init). */\n workspace?: string;\n /** Skip confirmation prompts in both destroy + init phases. */\n yes?: boolean;\n}\n\nexport async function resetDevInstallCommand(\n options: ResetDevInstallOptions,\n): Promise<number> {\n // We need both a slug AND the module's display name (init re-uses\n // these on re-create). Read once from module.json so destroy + init\n // both agree on the target.\n const projectRoot = resolvePath(options.dir ?? process.cwd());\n const manifest = (() => {\n try {\n return readManifest(projectRoot);\n } catch {\n return null;\n }\n })();\n\n const slug = options.module ?? manifest?.module?.slug;\n if (!slug) {\n fail(\n `No module slug — pass ${code('--module <slug>')} or run from a directory with a valid module.json.`,\n );\n return 1;\n }\n const name = manifest?.module?.name ?? slug;\n\n // ── Phase 1: destroy ──────────────────────────────────────────────\n info(`Resetting dev install for ${code(slug)} — phase 1/2: destroy…`);\n const destroyExit = await destroyDevInstallCommand({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n module: slug,\n ...(options.yes !== undefined ? { yes: options.yes } : {}),\n });\n if (destroyExit !== 0) {\n fail(\n `Destroy phase failed (exit ${destroyExit}); aborting reset. Fix the underlying error and re-run.`,\n );\n return destroyExit;\n }\n\n // ── Phase 2: re-init / provision ──────────────────────────────────\n info(`Reset phase 2/2: re-provisioning…`);\n return moduleInitCommand(slug, {\n name,\n ...(options.dir !== undefined ? { dir: options.dir } : { dir: projectRoot }),\n // `--force` so init doesn't refuse to overwrite the existing\n // module.json (we're keeping the local scaffold; only the\n // backend install is being recreated).\n force: true,\n // Keep the current scaffold layout — don't try to detect or\n // change `simple` vs `custom`. The user can re-init manually\n // with `dashwise init` if they want to swap scaffolds.\n provision: true,\n ...(options.workspace !== undefined ? { workspace: options.workspace } : {}),\n });\n}\n","/**\n * HH-CC-LDI-8 — parse `--field <slug>:<type>[:flags]` syntax for\n * `dashwise table create` / `dashwise field add`.\n *\n * Grammar (regular):\n *\n * spec := <slug> ':' <type> [ ':' <flag> (',' <flag>)* ]\n * slug := snake_case, ^[a-z][a-z0-9_]*[a-z0-9]$\n * type := one of FIELD_TYPES (defined here to avoid a backend\n * import; kept in sync with manifest-schema.ts on the\n * server side)\n * flag := 'required' | 'unique' (v1 — extend as needed)\n *\n * Examples:\n * \"title:text\" → { slug:'title', type:'text' }\n * \"title:text:required\" → { slug:'title', type:'text', required:true }\n * \"tags:multi_select:required\" → { slug:'tags', type:'multi_select', required:true }\n *\n * For field types that need extra config (`single_select` / `multi_select`\n * with `options`, `link_row` with `target`, `formula` with `formula`,\n * `ai` with `prompt`), use `--field-json '{...}'` instead — the JSON\n * shape mirrors `FieldDefBody` from `api-client.ts`. This split keeps\n * the simple syntax actually simple while still supporting the rich\n * cases.\n *\n * Pure function — easy to unit-test. No I/O.\n */\n\nimport type { FieldDefBody } from './api-client.js';\n\n/**\n * Closed set of field types the backend accepts. Mirrors\n * `dashwise-backend/src/modules/modules/manifest/manifest-schema.ts:FIELD_TYPES`.\n * Kept here to avoid a backend dep; backend's manifest validator is\n * still the source of truth at apply-time.\n */\nexport const FIELD_TYPES = [\n 'text',\n 'long_text',\n 'number',\n 'boolean',\n 'date',\n 'datetime',\n 'single_select',\n 'multi_select',\n 'link_row',\n 'file',\n 'multi_file',\n 'email',\n 'url',\n 'phone',\n 'formula',\n 'ai',\n] as const;\nexport type FieldType = (typeof FIELD_TYPES)[number];\n\nconst SLUG_REGEX = /^[a-z][a-z0-9_]*[a-z0-9]$/;\nconst KNOWN_FLAGS = new Set(['required', 'unique']);\n\n/**\n * Parse a single `--field <slug>:<type>[:flags]` spec into a FieldDef\n * body. Throws with a clear error message if any part is malformed —\n * callers surface to the user via `fail()`.\n */\nexport function parseFieldSpec(spec: string): FieldDefBody {\n const parts = spec.split(':');\n if (parts.length < 2) {\n throw new FieldSpecError(\n `Field spec ${quote(spec)} is malformed — expected ${quote('<slug>:<type>[:flags]')}.`,\n );\n }\n const [slug, type, ...flagParts] = parts;\n\n if (!SLUG_REGEX.test(slug!)) {\n throw new FieldSpecError(\n `Field slug ${quote(slug!)} must match ${quote(SLUG_REGEX.source)} (snake_case, 2+ chars).`,\n );\n }\n\n if (!(FIELD_TYPES as readonly string[]).includes(type!)) {\n throw new FieldSpecError(\n `Field type ${quote(type!)} is not a known type. Allowed: ${FIELD_TYPES.join(', ')}.`,\n );\n }\n\n const result: FieldDefBody = { slug: slug!, type: type! };\n\n if (flagParts.length > 0) {\n // Flags are comma-separated within a single colon segment OR\n // each flag is its own colon segment. We accept both for\n // ergonomics: `name:text:required,unique` and\n // `name:text:required:unique` both parse the same.\n const flags = flagParts\n .flatMap((segment) => segment.split(','))\n .map((f) => f.trim())\n .filter((f) => f.length > 0);\n\n for (const flag of flags) {\n if (!KNOWN_FLAGS.has(flag)) {\n throw new FieldSpecError(\n `Unknown flag ${quote(flag)} in field spec ${quote(spec)}. Known flags: ${[...KNOWN_FLAGS].join(', ')}. For options/target/default, use ${quote('--field-json')} instead.`,\n );\n }\n if (flag === 'required') result.required = true;\n // `unique` is a table-level index concern, not a field-level\n // attribute on FieldDef — we accept the flag for forward\n // compat with `dashwise table create --field foo:text:unique`\n // but turning it into a table-level unique index belongs in\n // the calling command. Silently dropped here; the command\n // handler reads it from the raw spec if it cares.\n }\n }\n\n // Types that need options / target / formula / prompt can't be\n // expressed in the simple syntax — direct the user to --field-json.\n // We validate post-flag-parse so the type check fires before the\n // options check (better error ordering for the user).\n if (\n (type === 'single_select' || type === 'multi_select') &&\n result.options === undefined\n ) {\n throw new FieldSpecError(\n `Type ${quote(type)} requires an ${quote('options')} list. Use ${quote('--field-json')} for this field — e.g. ${quote(`'{\"slug\":\"${slug}\",\"type\":\"${type}\",\"options\":[\"a\",\"b\"]}'`)}.`,\n );\n }\n if (type === 'link_row' && result.target === undefined) {\n throw new FieldSpecError(\n `Type ${quote('link_row')} requires a ${quote('target')}. Use ${quote('--field-json')}.`,\n );\n }\n if (type === 'formula' || type === 'ai') {\n throw new FieldSpecError(\n `Type ${quote(type)} requires extra config (${quote('formula')} or ${quote('prompt')}). Use ${quote('--field-json')}.`,\n );\n }\n\n return result;\n}\n\n/**\n * Parse a `--field-json '<json>'` value into a FieldDef body. Just a\n * thin wrapper around `JSON.parse` with shape validation against\n * `FieldDefBody`. Pure function.\n */\nexport function parseFieldJson(json: string): FieldDefBody {\n let parsed: unknown;\n try {\n parsed = JSON.parse(json);\n } catch (err) {\n throw new FieldSpecError(\n `--field-json value is not valid JSON: ${(err as Error).message}`,\n );\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new FieldSpecError('--field-json must be a JSON object.');\n }\n const o = parsed as Record<string, unknown>;\n if (typeof o.slug !== 'string' || !SLUG_REGEX.test(o.slug)) {\n throw new FieldSpecError(\n `--field-json missing or invalid ${quote('slug')}. Must match ${quote(SLUG_REGEX.source)}.`,\n );\n }\n if (typeof o.type !== 'string' || !(FIELD_TYPES as readonly string[]).includes(o.type)) {\n throw new FieldSpecError(\n `--field-json missing or invalid ${quote('type')}. Allowed: ${FIELD_TYPES.join(', ')}.`,\n );\n }\n // The rest of the fields are best-effort — the backend's manifest\n // validator is the final authority on what shapes are accepted.\n // Cast through unknown because Record<string, unknown> doesn't\n // structurally narrow to FieldDefBody (we've validated slug + type\n // above, which is enough for the runtime path).\n return o as unknown as FieldDefBody;\n}\n\nexport class FieldSpecError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'FieldSpecError';\n }\n}\n\nfunction quote(s: string): string {\n return `\\`${s}\\``;\n}\n","/**\n * `dashwise table create <slug> --field <spec>... [--field-json <json>...]`\n *\n * HH-CC-LDI-8 — create a new table in the current module's manifest +\n * materialize it as a physical Postgres table in the dev installation.\n *\n * Flow (REST-first / write-back-from-GET):\n * 1. Load context (manifest slug, runtime token, install id).\n * 2. Parse `--field` + `--field-json` flags into a FieldDef array.\n * 3. POST /api/installations/:id/schema/tables (LDI-4 endpoint).\n * 4. GET /api/installations/:id/schema to fetch the new manifest.\n * 5. Write the response to local module.json.\n *\n * No local-mutation logic — the backend's `SchemaProposeService`\n * is the source of truth for the manifest shape after the operation.\n * If the POST succeeds but the GET fails, local module.json is left\n * stale; `dashwise dev` reconciles on next startup.\n */\n\nimport { writeManifest, type ManifestShape } from '../../lib/manifest-io.js';\nimport {\n ApiError,\n createTable,\n getInstallationSchema,\n type FieldDefBody,\n} from '../../lib/api-client.js';\nimport { loadSchemaCommandContext } from '../../lib/schema-command-context.js';\nimport {\n FieldSpecError,\n parseFieldJson,\n parseFieldSpec,\n} from '../../lib/field-spec.js';\nimport { code, fail, info, success, warn } from '../../lib/output.js';\n\nexport interface TableCreateOptions {\n dir?: string;\n field?: string[];\n fieldJson?: string[];\n}\n\nexport async function tableCreateCommand(\n slug: string | undefined,\n options: TableCreateOptions,\n): Promise<number> {\n if (!slug) {\n fail('Usage: `dashwise table create <slug> --field <slug>:<type>[:required] [...]`');\n return 1;\n }\n\n // ── 1. Build the FieldDef array from --field + --field-json flags ──\n const fields: FieldDefBody[] = [];\n try {\n for (const spec of options.field ?? []) {\n fields.push(parseFieldSpec(spec));\n }\n for (const json of options.fieldJson ?? []) {\n fields.push(parseFieldJson(json));\n }\n } catch (err) {\n if (err instanceof FieldSpecError) {\n fail(err.message);\n return 1;\n }\n throw err;\n }\n if (fields.length === 0) {\n fail(\n `At least one field is required. Use ${code('--field <slug>:<type>')} (repeatable) or ${code(\"--field-json '{...}'\")} for fields with options/target/default.`,\n );\n return 1;\n }\n\n // Detect duplicate slugs within the input (the backend also rejects\n // but a local check gives a clearer error than the round-trip).\n const seen = new Set<string>();\n for (const f of fields) {\n if (seen.has(f.slug)) {\n fail(`Duplicate field slug ${code(f.slug)} in --field flags.`);\n return 1;\n }\n seen.add(f.slug);\n }\n\n // ── 2. Load command context ────────────────────────────────────────\n let ctx: ReturnType<typeof loadSchemaCommandContext>;\n try {\n ctx = loadSchemaCommandContext({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n });\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n // ── 3. POST /api/installations/:id/schema/tables ───────────────────\n info(`Creating table ${code(slug)} in installation ${ctx.entry.installationId}…`);\n try {\n const result = await createTable(\n ctx.entry.installationId,\n { slug, fields },\n ctx.requestOptions,\n );\n success(\n `Created table ${code(slug)} (physical_table_id=${result.physical_table_id}, manifest_version=${result.manifest_version})`,\n );\n } catch (err) {\n return surfaceFailure(err);\n }\n\n // ── 4. GET /schema + write back to local module.json ───────────────\n return syncLocalManifest(ctx);\n}\n\n/**\n * After a successful schema mutation, fetch the new server-side\n * manifest and write it to local `module.json`. Shared by every\n * schema-mutation command.\n *\n * Failure here is non-fatal — the mutation already succeeded\n * server-side, the local file just gets stale. We surface a warning\n * + tell the user to retry via `dashwise module reconcile` (future\n * LDI-9 sub-command) OR they can re-run their next `dashwise dev`\n * which will pick up the latest manifest automatically.\n */\nexport async function syncLocalManifest(\n ctx: ReturnType<typeof loadSchemaCommandContext>,\n): Promise<number> {\n try {\n const { manifest } = await getInstallationSchema(\n ctx.entry.installationId,\n ctx.requestOptions,\n );\n writeManifest(manifest as ManifestShape, ctx.projectRoot);\n return 0;\n } catch (err) {\n if (err instanceof ApiError) {\n warn(\n `Schema sync to local module.json failed (${err.code} ${err.status}): ${err.message}. The mutation succeeded server-side; re-run your next command to retry the local sync.`,\n );\n } else {\n warn(\n `Schema sync to local module.json failed: ${(err as Error).message}. The mutation succeeded server-side.`,\n );\n }\n // Exit 0 — the operation succeeded, only the local sync didn't.\n return 0;\n }\n}\n\n/**\n * Translate an ApiError from a schema-mutation REST call into a\n * user-facing failure message. Reused by every table/field command\n * since they all surface the same set of codes from\n * `SchemaProposeService → InstallationSchemaController.mapServiceError`.\n */\nexport function surfaceFailure(err: unknown): number {\n if (err instanceof ApiError) {\n switch (err.code) {\n case 'TABLE_SLUG_EXISTS':\n fail(`A table with this slug already exists in the manifest.`);\n break;\n case 'FIELD_SLUG_EXISTS':\n fail(`A field with this slug already exists on the table.`);\n break;\n case 'TABLE_NOT_FOUND':\n fail(`Table not found in the manifest.`);\n break;\n case 'FIELD_NOT_FOUND':\n fail(`Field not found on the table.`);\n break;\n case 'UNAUTHENTICATED':\n fail(\n `Runtime token rejected by backend. The cached token may be expired — re-run \\`dashwise init <slug> --force\\` to mint a fresh one.`,\n );\n break;\n case 'SANDBOX_TOKEN_NOT_ACCEPTED':\n fail(\n `Schema-mutation endpoints require a local-dev runtime token (kind=local). The cached token is the wrong kind — re-run \\`dashwise init <slug> --force\\`.`,\n );\n break;\n case 'INSTALL_MISMATCH':\n fail(\n `Runtime token is bound to a different installation than the URL. The cached install id may be stale — re-run \\`dashwise init <slug> --force\\`.`,\n );\n break;\n default:\n fail(`Backend rejected: ${err.code} ${err.status} — ${err.message}`);\n }\n return 1;\n }\n fail(`Unexpected error: ${(err as Error).message}`);\n return 1;\n}\n","/**\n * `dashwise table delete <slug>`\n *\n * HH-CC-LDI-8 — drop a table from the current module. Calls LDI-4's\n * `DELETE /api/installations/:id/schema/tables/:tableSlug`, which\n * (via the backend's `applyManifestDelta`) soft-deletes the physical\n * table — recoverable for 30 days through the dashboard's trash.\n *\n * Same REST-first / write-back-from-GET pattern as `table create`.\n */\n\nimport { dropTable } from '../../lib/api-client.js';\nimport { loadSchemaCommandContext } from '../../lib/schema-command-context.js';\nimport { code, fail, info, success } from '../../lib/output.js';\nimport { surfaceFailure, syncLocalManifest } from './create.js';\n\nexport interface TableDeleteOptions {\n dir?: string;\n}\n\nexport async function tableDeleteCommand(\n slug: string | undefined,\n options: TableDeleteOptions,\n): Promise<number> {\n if (!slug) {\n fail('Usage: `dashwise table delete <slug>`');\n return 1;\n }\n\n let ctx: ReturnType<typeof loadSchemaCommandContext>;\n try {\n ctx = loadSchemaCommandContext({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n });\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n info(`Dropping table ${code(slug)} from installation ${ctx.entry.installationId}…`);\n try {\n const result = await dropTable(\n ctx.entry.installationId,\n slug,\n ctx.requestOptions,\n );\n success(\n `Dropped table ${code(slug)} (manifest_version=${result.manifest_version}). Physical table soft-deleted; recoverable for 30 days via the dashboard's trash.`,\n );\n } catch (err) {\n return surfaceFailure(err);\n }\n\n return syncLocalManifest(ctx);\n}\n","/**\n * `dashwise field add <table-slug> <field-spec>`\n *\n * HH-CC-LDI-8 — add a new field to an existing table. The field spec\n * uses the same `<slug>:<type>[:flags]` syntax as `dashwise table\n * create --field`, OR the `--field-json '{...}'` escape hatch for\n * options/target/default.\n *\n * Examples:\n * dashwise field add tasks title:text:required\n * dashwise field add tasks done:boolean\n * dashwise field add tasks priority --field-json '{\"slug\":\"priority\",\"type\":\"single_select\",\"options\":[\"low\",\"medium\",\"high\"]}'\n *\n * REST-first / write-back-from-GET pattern (same as `table create`).\n */\n\nimport { addField } from '../../lib/api-client.js';\nimport { loadSchemaCommandContext } from '../../lib/schema-command-context.js';\nimport {\n FieldSpecError,\n parseFieldJson,\n parseFieldSpec,\n} from '../../lib/field-spec.js';\nimport { code, fail, info, success } from '../../lib/output.js';\nimport { surfaceFailure, syncLocalManifest } from '../table/create.js';\n\nexport interface FieldAddOptions {\n dir?: string;\n fieldJson?: string;\n}\n\nexport async function fieldAddCommand(\n tableSlug: string | undefined,\n fieldSpec: string | undefined,\n options: FieldAddOptions,\n): Promise<number> {\n if (!tableSlug) {\n fail(\n 'Usage: `dashwise field add <table-slug> <field-slug>:<type>[:required]` or `dashwise field add <table-slug> --field-json \\'{...}\\'`',\n );\n return 1;\n }\n\n // The field can come from either the positional `<spec>` arg OR\n // `--field-json`. Exactly one must be supplied; both would be\n // ambiguous (which wins?).\n const hasPositional = fieldSpec !== undefined;\n const hasJson = options.fieldJson !== undefined;\n if (!hasPositional && !hasJson) {\n fail(\n `Pass either a field spec (e.g. ${code('title:text:required')}) or ${code('--field-json')} with the field's JSON definition.`,\n );\n return 1;\n }\n if (hasPositional && hasJson) {\n fail(\n `Pass only ONE of the field spec or ${code('--field-json')} — they're mutually exclusive.`,\n );\n return 1;\n }\n\n let field;\n try {\n field = hasJson\n ? parseFieldJson(options.fieldJson!)\n : parseFieldSpec(fieldSpec!);\n } catch (err) {\n if (err instanceof FieldSpecError) {\n fail(err.message);\n return 1;\n }\n throw err;\n }\n\n let ctx: ReturnType<typeof loadSchemaCommandContext>;\n try {\n ctx = loadSchemaCommandContext({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n });\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n info(\n `Adding field ${code(`${tableSlug}.${field.slug}`)} (${field.type}) to installation ${ctx.entry.installationId}…`,\n );\n try {\n const result = await addField(\n ctx.entry.installationId,\n { table_slug: tableSlug, field },\n ctx.requestOptions,\n );\n success(\n `Added field ${code(`${tableSlug}.${field.slug}`)} (manifest_version=${result.manifest_version})`,\n );\n } catch (err) {\n return surfaceFailure(err);\n }\n\n return syncLocalManifest(ctx);\n}\n","/**\n * `dashwise field remove <table-slug> <field-slug>`\n *\n * HH-CC-LDI-8 — remove a field from a table. The backend's\n * `proposeField(operation='remove')` includes the M2-C-FIX\n * cascading-index-cleanup: any index referencing the removed field\n * is trimmed, and if the index becomes empty it's dropped entirely.\n *\n * REST-first / write-back-from-GET pattern.\n */\n\nimport { removeField } from '../../lib/api-client.js';\nimport { loadSchemaCommandContext } from '../../lib/schema-command-context.js';\nimport { code, fail, info, success } from '../../lib/output.js';\nimport { surfaceFailure, syncLocalManifest } from '../table/create.js';\n\nexport interface FieldRemoveOptions {\n dir?: string;\n}\n\nexport async function fieldRemoveCommand(\n tableSlug: string | undefined,\n fieldSlug: string | undefined,\n options: FieldRemoveOptions,\n): Promise<number> {\n if (!tableSlug || !fieldSlug) {\n fail('Usage: `dashwise field remove <table-slug> <field-slug>`');\n return 1;\n }\n\n let ctx: ReturnType<typeof loadSchemaCommandContext>;\n try {\n ctx = loadSchemaCommandContext({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n });\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n info(\n `Removing field ${code(`${tableSlug}.${fieldSlug}`)} from installation ${ctx.entry.installationId}…`,\n );\n try {\n const result = await removeField(\n ctx.entry.installationId,\n tableSlug,\n fieldSlug,\n ctx.requestOptions,\n );\n success(\n `Removed field ${code(`${tableSlug}.${fieldSlug}`)} (manifest_version=${result.manifest_version})`,\n );\n } catch (err) {\n return surfaceFailure(err);\n }\n\n return syncLocalManifest(ctx);\n}\n","/**\n * `dashwise field set-type <table-slug> <field-slug> <new-type>`\n *\n * HH-CC-LDI-8 — change an existing field's type. Maps to LDI-4's\n * `PATCH /api/installations/:id/schema/fields/:tableSlug/:fieldSlug`\n * with the new type passed in the body.\n *\n * Lossy type changes (text → number with non-numeric data; multi_select\n * → single_select with multi-value rows) are deferred to v1.1 per\n * `local-dev-installs-v1.md` §8.2 — the backend's manifest validator\n * rejects the unsafe cases today; v1.1 adds a structured\n * `RETYPE_UNSAFE` precheck.\n *\n * REST-first / write-back-from-GET pattern.\n */\n\nimport { updateField } from '../../lib/api-client.js';\nimport { loadSchemaCommandContext } from '../../lib/schema-command-context.js';\nimport { FIELD_TYPES } from '../../lib/field-spec.js';\nimport { code, fail, info, success } from '../../lib/output.js';\nimport { surfaceFailure, syncLocalManifest } from '../table/create.js';\n\nexport interface FieldSetTypeOptions {\n dir?: string;\n}\n\nexport async function fieldSetTypeCommand(\n tableSlug: string | undefined,\n fieldSlug: string | undefined,\n newType: string | undefined,\n options: FieldSetTypeOptions,\n): Promise<number> {\n if (!tableSlug || !fieldSlug || !newType) {\n fail(\n 'Usage: `dashwise field set-type <table-slug> <field-slug> <new-type>`',\n );\n return 1;\n }\n if (!(FIELD_TYPES as readonly string[]).includes(newType)) {\n fail(\n `Type ${code(newType)} is not a known type. Allowed: ${FIELD_TYPES.join(', ')}.`,\n );\n return 1;\n }\n\n let ctx: ReturnType<typeof loadSchemaCommandContext>;\n try {\n ctx = loadSchemaCommandContext({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n });\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n info(\n `Setting type of ${code(`${tableSlug}.${fieldSlug}`)} → ${code(newType)} on installation ${ctx.entry.installationId}…`,\n );\n try {\n const result = await updateField(\n ctx.entry.installationId,\n tableSlug,\n fieldSlug,\n { type: newType },\n ctx.requestOptions,\n );\n success(\n `Updated ${code(`${tableSlug}.${fieldSlug}`)} → ${code(newType)} (manifest_version=${result.manifest_version})`,\n );\n } catch (err) {\n return surfaceFailure(err);\n }\n\n return syncLocalManifest(ctx);\n}\n","/**\n * `dashwise dev` — the one-command local dev loop.\n *\n * What it does:\n * 1. Verifies the developer has run `dashwise login` (i.e. the auth.json\n * config file exists). Bails with a clear pointer otherwise.\n * 2. Resolves `DASHWISE_API_URL`, `DASHWISE_API_TOKEN`,\n * `DASHWISE_INSTALLATION_ID` from (a) explicit flags, (b) existing\n * env vars, (c) the saved CLI config — and injects them into BOTH\n * child processes' env so the SDK can authenticate without the\n * developer ever touching `.env.local`.\n * 3. Spawns two children:\n * - `dashwise module dev` — manifest watcher + SDK regen loop\n * - `next dev` — Next.js dev server\n * Both stdout/stderr streams are line-prefixed with `[sdk]` and\n * `[next]` so a single terminal can show both subsystems' output\n * without confusion.\n * 4. Forwards SIGINT/SIGTERM to both children, waits for them to exit,\n * then exits itself with the worst child's exit code (so CI catches\n * a crash on either side).\n *\n * Why two child processes rather than running `module dev` in-process:\n * - Symmetric output prefixing — same code path handles both.\n * - Signal isolation — Ctrl-C is forwarded cleanly to both, neither\n * can interfere with the other's shutdown by throwing async.\n * - Failure isolation — a crash in `module dev`'s generator can't\n * take down `next dev` or vice versa; users see a clear \"[sdk]\n * exited with code 1, [next] still running\" line.\n *\n * The Next.js process gets spawned via `npx next dev` (or the project's\n * own `dev:next` script if present), which avoids hard-coding a path\n * to the user's local node_modules.\n */\n\nimport { spawn, type ChildProcess } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { resolve as resolvePath } from 'node:path';\nimport { ApiError, apiRequest } from '../lib/api-client.js';\nimport { readConfig, readModuleEntry } from '../lib/config.js';\nimport { readManifest } from '../lib/manifest-io.js';\nimport {\n startManifestPollLoop,\n type ManifestPollHandle,\n} from '../lib/manifest-poll.js';\nimport { code, dim, fail, info, success, warn } from '../lib/output.js';\n\nexport interface DevCommandOptions {\n /** Project directory containing `module.json`. Defaults to cwd. */\n dir?: string;\n /**\n * Override the `DASHWISE_INSTALLATION_ID` env var passed to children.\n *\n * When set to a real installation id (numeric), prod-mode SSO is used\n * — the SDK's middleware hits `/api/auth/sso/start?client_id=<id>`\n * and that installation must already exist in your workspace.\n *\n * When NOT set (the default), `dashwise dev` registers a dev session\n * with the backend and injects `DASHWISE_DEV_SESSION_ID` instead —\n * no installation required (see auth/spec.md § Dev-Mode SSO).\n */\n installationId?: string;\n /**\n * Override the `DASHWISE_API_URL` env var passed to children.\n * Defaults to the saved CLI config's `apiUrl`.\n */\n apiUrl?: string;\n /**\n * Port for `next dev`. Defaults to 3000 — used both for the child\n * spawn AND for computing the default dev-session callback origin\n * (`http://localhost:<port>`).\n */\n port?: number;\n /**\n * Workspace to scope the dev session to. Either a numeric id (`'42'`)\n * or a slug (`'my-workspace'`). When omitted, defaults to the user's\n * primary workspace if they have only one; errors out asking for an\n * explicit `--workspace` if they have multiple.\n *\n * Only relevant when using dev-mode SSO (the default — ignored if\n * `--installation-id` is passed).\n */\n workspace?: string;\n /**\n * Additional callback origins to allowlist on the dev session, beyond\n * the default `http://localhost:<port>`. Repeatable.\n *\n * Example: `--callback-origin https://myapp.local` for custom-domain\n * local dev. Each origin must be a fully-qualified http(s) URL.\n *\n * Only relevant when using dev-mode SSO.\n */\n callbackOrigin?: string[];\n /**\n * Skip the Next.js dev server — only run the manifest watcher.\n * Useful if the developer is running `next dev` separately for\n * some reason (e.g. they want a debugger attached to it).\n */\n sdkOnly?: boolean;\n /**\n * Skip the manifest watcher — only run `next dev`. Symmetric escape\n * hatch to `--sdk-only`.\n */\n nextOnly?: boolean;\n /**\n * HH-CC-P1-E3 — disable the backend manifest poll loop. Without this\n * flag, `dashwise dev` periodically fetches `/api/installations/:id/\n * schema` + writes to local `module.json` if the backend has\n * advanced (dashboard edits, AI builder mutations, teammate\n * commands). With `--no-remote-poll`, the watcher only reacts to\n * local file changes (CLI-driven mutations).\n *\n * Use when actively hand-editing module.json and don't want the\n * watcher clobbering your in-progress edits. The hand-edit-doesn't-\n * get-clobbered logic in `manifest-poll.ts` makes this rarely\n * needed in practice, but the escape hatch is here.\n */\n noRemotePoll?: boolean;\n /**\n * HH-CC-P1-E3 — backend manifest poll interval in seconds. Default\n * `5`. Ignored when `--no-remote-poll` is set.\n */\n remotePollIntervalSec?: number;\n}\n\n/**\n * Default port for the scaffolded Next.js dev server. Used both for\n * the `--port` default AND for computing the default callback origin\n * passed to `POST /api/auth/dev/sessions`. Single source of truth —\n * if the user overrides one without the other, the dev session's\n * allowlist won't match the actual dev server origin and SSO fails\n * with `INVALID_RETURN_TO`.\n */\nconst DEFAULT_NEXT_PORT = 3000;\n\n/**\n * ANSI-styled prefix prepended to every line of a child's output.\n * Colors are kept faint so a long dev session doesn't strain the eye.\n *\n * `[sdk]` is cyan-ish, `[next]` is magenta-ish — they map cleanly to\n * the two subsystems and stay distinguishable on dark + light terminals.\n */\nconst PREFIX_SDK = `\\x1b[36m[sdk]\\x1b[0m `;\nconst PREFIX_NEXT = `\\x1b[35m[next]\\x1b[0m `;\n// HH-CC-P1-E3 — backend manifest poll loop's log prefix. Yellow so\n// it's visually distinct from sdk (cyan) and next (magenta).\nconst PREFIX_POLL = `\\x1b[33m[poll]\\x1b[0m `;\n/** Default backend-manifest poll interval, seconds. */\nconst DEFAULT_REMOTE_POLL_INTERVAL_SEC = 5;\n/** Minimum poll interval — avoid hammering the backend. */\nconst MIN_REMOTE_POLL_INTERVAL_SEC = 1;\n\nexport async function devCommand(\n options: DevCommandOptions,\n): Promise<number> {\n if (options.sdkOnly && options.nextOnly) {\n fail(\n `Cannot pass both ${code('--sdk-only')} and ${code('--next-only')} — they're mutually exclusive.`,\n );\n return 1;\n }\n\n const projectRoot = resolvePath(options.dir ?? process.cwd());\n const manifestPath = `${projectRoot}/module.json`;\n if (!existsSync(manifestPath)) {\n fail(`No ${code('module.json')} found in ${code(projectRoot)}.`);\n info(`Run ${code('dashwise module init <slug>')} to scaffold a new module first.`);\n return 1;\n }\n\n // HH-CC-LDI-7: read the manifest to learn this module's slug, so we\n // can look up its per-module runtime token from auth.json#modules[slug].\n // Failing to parse the manifest isn't fatal — `module dev` will catch\n // it downstream with a clearer error message. We just lose the\n // runtime-token injection in that case.\n const manifestSlug = (() => {\n try {\n return readManifest(projectRoot)?.module?.slug;\n } catch {\n return undefined;\n }\n })();\n\n // ── 1. Auth resolution ───────────────────────────────────────────────\n // Saved config is the source of truth; --api-url / env can override\n // individual fields. Refuse to start if no auth at all — the dev\n // server would just 401 on every request.\n const savedConfig = (() => {\n try {\n return readConfig();\n } catch {\n // Corrupt config — treat as if not logged in. The login command\n // will surface the real error if re-run.\n return null;\n }\n })();\n\n const apiToken = process.env.DASHWISE_API_TOKEN ?? savedConfig?.token;\n if (!apiToken) {\n fail(`Not authenticated. Run ${code('dashwise login')} first.`);\n info(\n 'The unified dev loop reads your CLI token from ~/.config/dashwise/auth.json ' +\n 'and injects it into both child processes so the SDK can authenticate ' +\n 'without you editing .env.local.',\n );\n return 1;\n }\n const apiUrl =\n options.apiUrl ??\n process.env.DASHWISE_API_URL ??\n savedConfig?.apiUrl ??\n 'http://localhost:3000';\n // HH-CC-FUP-7: port resolution + collision handling.\n // - User passed --port <N>: try exactly N. If taken, fail fast with\n // the next free port suggested in the error message (don't auto-\n // reassign — explicit user intent is preserved).\n // - User didn't pass --port: probe DEFAULT_NEXT_PORT upward until we\n // find a free port (capped at PORT_PROBE_LIMIT attempts) so a\n // stray process on :3000 doesn't crash `dashwise dev` for users\n // who don't care about the specific port.\n //\n // The chosen port flows into BOTH the dev session's callback origin\n // (registered with the backend before next dev starts) AND the\n // child's --port arg. They MUST agree, otherwise SSO callbacks\n // 404 against the wrong port.\n let port: number;\n try {\n port = await resolveDevPort(options.port);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n // ── 2. Resolve auth mode ─────────────────────────────────────────────\n // Three paths, in priority order:\n //\n // (a) `--installation-id <id>` (or `DASHWISE_INSTALLATION_ID` env)\n // — prod-like mode. SDK's sign-in route uses /sso/start with\n // client_id=<id>. The installation must already exist.\n //\n // (b) `DASHWISE_DEV_SESSION_ID` env set (e.g. for testing) — reuse\n // the existing dev session id without re-registering.\n //\n // (c) Default — register a fresh dev session with the backend,\n // inject DASHWISE_DEV_SESSION_ID into the child env, revoke\n // on graceful shutdown.\n const explicitInstallationId =\n options.installationId ?? process.env.DASHWISE_INSTALLATION_ID;\n const reuseDevSessionId = process.env.DASHWISE_DEV_SESSION_ID;\n\n // HH-CC-LDI-7: per-module runtime-token lookup. We read it BEFORE\n // the auth-mode branching below so the path can branch on its\n // presence — but we don't make the runtime token gate dev-session\n // setup. The two are orthogonal: the dev session powers SSO sign-in\n // callbacks for end users hitting the running module; the runtime\n // token powers the SDK's data-plane calls. Both can be active\n // simultaneously.\n const moduleEntry =\n manifestSlug !== undefined ? readModuleEntry(manifestSlug) : null;\n const runtimeTokenEnv = process.env.DASHWISE_RUNTIME_TOKEN ?? moduleEntry?.runtimeToken;\n\n let installationIdEnv: string | undefined;\n let devSessionIdEnv: string | undefined;\n let revokeDevSession: (() => Promise<void>) | undefined;\n\n if (explicitInstallationId && explicitInstallationId !== 'local') {\n installationIdEnv = explicitInstallationId;\n } else if (reuseDevSessionId) {\n devSessionIdEnv = reuseDevSessionId;\n } else {\n // Default — register a dev session.\n let workspaceContext: { id: number; name: string; slug: string };\n try {\n workspaceContext = await resolveTargetWorkspace(apiUrl, apiToken, options.workspace);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n const callbackOrigins = computeCallbackOrigins(port, options.callbackOrigin ?? []);\n try {\n const session = await registerDevSession(apiUrl, apiToken, {\n target_workspace_id: workspaceContext.id,\n callback_origins: callbackOrigins,\n });\n devSessionIdEnv = session.id;\n revokeDevSession = () => revokeDevSessionBestEffort(apiUrl, apiToken, session.id);\n info(` ${dim('dev session')} ${session.id}`);\n info(` ${dim('workspace')} ${workspaceContext.name} (id=${workspaceContext.id}, slug=${workspaceContext.slug})`);\n info(` ${dim('callbacks')} ${callbackOrigins.join(', ')}`);\n info(` ${dim('expires')} ${session.expires_at}`);\n } catch (err) {\n if (err instanceof ApiError) {\n fail(`Failed to register dev session: ${err.code} — ${err.message}`);\n } else {\n fail(`Failed to register dev session: ${(err as Error).message}`);\n }\n return 1;\n }\n }\n\n // ── 3. Build child env ───────────────────────────────────────────────\n // Inherit the parent's env so user-set vars (e.g. NEXT_TELEMETRY_DISABLED,\n // NODE_OPTIONS) flow through unchanged. Overlay the DASHWISE_* vars\n // so the SDK can read them — these win over anything the user set\n // in .env.local because Next.js loads .env.local AFTER process.env.\n //\n // Set DASHWISE_INSTALLATION_ID to empty string when in dev mode so\n // the scaffolded sign-in route sees `process.env.DASHWISE_INSTALLATION_ID\n // === ''` (falsy) and correctly branches on DASHWISE_DEV_SESSION_ID\n // instead — without explicitly unsetting an inherited value.\n //\n // HH-CC-LDI-7: when a per-module runtime token is available (from\n // auth.json#modules[slug] written by `dashwise init`, or from a\n // DASHWISE_RUNTIME_TOKEN env override), inject it into the child env\n // so `@dashai/sdk`'s `createDevClient()` can pick it up for the\n // data plane. We also flip DASHWISE_INSTALLATION_ID to the literal\n // 'sandbox' (URL placeholder for runtime-token auth) WHEN no\n // explicit installation id is set — the backend's RuntimeTokenGuard\n // resolves the actual install from the JWT claims, not the URL.\n const childInstallationId =\n installationIdEnv ??\n (runtimeTokenEnv !== undefined ? 'sandbox' : '');\n const childEnv: Record<string, string | undefined> = {\n ...process.env,\n DASHWISE_API_URL: apiUrl,\n // HH-CC-FUP-3: client-side mirror. Next.js inlines NEXT_PUBLIC_*\n // env vars into the browser bundle at build time (or, in dev, at\n // process-start time). Without this, the SDK's <AuthProvider> hits\n // `/api/auth/sessions/me` on its own origin (localhost:<port>),\n // 404s, and stays unauthenticated. We mirror DASHWISE_API_URL so\n // the client + server agree on the backend origin without the\n // module author having to touch .env.local.\n NEXT_PUBLIC_DASHWISE_API_URL: apiUrl,\n DASHWISE_API_TOKEN: apiToken,\n DASHWISE_INSTALLATION_ID: childInstallationId,\n ...(devSessionIdEnv !== undefined ? { DASHWISE_DEV_SESSION_ID: devSessionIdEnv } : {}),\n ...(runtimeTokenEnv !== undefined\n ? { DASHWISE_RUNTIME_TOKEN: runtimeTokenEnv }\n : {}),\n };\n\n // ── 4. Pre-flight banner ─────────────────────────────────────────────\n info(`Dev loop starting — Ctrl-C to stop.`);\n info(` ${dim('api')} ${apiUrl}`);\n if (installationIdEnv !== undefined) {\n info(` ${dim('installation')} ${installationIdEnv} (prod-mode SSO)`);\n } else {\n info(` ${dim('mode')} dev (DASHWISE_DEV_SESSION_ID injected)`);\n }\n info(` ${dim('token')} ${maskedToken(apiToken)} ${dim(`(from ${apiToken === savedConfig?.token ? '~/.config/dashwise/auth.json' : '$DASHWISE_API_TOKEN'})`)}`);\n // HH-CC-LDI-7: surface the runtime-token source so developers know\n // which auth credentials the SDK will pick up. Three observable\n // states:\n // - cached: per-module entry in auth.json (the LDI-6 happy path)\n // - env: DASHWISE_RUNTIME_TOKEN explicit override\n // - missing: no runtime token; data-plane calls will fail with\n // UnauthenticatedError. Surface a hint to run `dashwise init`.\n if (runtimeTokenEnv !== undefined) {\n const source =\n process.env.DASHWISE_RUNTIME_TOKEN === runtimeTokenEnv\n ? '$DASHWISE_RUNTIME_TOKEN'\n : `~/.config/dashwise/auth.json#modules[${manifestSlug}]`;\n const installId = moduleEntry?.installationId;\n info(\n ` ${dim('runtime')} ${maskedToken(runtimeTokenEnv)} ${dim(`(from ${source}${installId ? `, install id=${installId}` : ''})`)}`,\n );\n } else if (manifestSlug !== undefined && installationIdEnv === undefined) {\n // No runtime token + no explicit install id → the SDK's data plane\n // will 401 on every call. Print a one-line hint so the dev knows\n // why; don't block the dev loop because SSO + scaffolding still\n // work without it.\n warn(\n `No runtime token cached for module ${code(manifestSlug)}. ` +\n `Data-plane calls (db, qb) will fail with UnauthenticatedError. ` +\n `Run ${code(`dashwise init ${manifestSlug} --force`)} to provision a dev install + cache the token.`,\n );\n }\n info('');\n\n // ── 4. Spawn children ────────────────────────────────────────────────\n const children: { name: string; child: ChildProcess; prefix: string }[] = [];\n\n if (!options.nextOnly) {\n const sdkChild = spawnSdkWatcher(projectRoot, childEnv);\n children.push({ name: 'sdk', child: sdkChild, prefix: PREFIX_SDK });\n }\n if (!options.sdkOnly) {\n // Always pass `port` (default DEFAULT_NEXT_PORT, overridden by\n // --port). This ensures the actual dev server port matches the\n // dev session's callback origin allowlist computed above.\n const nextChild = spawnNextDev(projectRoot, childEnv, port);\n children.push({ name: 'next', child: nextChild, prefix: PREFIX_NEXT });\n }\n\n // ── 5. Wire output multiplexing ──────────────────────────────────────\n for (const { child, prefix } of children) {\n pipeWithPrefix(child.stdout, process.stdout, prefix);\n pipeWithPrefix(child.stderr, process.stderr, prefix);\n }\n\n // ── 5b. Backend manifest poll loop (HH-CC-P1-E3) ────────────────────\n // Fetches `/api/installations/:id/schema` periodically and writes\n // module.json when the backend has advanced. The sdk-watcher child\n // then picks up the file change + regenerates @dashai/generated.\n //\n // Gated on: a per-module runtime token being available (no token =\n // no auth = can't poll), and the user not opting out via\n // `--no-remote-poll`. Also disabled when `--sdk-only` is set without\n // any next dev — the poll loop is only valuable when the dev server\n // is also running.\n let manifestPoll: ManifestPollHandle | null = null;\n const enablePoll =\n !options.noRemotePoll &&\n moduleEntry !== null &&\n manifestSlug !== undefined;\n if (enablePoll) {\n const intervalSec = Math.max(\n MIN_REMOTE_POLL_INTERVAL_SEC,\n options.remotePollIntervalSec ?? DEFAULT_REMOTE_POLL_INTERVAL_SEC,\n );\n manifestPoll = startManifestPollLoop({\n installationId: moduleEntry.installationId,\n manifestPath,\n requestOptions: {\n baseUrl: apiUrl,\n auth: { token: moduleEntry.runtimeToken },\n },\n intervalMs: intervalSec * 1000,\n onUpdate: (msg) => {\n process.stdout.write(`${PREFIX_POLL}${msg}\\n`);\n },\n onError: (err) => {\n // Persistent failures should be visible but not noisy — write\n // to stderr through the [poll] prefix and keep going.\n process.stderr.write(`${PREFIX_POLL}${err.message}\\n`);\n },\n });\n info(\n ` ${dim('poll')} backend manifest every ${intervalSec}s ${dim('(--no-remote-poll to disable)')}`,\n );\n info('');\n }\n\n // ── 6. Signal forwarding + exit aggregation ─────────────────────────\n let shuttingDown = false;\n const forwardSignal = (sig: NodeJS.Signals) => {\n if (shuttingDown) return;\n shuttingDown = true;\n // Stop the poll loop first so no late writes race with shutdown.\n if (manifestPoll) {\n manifestPoll.stop();\n manifestPoll = null;\n }\n info(`\\nReceived ${sig}, stopping children…`);\n for (const { child } of children) {\n if (child.exitCode === null && child.signalCode === null) {\n child.kill(sig);\n }\n }\n // Best-effort revoke the dev session — fire-and-forget so we\n // don't delay shutdown if the API is slow. If the request fails\n // (offline, backend down, etc.) the dev session naturally expires\n // in 24h, so the leftover is harmless.\n if (revokeDevSession) {\n revokeDevSession().catch(() => {\n /* swallowed — best-effort */\n });\n }\n };\n process.on('SIGINT', () => forwardSignal('SIGINT'));\n process.on('SIGTERM', () => forwardSignal('SIGTERM'));\n\n // Wait for each child's exit. Aggregate exit codes — if either fails\n // non-zero (and we didn't kill it intentionally), surface the worst\n // code so CI catches a crash.\n const results = await Promise.all(\n children.map(\n ({ name, child }) =>\n new Promise<{ name: string; code: number; killed: boolean }>(\n (resolveExit) => {\n child.on('exit', (exitCode, signal) => {\n const killed = signal !== null;\n const finalCode =\n exitCode ?? (killed ? 0 : 1); // signal-only exit treated as clean\n resolveExit({ name, code: finalCode, killed });\n });\n },\n ),\n ),\n );\n\n // If ANY child exits non-zero AND wasn't killed by our signal forward,\n // kill the others so we don't leave orphans. Then aggregate.\n const crashed = results.find((r) => !r.killed && r.code !== 0);\n if (crashed && !shuttingDown) {\n warn(`[${crashed.name}] exited with code ${crashed.code} — stopping others.`);\n for (const { child } of children) {\n if (child.exitCode === null && child.signalCode === null) {\n child.kill('SIGTERM');\n }\n }\n }\n\n // Stop the poll loop in case shutdown was triggered by a child\n // crash rather than a signal (forwardSignal already stops it on\n // SIGINT/SIGTERM, but a crashed `next dev` reaches here without\n // going through forwardSignal — idempotent stop() handles both).\n if (manifestPoll) {\n manifestPoll.stop();\n manifestPoll = null;\n }\n\n const exitCode = Math.max(0, ...results.map((r) => r.code));\n if (exitCode === 0) {\n success('Dev loop stopped cleanly.');\n }\n return exitCode;\n}\n\n// ── Internals ───────────────────────────────────────────────────────────\n\n/**\n * Spawn `dashwise module dev` as a child. We re-exec the same CLI binary\n * via `process.execPath` + `process.argv[1]` so we never depend on the\n * binary being on $PATH (npm-install-globally is common but not\n * universal; pnpm workspace setups can put the bin in a non-PATH\n * directory).\n *\n * The child inherits stdio for stdin (so a future interactive-prompt\n * inside `module dev` could still work), but stdout/stderr are piped so\n * we can prefix the lines.\n */\nfunction spawnSdkWatcher(\n projectRoot: string,\n env: Record<string, string | undefined>,\n): ChildProcess {\n const child = spawn(\n process.execPath,\n [process.argv[1]!, 'module', 'dev', '--dir', projectRoot],\n {\n cwd: projectRoot,\n env,\n stdio: ['ignore', 'pipe', 'pipe'],\n },\n );\n return child;\n}\n\n/**\n * Spawn `next dev`. We prefer the project's `dev:next` npm script (which\n * the scaffold writes out) so the dev experience stays consistent with\n * what a user gets when running `npm run dev:next` directly. Falls back\n * to `npx next dev` if no script is defined.\n *\n * Pass `--port` explicitly if the caller asked, otherwise let Next pick\n * its default (3000 by default; Next falls forward to 3001/3002/...\n * when the port is taken — our local backend usually owns 3000).\n */\nfunction spawnNextDev(\n projectRoot: string,\n env: Record<string, string | undefined>,\n port: number | undefined,\n): ChildProcess {\n const portArgs = port !== undefined ? ['--', '--port', String(port)] : [];\n const hasDevNextScript = hasNpmScript(projectRoot, 'dev:next');\n // npm/yarn/pnpm differ on how they locate `next` — the safest cross-tool\n // path is to delegate to the project's own package manager via `npm run\n // dev:next`. If the script is missing, fall back to `npx next dev`.\n const [cmd, args] = hasDevNextScript\n ? ['npm', ['run', 'dev:next', ...portArgs]]\n : ['npx', ['next', 'dev', ...(port !== undefined ? ['--port', String(port)] : [])]];\n\n const child = spawn(cmd, args, {\n cwd: projectRoot,\n env,\n stdio: ['ignore', 'pipe', 'pipe'],\n // Windows requires `shell: true` for `npm` / `npx` because they're\n // `.cmd` shims, not real binaries.\n shell: process.platform === 'win32',\n });\n return child;\n}\n\n/**\n * Read the project's `package.json` and check whether the named script\n * exists. Returns false on any error (missing package.json, malformed\n * JSON, etc.) — the caller falls back to npx in that case.\n */\nfunction hasNpmScript(projectRoot: string, scriptName: string): boolean {\n try {\n const pkgPath = `${projectRoot}/package.json`;\n if (!existsSync(pkgPath)) return false;\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8')) as {\n scripts?: Record<string, string>;\n };\n return typeof pkg.scripts?.[scriptName] === 'string';\n } catch {\n return false;\n }\n}\n\n/**\n * Pipe a child's readable stream into our output stream, prefixing each\n * line with the given prefix. Uses line-buffered prefixing: partial\n * lines (no trailing newline) get prefixed too so e.g. spinner output\n * still surfaces — but if a child emits a stream of \\r-overwrites for a\n * fancy progress bar, the prefix collapses correctly because we re-emit\n * the partial line as-is.\n *\n * Edge case: if the stream is null (child was spawned without piping),\n * silently no-op. Real spawn calls above always pipe both, so this is\n * defence-in-depth.\n */\nfunction pipeWithPrefix(\n src: NodeJS.ReadableStream | null,\n dst: NodeJS.WritableStream,\n prefix: string,\n): void {\n if (!src) return;\n let leftover = '';\n src.on('data', (chunk: Buffer | string) => {\n const text = typeof chunk === 'string' ? chunk : chunk.toString('utf-8');\n const combined = leftover + text;\n const lines = combined.split('\\n');\n leftover = lines.pop() ?? '';\n for (const line of lines) {\n dst.write(`${prefix}${line}\\n`);\n }\n });\n src.on('end', () => {\n if (leftover.length > 0) {\n dst.write(`${prefix}${leftover}\\n`);\n }\n });\n}\n\n/**\n * Mask a bearer token for log display. Shows the prefix (so users can\n * recognize WHICH token is being used — `dwc_*` vs JWT etc.) and a\n * 4-char tail (for distinguishing between two tokens at a glance) but\n * never the middle.\n */\nfunction maskedToken(token: string): string {\n if (token.length <= 12) return '****';\n const prefix = token.slice(0, 4);\n const tail = token.slice(-4);\n return `${prefix}…${tail}`;\n}\n\n// ── Dev-Mode SSO session lifecycle ──────────────────────────────────────\n\ninterface WorkspaceListItem {\n id: number;\n name: string;\n slug: string;\n}\n\ninterface DevSessionApiResponse {\n id: string;\n target_workspace_id: number;\n allowed_callback_origins: string[];\n expires_at: string;\n}\n\n/**\n * Compute the dev session's allowed callback origins. Defaults to the\n * dev server's bind URL (`http://localhost:<port>`); the user can add\n * more via `--callback-origin <url>` (repeatable).\n *\n * Backend validates each entry is a well-formed http(s) URL — we do\n * NOT pre-validate here; let the BE's error response (with code\n * `INVALID_CALLBACK_ORIGIN`) be the source of truth.\n */\nfunction computeCallbackOrigins(port: number, extra: string[]): string[] {\n const def = `http://localhost:${port}`;\n // De-dup: prevent the BE from rejecting a list with redundant\n // entries (the BE doesn't reject — it stores them as-is — but\n // sending unique values is the kinder client behavior).\n return Array.from(new Set([def, ...extra]));\n}\n\n/**\n * HH-CC-FUP-7 — port resolution + collision handling.\n *\n * Two modes depending on whether the user passed `--port`:\n *\n * - **Explicit `--port N`** (caller intent is \"use exactly N\"):\n * probe N once. If taken, throw a friendly error suggesting the\n * next free port the user could try. Do NOT auto-reassign — the\n * user picked a specific port for a reason (URL-shaped scripts,\n * bookmarks, hosts file entries, etc.).\n *\n * - **No --port** (caller doesn't care): probe DEFAULT_NEXT_PORT\n * upward until we find a free port, capped at PORT_PROBE_LIMIT\n * attempts. Mirrors Next.js's own \"port already in use, trying\n * 3001\" UX, but done up-front so the dev session's callback\n * origin matches the port that next dev will actually bind to.\n *\n * The chosen port becomes the dev session's `callback_origins[0]`\n * (`http://localhost:<port>`) AND the `--port` arg passed to next dev.\n * If they didn't agree, SSO callbacks would land on the wrong port.\n */\nconst PORT_PROBE_LIMIT = 10;\n\nexport async function resolveDevPort(\n requested: number | undefined,\n): Promise<number> {\n if (requested !== undefined) {\n if (await isPortFree(requested)) return requested;\n const suggestion = await findFirstFreePort(requested + 1, PORT_PROBE_LIMIT);\n const suggestionHint =\n suggestion !== null\n ? `Try \\`dashwise dev --port ${suggestion}\\`.`\n : `No free port found between ${requested + 1} and ${requested + PORT_PROBE_LIMIT} either — check what's listening with \\`lsof -i :${requested}\\`.`;\n throw new Error(\n `Port ${requested} is already in use. ${suggestionHint}`,\n );\n }\n const found = await findFirstFreePort(DEFAULT_NEXT_PORT, PORT_PROBE_LIMIT);\n if (found === null) {\n throw new Error(\n `No free port found between ${DEFAULT_NEXT_PORT} and ${DEFAULT_NEXT_PORT + PORT_PROBE_LIMIT - 1}. ` +\n `Free a port (e.g. \\`lsof -i :${DEFAULT_NEXT_PORT}\\`) or pass \\`--port <N>\\` explicitly.`,\n );\n }\n return found;\n}\n\n/**\n * True if no process is listening on the given port on any local\n * interface. Implemented by attempting to bind a transient server\n * to 0.0.0.0:port; if that succeeds we close immediately and the\n * port is free. EADDRINUSE → port is taken. Any other error → treat\n * as unknown / not-free (safer than assuming free).\n */\nasync function isPortFree(port: number): Promise<boolean> {\n const { createServer } = await import('node:net');\n return new Promise<boolean>((resolve) => {\n const server = createServer();\n server.once('error', () => {\n // Common error codes here: EADDRINUSE (port taken), EACCES\n // (privileged port under 1024). Either way the port isn't\n // usable for `next dev`, so report not-free.\n resolve(false);\n });\n server.once('listening', () => {\n server.close(() => resolve(true));\n });\n server.listen(port, '0.0.0.0');\n });\n}\n\n/**\n * Probe ports `start..start+limit-1` and return the first one that's\n * free, or null if none are. Sequential probe (cheap — sub-ms per port\n * locally; user-visible latency stays negligible).\n */\nasync function findFirstFreePort(\n start: number,\n limit: number,\n): Promise<number | null> {\n for (let i = 0; i < limit; i++) {\n const port = start + i;\n if (await isPortFree(port)) return port;\n }\n return null;\n}\n\n/**\n * Resolve the target workspace for the dev session, given the\n * optional `--workspace` flag. Three paths:\n *\n * - Flag is numeric → treat as id, fetch by id.\n * - Flag is non-numeric → treat as slug, look up.\n * - Flag absent → list user's workspaces. If exactly 1, auto-pick.\n * If 0, error. If >1, error with a list so the user can pick.\n *\n * Returns `{ id, name, slug }` for the chosen workspace.\n */\nasync function resolveTargetWorkspace(\n apiUrl: string,\n apiToken: string,\n flag: string | undefined,\n): Promise<{ id: number; name: string; slug: string }> {\n const workspaces = await apiRequest<WorkspaceListItem[]>(\n 'GET',\n '/api/workspaces',\n undefined,\n { baseUrl: apiUrl, auth: { token: apiToken } },\n );\n if (workspaces.length === 0) {\n throw new Error(\n 'No workspaces found for your account. Create a workspace at the DashWise dashboard first.',\n );\n }\n if (flag === undefined) {\n if (workspaces.length === 1) {\n return workspaces[0];\n }\n const list = workspaces.map((w) => ` - ${w.slug} (id=${w.id}, name=\"${w.name}\")`).join('\\n');\n throw new Error(\n `You have ${workspaces.length} workspaces. Re-run with --workspace <slug-or-id> to pick one:\\n${list}`,\n );\n }\n const asNumber = Number.parseInt(flag, 10);\n const isNumeric = !Number.isNaN(asNumber) && String(asNumber) === flag;\n const match = isNumeric\n ? workspaces.find((w) => w.id === asNumber)\n : workspaces.find((w) => w.slug === flag);\n if (!match) {\n const list = workspaces.map((w) => ` - ${w.slug} (id=${w.id})`).join('\\n');\n throw new Error(\n `No workspace matching --workspace=${flag}. Available:\\n${list}`,\n );\n }\n return match;\n}\n\n/**\n * `POST /api/auth/dev/sessions`. CLI-token authenticated. Returns the\n * dev session row the SDK keys off of.\n */\nasync function registerDevSession(\n apiUrl: string,\n apiToken: string,\n body: { target_workspace_id: number; callback_origins: string[] },\n): Promise<DevSessionApiResponse> {\n return apiRequest<DevSessionApiResponse>(\n 'POST',\n '/api/auth/dev/sessions',\n body,\n { baseUrl: apiUrl, auth: { token: apiToken } },\n );\n}\n\n/**\n * `DELETE /api/auth/dev/sessions/:id`. Best-effort — errors are\n * swallowed by the caller. If the call fails (offline, BE down,\n * CLI token revoked since registration), the session naturally\n * expires within 24h so leaving it is harmless.\n */\nasync function revokeDevSessionBestEffort(\n apiUrl: string,\n apiToken: string,\n id: string,\n): Promise<void> {\n await apiRequest<void>(\n 'DELETE',\n `/api/auth/dev/sessions/${encodeURIComponent(id)}`,\n undefined,\n { baseUrl: apiUrl, auth: { token: apiToken } },\n );\n}\n","/**\n * Backend manifest polling loop. Used by `dashwise dev` to auto-sync\n * local `module.json` whenever the backend canonical manifest changes\n * (P1-E3 — BaaS Phase 1, Bucket E sprint 3).\n *\n * Decoupled from `dev.ts` so it's:\n * 1. Testable in isolation (vitest can mock the api-client + assert\n * write-on-change behavior without spawning child processes).\n * 2. Reusable — future commands (`dashwise watch`, `dashwise mcp`,\n * etc.) can drop the same loop in without copy-paste.\n *\n * Design notes:\n *\n * - Polling cadence: setTimeout (not setInterval) chained from the\n * tick handler. This guarantees ≥`intervalMs` between consecutive\n * tick STARTS — never overlaps if a tick takes longer than the\n * interval (slow network, big manifest). setInterval would queue up\n * ticks under contention.\n *\n * - Initial baseline: read the local file BEFORE starting the loop.\n * First poll only writes if the backend differs from THAT baseline.\n * Prevents a write-storm on dev-start when the file already matches\n * the backend.\n *\n * - Failure handling: a single tick failure (network blip, backend\n * 500, expired token) logs via `onError` and keeps the loop\n * running. Persistent failures should be surfaced via UI by the\n * caller — the loop itself never gives up.\n *\n * - Stop semantics: the returned stop function is idempotent + cancels\n * any in-flight setTimeout. In-flight HTTP requests are NOT aborted\n * (no AbortController plumbing yet); they complete to no-op.\n */\n\nimport { readFileSync, writeFileSync, existsSync } from 'node:fs';\nimport { ApiError, getInstallationSchema } from './api-client.js';\nimport type { RequestOptions } from './api-client.js';\n\nexport interface ManifestPollOptions {\n installationId: number;\n manifestPath: string;\n requestOptions: RequestOptions;\n intervalMs: number;\n /** Called when the backend manifest changes + we wrote locally. */\n onUpdate?: (msg: string) => void;\n /** Called on a single-tick failure. Loop keeps running. */\n onError?: (err: Error) => void;\n}\n\nexport interface ManifestPollHandle {\n /** Idempotent stop. Cancels any pending setTimeout. */\n stop: () => void;\n /** True until stop() is called. */\n isRunning: () => boolean;\n}\n\n/**\n * Start polling the backend canonical manifest. Returns a handle to\n * stop the loop. Loop begins on the NEXT tick (after `intervalMs`),\n * not immediately — `dashwise dev` already has the current local\n * state from its initial read; no point fetching again right away.\n *\n * Callers SHOULD invoke `handle.stop()` on shutdown. The loop will\n * otherwise run until process exit (which is fine for `dashwise dev`\n * but not for tests that need clean teardown).\n */\nexport function startManifestPollLoop(\n opts: ManifestPollOptions,\n): ManifestPollHandle {\n const {\n installationId,\n manifestPath,\n requestOptions,\n intervalMs,\n onUpdate,\n onError,\n } = opts;\n\n let lastSeenJson: string = existsSync(manifestPath)\n ? readFileSync(manifestPath, 'utf-8')\n : '';\n let timer: NodeJS.Timeout | null = null;\n let stopped = false;\n\n const tick = async (): Promise<void> => {\n if (stopped) return;\n try {\n const { manifest } = await getInstallationSchema(\n installationId,\n requestOptions,\n );\n const remoteJson = JSON.stringify(manifest, null, 2) + '\\n';\n // Re-read the local file every tick — a hand-edit or another\n // CLI command (e.g. `dashwise table create` in another terminal)\n // might have changed it under us. If local == remote, no write.\n // If local != remote BUT remote == lastSeen, also no write —\n // the user's hand-edit is the latest and we shouldn't clobber\n // it (they can explicitly `dashwise pull` to discard).\n const currentLocal = existsSync(manifestPath)\n ? readFileSync(manifestPath, 'utf-8')\n : '';\n if (remoteJson === currentLocal) {\n lastSeenJson = remoteJson;\n } else if (remoteJson !== lastSeenJson) {\n // Backend advanced. Write through.\n writeFileSync(manifestPath, remoteJson, 'utf-8');\n lastSeenJson = remoteJson;\n if (onUpdate) {\n const delta =\n Buffer.byteLength(remoteJson, 'utf8') -\n Buffer.byteLength(currentLocal, 'utf8');\n const deltaStr =\n delta === 0\n ? '0 bytes'\n : `${delta > 0 ? '+' : ''}${delta} bytes`;\n onUpdate(\n `Backend manifest changed — synced to module.json (${deltaStr}).`,\n );\n }\n }\n // Else: backend == lastSeen but local has drifted (hand-edit).\n // Don't clobber — the user owns their working copy.\n } catch (err) {\n if (onError) {\n const message =\n err instanceof ApiError\n ? `${err.code} (HTTP ${err.status}): ${err.message}`\n : (err as Error).message;\n onError(new Error(message));\n }\n } finally {\n if (!stopped) {\n timer = setTimeout(() => void tick(), intervalMs);\n }\n }\n };\n\n // Schedule first tick after `intervalMs`. Don't poll immediately —\n // the caller already has the local state.\n timer = setTimeout(() => void tick(), intervalMs);\n\n return {\n stop: (): void => {\n if (stopped) return;\n stopped = true;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n },\n isRunning: (): boolean => !stopped,\n };\n}\n","/**\n * `dashwise login` — OAuth 2.0 Device Authorization Grant.\n *\n * Flow:\n * 1. POST /api/auth/cli/device-code → get `userCode` + `verificationUri`\n * 2. Display the code + URL; offer to open the browser\n * 3. Poll /api/auth/cli/poll on the published interval until the\n * user approves (or denies / it expires)\n * 4. On `approved`, save the returned token to ~/.config/dashwise/auth.json\n * 5. Fetch /api/auth/me to confirm + cache user identity\n *\n * UX: clack spinner during the poll loop; explicit prompts when\n * something needs the user's attention (e.g. opening the browser).\n * Non-interactive mode (`--no-prompt`) skips browser-open + just\n * prints the URL.\n */\n\nimport { cancel, intro, isCancel, log, outro, select, spinner } from '@clack/prompts';\nimport open from 'open';\nimport { ApiError, apiRequest } from '../lib/api-client.js';\nimport type {\n AuthMeResponse,\n CliDeviceCodeResponse,\n CliPollResponse,\n} from '../lib/backend-types.js';\nimport { resolveApiUrl, writeConfig, type CliConfig } from '../lib/config.js';\nimport { code, dim, fail, info, success } from '../lib/output.js';\n\nexport interface LoginOptions {\n /** Override the backend URL for this login (`--api-url`). */\n apiUrl?: string;\n /** Skip the \"open in browser\" prompt; just print the URL. */\n noPrompt?: boolean;\n /** Token name to suggest to the backend (shown in `me/cli-tokens`). */\n name?: string;\n}\n\nconst DEFAULT_TOKEN_NAME = 'dashwise-cli';\n\nexport async function loginCommand(options: LoginOptions): Promise<number> {\n const apiUrl = (options.apiUrl ?? resolveApiUrl()).replace(/\\/+$/, '');\n intro(`Logging into ${code(apiUrl)}`);\n\n // 1. Kick off the device-code grant.\n let dc: CliDeviceCodeResponse;\n try {\n dc = await apiRequest<CliDeviceCodeResponse>(\n 'POST',\n '/api/auth/cli/device-code',\n {\n name: options.name ?? DEFAULT_TOKEN_NAME,\n },\n { auth: 'public', baseUrl: apiUrl },\n );\n } catch (err) {\n fail(formatApiError('Could not start login flow', err));\n return 1;\n }\n\n log.message(\n [\n `Open the verification URL and confirm the code:`,\n ``,\n ` URL: ${code(dc.verificationUriComplete)}`,\n ` Code: ${code(dc.userCode)}`,\n ``,\n dim(\n `Code expires in ${formatSeconds(dc.expiresIn)}. The CLI will keep polling until you approve.`,\n ),\n ].join('\\n'),\n );\n\n // 2. Offer to open the browser (skipped in non-interactive mode).\n if (!options.noPrompt && process.stdout.isTTY) {\n const choice = await select({\n message: 'Open the verification URL in your browser?',\n options: [\n { value: 'open', label: 'Open now' },\n { value: 'skip', label: 'I’ll open it manually' },\n ],\n initialValue: 'open',\n });\n if (isCancel(choice)) {\n cancel('Login cancelled.');\n return 130; // SIGINT-equivalent exit code\n }\n if (choice === 'open') {\n try {\n await open(dc.verificationUriComplete);\n } catch (err) {\n info(`Could not open browser automatically (${(err as Error).message}). Open the URL above manually.`);\n }\n }\n }\n\n // 3. Poll until approved / denied / expired / overall deadline.\n const sp = spinner();\n sp.start('Waiting for approval');\n const overallDeadline = Date.now() + dc.expiresIn * 1000;\n let outcome: CliPollResponse | null = null;\n // Use 1s sleeps + let the backend's `slow_down` response push us\n // back if we exceed the published interval. Cheap; no need to be\n // clever with the polling cadence.\n const pollIntervalMs = Math.max(1000, dc.interval * 1000);\n\n pollLoop: while (Date.now() < overallDeadline) {\n let res: CliPollResponse;\n try {\n res = await apiRequest<CliPollResponse>(\n 'POST',\n '/api/auth/cli/poll',\n { deviceCode: dc.deviceCode },\n { auth: 'public', baseUrl: apiUrl },\n );\n } catch (err) {\n sp.stop(`Poll failed: ${(err as Error).message}`);\n fail('Poll failed mid-flight; you can re-run `dashwise login` to retry.');\n return 1;\n }\n switch (res.status) {\n case 'pending':\n case 'slow_down':\n await sleep(pollIntervalMs);\n continue pollLoop;\n case 'denied':\n sp.stop('Login denied by user.');\n cancel('Aborted.');\n return 1;\n case 'expired':\n sp.stop('Login code expired.');\n fail('The code expired before approval. Run `dashwise login` again.');\n return 1;\n case 'approved':\n outcome = res;\n break pollLoop;\n }\n }\n\n if (!outcome) {\n sp.stop('Timed out waiting for approval.');\n fail('Login took too long to be approved. Run `dashwise login` again.');\n return 1;\n }\n\n if (!outcome.token || !outcome.tokenId) {\n // Shouldn't happen on a fresh approval — but guard anyway.\n sp.stop('Approval received but token missing from response.');\n fail(\n 'Approval received but the backend did not return a token. Run `dashwise logout` then `dashwise login` to retry.',\n );\n return 1;\n }\n\n // 4. Confirm the token works + cache the profile.\n let me: AuthMeResponse;\n try {\n me = await apiRequest<AuthMeResponse>('GET', '/api/auth/me', undefined, {\n auth: { token: outcome.token },\n baseUrl: apiUrl,\n });\n } catch (err) {\n sp.stop('Approval accepted but profile fetch failed.');\n fail(formatApiError('Could not load user profile', err));\n return 1;\n }\n\n const cfg: CliConfig = {\n apiUrl,\n token: outcome.token,\n tokenId: outcome.tokenId,\n user: {\n id: me.id,\n email: me.email,\n username: me.username,\n firstName: me.first_name,\n lastName: me.last_name,\n },\n };\n writeConfig(cfg);\n sp.stop('Approved.');\n success(`Logged in as ${code(me.email)}`);\n outro('You can now run `dashwise profile`, `dashwise workspace list`, etc.');\n return 0;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction formatSeconds(seconds: number): string {\n if (seconds < 60) return `${seconds}s`;\n const minutes = Math.round(seconds / 60);\n return `${minutes}m`;\n}\n\nfunction formatApiError(prefix: string, err: unknown): string {\n if (err instanceof ApiError) {\n return `${prefix}: ${err.message} (code: ${err.code}, status: ${err.status})`;\n }\n if (err instanceof Error) return `${prefix}: ${err.message}`;\n return `${prefix}: ${String(err)}`;\n}\n","/**\n * `dashwise logout` — clear the local credentials and best-effort\n * revoke the server-side token row.\n *\n * Behavior:\n * 1. Read the saved config; if there's no token, exit 0 with an\n * info message (idempotent).\n * 2. Call `DELETE /api/auth/cli-tokens/:id` to revoke the row.\n * 404 / 403 / network errors are tolerated — the local file is\n * cleared regardless. We never want a server-side hiccup to\n * keep stale credentials on disk.\n * 3. Delete the local config file.\n */\n\nimport { apiRequest } from '../lib/api-client.js';\nimport { deleteConfig, readConfig } from '../lib/config.js';\nimport { code, info, success, warn } from '../lib/output.js';\n\nexport async function logoutCommand(): Promise<number> {\n let cfg;\n try {\n cfg = readConfig();\n } catch {\n // Corrupt file — clearing it is precisely what `logout` should do.\n deleteConfig();\n success('Cleared a corrupted local credential file.');\n return 0;\n }\n if (!cfg) {\n info('Already logged out (no saved credentials).');\n return 0;\n }\n\n // Best-effort server-side revocation.\n try {\n await apiRequest(\n 'DELETE',\n `/api/auth/cli-tokens/${cfg.tokenId}`,\n undefined,\n { auth: { token: cfg.token }, baseUrl: cfg.apiUrl },\n );\n } catch (err) {\n warn(\n `Could not revoke the server-side token (${(err as Error).message}). Local credentials cleared anyway.`,\n );\n }\n\n deleteConfig();\n success(`Logged out ${code(cfg.user.email)}`);\n return 0;\n}\n","/**\n * `dashwise profile` — show the current user + (briefly) workspaces.\n *\n * Reads the saved config first so the basic identity prints\n * instantly; then makes a live `/api/auth/me` call to refresh the\n * cached profile (network errors are tolerated — we fall back to\n * the cached values and warn).\n *\n * Output is plain key/value to stdout so the command is pipeable\n * (e.g. `dashwise profile | grep email`). For machine-readable\n * output a future `--json` flag is the right call.\n */\n\nimport { ApiError, apiRequest } from '../lib/api-client.js';\nimport type { AuthMeResponse, WorkspaceListItem } from '../lib/backend-types.js';\nimport { readConfig, writeConfig } from '../lib/config.js';\nimport { code, dim, fail, info, kv, out, warn } from '../lib/output.js';\n\nexport interface ProfileOptions {\n /** Emit the profile + workspaces as a single JSON object instead of human-readable kv pairs. */\n json?: boolean;\n}\n\nexport async function profileCommand(options: ProfileOptions = {}): Promise<number> {\n const cfg = readConfig();\n if (!cfg) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'NOT_LOGGED_IN', message: 'Run `dashwise login` first.' } }));\n } else {\n fail('Not logged in. Run `dashwise login` first.');\n }\n return 1;\n }\n\n // Refresh identity. Tolerate transient network errors.\n let me: AuthMeResponse | null = null;\n let refreshError: string | null = null;\n try {\n me = await apiRequest<AuthMeResponse>('GET', '/api/auth/me');\n } catch (err) {\n if (err instanceof ApiError && err.status === 401) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'TOKEN_INVALID', message: 'Saved token is no longer valid.' } }));\n } else {\n fail('Saved token is no longer valid. Run `dashwise login` again.');\n }\n return 1;\n }\n refreshError = (err as Error).message;\n if (!options.json) {\n warn(\n `Could not refresh profile from the server (${refreshError}). Showing cached values.`,\n );\n }\n }\n\n if (me) {\n // Persist any drift between cached + server values.\n const refreshed = {\n ...cfg,\n user: {\n id: me.id,\n email: me.email,\n username: me.username,\n firstName: me.first_name,\n lastName: me.last_name,\n },\n };\n writeConfig(refreshed);\n }\n const u = (me ?? toMe(cfg.user));\n\n // Workspace list — best-effort.\n let workspaces: WorkspaceListItem[] = [];\n let workspaceError: string | null = null;\n try {\n const fetched = await apiRequest<WorkspaceListItem[]>(\n 'GET',\n '/api/workspaces',\n );\n workspaces = Array.isArray(fetched) ? fetched : [];\n } catch (err) {\n workspaceError = (err as Error).message;\n }\n\n if (options.json) {\n out(\n JSON.stringify({\n ok: true,\n user: {\n id: u.id,\n username: u.username,\n email: u.email,\n first_name: u.first_name,\n last_name: u.last_name,\n },\n default_workspace: cfg.workspaceSlug ?? null,\n workspaces,\n api_url: cfg.apiUrl,\n ...(refreshError ? { profile_refresh_error: refreshError } : {}),\n ...(workspaceError ? { workspaces_error: workspaceError } : {}),\n }),\n );\n return 0;\n }\n\n out('');\n kv('User ID', `${u.id}`);\n kv('Username', u.username);\n kv('Email', u.email);\n kv('Name', `${u.first_name} ${u.last_name}`.trim() || dim('(not set)'));\n\n out('');\n if (workspaceError) {\n warn(\n `Could not list workspaces (${workspaceError}). Try \\`dashwise workspace list\\`.`,\n );\n } else if (workspaces.length === 0) {\n info('No workspaces yet.');\n } else {\n kv('Workspaces', `${workspaces.length}`);\n for (const w of workspaces) {\n const slug = w.slug ?? `id:${w.id}`;\n const role = w.role ?? w.permissions ?? '';\n const star = cfg.workspaceSlug === slug ? code(' (default)') : '';\n out(` - ${slug}${role ? dim(` [${role}]`) : ''}${star} ${dim(w.name)}`);\n }\n }\n\n out('');\n kv('API URL', cfg.apiUrl);\n return 0;\n}\n\nfunction toMe(cached: { id: number; email: string; username: string; firstName: string; lastName: string }): AuthMeResponse {\n return {\n id: cached.id,\n email: cached.email,\n username: cached.username,\n first_name: cached.firstName,\n last_name: cached.lastName,\n is_staff: false,\n is_active: true,\n date_joined: '',\n };\n}\n","/**\n * `dashwise workspace list` — list workspaces the user belongs to.\n * `dashwise workspace use <slug>` — set the default workspace (saved\n * to ~/.config/dashwise/auth.json).\n *\n * The \"default workspace\" is consumed by subsequent commands\n * (`module init`, `module publish`, etc.) so the user doesn't have\n * to pass `--workspace <slug>` every time. Persists across\n * `dashwise` invocations until `workspace use` is called again.\n */\n\nimport { ApiError, apiRequest } from '../lib/api-client.js';\nimport type { WorkspaceListItem } from '../lib/backend-types.js';\nimport { readConfig, writeConfig } from '../lib/config.js';\nimport { code, dim, fail, info, kv, out, success } from '../lib/output.js';\n\nexport interface WorkspaceListOptions {\n json?: boolean;\n}\n\nexport async function workspaceListCommand(options: WorkspaceListOptions = {}): Promise<number> {\n const cfg = readConfig();\n if (!cfg) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'NOT_LOGGED_IN', message: 'Run `dashwise login` first.' } }));\n } else {\n fail('Not logged in. Run `dashwise login` first.');\n }\n return 1;\n }\n let workspaces: WorkspaceListItem[];\n try {\n workspaces = await apiRequest<WorkspaceListItem[]>('GET', '/api/workspaces');\n } catch (err) {\n if (err instanceof ApiError && err.status === 401) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'TOKEN_INVALID', message: 'Saved token is no longer valid.' } }));\n } else {\n fail('Saved token is no longer valid. Run `dashwise login` again.');\n }\n return 1;\n }\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'FETCH_FAILED', message: (err as Error).message } }));\n } else {\n fail(`Could not list workspaces: ${(err as Error).message}`);\n }\n return 1;\n }\n if (options.json) {\n out(\n JSON.stringify({\n ok: true,\n default_workspace: cfg.workspaceSlug ?? null,\n workspaces: Array.isArray(workspaces) ? workspaces : [],\n }),\n );\n return 0;\n }\n if (!Array.isArray(workspaces) || workspaces.length === 0) {\n info('No workspaces yet.');\n return 0;\n }\n out('');\n for (const w of workspaces) {\n const slug = w.slug ?? `id:${w.id}`;\n const role = w.role ?? w.permissions ?? '';\n const isDefault = cfg.workspaceSlug === slug;\n const marker = isDefault ? code(' *') : ' ';\n out(`${marker} ${slug.padEnd(28)} ${dim(w.name)}${role ? dim(` [${role}]`) : ''}`);\n }\n out('');\n if (cfg.workspaceSlug) {\n info(`Default workspace: ${code(cfg.workspaceSlug)}`);\n } else {\n info('No default workspace set. Use `dashwise workspace use <slug>` to set one.');\n }\n return 0;\n}\n\nexport async function workspaceUseCommand(slug: string): Promise<number> {\n const cfg = readConfig();\n if (!cfg) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n if (typeof slug !== 'string' || slug.length === 0) {\n fail('Usage: `dashwise workspace use <slug>`');\n return 1;\n }\n // Validate the slug exists + the user has access. Avoids the\n // footgun of setting a default to a workspace the user can't\n // actually use.\n let workspaces: WorkspaceListItem[] = [];\n try {\n workspaces = await apiRequest<WorkspaceListItem[]>('GET', '/api/workspaces');\n } catch (err) {\n fail(`Could not validate the workspace (${(err as Error).message}).`);\n return 1;\n }\n const match = workspaces.find(\n (w) => w.slug === slug || `id:${w.id}` === slug || String(w.id) === slug,\n );\n if (!match) {\n fail(`Workspace ${code(slug)} not found in your accessible workspaces.`);\n out('');\n info('Run `dashwise workspace list` to see what you can choose.');\n return 1;\n }\n const matchedSlug = match.slug ?? `id:${match.id}`;\n writeConfig({ ...cfg, workspaceSlug: matchedSlug });\n success(`Default workspace set to ${code(matchedSlug)}`);\n kv('Name', match.name);\n if (match.role ?? match.permissions) {\n kv('Role', String(match.role ?? match.permissions));\n }\n return 0;\n}\n","/**\n * `dashwise module clone <slug>` — bring a published module's\n * source into a local directory.\n *\n * Two flavors based on what's available on the backend:\n *\n * 1. **Git mode** — when the module's published manifest carries\n * `repository.url`, we shell out to `git clone` to fetch the\n * source. This is the recommended path: full file history,\n * branch awareness, future `git pull` for updates.\n *\n * 2. **Manifest-only mode** — when no `repository.url` is set,\n * we write the published manifest into a fresh directory plus\n * a minimal scaffold (.gitignore, package.json, README) so the\n * user has a workable starting point. They can then layer\n * their own app code on top + run `dashwise module dev`.\n *\n * Refuses to write into a non-empty directory unless `--force` is\n * passed.\n */\n\nimport { spawnSync } from 'node:child_process';\nimport { existsSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { gitignore, packageJson, packageJsonCustom } from '../../lib/scaffold.js';\nimport { code, dim, fail, info, out, success, warn } from '../../lib/output.js';\n\ninterface SourceMetadataResponse {\n module_slug: string;\n module_name: string;\n current_version: string | null;\n repository_url: string | null;\n manifest: Record<string, unknown> | null;\n}\n\nexport interface CloneOptions {\n /** Target directory (default: `./<slug>`). */\n dir?: string;\n /** Overwrite an existing non-empty directory. */\n force?: boolean;\n /** Skip git clone even when repository.url is set (use manifest mode). */\n noGit?: boolean;\n}\n\nexport async function moduleCloneCommand(\n slug: string,\n options: CloneOptions,\n): Promise<number> {\n if (!slug) {\n fail('Usage: `dashwise module clone <slug>`');\n return 1;\n }\n\n let meta: SourceMetadataResponse;\n try {\n meta = await apiRequest<SourceMetadataResponse>(\n 'GET',\n `/api/modules/${encodeURIComponent(slug)}/source-tarball`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n fail(`Module ${code(slug)} not found.`);\n return 1;\n }\n if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n if (err instanceof ApiError && err.status === 403) {\n fail(`No access to module ${code(slug)}. You must be a member of its owner workspace.`);\n return 1;\n }\n fail(`Could not fetch module metadata: ${(err as Error).message}`);\n return 1;\n }\n\n const target = resolve(options.dir ?? slug);\n\n // Refuse to overwrite an existing non-empty directory unless --force.\n if (existsSync(target)) {\n const entries = readdirSync(target);\n if (entries.length > 0 && !options.force) {\n fail(\n `Directory ${code(target)} is not empty. Pass ${code('--force')} to clone anyway.`,\n );\n return 1;\n }\n }\n\n // Decide between git mode + manifest-only fallback.\n const wantGit = !options.noGit && meta.repository_url !== null;\n if (wantGit) {\n return cloneViaGit(meta, target);\n }\n\n if (meta.repository_url !== null && options.noGit) {\n info(`--no-git: skipping git clone for ${code(meta.repository_url)}; writing manifest-only scaffold.`);\n } else {\n info(`Module ${code(slug)} has no ${code('repository.url')}; writing manifest-only scaffold.`);\n }\n return cloneViaManifest(slug, meta, target);\n}\n\n/**\n * Shell out to `git clone <url> <target>`. Inherits stdio so the\n * user sees git's progress + error messages directly. Returns 0 on\n * success, propagating git's exit code on failure.\n */\nfunction cloneViaGit(meta: SourceMetadataResponse, target: string): number {\n const repoUrl = meta.repository_url!;\n info(`Cloning ${code(repoUrl)} into ${code(target)}...`);\n const result = spawnSync('git', ['clone', repoUrl, target], {\n stdio: 'inherit',\n });\n if (result.error) {\n fail(`Failed to invoke git: ${result.error.message}`);\n return 1;\n }\n if (result.status !== 0) {\n fail(`git clone exited with status ${result.status}.`);\n return result.status ?? 1;\n }\n success(`Cloned ${code(meta.module_slug)} from ${code(repoUrl)}.`);\n if (meta.current_version) {\n info(`Current published version: ${code(`v${meta.current_version}`)}`);\n }\n return 0;\n}\n\n/**\n * Fallback when no Git URL is available: lay down `module.json` +\n * `.gitignore` + `package.json` + `README.md` so the user has a\n * starting point. The user has to recreate `app/` themselves —\n * we don't have access to the original source (no Git URL).\n */\nfunction cloneViaManifest(\n slug: string,\n meta: SourceMetadataResponse,\n target: string,\n): number {\n if (!meta.manifest) {\n fail(\n `Module ${code(slug)} has no published manifest yet (publish at least one version first).`,\n );\n return 1;\n }\n\n mkdirSync(target, { recursive: true });\n\n // Inspect the manifest to pick the right scaffold flavor.\n const manifestObj = meta.manifest as Record<string, unknown>;\n const moduleKind = manifestObj.module_kind === 'custom' ? 'custom' : 'hand_authored';\n const pkgFn = moduleKind === 'custom' ? packageJsonCustom : packageJson;\n\n writeFileSync(\n join(target, 'module.json'),\n JSON.stringify(manifestObj, null, 2) + '\\n',\n 'utf-8',\n );\n writeFileSync(\n join(target, 'package.json'),\n pkgFn({ slug: meta.module_slug, name: meta.module_name, kind: moduleKind }),\n 'utf-8',\n );\n writeFileSync(join(target, '.gitignore'), gitignore(), 'utf-8');\n writeFileSync(\n join(target, 'README.md'),\n readmeForClone(meta, moduleKind),\n 'utf-8',\n );\n\n success(`Wrote ${moduleKind} scaffold for ${code(meta.module_slug)} into ${code(target)}`);\n info(`Next steps:`);\n out('');\n out(` ${dim('1.')} ${code(`cd ${target}`)}`);\n out(` ${dim('2.')} ${code('npm install')}`);\n out(` ${dim('3.')} ${code('dashwise module generate')}`);\n out(` ${dim('4.')} Recreate your ${code('app/')} (manifest-only clone — no source code available).`);\n out('');\n if (meta.repository_url) {\n warn(\n `Module's manifest declared ${code(meta.repository_url)} as its repo; consider running ${code(`dashwise module clone ${slug}`)} without ${code('--no-git')} to get the full source.`,\n );\n } else {\n info(\n `If you have access to the original source, ` +\n `consider running ${code(`dashwise module connect-git <repo-url>`)} ` +\n `so future clones use it.`,\n );\n }\n return 0;\n}\n\nfunction readmeForClone(\n meta: SourceMetadataResponse,\n kind: 'hand_authored' | 'custom',\n): string {\n return `# ${meta.module_name}\n\nManifest-only clone of \\`${meta.module_slug}\\` (${kind}) at version \\`${meta.current_version ?? 'unpublished'}\\`.\n\nThe original source code wasn't available — this directory contains\nonly the published \\`module.json\\` + a starter scaffold. Recreate\n\\`app/\\` based on the manifest.\n\n## Get started\n\n\\`\\`\\`bash\nnpm install\ndashwise module generate\ndashwise module dev\n\\`\\`\\`\n`;\n}\n","/**\n * `dashwise module connect-git <repo-url>` — write the Git repository\n * URL into the local `module.json#repository.url`.\n *\n * v1 scope: local manifest mutation only. The backend reads\n * `repository` from the manifest on the next `module publish` and\n * captures the URL + the actual `commit` + `branch` from the local\n * git working tree at publish time (P5b for the commit-capture\n * follow-up). For now, this command just sets the URL so the\n * marketplace + `module clone` know where to look.\n *\n * The URL is light-validated: must be a real URL, https:// or git@\n * shorthand also accepted. Branch can be passed via `--branch\n * <name>` to default to a non-`main` branch (rare, but common\n * for monorepos).\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { code, fail, info, success } from '../../lib/output.js';\n\nexport interface ConnectGitOptions {\n dir?: string;\n branch?: string;\n}\n\nexport async function moduleConnectGitCommand(\n repoUrl: string,\n options: ConnectGitOptions,\n): Promise<number> {\n if (!repoUrl || typeof repoUrl !== 'string') {\n fail('Usage: `dashwise module connect-git <repo-url>`');\n return 1;\n }\n if (!isPlausibleRepoUrl(repoUrl)) {\n fail(`Repo URL ${code(repoUrl)} doesn't look like https:// or git@host:owner/repo.`);\n return 1;\n }\n\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n fail(\n `No ${code('module.json')} found in ${code(projectRoot)}. Run \\`dashwise module init\\` first.`,\n );\n return 1;\n }\n let manifest: Record<string, unknown>;\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n } catch (err) {\n fail(`Could not parse ${code(manifestPath)}: ${(err as Error).message}`);\n return 1;\n }\n\n const existing = (manifest.repository as Record<string, unknown> | undefined) ?? {};\n const next: Record<string, unknown> = {\n ...existing,\n type: 'git',\n url: repoUrl,\n };\n if (options.branch) {\n next.branch = options.branch;\n } else if (typeof existing.branch === 'string') {\n // Preserve any branch already set.\n next.branch = existing.branch;\n }\n manifest.repository = next;\n\n writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\\n', 'utf-8');\n success(`Connected to ${code(repoUrl)}`);\n if (next.branch) info(`Branch: ${code(String(next.branch))}`);\n info(`Updated ${code('module.json')}.`);\n return 0;\n}\n\n/**\n * Accept three URL shapes commonly used for Git remotes:\n * - https://github.com/org/repo\n * - https://github.com/org/repo.git\n * - git@github.com:org/repo.git\n *\n * Rejects obvious garbage; the backend (or git itself, at clone\n * time) does the real validation.\n */\nfunction isPlausibleRepoUrl(url: string): boolean {\n if (url.startsWith('https://') || url.startsWith('http://')) {\n try {\n new URL(url);\n return true;\n } catch {\n return false;\n }\n }\n // git@host:owner/repo[.git] shorthand\n return /^git@[^:]+:[^/]+\\/.+/.test(url);\n}\n","/**\n * `dashwise module convert [dir]` — turn an EXISTING standalone Next.js\n * app into a DashWise module, idempotently.\n *\n * The \"build standalone now, link to DashWise later\" on-ramp: a developer\n * builds a normal Next.js app, then runs `convert` to inject the module\n * shape (manifest + auth wiring + SDK dep + runtime config). It is\n * deliberately CONSERVATIVE — it creates missing files but never\n * overwrites an author's existing `module.json`, `layout`, or\n * `next.config`; for those it warns with the manual edit needed. Reuses\n * the same file generators as `dashwise module init` so a converted app\n * matches a scaffolded one.\n *\n * Decoupled from any backend module id — `convert` is purely local. Link\n * to DashWise afterwards with `dashwise dev` (local) or `dashwise module\n * publish` (deploy).\n */\n\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n statSync,\n writeFileSync,\n} from 'node:fs';\nimport { basename, dirname, join, resolve } from 'node:path';\nimport {\n appApiAuthCallbackTs,\n appApiAuthSignInTs,\n appApiAuthSignOutTs,\n appLayoutCustomTsx,\n appSignInErrorPageTsx,\n envLocalExample,\n isValidSlug,\n manifestJson,\n middlewareTs,\n type ScaffoldOptions,\n} from '../../lib/scaffold.js';\n\n/** Pinned to match the scaffold's `@dashai/sdk` dependency. */\nconst SDK_DEP_RANGE = '^0.8.0';\n\n/** Source dirs scanned for outbound `https://` hosts (allowlist seeding). */\nconst SCAN_DIRS = ['app', 'src', 'pages', 'lib', 'components'];\nconst SCAN_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.mjs'];\nconst MAX_SCAN_FILES = 2000;\n\nexport interface ConvertResult {\n slug: string;\n name: string;\n /** Files newly written. */\n created: string[];\n /** Files already present, left untouched. */\n skipped: string[];\n /** Manual actions the author must take (we don't auto-edit these). */\n warnings: string[];\n /** Hosts discovered in source + merged into runtime.outbound_apis. */\n outboundApis: string[];\n /** True when an existing custom manifest was missing its runtime block. */\n runtimeBlockAdded: boolean;\n}\n\nfunction deriveSlug(input: string): string {\n return input\n .toLowerCase()\n .replace(/^@[^/]+\\//, '') // drop npm scope\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 63);\n}\n\n/**\n * The convert engine (pure-ish: only touches the target dir). Throws on a\n * non-Next.js dir or an unusable slug; otherwise returns a change report.\n */\nexport function convertModule(opts: {\n dir: string;\n slug?: string;\n name?: string;\n repositoryUrl?: string;\n}): ConvertResult {\n const dir = resolve(opts.dir);\n const pkgPath = join(dir, 'package.json');\n if (!existsSync(pkgPath)) {\n throw new Error(\n 'No package.json found — run `dashwise module convert` inside a Next.js project.',\n );\n }\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8')) as {\n name?: string;\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n const nextConfigFile = ['next.config.mjs', 'next.config.js', 'next.config.ts'].find(\n (f) => existsSync(join(dir, f)),\n );\n const looksNext =\n Boolean(pkg.dependencies?.next || pkg.devDependencies?.next) ||\n nextConfigFile !== undefined ||\n existsSync(join(dir, 'app')) ||\n existsSync(join(dir, 'src', 'app'));\n if (!looksNext) {\n throw new Error(\n 'This does not look like a Next.js app (no `next` dependency, next.config, or app/ directory).',\n );\n }\n\n const slug = opts.slug ?? deriveSlug(pkg.name ?? basename(dir));\n if (!isValidSlug(slug)) {\n throw new Error(\n `Could not derive a valid module slug (\"${slug}\"). Pass --slug (must match /^[a-z][a-z0-9_-]*$/).`,\n );\n }\n const name = opts.name ?? pkg.name ?? slug;\n const sopts: ScaffoldOptions = {\n slug,\n name,\n kind: 'custom',\n ...(opts.repositoryUrl ? { repositoryUrl: opts.repositoryUrl } : {}),\n };\n\n const created: string[] = [];\n const skipped: string[] = [];\n const warnings: string[] = [];\n\n const writeIfMissing = (rel: string, content: string): void => {\n const p = join(dir, rel);\n if (existsSync(p)) {\n skipped.push(rel);\n return;\n }\n mkdirSync(dirname(p), { recursive: true });\n writeFileSync(p, content, 'utf-8');\n created.push(rel);\n };\n\n // 1. The manifest (created if missing; normalized below either way).\n writeIfMissing('module.json', manifestJson(sopts));\n\n // 2. Edge auth middleware + the SSO route handlers + error page.\n writeIfMissing('middleware.ts', middlewareTs());\n writeIfMissing('app/api/auth/sign-in/route.ts', appApiAuthSignInTs());\n writeIfMissing('app/api/auth/callback/route.ts', appApiAuthCallbackTs());\n writeIfMissing('app/api/auth/sign-out/route.ts', appApiAuthSignOutTs());\n writeIfMissing('app/sign-in-error/page.tsx', appSignInErrorPageTsx());\n writeIfMissing('.env.local.example', envLocalExample());\n\n // 3. Layout: only create if absent; never rewrite the author's layout.\n const layoutFile = [\n 'app/layout.tsx',\n 'app/layout.jsx',\n 'src/app/layout.tsx',\n ].find((f) => existsSync(join(dir, f)));\n if (!layoutFile) {\n writeIfMissing('app/layout.tsx', appLayoutCustomTsx(sopts));\n } else if (!readFileSync(join(dir, layoutFile), 'utf-8').includes('AuthProvider')) {\n warnings.push(\n `${layoutFile}: wrap your tree in <AuthProvider> from \"@dashai/sdk/auth/client\" so client components can read the session.`,\n );\n } else {\n skipped.push(layoutFile);\n }\n\n // 4. next.config: ensure output:'standalone' (the module runtime bundle\n // harvests `.next/standalone/server.js`). Create when absent; warn\n // when present but missing it — we don't edit arbitrary configs.\n if (!nextConfigFile) {\n writeIfMissing('next.config.mjs', standaloneNextConfig());\n } else if (!readFileSync(join(dir, nextConfigFile), 'utf-8').includes('standalone')) {\n warnings.push(\n `${nextConfigFile}: add \\`output: 'standalone'\\` — required for the module runtime bundle.`,\n );\n }\n\n // 5. @dashai/sdk dependency.\n if (!pkg.dependencies?.['@dashai/sdk']) {\n pkg.dependencies = { ...(pkg.dependencies ?? {}), '@dashai/sdk': SDK_DEP_RANGE };\n writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\\n', 'utf-8');\n created.push('package.json (added @dashai/sdk)');\n }\n\n // 6. Scan source for outbound https hosts → merge into the manifest's\n // allowlist, and normalize the manifest (ensure custom + runtime).\n const outboundApis = scanOutboundHosts(dir);\n const runtimeBlockAdded = normalizeManifest(join(dir, 'module.json'), {\n slug,\n name,\n outboundApis,\n });\n\n return {\n slug,\n name,\n created,\n skipped,\n warnings,\n outboundApis,\n runtimeBlockAdded,\n };\n}\n\nfunction standaloneNextConfig(): string {\n return `/** @type {import(\"next\").NextConfig} */\nconst nextConfig = {\n output: 'standalone',\n typescript: { ignoreBuildErrors: true },\n eslint: { ignoreDuringBuilds: true },\n};\nexport default nextConfig;\n`;\n}\n\n/**\n * Ensure module.json is a `custom`/`machine` manifest and merge any\n * discovered outbound hosts into `runtime.outbound_apis`. Returns true if\n * a missing runtime block was added (so the caller can surface it).\n */\nfunction normalizeManifest(\n manifestPath: string,\n opts: { slug: string; name: string; outboundApis: string[] },\n): boolean {\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as Record<\n string,\n unknown\n >;\n let runtimeAdded = false;\n\n if (manifest.module_kind === undefined) manifest.module_kind = 'custom';\n\n let runtime = manifest.runtime as Record<string, unknown> | undefined;\n if (manifest.module_kind === 'custom' && !runtime) {\n runtime = {\n type: 'nextjs',\n kind: 'machine',\n machine_size: 'shared-cpu-1x',\n server_actions: true,\n };\n manifest.runtime = runtime;\n runtimeAdded = true;\n }\n\n if (runtime && opts.outboundApis.length > 0) {\n const existing = Array.isArray(runtime.outbound_apis)\n ? (runtime.outbound_apis as string[])\n : [];\n runtime.outbound_apis = Array.from(\n new Set([...existing, ...opts.outboundApis]),\n ).sort();\n }\n\n writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\\n', 'utf-8');\n return runtimeAdded;\n}\n\n/** Walk source dirs and collect distinct external `https://` hostnames. */\nexport function scanOutboundHosts(dir: string): string[] {\n const hosts = new Set<string>();\n let scanned = 0;\n const hostRe = /https:\\/\\/([a-zA-Z0-9.-]+)/g;\n\n const walk = (abs: string): void => {\n if (scanned >= MAX_SCAN_FILES) return;\n let entries: string[];\n try {\n entries = readdirSync(abs);\n } catch {\n return;\n }\n for (const entry of entries) {\n if (entry === 'node_modules' || entry.startsWith('.')) continue;\n const p = join(abs, entry);\n let st;\n try {\n st = statSync(p);\n } catch {\n continue;\n }\n if (st.isDirectory()) {\n walk(p);\n } else if (SCAN_EXTENSIONS.some((e) => entry.endsWith(e))) {\n if (scanned >= MAX_SCAN_FILES) return;\n scanned++;\n let body: string;\n try {\n body = readFileSync(p, 'utf-8');\n } catch {\n continue;\n }\n for (const m of body.matchAll(hostRe)) {\n const host = m[1].toLowerCase();\n if (host === 'localhost' || host.endsWith('.local')) continue;\n // Skip the DashWise API itself + plain ip-ish noise.\n if (host.includes('dashwise')) continue;\n if (/^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(host)) continue;\n hosts.add(host);\n }\n }\n }\n };\n\n for (const d of SCAN_DIRS) {\n const abs = join(dir, d);\n if (existsSync(abs)) walk(abs);\n }\n // Emit full `https://<host>` patterns — the manifest's\n // runtime.outbound_apis schema (RUNTIME_OUTBOUND_PATTERN_REGEX) requires\n // the scheme; a bare host is rejected at publish/generate time.\n return Array.from(hosts, (h) => `https://${h}`).sort();\n}\n\n/** CLI wrapper: run convert, print a change report, return an exit code. */\nexport async function moduleConvertCommand(opts: {\n dir?: string;\n slug?: string;\n name?: string;\n git?: string;\n}): Promise<number> {\n try {\n const result = convertModule({\n dir: opts.dir ?? process.cwd(),\n ...(opts.slug !== undefined ? { slug: opts.slug } : {}),\n ...(opts.name !== undefined ? { name: opts.name } : {}),\n ...(opts.git !== undefined ? { repositoryUrl: opts.git } : {}),\n });\n\n console.log(`Converted \"${result.name}\" (slug: ${result.slug}) to a DashWise module.\\n`);\n if (result.created.length) {\n console.log(' Created:');\n for (const f of result.created) console.log(` + ${f}`);\n }\n if (result.skipped.length) {\n console.log(' Left as-is:');\n for (const f of result.skipped) console.log(` · ${f}`);\n }\n if (result.runtimeBlockAdded) {\n console.log(' + module.json: added runtime block (nextjs/machine)');\n }\n if (result.outboundApis.length) {\n console.log(\n ` + module.json runtime.outbound_apis: ${result.outboundApis.join(', ')}`,\n );\n }\n if (result.warnings.length) {\n console.log('\\n Manual steps needed:');\n for (const w of result.warnings) console.log(` ! ${w}`);\n }\n console.log(\n '\\nNext: `npm install`, then `dashwise dev` to run it against DashWise, or `dashwise module publish` to deploy.',\n );\n return 0;\n } catch (err) {\n console.error(\n `convert failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n return 1;\n }\n}\n","/**\n * `dashwise module export [dir]` — package a local module into a portable\n * `<slug>.zip` in the exact shape the operator ZIP-import expects\n * (`POST /api/admin/modules/import/zip` / the HQ \"Import ZIP\" action):\n * `module.json` at the archive root, no wrapper directory, with deps /\n * build output / VCS / local env files excluded.\n *\n * Closes the round-trip: a developer builds + `convert`s a module, runs\n * `export`, and hands the ZIP to an operator who deploys it. Purely local\n * — no login, no backend call.\n *\n * Note: the operator import commits text files only, so binary assets\n * (images/fonts) in the ZIP are dropped on import. They're still included\n * here so the archive is a faithful copy of the module.\n */\n\nimport {\n existsSync,\n readFileSync,\n readdirSync,\n statSync,\n} from 'node:fs';\nimport { basename, join, relative, resolve, sep } from 'node:path';\nimport AdmZip from 'adm-zip';\n\n/** Directory names never packaged (deps / build output / VCS) — mirrors the\n * backend extractor's ignore set so the round-trip is predictable. */\nconst IGNORE_DIRS = new Set([\n 'node_modules',\n '.git',\n '.next',\n '.turbo',\n '.vercel',\n 'dist',\n 'build',\n 'out',\n 'coverage',\n '.cache',\n]);\n\n/** Mirror the import limits so `export` warns before producing an un-importable ZIP. */\nconst MAX_FILES = 5_000;\nconst MAX_TOTAL_BYTES = 25 * 1024 * 1024; // 25 MiB\n\nexport interface ExportResult {\n slug: string;\n name: string;\n outPath: string;\n fileCount: number;\n totalBytes: number;\n /** True when content exceeds the import's caps (the ZIP may be rejected). */\n exceedsImportLimits: boolean;\n}\n\nfunction deriveSlug(input: string): string {\n return input\n .toLowerCase()\n .replace(/^@[^/]+\\//, '')\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 63);\n}\n\n/**\n * A local env file carries secrets and must NEVER ship — EXCEPT `*.example`\n * templates, which are safe and useful to the importer.\n */\nfunction isLocalEnvSecret(name: string): boolean {\n if (name.endsWith('.example')) return false;\n return name === '.env' || name.startsWith('.env.');\n}\n\n/**\n * Package the module at `dir` into a ZIP at `out` (default `<slug>.zip` in\n * the cwd). Throws on a missing/invalid `module.json` or an empty result.\n */\nexport function exportModule(opts: { dir: string; out?: string }): ExportResult {\n const dir = resolve(opts.dir);\n const manifestPath = join(dir, 'module.json');\n if (!existsSync(manifestPath)) {\n throw new Error(\n 'No module.json found — point at a module directory (run `dashwise module convert` first if needed).',\n );\n }\n let manifest: { name?: string; slug?: string };\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as {\n name?: string;\n slug?: string;\n };\n } catch (err) {\n throw new Error(`module.json is not valid JSON: ${(err as Error).message}`);\n }\n\n const slug =\n manifest.slug?.trim() || deriveSlug(manifest.name?.trim() || basename(dir));\n const name = manifest.name?.trim() || slug;\n const outPath = resolve(opts.out ?? `${slug}.zip`);\n\n const zip = new AdmZip();\n let fileCount = 0;\n let totalBytes = 0;\n\n const walk = (abs: string): void => {\n let entries: string[];\n try {\n entries = readdirSync(abs);\n } catch {\n return;\n }\n for (const entry of entries) {\n const p = join(abs, entry);\n let st;\n try {\n st = statSync(p);\n } catch {\n continue;\n }\n if (st.isDirectory()) {\n if (IGNORE_DIRS.has(entry)) continue;\n walk(p);\n continue;\n }\n if (isLocalEnvSecret(entry)) continue;\n // Never package the output ZIP into itself.\n if (resolve(p) === outPath) continue;\n // Repo-relative path, forward slashes — lands at the archive root.\n const rel = relative(dir, p).split(sep).join('/');\n const data = readFileSync(p);\n zip.addFile(rel, data);\n fileCount += 1;\n totalBytes += data.length;\n if (fileCount > MAX_FILES) {\n throw new Error(\n `Too many files (> ${MAX_FILES}); the import limit would reject this archive. Is a build-output dir not being ignored?`,\n );\n }\n }\n };\n walk(dir);\n\n if (fileCount === 0 || !zip.getEntry('module.json')) {\n throw new Error('Nothing to export (no module.json reached the archive).');\n }\n zip.writeZip(outPath);\n\n return {\n slug,\n name,\n outPath,\n fileCount,\n totalBytes,\n exceedsImportLimits: totalBytes > MAX_TOTAL_BYTES,\n };\n}\n\nfunction humanSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / 1024 / 1024).toFixed(1)} MB`;\n}\n\n/** CLI wrapper: run export, print a summary, return an exit code. */\nexport async function moduleExportCommand(opts: {\n dir?: string;\n out?: string;\n}): Promise<number> {\n try {\n const result = exportModule({\n dir: opts.dir ?? process.cwd(),\n ...(opts.out !== undefined ? { out: opts.out } : {}),\n });\n\n console.log(\n `Exported \"${result.name}\" → ${relative(process.cwd(), result.outPath) || result.outPath} ` +\n `(${result.fileCount} files, ${humanSize(result.totalBytes)}).`,\n );\n console.log(\n '\\nImport-ready: an operator can deploy it via the HQ admin panel (\"Import ZIP\")\\n' +\n 'or POST /api/admin/modules/import/zip. module.json is at the archive root.',\n );\n console.log(\n 'Note: binary assets (images/fonts) are dropped on import (text-only commit);\\n' +\n 'node_modules, build output, .git, and local .env files were excluded.',\n );\n if (result.exceedsImportLimits) {\n console.warn(\n `\\n⚠ Uncompressed content exceeds the import's 25 MiB cap — the ZIP may be rejected.`,\n );\n }\n return 0;\n } catch (err) {\n console.error(\n `export failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n return 1;\n }\n}\n","/**\n * `dashwise module register [dir]` — link an EXISTING local module to\n * DashWise.\n *\n * The \"link later\" half of the build-standalone-now flow: after\n * `dashwise module convert` (or hand-authoring a `module.json`), this\n * creates the backend module record + a local-dev installation and\n * caches the runtime token in `~/.config/dashwise/auth.json#modules[slug]`\n * — exactly what `dashwise init` does as its provisioning step, but\n * against the EXISTING directory (no scaffolding). After it succeeds,\n * `dashwise dev` runs the app against DashWise (auth + data) and\n * `dashwise module publish` can deploy it.\n *\n * Reuses `POST /api/installations/dev` (which creates the module via\n * `ModulesService.createDraft` + mints the token). The manifest's\n * `owns.tables` are NOT pushed here (the draft starts empty, same as\n * `init`); add them with `dashwise table create` once registered.\n */\n\nimport {\n isLoggedIn,\n readConfig,\n resolveApiUrl,\n upsertModuleEntry,\n} from '../../lib/config.js';\nimport { code, fail, info, success, warn } from '../../lib/output.js';\nimport { readManifest } from '../../lib/manifest-io.js';\nimport { selectWorkspace } from '../../lib/workspaces.js';\nimport {\n ApiError,\n createDevInstallation,\n type DevInstallationResponse,\n} from '../../lib/api-client.js';\n\nconst MODULE_KINDS = ['ai_builder', 'hand_authored', 'custom'] as const;\ntype ModuleKind = (typeof MODULE_KINDS)[number];\n\nexport async function moduleRegisterCommand(opts: {\n dir?: string;\n workspace?: string;\n name?: string;\n}): Promise<number> {\n // 1. Read the local manifest (the thing that makes this a module).\n let manifest;\n try {\n manifest = readManifest(opts.dir);\n } catch (err) {\n fail(`Could not read module.json: ${(err as Error).message}`);\n return 1;\n }\n if (!manifest) {\n fail(\n `No module.json found${opts.dir ? ` in ${opts.dir}` : ' in the current directory'}. ` +\n `Run ${code('dashwise module convert')} (existing app) or ${code('dashwise init')} (new) first.`,\n );\n return 1;\n }\n const slug = manifest.module?.slug;\n if (!slug || typeof slug !== 'string') {\n fail('module.json is missing `module.slug`.');\n return 1;\n }\n const name =\n opts.name ?? (typeof manifest.module?.name === 'string' ? manifest.module.name : slug);\n const moduleKind: ModuleKind | undefined = MODULE_KINDS.includes(\n manifest.module_kind as ModuleKind,\n )\n ? (manifest.module_kind as ModuleKind)\n : undefined;\n const description =\n typeof manifest.module?.description === 'string'\n ? manifest.module.description\n : undefined;\n\n // 2. Require login.\n if (!isLoggedIn()) {\n fail(`Not logged in. Run ${code('dashwise login')} first.`);\n return 1;\n }\n const cfg = readConfig();\n if (!cfg) {\n fail(`CLI config missing. Run ${code('dashwise login')}.`);\n return 1;\n }\n\n // 3. Resolve the target workspace (flag or interactive picker).\n let workspace: { id: number; slug: string };\n try {\n workspace = await selectWorkspace({\n apiUrl: resolveApiUrl(),\n apiToken: cfg.token,\n ...(opts.workspace !== undefined ? { flag: opts.workspace } : {}),\n interactive: true,\n });\n } catch (err) {\n fail(`Workspace selection failed: ${(err as Error).message}`);\n return 1;\n }\n\n // 4. Create the backend module + dev install + runtime token.\n info(\n `Registering \"${name}\" (slug: ${code(slug)}) in workspace ${code(workspace.slug)} (id=${workspace.id})…`,\n );\n let response: DevInstallationResponse;\n try {\n response = await createDevInstallation(\n {\n slug,\n name,\n ...(description !== undefined ? { description } : {}),\n workspaceId: workspace.id,\n ...(moduleKind !== undefined ? { moduleKind } : {}),\n },\n { baseUrl: resolveApiUrl(), auth: { token: cfg.token } },\n );\n } catch (err) {\n if (err instanceof ApiError) {\n if (err.code === 'SLUG_ALREADY_EXISTS') {\n fail(\n `A module with slug \"${slug}\" already exists. Pick a different slug in module.json, or run ${code('dashwise module destroy-dev-install')} to reclaim it.`,\n );\n } else if (err.code === 'FORBIDDEN') {\n fail(`Not a member of workspace \"${workspace.slug}\". Join it, then retry.`);\n } else {\n fail(`Registration failed (${err.code || err.status}): ${err.message}`);\n }\n return 1;\n }\n fail(`Registration failed: ${(err as Error).message}`);\n return 1;\n }\n\n // 5. Cache the runtime token so `dashwise dev` / the SDK pick it up.\n try {\n upsertModuleEntry(slug, {\n runtimeToken: response.runtime_token,\n installationId: response.installation.id,\n expiresAt: response.runtime_token_expires_at,\n });\n } catch (err) {\n warn(\n `Registered (installation id=${response.installation.id}) but failed to cache the runtime token: ${(err as Error).message}\\n` +\n ` Runtime token (save this manually): ${response.runtime_token}\\n` +\n ` Expires: ${response.runtime_token_expires_at}`,\n );\n return 0;\n }\n\n success(\n `Registered \"${name}\" → module #${response.module.id}, dev install #${response.installation.id}. Runtime token cached.`,\n );\n info(\n `Next: ${code('dashwise dev')} to run it against DashWise, or ${code('dashwise module publish')} to deploy. Add tables with ${code('dashwise table create')}.`,\n );\n return 0;\n}\n","/**\n * `dashwise module generate` — regenerate the typed wrappers from the\n * local `module.json`.\n *\n * Flow:\n * 1. Read + parse `<cwd>/module.json`.\n * 2. POST it to `/api/modules/draft/generate-sdk`.\n * 3. Write each returned file to `node_modules/@dashai/generated/<path>`.\n * 4. Print summary (file count + content hash).\n *\n * Idempotent: re-running produces bit-identical output for an\n * unchanged manifest (per the generator's content-hash guarantee).\n * Returning a fresh generation counter on each call is reserved for\n * `module dev` — the one-shot CLI path uses generation=0.\n *\n * Requires the user to be logged in (uses the saved CLI token).\n */\n\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { code, dim, fail, info, success } from '../../lib/output.js';\n\nexport interface GenerateOptions {\n /** Project root containing `module.json` (defaults to `process.cwd()`). */\n dir?: string;\n /** Monotonic counter passed to the generator (default 0). */\n generation?: number;\n /** Skip writing to node_modules — print summary only. */\n dryRun?: boolean;\n}\n\ninterface GenerateResponse {\n files: Record<string, string>;\n contentHash: string;\n}\n\n/** Resolved output directory: `<project>/node_modules/@dashai/generated/`. */\nfunction outputDir(projectRoot: string): string {\n return join(projectRoot, 'node_modules', '@dashai', 'generated');\n}\n\nexport async function moduleGenerateCommand(\n options: GenerateOptions,\n): Promise<number> {\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n fail(\n `No ${code('module.json')} found in ${code(projectRoot)}. Run \\`dashwise module init <slug>\\` first.`,\n );\n return 1;\n }\n let manifest: unknown;\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n } catch (err) {\n fail(`Could not parse ${code(manifestPath)}: ${(err as Error).message}`);\n return 1;\n }\n\n let res: GenerateResponse;\n try {\n res = await apiRequest<GenerateResponse>(\n 'POST',\n '/api/modules/draft/generate-sdk',\n {\n manifest,\n generation: options.generation ?? 0,\n },\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n if (err instanceof ApiError && err.status === 400) {\n fail(`Manifest validation failed: ${err.message}`);\n if (err.context) {\n process.stderr.write(JSON.stringify(err.context, null, 2) + '\\n');\n }\n return 1;\n }\n fail(`Could not generate SDK: ${(err as Error).message}`);\n return 1;\n }\n\n if (options.dryRun) {\n info(`Dry run: ${Object.keys(res.files).length} files`);\n info(`Hash: ${code(res.contentHash)}`);\n return 0;\n }\n\n const out = outputDir(projectRoot);\n // Wipe any prior generated content so a renamed/removed table\n // doesn't leave a stale wrapper file behind. The directory itself\n // is gitignored, so a wipe-then-rewrite is safe.\n if (existsSync(out)) {\n rmSync(out, { recursive: true, force: true });\n }\n mkdirSync(out, { recursive: true });\n for (const [relPath, content] of Object.entries(res.files)) {\n const absPath = join(out, relPath);\n const parent = dirname(absPath);\n if (!existsSync(parent)) {\n mkdirSync(parent, { recursive: true });\n }\n writeFileSync(absPath, content, 'utf-8');\n }\n\n success(\n `Generated ${Object.keys(res.files).length} files into ${code('node_modules/@dashai/generated/')}`,\n );\n info(`Hash: ${dim(res.contentHash)}`);\n return 0;\n}\n","/**\n * `dashwise module dev` — watch `module.json` + auto-regenerate the\n * SDK on every change.\n *\n * Behavior:\n * 1. Read `module.json`; run an initial `module generate` so the\n * caller starts in a coherent state.\n * 2. Watch the manifest file for changes (`fs.watch`).\n * 3. On each change event, debounce 250ms (editor saves often\n * fire two events in quick succession), then regenerate.\n * 4. Bumps the `generation` counter per regen so the emitted\n * `package.json#version` shifts (`0.0.1-gen.N`), invalidating\n * any naïve caches keyed off it.\n * 5. Runs until Ctrl-C (clean exit on SIGINT/SIGTERM).\n *\n * Does NOT spawn `next dev` itself — the user runs that in another\n * terminal. Justification: `next dev`'s own output is dense + we\n * don't want to swallow/buffer it. If users want both, an\n * orchestrator like `npm-run-all` works (`npm run dev:next` and\n * `dashwise module dev` in parallel).\n */\n\nimport { existsSync, watch as fsWatch } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { moduleGenerateCommand } from './generate.js';\nimport { code, dim, fail, info, success, warn } from '../../lib/output.js';\n\nexport interface DevOptions {\n dir?: string;\n /** Debounce window in ms for filesystem change coalescing. */\n debounceMs?: number;\n}\n\nconst DEFAULT_DEBOUNCE_MS = 250;\n\nexport async function moduleDevCommand(options: DevOptions): Promise<number> {\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n fail(`No ${code('module.json')} found in ${code(projectRoot)}.`);\n info('Run `dashwise module init <slug>` to scaffold a new module.');\n return 1;\n }\n\n info(`Watching ${code(manifestPath)} — Ctrl-C to stop.`);\n\n // 1. Initial regen.\n let generation = 0;\n const initial = await moduleGenerateCommand({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n generation,\n });\n if (initial !== 0) {\n warn('Initial regen failed; watcher will retry on the next change.');\n }\n generation += 1;\n\n // 2. Watch loop with debounce. We deliberately use `fs.watch` (vs\n // chokidar) to keep deps small — chokidar weighs ~1MB packed, fs.watch\n // is built-in. Editor saves on macOS sometimes fire 2 events\n // back-to-back; the debounce coalesces them into one regen call.\n const debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;\n let timer: NodeJS.Timeout | null = null;\n let isRunning = false;\n let pendingRegen = false;\n\n async function doRegen() {\n if (isRunning) {\n // Another regen is in flight — flag for re-run when it finishes.\n pendingRegen = true;\n return;\n }\n isRunning = true;\n try {\n const start = Date.now();\n const exit = await moduleGenerateCommand({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n generation,\n });\n const elapsedMs = Date.now() - start;\n if (exit === 0) {\n success(`Regen complete (${elapsedMs}ms, gen=${generation})`);\n } else {\n warn(`Regen failed (exit ${exit}, gen=${generation}) — will retry on next change.`);\n }\n generation += 1;\n } finally {\n isRunning = false;\n if (pendingRegen) {\n pendingRegen = false;\n // Schedule a follow-up — keeps the loop responsive when\n // the user saves rapidly.\n setImmediate(doRegen);\n }\n }\n }\n\n const watcher = fsWatch(manifestPath, (eventType) => {\n if (eventType !== 'change') return;\n if (timer !== null) clearTimeout(timer);\n timer = setTimeout(() => {\n timer = null;\n void doRegen();\n }, debounceMs);\n });\n\n // Clean shutdown.\n return new Promise<number>((resolveExit) => {\n const stop = (signal: NodeJS.Signals | 'shutdown') => {\n if (timer !== null) clearTimeout(timer);\n watcher.close();\n info(`Stopping watcher${signal === 'shutdown' ? '' : ` (${signal})`}.`);\n // Use process.stdout flush hint to ensure the message lands\n // before exit.\n process.stdout.write(dim('Goodbye.\\n'));\n resolveExit(0);\n };\n process.once('SIGINT', () => stop('SIGINT'));\n process.once('SIGTERM', () => stop('SIGTERM'));\n });\n}\n","/**\n * `dashwise module diff` — preview what will change at the next\n * publish vs the currently-published version.\n *\n * Flow:\n * 1. Read local `module.json` for the slug.\n * 2. Resolve `slug → module.id` via `/api/modules/by-slug/:slug`.\n * 3. POST the local manifest to `/api/modules/:id/draft/diff`.\n * 4. Render the structured diff as a readable summary:\n * - \"unchanged\" short-circuit\n * - tables added/removed/changed\n * - dependencies added/removed\n * - top-level meta changes (version, name, module_kind, ...)\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { code, dim, fail, info, out, success } from '../../lib/output.js';\n\ninterface FieldChange {\n field: string;\n changes: Record<string, unknown>;\n}\n\ninterface TableChange {\n table: string;\n fields_added: Array<{ slug: string; type: string }>;\n fields_removed: Array<{ slug: string; type: string }>;\n fields_changed: FieldChange[];\n}\n\ninterface DiffResponse {\n current_version: string | null;\n unchanged: boolean;\n meta_changes: Array<{ field: string; before: unknown; after: unknown }>;\n tables_added: string[];\n tables_removed: string[];\n tables_changed: TableChange[];\n deps_added: Array<{ module: string; version: string }>;\n deps_removed: Array<{ module: string; version: string }>;\n}\n\nexport interface DiffOptions {\n dir?: string;\n /** Emit the structured diff as JSON instead of the human-readable summary. */\n json?: boolean;\n}\n\nexport async function moduleDiffCommand(\n options: DiffOptions,\n): Promise<number> {\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'NO_MANIFEST', message: `No module.json found in ${projectRoot}.` } }));\n } else {\n fail(\n `No ${code('module.json')} found in ${code(projectRoot)}. Run \\`dashwise module init <slug>\\` first.`,\n );\n }\n return 1;\n }\n let manifest: { module?: { slug?: string } };\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n } catch (err) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'MANIFEST_PARSE_FAILED', message: (err as Error).message } }));\n } else {\n fail(`Could not parse ${code(manifestPath)}: ${(err as Error).message}`);\n }\n return 1;\n }\n const slug = manifest.module?.slug;\n if (!slug) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'MANIFEST_MISSING_SLUG', message: 'module.json is missing module.slug.' } }));\n } else {\n fail(`${code('module.json')} is missing ${code('module.slug')}.`);\n }\n return 1;\n }\n\n // Resolve slug → moduleId.\n let mod: { id: number; current_version: string | null };\n try {\n mod = await apiRequest<{ id: number; current_version: string | null }>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(slug)}`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'MODULE_NOT_FOUND', message: `Module ${slug} not found on the backend.` } }));\n } else {\n fail(\n `Module ${code(slug)} not found on the backend. Create + publish it first; `\n + `diff has nothing to compare against until then.`,\n );\n }\n return 1;\n }\n if (err instanceof ApiError && err.status === 401) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'NOT_LOGGED_IN', message: 'Run `dashwise login` first.' } }));\n } else {\n fail('Not logged in. Run `dashwise login` first.');\n }\n return 1;\n }\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'RESOLVE_FAILED', message: (err as Error).message } }));\n } else {\n fail(`Could not resolve module: ${(err as Error).message}`);\n }\n return 1;\n }\n\n let diff: DiffResponse;\n try {\n diff = await apiRequest<DiffResponse>(\n 'POST',\n `/api/modules/${mod.id}/draft/diff`,\n { manifest },\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 400) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'VALIDATION_FAILED', message: err.message, context: err.context ?? null } }));\n } else {\n fail(`Manifest validation failed: ${err.message}`);\n if (err.context) {\n out(JSON.stringify(err.context, null, 2));\n }\n }\n return 1;\n }\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'FETCH_FAILED', message: (err as Error).message } }));\n } else {\n fail(`Could not compute diff: ${(err as Error).message}`);\n }\n return 1;\n }\n\n if (options.json) {\n out(JSON.stringify({ ok: true, ...diff }));\n return 0;\n }\n\n if (diff.unchanged) {\n success(\n `No changes vs ${code(diff.current_version ? `v${diff.current_version}` : '(unpublished)')} — manifest is in sync.`,\n );\n return 0;\n }\n\n // Header.\n out('');\n info(\n diff.current_version\n ? `Diff vs ${code(`v${diff.current_version}`)}:`\n : 'Diff vs ' + code('(unpublished — first version)') + ':',\n );\n\n if (diff.meta_changes.length > 0) {\n out('');\n out(code('Meta:'));\n for (const m of diff.meta_changes) {\n out(` ${m.field}: ${dim(JSON.stringify(m.before))} → ${JSON.stringify(m.after)}`);\n }\n }\n\n if (diff.tables_added.length > 0) {\n out('');\n out(code(`Tables added (${diff.tables_added.length}):`));\n for (const t of diff.tables_added) out(` + ${t}`);\n }\n\n if (diff.tables_removed.length > 0) {\n out('');\n out(code(`Tables removed (${diff.tables_removed.length}):`));\n for (const t of diff.tables_removed) out(` - ${t}`);\n }\n\n if (diff.tables_changed.length > 0) {\n out('');\n out(code(`Tables changed (${diff.tables_changed.length}):`));\n for (const t of diff.tables_changed) {\n out(` ${dim('•')} ${code(t.table)}`);\n for (const f of t.fields_added) {\n out(` + field ${f.slug} (${f.type})`);\n }\n for (const f of t.fields_removed) {\n out(` - field ${f.slug} (${f.type})`);\n }\n for (const f of t.fields_changed) {\n const changeSummary = Object.entries(f.changes)\n .map(([k, v]) => `${k}=${JSON.stringify(v)}`)\n .join(' ');\n out(` ~ field ${f.field}: ${dim(changeSummary)}`);\n }\n }\n }\n\n if (diff.deps_added.length > 0) {\n out('');\n out(code(`Dependencies added (${diff.deps_added.length}):`));\n for (const d of diff.deps_added) {\n out(` + ${d.module}@${d.version}`);\n }\n }\n\n if (diff.deps_removed.length > 0) {\n out('');\n out(code(`Dependencies removed (${diff.deps_removed.length}):`));\n for (const d of diff.deps_removed) {\n out(` - ${d.module}@${d.version}`);\n }\n }\n\n out('');\n info('Run `dashwise module publish --bump <patch|minor|major>` when ready.');\n return 0;\n}\n","/**\n * `dashwise` CLI entry point.\n *\n * commander-based command tree. Each command sits in `./commands/`\n * and returns a numeric exit code; the entry handler awaits the\n * result + sets `process.exitCode` accordingly. Unhandled errors\n * are caught + printed via the shared output helpers.\n */\n\nimport { Command, Option } from 'commander';\nimport { devCommand } from './commands/dev.js';\nimport { loginCommand } from './commands/login.js';\nimport { logoutCommand } from './commands/logout.js';\nimport { profileCommand } from './commands/profile.js';\nimport { workspaceListCommand, workspaceUseCommand } from './commands/workspace.js';\nimport { moduleCloneCommand } from './commands/module/clone.js';\nimport { moduleConnectGitCommand } from './commands/module/connect-git.js';\nimport { moduleConvertCommand } from './commands/module/convert.js';\nimport { moduleExportCommand } from './commands/module/export.js';\nimport { moduleRegisterCommand } from './commands/module/register.js';\nimport { moduleDevCommand } from './commands/module/dev.js';\nimport { moduleDiffCommand } from './commands/module/diff.js';\nimport { moduleGenerateCommand } from './commands/module/generate.js';\nimport { moduleInitCommand } from './commands/module/init.js';\nimport { moduleListCommand } from './commands/module/list.js';\nimport { modulePublishCommand } from './commands/module/publish.js';\nimport { modulePullDataCommand } from './commands/module/pull-data.js';\nimport { moduleValidateCommand } from './commands/module/validate.js';\nimport { depsAddCommand } from './commands/deps/add.js';\nimport { depsCheckCommand } from './commands/deps/check.js';\nimport { depsListCommand } from './commands/deps/list.js';\nimport { depsRemoveCommand } from './commands/deps/remove.js';\nimport { pullCommand } from './commands/pull.js';\nimport { DEPLOY_TARGETS, type DeployTarget } from './lib/scaffold.js';\n// HH-CC-P1-C4 — `dashwise api-keys` subcommands.\nimport {\n apiKeysCreateCommand,\n apiKeysListCommand,\n apiKeysRevokeCommand,\n} from './commands/api-keys.js';\n// HH-CC-P1-D1 — `dashwise env export`.\nimport {\n envExportCommand,\n type EnvExportFormat,\n} from './commands/env-export.js';\nimport { queryCommand } from './commands/query.js';\nimport { moduleQueryLogCommand } from './commands/module/query-log.js';\nimport { moduleActionLogCommand } from './commands/module/action-log.js';\nimport { fail } from './lib/output.js';\n\nconst program = new Command();\n\nprogram\n .name('dashwise')\n .description('DashWise CLI — log in, author modules, publish to the marketplace.')\n .version(getVersion(), '-v, --version', 'Show the CLI version + exit')\n .option(\n '--api-url <url>',\n 'Override DashWise backend URL (default: $DASHWISE_API_URL or saved config or http://localhost:3000)',\n );\n\nprogram\n .command('login')\n .description('Sign in via the device-code flow.')\n .option('--no-prompt', 'Skip the \"open browser\" prompt; just print the URL.')\n .option('--name <name>', 'Suggested name for the minted token (default: dashwise-cli).')\n .action(async (cmdOpts: { prompt?: boolean; name?: string }) => {\n const apiUrl = program.opts<{ apiUrl?: string }>().apiUrl;\n const exit = await loginCommand({\n ...(apiUrl !== undefined ? { apiUrl } : {}),\n noPrompt: cmdOpts.prompt === false,\n ...(cmdOpts.name !== undefined ? { name: cmdOpts.name } : {}),\n });\n process.exitCode = exit;\n });\n\nprogram\n .command('logout')\n .description('Clear the local credentials and revoke the server-side token.')\n .action(async () => {\n process.exitCode = await logoutCommand();\n });\n\nprogram\n .command('profile')\n .description('Show the current user, default workspace, and accessible workspaces.')\n .option('--json', 'Emit JSON to stdout instead of human-readable kv pairs.')\n .action(async (cmdOpts: { json?: boolean }) => {\n process.exitCode = await profileCommand({\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\nconst workspace = program\n .command('workspace')\n .description('Workspace context commands.');\n\nworkspace\n .command('list')\n .description('List accessible workspaces.')\n .option('--json', 'Emit JSON to stdout instead of human-readable columns.')\n .action(async (cmdOpts: { json?: boolean }) => {\n process.exitCode = await workspaceListCommand({\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\nworkspace\n .command('use <slug>')\n .description('Set the default workspace for subsequent commands.')\n .action(async (slug: string) => {\n process.exitCode = await workspaceUseCommand(slug);\n });\n\n// One-command local dev loop. Spawns `dashwise module dev` + `next dev`\n// together with auth env vars auto-injected from the saved CLI config —\n// collapses the historical \"two terminals + manually edit .env.local\"\n// workflow into a single command. Top-level (not under `module`) because\n// it's the daily-driver entry point most developers will spend the most\n// time with.\nprogram\n .command('dev')\n .description(\n 'One-command local dev loop: runs the manifest watcher + Next.js dev server ' +\n 'together. Registers a dev-mode SSO session with the backend so workspace ' +\n 'members can sign into your locally-running module via DashWise SSO (no ' +\n 'installation_id required). Auth + dev-session env auto-injected into ' +\n 'both child processes from your saved CLI config. Run `dashwise login` first.',\n )\n .option('--dir <path>', 'Project root containing `module.json` (default: current directory).')\n .option(\n '--installation-id <id>',\n 'Use prod-mode SSO with this installation id instead of registering a dev session. ' +\n 'The installation must already exist in the target workspace.',\n )\n .option(\n '--workspace <slug-or-id>',\n 'Workspace to scope the dev session to (slug or numeric id). Required if your ' +\n 'account belongs to more than one workspace; auto-picked if you have just one.',\n )\n .option(\n '--callback-origin <url>',\n 'Additional callback origin to allowlist on the dev session (repeatable). ' +\n 'The dev server URL (http://localhost:<port>) is always allowlisted; pass ' +\n 'this for custom-domain local dev (e.g. https://myapp.local).',\n collectRepeated,\n [] as string[],\n )\n .option(\n '--api-url <url>',\n 'Override the `DASHWISE_API_URL` env var passed to children (default: saved CLI config).',\n )\n .option('--port <number>', 'Port for `next dev` (default: 3000).', parseIntOption)\n .option('--sdk-only', 'Only run the manifest watcher; skip `next dev`.')\n .option('--next-only', 'Only run `next dev`; skip the manifest watcher.')\n // HH-CC-P1-E3 — backend manifest poll loop.\n .option(\n '--no-remote-poll',\n 'Disable periodic backend manifest polling. By default, `dashwise dev` polls `GET /api/installations/:id/schema` every few seconds + writes module.json when the backend has advanced (dashboard edits, AI builder mutations, teammate commands).',\n )\n .option(\n '--remote-poll-interval <seconds>',\n 'Backend manifest poll interval, in seconds. Default: 5. Minimum: 1.',\n parseIntOption,\n )\n .action(\n async (cmdOpts: {\n dir?: string;\n installationId?: string;\n workspace?: string;\n callbackOrigin?: string[];\n apiUrl?: string;\n port?: number;\n sdkOnly?: boolean;\n nextOnly?: boolean;\n remotePoll?: boolean; // Commander negates: --no-remote-poll → remotePoll=false\n remotePollInterval?: number;\n }) => {\n process.exitCode = await devCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.installationId !== undefined ? { installationId: cmdOpts.installationId } : {}),\n ...(cmdOpts.workspace !== undefined ? { workspace: cmdOpts.workspace } : {}),\n ...(cmdOpts.callbackOrigin !== undefined && cmdOpts.callbackOrigin.length > 0\n ? { callbackOrigin: cmdOpts.callbackOrigin }\n : {}),\n ...(cmdOpts.apiUrl !== undefined ? { apiUrl: cmdOpts.apiUrl } : {}),\n ...(cmdOpts.port !== undefined ? { port: cmdOpts.port } : {}),\n ...(cmdOpts.sdkOnly !== undefined ? { sdkOnly: cmdOpts.sdkOnly } : {}),\n ...(cmdOpts.nextOnly !== undefined ? { nextOnly: cmdOpts.nextOnly } : {}),\n // Commander's --no-foo flag maps to `foo: false`. devCommand's\n // option is `noRemotePoll: boolean` — invert to map cleanly.\n ...(cmdOpts.remotePoll === false ? { noRemotePoll: true } : {}),\n ...(cmdOpts.remotePollInterval !== undefined\n ? { remotePollIntervalSec: cmdOpts.remotePollInterval }\n : {}),\n });\n },\n );\n\n// FUP-3: top-level alias for `dashwise module init`. The two-command\n// bootstrap (`dashwise login` + `dashwise init`) is the headline daily-\n// driver flow per `building-modules.md` + the LDI v1 plan — making the\n// second command three words (`dashwise module init`) was a paper-cut\n// during the dogfood. This alias preserves both spellings: muscle\n// memory continues to work, the README docs are honest.\nconst initOptions = (cmd: Command): Command =>\n cmd\n .option('--dir <path>', 'Override the target directory (default: ./<slug>).')\n .option('--name <name>', 'Human-readable module name (default: derived from slug).')\n .option('--force', 'Overwrite an existing non-empty directory.')\n .option(\n '--simple',\n 'Use the legacy minimal scaffold (hand-authored, no Next.js auth wiring). Default before 2026-05-18; opt-in now.',\n )\n .option(\n '--custom',\n \"[Deprecated alias — kept for backward compatibility.] Equivalent to the default (full Next.js + auth). Will be removed in a future major version; just call `dashwise init` without flags.\",\n )\n .option('--git <url>', 'Initial Git repository URL — written to module.json#repository.url.')\n // HH-CC-LDI-6 flags.\n .option(\n '--description <text>',\n 'Module description — forwarded to the backend when provisioning the dev installation.',\n )\n .option(\n '--workspace <slug-or-id>',\n 'Target workspace for the dev installation (slug or numeric id). When omitted in a TTY, the CLI prompts; in non-interactive mode it auto-picks when you have one workspace and errors out otherwise.',\n )\n .option(\n '--no-provision',\n 'Skip the `POST /api/installations/dev` step. Local scaffold is still written; you can provision later by re-running `dashwise init --force` (or, once it ships, `dashwise module provision-dev-install`).',\n )\n // HH-CC-P1-D2: optional platform config emission.\n .addOption(\n new Option(\n '--deploy-target <platform>',\n 'Emit a platform deploy config file alongside the scaffold (railway.json | vercel.json | fly.toml). Default: none (clean repo). Pair with `dashwise env export --format <platform>` to push env vars after provisioning.',\n ).choices([...DEPLOY_TARGETS]),\n );\n\ninterface InitCmdOpts {\n dir?: string;\n name?: string;\n force?: boolean;\n simple?: boolean;\n custom?: boolean;\n git?: string;\n description?: string;\n workspace?: string;\n // Commander maps `--no-provision` → `provision: false`.\n provision?: boolean;\n // HH-CC-P1-D2 — commander returns a string narrowed by `.choices(...)`.\n deployTarget?: DeployTarget;\n}\n\nconst initAction = async (slugArg: string | undefined, cmdOpts: InitCmdOpts): Promise<void> => {\n process.exitCode = await moduleInitCommand(slugArg, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.name !== undefined ? { name: cmdOpts.name } : {}),\n ...(cmdOpts.force !== undefined ? { force: cmdOpts.force } : {}),\n ...(cmdOpts.simple !== undefined ? { simple: cmdOpts.simple } : {}),\n ...(cmdOpts.custom !== undefined ? { custom: cmdOpts.custom } : {}),\n ...(cmdOpts.git !== undefined ? { git: cmdOpts.git } : {}),\n ...(cmdOpts.description !== undefined ? { description: cmdOpts.description } : {}),\n ...(cmdOpts.workspace !== undefined ? { workspace: cmdOpts.workspace } : {}),\n ...(cmdOpts.provision !== undefined ? { provision: cmdOpts.provision } : {}),\n ...(cmdOpts.deployTarget !== undefined ? { deployTarget: cmdOpts.deployTarget } : {}),\n });\n};\n\ninitOptions(\n program\n .command('init [slug]')\n .description(\n 'Scaffold a new DashWise module — full Next.js app with auth wiring + SSO callback + protected dashboard. Pass --simple for the legacy minimal scaffold (no auth). Top-level alias for `dashwise module init`.',\n ),\n).action(initAction);\n\nconst moduleCmd = program\n .command('module')\n .description('Module authoring commands.');\n\ninitOptions(\n moduleCmd\n .command('init [slug]')\n .description(\n 'Scaffold a new DashWise module — full Next.js app with auth wiring + SSO callback + protected dashboard. Pass --simple for the legacy minimal scaffold (no auth).',\n ),\n).action(initAction);\n\nmoduleCmd\n .command('connect-git <repo-url>')\n .description('Link the local module to a Git repository (writes module.json#repository).')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--branch <name>', 'Default branch to publish from (e.g. `main`).')\n .action(\n async (repoUrl: string, cmdOpts: { dir?: string; branch?: string }) => {\n process.exitCode = await moduleConnectGitCommand(repoUrl, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.branch !== undefined ? { branch: cmdOpts.branch } : {}),\n });\n },\n );\n\nmoduleCmd\n .command('convert [dir]')\n .description(\n 'Convert an EXISTING Next.js app into a DashWise module — idempotently inject module.json, auth wiring, the SDK dep, and output:standalone. Creates missing files; warns (never overwrites) for an existing layout/next.config/module.json.',\n )\n .option('--slug <slug>', 'Module slug (default: derived from package.json name / dir).')\n .option('--name <name>', 'Human-readable module name (default: package.json name).')\n .option('--git <url>', 'Git repository URL — written to module.json#repository.url.')\n .action(\n async (\n dir: string | undefined,\n cmdOpts: { slug?: string; name?: string; git?: string },\n ) => {\n process.exitCode = await moduleConvertCommand({\n ...(dir !== undefined ? { dir } : {}),\n ...(cmdOpts.slug !== undefined ? { slug: cmdOpts.slug } : {}),\n ...(cmdOpts.name !== undefined ? { name: cmdOpts.name } : {}),\n ...(cmdOpts.git !== undefined ? { git: cmdOpts.git } : {}),\n });\n },\n );\n\nmoduleCmd\n .command('register [dir]')\n .description(\n 'Link an existing local module (a directory with module.json — e.g. after `module convert`) to DashWise: creates the backend module record + a dev install and caches the runtime token, so `dashwise dev` / `publish` work. Requires login.',\n )\n .option('--workspace <slug-or-id>', 'Target workspace (default: interactive picker).')\n .option('--name <name>', 'Override the module name (default: module.json name).')\n .action(\n async (\n dir: string | undefined,\n cmdOpts: { workspace?: string; name?: string },\n ) => {\n process.exitCode = await moduleRegisterCommand({\n ...(dir !== undefined ? { dir } : {}),\n ...(cmdOpts.workspace !== undefined ? { workspace: cmdOpts.workspace } : {}),\n ...(cmdOpts.name !== undefined ? { name: cmdOpts.name } : {}),\n });\n },\n );\n\nmoduleCmd\n .command('export [dir]')\n .description(\n 'Package a local module into a portable <slug>.zip (module.json at the root, deps/build-output/VCS/local-.env excluded) — the exact shape the operator ZIP-import (HQ \"Import ZIP\" / POST /api/admin/modules/import/zip) expects. Closes the build → export → operator-deploy round-trip.',\n )\n .option('--out <path>', 'Output ZIP path (default: <slug>.zip in the current directory).')\n .action(\n async (dir: string | undefined, cmdOpts: { out?: string }) => {\n process.exitCode = await moduleExportCommand({\n ...(dir !== undefined ? { dir } : {}),\n ...(cmdOpts.out !== undefined ? { out: cmdOpts.out } : {}),\n });\n },\n );\n\nmoduleCmd\n .command('generate')\n .description(\"Regenerate typed wrappers from the local module.json into node_modules/@dashai/generated/.\")\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--dry-run', 'Print summary without writing files.')\n .action(async (cmdOpts: { dir?: string; dryRun?: boolean }) => {\n process.exitCode = await moduleGenerateCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.dryRun !== undefined ? { dryRun: cmdOpts.dryRun } : {}),\n });\n });\n\nmoduleCmd\n .command('dev')\n .description('Watch module.json + regenerate typed wrappers on every save. Ctrl-C to stop.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--debounce-ms <n>', 'Filesystem change debounce window (default: 250ms).', parseIntOption)\n .action(async (cmdOpts: { dir?: string; debounceMs?: number }) => {\n process.exitCode = await moduleDevCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.debounceMs !== undefined ? { debounceMs: cmdOpts.debounceMs } : {}),\n });\n });\n\nmoduleCmd\n .command('validate')\n .description('Validate the local module.json against the backend manifest validator.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .action(async (cmdOpts: { dir?: string }) => {\n process.exitCode = await moduleValidateCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n });\n });\n\nmoduleCmd\n .command('list')\n .description('List modules you own (or `--all` for owned + public).')\n .option('--all', 'Include public modules you can install but do not own.')\n .option('--workspace <slug>', 'Filter by workspace slug (default: saved default workspace).')\n .option('--json', 'Emit JSON to stdout instead of column-aligned text.')\n .action(async (cmdOpts: { all?: boolean; workspace?: string; json?: boolean }) => {\n process.exitCode = await moduleListCommand({\n ...(cmdOpts.all !== undefined ? { all: cmdOpts.all } : {}),\n ...(cmdOpts.workspace !== undefined ? { workspace: cmdOpts.workspace } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\nmoduleCmd\n .command('diff')\n .description('Show what would change at the next publish vs the currently-published version.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--json', 'Emit the structured diff as JSON instead of the human-readable summary.')\n .action(async (cmdOpts: { dir?: string; json?: boolean }) => {\n process.exitCode = await moduleDiffCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\nmoduleCmd\n .command('pull-data')\n .description(\"Export the module's own-table rows to a local JSON file (for fixtures, local dev seeding).\")\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--limit <n>', 'Max rows per table (1-1000, default 100).', parseIntOption)\n .option('--out <path>', 'Output file path (default: ./dashwise-data.json).')\n .action(async (cmdOpts: { dir?: string; limit?: number; out?: string }) => {\n process.exitCode = await modulePullDataCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.limit !== undefined ? { limit: cmdOpts.limit } : {}),\n ...(cmdOpts.out !== undefined ? { out: cmdOpts.out } : {}),\n });\n });\n\nmoduleCmd\n .command('clone <slug>')\n .description('Clone a published module locally. Uses git if repository.url is set, else writes a manifest-only scaffold.')\n .option('--dir <path>', 'Target directory (default: ./<slug>).')\n .option('--force', 'Overwrite an existing non-empty directory.')\n .option('--no-git', 'Skip git clone even when repository.url is set; use the manifest-only scaffold.')\n .action(\n async (\n slug: string,\n cmdOpts: { dir?: string; force?: boolean; git?: boolean },\n ) => {\n // commander maps `--no-git` to `git: false`; convert to our internal shape.\n process.exitCode = await moduleCloneCommand(slug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.force !== undefined ? { force: cmdOpts.force } : {}),\n ...(cmdOpts.git === false ? { noGit: true } : {}),\n });\n },\n );\n\nconst depsCmd = program\n .command('deps')\n .description('Cross-module dependency commands (manipulate module.json#dependencies).');\n\ndepsCmd\n .command('list')\n .description('List declared cross-module dependencies.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--json', 'Emit JSON to stdout instead of human-readable columns.')\n .action(async (cmdOpts: { dir?: string; json?: boolean }) => {\n process.exitCode = await depsListCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\ndepsCmd\n .command('add <provider-slug>')\n .description(\n 'Declare a cross-module dependency. Interactive in TTY (picks tables + fields from the provider\\'s exposes); non-interactive requires --table, --fields, --purpose.',\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--table <slug>', 'Provider table slug to read from (non-interactive mode).')\n .option('--fields <list>', 'Comma-separated field slugs for --table (non-interactive mode).')\n .option('--purpose <text>', 'Human-readable explanation (10-500 chars, shown at install consent).')\n .option('--version <range>', 'SemVer range to pin (default: ^<provider-current-version>).')\n .option('-y, --yes', 'Skip the replace-existing confirmation prompt.')\n .action(\n async (\n providerSlug: string,\n cmdOpts: {\n dir?: string;\n table?: string;\n fields?: string;\n purpose?: string;\n version?: string;\n yes?: boolean;\n },\n ) => {\n process.exitCode = await depsAddCommand(providerSlug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.table !== undefined ? { table: cmdOpts.table } : {}),\n ...(cmdOpts.fields !== undefined ? { fields: cmdOpts.fields } : {}),\n ...(cmdOpts.purpose !== undefined ? { purpose: cmdOpts.purpose } : {}),\n ...(cmdOpts.version !== undefined ? { version: cmdOpts.version } : {}),\n ...(cmdOpts.yes !== undefined ? { yes: cmdOpts.yes } : {}),\n });\n },\n );\n\ndepsCmd\n .command('remove <provider-slug>')\n .description('Remove a declared cross-module dependency.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('-y, --yes', 'Skip the confirmation prompt.')\n .action(async (providerSlug: string, cmdOpts: { dir?: string; yes?: boolean }) => {\n process.exitCode = await depsRemoveCommand(providerSlug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.yes !== undefined ? { yes: cmdOpts.yes } : {}),\n });\n });\n\ndepsCmd\n .command('check')\n .description('Verify each declared dep still resolves to a published provider + that every field/op is still exposed. Exits 1 on drift.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--json', 'Emit a JSON drift report to stdout.')\n .action(async (cmdOpts: { dir?: string; json?: boolean }) => {\n process.exitCode = await depsCheckCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\nprogram\n .command('query')\n .description(\n 'Run a typed query against the local module installation via @dashai/sdk/query. ' +\n 'Pass one of `--inline \"<expr>\"`, `--file <path>`, or `--repl`. ' +\n '`qb`, `deps`, `db` are pre-bound to the local module\\'s generated SDK.',\n )\n .option('--dir <path>', 'Project root containing `module.json` (default: current directory).')\n .option('--inline <expression>', 'Evaluate a one-liner. e.g., `qb.tasks.where({done:false}).count()`.')\n .option('--file <path>', 'Dynamic-import a .mjs/.js file. Default export = Query | AggQuery | Promise | value.')\n .option('--repl', 'Open an interactive Node REPL with the generated SDK pre-bound. Top-level await supported.')\n .option('--json', 'Emit compact JSON (default: pretty-printed).')\n .option(\n '--explain',\n 'Call .explain() instead of .execute() — returns the Postgres plan + estimatedCost without executing the query. MVP supports joined queries; bare own/dep/view paths reject with EXPLAIN_NOT_SUPPORTED_YET.',\n )\n .option(\n '--stream',\n 'Call .stream() instead of .execute() — prints rows incrementally as JSON-lines (one row per line). Lets you see progress on big queries + Ctrl-C cleanly midway. Mutually exclusive with --explain and --repl.',\n )\n .action(\n async (cmdOpts: {\n dir?: string;\n inline?: string;\n file?: string;\n repl?: boolean;\n json?: boolean;\n explain?: boolean;\n stream?: boolean;\n }) => {\n process.exitCode = await queryCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.inline !== undefined ? { inline: cmdOpts.inline } : {}),\n ...(cmdOpts.file !== undefined ? { file: cmdOpts.file } : {}),\n ...(cmdOpts.repl !== undefined ? { repl: cmdOpts.repl } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n ...(cmdOpts.explain !== undefined ? { explain: cmdOpts.explain } : {}),\n ...(cmdOpts.stream !== undefined ? { stream: cmdOpts.stream } : {}),\n });\n },\n );\n\n// HH-CC-P1-E2 — `dashwise pull`. Top-level (sibling of `dev`, `login`,\n// `query`) because pulling the manifest is part of the daily-driver\n// loop: dashboard-side schema edits, AI-builder mutations, or\n// teammate-driven changes show up via this primitive.\nprogram\n .command('pull')\n .description(\n 'Sync local module.json from the backend. Fetches the canonical manifest for the current install and writes it to disk. Inverse of `dashwise table/field` commands.',\n )\n .option('--dir <path>', 'Project root containing `module.json` (default: current directory).')\n .option('--dry-run', 'Fetch + report drift but do not write to module.json.')\n .action(async (cmdOpts: { dir?: string; dryRun?: boolean }) => {\n process.exitCode = await pullCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.dryRun !== undefined ? { dryRun: cmdOpts.dryRun } : {}),\n });\n });\n\n// HH-CC-P1-C4 — `dashwise api-keys` subcommand group.\n// Pairs with the backend P1-C1 minting endpoint + P1-C2 runtime-guard\n// recognition. Top-level (sibling of `dev`, `pull`) because API keys\n// are a daily-driver concept for module authors deploying to Railway\n// / Vercel / Fly — not buried under `module`.\nconst apiKeysCmd = program\n .command('api-keys')\n .description(\n 'Manage per-installation API keys (`dwk_*`). Pasted into a deployed module\\'s env for production data-plane auth.',\n );\n\napiKeysCmd\n .command('list')\n .description(\n 'List API keys for the current module\\'s installation. Active only by default; pass --all for revoked too.',\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--all', 'Include revoked + expired keys in the output.')\n .option('--json', 'Emit JSON instead of the human-friendly table.')\n .action(async (cmdOpts: { dir?: string; all?: boolean; json?: boolean }) => {\n process.exitCode = await apiKeysListCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.all !== undefined ? { all: cmdOpts.all } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\napiKeysCmd\n .command('create [name]')\n .description(\n 'Mint a new API key. The plaintext key is displayed ONCE — save it then.',\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--name <name>', 'Override the positional name arg (e.g. for scripted use).')\n .option(\n '--scopes <csv>',\n 'Comma-separated scope strings (e.g. `runtime:read,runtime:write`). Default: full install access.',\n )\n .option(\n '--expires-at <iso>',\n 'ISO-8601 expiry timestamp (e.g. 2026-12-31T23:59:59Z). Default: never expires.',\n )\n .option(\n '--raw-only',\n 'Print only the plaintext key on stdout; chatter goes to stderr. Useful for shell capture: `KEY=$(dashwise api-keys create prod --raw-only)`',\n )\n .action(\n async (\n nameArg: string | undefined,\n cmdOpts: {\n dir?: string;\n name?: string;\n scopes?: string;\n expiresAt?: string;\n rawOnly?: boolean;\n },\n ) => {\n process.exitCode = await apiKeysCreateCommand(nameArg, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.name !== undefined ? { name: cmdOpts.name } : {}),\n ...(cmdOpts.scopes !== undefined ? { scopes: cmdOpts.scopes } : {}),\n ...(cmdOpts.expiresAt !== undefined\n ? { expiresAt: cmdOpts.expiresAt }\n : {}),\n ...(cmdOpts.rawOnly !== undefined ? { rawOnly: cmdOpts.rawOnly } : {}),\n });\n },\n );\n\napiKeysCmd\n .command('revoke [key-id]')\n .description(\n 'Soft-revoke an API key. Backend keeps the row for audit; further requests return 401.',\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('-y, --yes', 'Skip the per-key confirmation message (for CI / scripts).')\n .action(\n async (\n keyIdArg: string | undefined,\n cmdOpts: { dir?: string; yes?: boolean },\n ) => {\n process.exitCode = await apiKeysRevokeCommand(keyIdArg, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.yes !== undefined ? { yes: cmdOpts.yes } : {}),\n });\n },\n );\n\n// HH-CC-P1-D1 — `dashwise env [...]` subcommand group. Today: just\n// `export`. Future home for `env get` / `env set` if we add a\n// CLI-managed config surface beyond what the deploy story needs.\nconst envCmd = program\n .command('env')\n .description('Environment-variable helpers for deploying a module.');\n\nenvCmd\n .command('export')\n .description(\n \"Emit the env vars a deployed module needs to authenticate against DashWise. By default emits .env-style KEY=value lines; --format = env | json | railway | vercel | fly to wrap in platform-native syntax. Use --new-key <name> to mint + inline an API key in one step.\",\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option(\n '--format <fmt>',\n 'Output format: env | json | railway | vercel | fly (default: env).',\n )\n .option(\n '--new-key <name>',\n 'Mint a fresh API key with this name and inline the plaintext. (Mutually exclusive with --key.)',\n )\n .option(\n '--key <dwk_value>',\n 'Use a previously-minted API key (paste plaintext). (Mutually exclusive with --new-key.)',\n )\n .action(\n async (cmdOpts: {\n dir?: string;\n format?: string;\n newKey?: string;\n key?: string;\n }) => {\n process.exitCode = await envExportCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.format !== undefined\n ? { format: cmdOpts.format as EnvExportFormat }\n : {}),\n ...(cmdOpts.newKey !== undefined ? { newKey: cmdOpts.newKey } : {}),\n ...(cmdOpts.key !== undefined ? { key: cmdOpts.key } : {}),\n });\n },\n );\n\nmoduleCmd\n .command('publish')\n .description('Pack the current directory + upload it as a new module version.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--bump <direction>', 'Semver bump: patch | minor | major.')\n .option('--dry-run', 'Validate + upload but do not persist the version row.')\n .option('-y, --yes', 'Skip the confirmation prompt (for CI / scripted use).')\n .option(\n '--exclude <pattern...>',\n 'Extra exclude patterns (segment-matched) appended to the defaults.',\n )\n .action(\n async (cmdOpts: {\n dir?: string;\n bump?: 'patch' | 'minor' | 'major';\n dryRun?: boolean;\n yes?: boolean;\n exclude?: string[];\n }) => {\n process.exitCode = await modulePublishCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.bump !== undefined ? { bump: cmdOpts.bump } : {}),\n ...(cmdOpts.dryRun !== undefined ? { dryRun: cmdOpts.dryRun } : {}),\n ...(cmdOpts.yes !== undefined ? { yes: cmdOpts.yes } : {}),\n ...(cmdOpts.exclude !== undefined ? { exclude: cmdOpts.exclude } : {}),\n });\n },\n );\n\n// Phase 6 slice 6.4 (2026-05-19): per-module SDK query log reader.\n// Workspace-member-scoped on the backend.\nmoduleCmd\n .command('query-log')\n .description(\n 'Read the per-module SDK query log. Default: 50 most recent entries. ' +\n '`--slow` filters to duration_ms > 500ms; `--since 1h` narrows by time; ' +\n '`--tail` streams new entries every 5s.',\n )\n .option(\n '--module <id-or-slug>',\n 'Module to inspect (default: slug from current directory\\'s module.json).',\n )\n .option('--slow', 'Filter to slow queries only (duration_ms > 500).')\n .option(\n '--since <duration>',\n 'Only entries newer than this. Accepts \"30m\", \"1h\", \"6h\", \"2d\", \"7d\", or an ISO 8601 timestamp.',\n )\n .option('--limit <n>', 'Max rows per fetch (1-500, default 50).', parseIntOption)\n .option('--tail', 'Poll every 5s for new entries. Ctrl-C to stop.')\n .option('--json', 'Emit compact JSON instead of the table. Ignored with --tail.')\n .option('--dir <path>', 'Override project directory for module.json lookup.')\n .action(\n async (cmdOpts: {\n module?: string;\n slow?: boolean;\n since?: string;\n limit?: number;\n tail?: boolean;\n json?: boolean;\n dir?: string;\n }) => {\n process.exitCode = await moduleQueryLogCommand({\n ...(cmdOpts.module !== undefined ? { module: cmdOpts.module } : {}),\n ...(cmdOpts.slow !== undefined ? { slow: cmdOpts.slow } : {}),\n ...(cmdOpts.since !== undefined ? { since: cmdOpts.since } : {}),\n ...(cmdOpts.limit !== undefined ? { limit: cmdOpts.limit } : {}),\n ...(cmdOpts.tail !== undefined ? { tail: cmdOpts.tail } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n });\n },\n );\n\n// P7 slice 7.5b (2026-05-20): per-installation server-action audit log.\n// Follow-up (2026-05-20): added `--module <slug>` resolver.\nmoduleCmd\n .command('action-log')\n .description(\n 'Read the per-installation server-action audit log. Shows both ' +\n 'cross-module and own-module dispatches. Filter by role (caller / ' +\n 'provider), slow, since, cross-module-only. `--tail` streams new ' +\n 'entries every 5s. Pass either `--installation <id>` or ' +\n '`--module <slug>` (slug resolves to your accessible installation).',\n )\n .option(\n '--installation <id>',\n 'Installation id to inspect. Mutually exclusive with `--module`.',\n parseIntOption,\n )\n .option(\n '--module <slug>',\n \"Module slug. Resolves to the caller's accessible installation of \" +\n 'that module (first match if multi-workspace). Mutually exclusive with `--installation`.',\n )\n .option(\n '--role <caller|provider>',\n \"Which side of cross-module dispatches to show. 'caller' (default) \" +\n \"shows outbound; 'provider' shows inbound calls on this installation.\",\n )\n .option('--slow', 'Filter to slow actions only (elapsed_ms > 500).')\n .option('--cross-module-only', 'Hide own-module dispatches (cross_module=false rows).')\n .option(\n '--since <duration>',\n 'Only entries newer than this. Accepts \"30m\", \"1h\", \"6h\", \"2d\", \"7d\", or an ISO 8601 timestamp.',\n )\n .option('--limit <n>', 'Max rows per fetch (1-500, default 50).', parseIntOption)\n .option('--tail', 'Poll every 5s for new entries. Ctrl-C to stop.')\n .option('--json', 'Emit compact JSON instead of the table. Ignored with --tail.')\n .action(\n async (cmdOpts: {\n installation?: number;\n module?: string;\n role?: string;\n slow?: boolean;\n crossModuleOnly?: boolean;\n since?: string;\n limit?: number;\n tail?: boolean;\n json?: boolean;\n }) => {\n if (cmdOpts.role !== undefined && cmdOpts.role !== 'caller' && cmdOpts.role !== 'provider') {\n fail(`--role must be 'caller' or 'provider' (got \"${cmdOpts.role}\").`);\n process.exitCode = 1;\n return;\n }\n process.exitCode = await moduleActionLogCommand({\n ...(cmdOpts.installation !== undefined ? { installation: cmdOpts.installation } : {}),\n ...(cmdOpts.module !== undefined ? { module: cmdOpts.module } : {}),\n ...(cmdOpts.role !== undefined ? { role: cmdOpts.role as 'caller' | 'provider' } : {}),\n ...(cmdOpts.slow !== undefined ? { slow: cmdOpts.slow } : {}),\n ...(cmdOpts.crossModuleOnly !== undefined ? { crossModuleOnly: cmdOpts.crossModuleOnly } : {}),\n ...(cmdOpts.since !== undefined ? { since: cmdOpts.since } : {}),\n ...(cmdOpts.limit !== undefined ? { limit: cmdOpts.limit } : {}),\n ...(cmdOpts.tail !== undefined ? { tail: cmdOpts.tail } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n },\n );\n\n// ── HH-CC-LDI-9: dashwise module destroy-dev-install + reset-dev-install ──\n\nmoduleCmd\n .command('destroy-dev-install')\n .description(\n \"Destroy the local-dev install for the current module. Tears down the install row + dashboard tile; if the module had no other installs and was never published, drops the module too. Local module.json is preserved (only the cached runtime token + install id in auth.json get cleared).\",\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option(\n '--module <slug>',\n \"Override the module slug (default: read from local module.json). Useful when the project dir is gone but auth.json still has the entry.\",\n )\n .option('-y, --yes', 'Skip the confirmation prompt — for CI.')\n .action(\n async (cmdOpts: { dir?: string; module?: string; yes?: boolean }) => {\n const { destroyDevInstallCommand } = await import(\n './commands/module/destroy-dev-install.js'\n );\n process.exitCode = await destroyDevInstallCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.module !== undefined ? { module: cmdOpts.module } : {}),\n ...(cmdOpts.yes !== undefined ? { yes: cmdOpts.yes } : {}),\n });\n },\n );\n\nmoduleCmd\n .command('reset-dev-install')\n .description(\n 'Destroy + re-provision the local-dev install in one shot. Useful for nuking accumulated test data, refreshing a compromised runtime token, or recovering from a wedged schema state. Keeps local module.json intact.',\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option(\n '--module <slug>',\n 'Override the module slug (default: from local module.json).',\n )\n .option(\n '--workspace <slug-or-id>',\n 'Target workspace for re-provisioning (passed through to `dashwise init`).',\n )\n .option('-y, --yes', 'Skip prompts in both destroy + re-init phases.')\n .action(\n async (cmdOpts: {\n dir?: string;\n module?: string;\n workspace?: string;\n yes?: boolean;\n }) => {\n const { resetDevInstallCommand } = await import(\n './commands/module/reset-dev-install.js'\n );\n process.exitCode = await resetDevInstallCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.module !== undefined ? { module: cmdOpts.module } : {}),\n ...(cmdOpts.workspace !== undefined\n ? { workspace: cmdOpts.workspace }\n : {}),\n ...(cmdOpts.yes !== undefined ? { yes: cmdOpts.yes } : {}),\n });\n },\n );\n\n// ── HH-CC-LDI-8: dashwise table / dashwise field schema commands ──\n\nconst tableCmd = program\n .command('table')\n .description(\n 'Schema commands for the current module — create/delete tables in the dev installation. Requires a per-module dev install (run `dashwise init` first).',\n );\n\ntableCmd\n .command('create <slug>')\n .description(\n 'Create a new table. Pass --field flags to define columns. Calls POST /api/installations/:id/schema/tables and syncs the updated manifest back to local module.json.',\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option(\n '-f, --field <spec>',\n \"Field spec — `<slug>:<type>[:required]`. Repeat for multiple fields. For options/target/default, use --field-json instead. Example: `--field title:text:required --field done:boolean`.\",\n (val: string, prev: string[] = []) => [...prev, val],\n [] as string[],\n )\n .option(\n '--field-json <json>',\n \"Field as a JSON object — `{slug,type,required?,options?,target?,default?}`. Repeatable. Use for fields where the simple syntax can't express the shape.\",\n (val: string, prev: string[] = []) => [...prev, val],\n [] as string[],\n )\n .action(\n async (\n slug: string | undefined,\n cmdOpts: { dir?: string; field?: string[]; fieldJson?: string[] },\n ) => {\n const { tableCreateCommand } = await import('./commands/table/create.js');\n process.exitCode = await tableCreateCommand(slug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.field !== undefined ? { field: cmdOpts.field } : {}),\n ...(cmdOpts.fieldJson !== undefined ? { fieldJson: cmdOpts.fieldJson } : {}),\n });\n },\n );\n\ntableCmd\n .command('delete <slug>')\n .description(\n \"Drop a table. Calls DELETE /api/installations/:id/schema/tables/:slug — the physical table is soft-deleted (recoverable for 30 days via the dashboard's trash). Updates local module.json.\",\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .action(async (slug: string | undefined, cmdOpts: { dir?: string }) => {\n const { tableDeleteCommand } = await import('./commands/table/delete.js');\n process.exitCode = await tableDeleteCommand(slug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n });\n });\n\nconst fieldCmd = program\n .command('field')\n .description(\n 'Schema commands for fields within the current module — add/remove/change-type. Field rename is deferred to v1.1 per the plan.',\n );\n\nfieldCmd\n .command('add <table-slug> [field-spec]')\n .description(\n \"Add a field to a table. Pass the spec as `<slug>:<type>[:required]` OR use --field-json for fields with options/target/default. Example: `dashwise field add tasks priority --field-json '{\\\"slug\\\":\\\"priority\\\",\\\"type\\\":\\\"single_select\\\",\\\"options\\\":[\\\"low\\\",\\\"medium\\\",\\\"high\\\"]}'`.\",\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option(\n '--field-json <json>',\n \"Field as a JSON object. Mutually exclusive with the positional field spec.\",\n )\n .action(\n async (\n tableSlug: string | undefined,\n fieldSpec: string | undefined,\n cmdOpts: { dir?: string; fieldJson?: string },\n ) => {\n const { fieldAddCommand } = await import('./commands/field/add.js');\n process.exitCode = await fieldAddCommand(tableSlug, fieldSpec, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.fieldJson !== undefined ? { fieldJson: cmdOpts.fieldJson } : {}),\n });\n },\n );\n\nfieldCmd\n .command('remove <table-slug> <field-slug>')\n .description(\n 'Remove a field from a table. The backend cascades index cleanup (M2-C-FIX): any index referencing the removed field is trimmed; empty indexes are dropped.',\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .action(\n async (\n tableSlug: string | undefined,\n fieldSlug: string | undefined,\n cmdOpts: { dir?: string },\n ) => {\n const { fieldRemoveCommand } = await import('./commands/field/remove.js');\n process.exitCode = await fieldRemoveCommand(tableSlug, fieldSlug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n });\n },\n );\n\nfieldCmd\n .command('set-type <table-slug> <field-slug> <new-type>')\n .description(\n \"Change a field's type (e.g. text → long_text). Lossy changes (text → number with non-numeric data) are rejected by the backend's manifest validator today; v1.1 will add a structured RETYPE_UNSAFE precheck.\",\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .action(\n async (\n tableSlug: string | undefined,\n fieldSlug: string | undefined,\n newType: string | undefined,\n cmdOpts: { dir?: string },\n ) => {\n const { fieldSetTypeCommand } = await import('./commands/field/set-type.js');\n process.exitCode = await fieldSetTypeCommand(\n tableSlug,\n fieldSlug,\n newType,\n {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n },\n );\n },\n );\n\n// Single async entry so unhandled errors hit the same formatter.\n(async () => {\n try {\n await program.parseAsync(process.argv);\n } catch (err) {\n fail(`Unhandled error: ${(err as Error).message ?? String(err)}`);\n if (process.env.DASHWISE_DEBUG) {\n // Print full stack when debugging — opt-in to keep normal\n // output uncluttered.\n // eslint-disable-next-line no-console\n console.error(err);\n }\n process.exitCode = 1;\n }\n})();\n\n/**\n * CLI version, injected at build time by tsup's `define` from\n * `packages/cli/package.json#version`. See tsup.config.ts.\n */\ndeclare const __CLI_VERSION__: string;\n\nfunction getVersion(): string {\n return __CLI_VERSION__;\n}\n\n/** commander helper: parse a `<n>` argument as an integer. */\nfunction parseIntOption(value: string): number {\n const n = Number.parseInt(value, 10);\n if (!Number.isFinite(n)) {\n throw new Error(`Expected an integer, got '${value}'`);\n }\n return n;\n}\n\n/**\n * commander helper: collect repeated `--option <value>` flags into\n * an array. Use as the third arg to `.option()` along with `[]` as\n * the default (fourth arg).\n *\n * Example: `--callback-origin http://localhost:3000 --callback-origin https://myapp.local`\n * yields `['http://localhost:3000', 'https://myapp.local']`.\n */\nfunction collectRepeated(value: string, previous: string[]): string[] {\n return [...previous, value];\n}\n","/**\n * `dashwise module list` — list modules the current user can author.\n *\n * Hits `GET /api/modules?owned_only=true` so the listing scope is\n * \"modules I own\" by default. Add `--all` to include public modules\n * the user could install but doesn't own. Workspace filter (`--workspace\n * <slug>`) narrows further when the user has multiple workspaces.\n *\n * Output is plain text — column-aligned slug + version + name — so\n * it pipes cleanly into grep / awk.\n */\n\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { readConfig } from '../../lib/config.js';\nimport { code, dim, fail, info, out } from '../../lib/output.js';\n\nexport interface ModuleListOptions {\n /** Include public modules (default: false — owned only). */\n all?: boolean;\n /**\n * Filter by workspace slug. Falls back to the saved default if\n * omitted, no filter if neither.\n */\n workspace?: string;\n /** Emit JSON to stdout instead of column-aligned text. */\n json?: boolean;\n}\n\ninterface ModuleSummary {\n id: number;\n slug: string;\n name: string;\n owner_workspace_id: number;\n current_version: string | null;\n verified: boolean;\n public: boolean;\n}\n\nexport async function moduleListCommand(\n options: ModuleListOptions,\n): Promise<number> {\n const cfg = readConfig();\n if (!cfg) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'NOT_LOGGED_IN', message: 'Run `dashwise login` first.' } }));\n } else {\n fail('Not logged in. Run `dashwise login` first.');\n }\n return 1;\n }\n\n // Resolve workspaceId from slug if requested.\n let workspaceId: number | undefined;\n const targetSlug = options.workspace ?? cfg.workspaceSlug;\n if (targetSlug) {\n try {\n const workspaces = await apiRequest<Array<{ id: number; slug?: string }>>(\n 'GET',\n '/api/workspaces',\n );\n const match = workspaces.find((w) => w.slug === targetSlug);\n if (!match) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'WORKSPACE_NOT_FOUND', message: `Workspace ${targetSlug} not found.` } }));\n } else {\n fail(\n `Workspace ${code(targetSlug)} not found in your accessible workspaces. Run \\`dashwise workspace list\\` to see the choices.`,\n );\n }\n return 1;\n }\n workspaceId = match.id;\n } catch (err) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'FETCH_FAILED', message: (err as Error).message } }));\n } else {\n fail(`Could not load workspaces: ${(err as Error).message}`);\n }\n return 1;\n }\n }\n\n // Build query.\n const params = new URLSearchParams();\n if (!options.all) params.set('owned_only', 'true');\n if (workspaceId !== undefined) params.set('workspaceId', String(workspaceId));\n const path = `/api/modules${params.toString() ? `?${params.toString()}` : ''}`;\n\n let modules: ModuleSummary[];\n try {\n modules = await apiRequest<ModuleSummary[]>('GET', path);\n } catch (err) {\n if (err instanceof ApiError && err.status === 401) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'NOT_LOGGED_IN', message: 'Run `dashwise login` first.' } }));\n } else {\n fail('Not logged in. Run `dashwise login` first.');\n }\n return 1;\n }\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'FETCH_FAILED', message: (err as Error).message } }));\n } else {\n fail(`Could not list modules: ${(err as Error).message}`);\n }\n return 1;\n }\n\n if (options.json) {\n out(\n JSON.stringify({\n ok: true,\n modules: Array.isArray(modules) ? modules : [],\n total: Array.isArray(modules) ? modules.length : 0,\n }),\n );\n return 0;\n }\n\n if (!Array.isArray(modules) || modules.length === 0) {\n info(\n options.all\n ? 'No modules found.'\n : 'No modules owned by you yet. Use `dashwise module init <slug>` to scaffold one.',\n );\n return 0;\n }\n\n // Column-aligned plain output. Two passes: compute widths, then format.\n const slugWidth = Math.max(...modules.map((m) => m.slug.length), 4);\n const versionWidth = Math.max(\n ...modules.map((m) => (m.current_version ?? '(draft)').length),\n 7,\n );\n out('');\n out(\n `${'SLUG'.padEnd(slugWidth)} ${'VERSION'.padEnd(versionWidth)} NAME`,\n );\n out(\n `${'-'.repeat(slugWidth)} ${'-'.repeat(versionWidth)} ${'-'.repeat(20)}`,\n );\n for (const m of modules) {\n const version = m.current_version ?? '(draft)';\n const flags = [\n m.verified ? code('✓') : '',\n m.public ? dim('public') : '',\n ]\n .filter(Boolean)\n .join(' ');\n const flagsCol = flags ? ` ${flags}` : '';\n out(`${m.slug.padEnd(slugWidth)} ${version.padEnd(versionWidth)} ${m.name}${flagsCol}`);\n }\n out('');\n info(`${modules.length} module${modules.length === 1 ? '' : 's'}.`);\n return 0;\n}\n","/**\n * `dashwise module publish` — package the local project + upload it\n * as a new module version.\n *\n * Steps:\n * 1. Read local `module.json` to get the slug + module_kind.\n * 2. Resolve `slug → module_id` via `GET /api/modules/by-slug/:slug`.\n * 3. Pack `cwd` into a gzipped tarball via `packTarball()`. The\n * tarball excludes node_modules / .next / .git / .dashwise +\n * caps per-file at 10MB and total at 100MB (matches backend).\n * 4. POST the tarball as multipart form-data to\n * `/api/modules/:id/publish/cli` with the user's bump + flags.\n * 5. Print the resulting version + bundle hash.\n *\n * Confirms before uploading (in TTY) unless `--yes` is passed —\n * publish is the one command where a typo costs a real version bump.\n *\n * Tarball bytes live in memory (≤100MB) — no temp file. We use\n * the native `FormData` + `Blob` available on Node 18+.\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { intro, isCancel, outro, select } from '@clack/prompts';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { readConfig, resolveApiUrl } from '../../lib/config.js';\nimport { code, dim, fail, info, out, success, warn } from '../../lib/output.js';\nimport { MAX_TARBALL_BYTES, packTarball } from '../../lib/tarball.js';\n\nexport interface PublishOptions {\n /** Project root containing `module.json` (defaults to `process.cwd()`). */\n dir?: string;\n /** SemVer bump direction; required. */\n bump?: 'patch' | 'minor' | 'major';\n /** Dry run: send `dry_run=true`; backend validates without persisting. */\n dryRun?: boolean;\n /** Skip the confirmation prompt (CI / scripted runs). */\n yes?: boolean;\n /** Additional exclude patterns appended to the defaults. */\n exclude?: string[];\n}\n\ninterface ModuleByslugResponse {\n id: number;\n slug: string;\n name: string;\n current_version: string | null;\n}\n\ninterface PublishResponse {\n module_version_id: number;\n module_slug: string;\n version: string;\n bundle_url: string;\n bundle_hash: string;\n bytes_uploaded: number;\n publisher_type: string;\n verified: boolean;\n warnings: string[];\n pipeline_version: string;\n}\n\nconst VALID_BUMP = new Set(['patch', 'minor', 'major']);\n\nexport async function modulePublishCommand(\n options: PublishOptions,\n): Promise<number> {\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n fail(\n `No ${code('module.json')} found in ${code(projectRoot)}. Run \\`dashwise module init <slug>\\` first.`,\n );\n return 1;\n }\n let manifest: { module?: { slug?: string; name?: string; version?: string } };\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n } catch (err) {\n fail(`Could not parse ${code(manifestPath)}: ${(err as Error).message}`);\n return 1;\n }\n const slug = manifest.module?.slug;\n if (!slug) {\n fail(`${code('module.json')} is missing ${code('module.slug')}. Cannot publish.`);\n return 1;\n }\n\n if (!readConfig()) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n\n // Resolve / prompt for bump.\n let bump = options.bump;\n if (!bump && process.stdout.isTTY) {\n intro(`Publishing module ${code(slug)}`);\n const answer = await select({\n message: 'Bump direction?',\n options: [\n { value: 'patch', label: 'patch — bug fixes only (recommended for first publish)' },\n { value: 'minor', label: 'minor — additive changes (new fields, new tables)' },\n { value: 'major', label: 'major — breaking changes' },\n ],\n initialValue: 'patch',\n });\n if (isCancel(answer)) {\n fail('Aborted.');\n return 130;\n }\n bump = answer as 'patch' | 'minor' | 'major';\n }\n if (!bump || !VALID_BUMP.has(bump)) {\n fail('Bump direction required: `--bump patch|minor|major`.');\n return 1;\n }\n\n // Resolve slug → module id.\n let mod: ModuleByslugResponse;\n try {\n mod = await apiRequest<ModuleByslugResponse>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(slug)}`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n fail(\n `Module ${code(slug)} not found on the backend. Create it via the UI / API first, then re-run publish.`,\n );\n return 1;\n }\n if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n fail(`Could not resolve module: ${(err as Error).message}`);\n return 1;\n }\n\n info(\n `Module: ${code(mod.slug)} (id ${mod.id})${\n mod.current_version ? `, current ${code(`v${mod.current_version}`)}` : dim(', no published version yet')\n }`,\n );\n\n // Pack tarball.\n let tarball;\n try {\n tarball = await packTarball({\n cwd: projectRoot,\n ...(options.exclude !== undefined ? { extraExclude: options.exclude } : {}),\n });\n } catch (err) {\n fail(`Could not pack tarball: ${(err as Error).message}`);\n return 1;\n }\n info(\n `Packed ${tarball.filesIncluded.length} file${tarball.filesIncluded.length === 1 ? '' : 's'} into ${formatBytes(tarball.bytes.byteLength)} (cap ${formatBytes(MAX_TARBALL_BYTES)}).`,\n );\n for (const w of tarball.warnings) warn(w);\n\n // Confirm.\n if (!options.yes && process.stdout.isTTY && !options.dryRun) {\n const answer = await select({\n message: `Upload + publish ${code(`bump:${bump}`)}?`,\n options: [\n { value: 'go', label: 'Yes, upload now' },\n { value: 'cancel', label: 'No, abort' },\n ],\n initialValue: 'go',\n });\n if (isCancel(answer) || answer === 'cancel') {\n fail('Aborted.');\n return 130;\n }\n }\n\n // Multipart upload.\n const cfg = readConfig();\n if (!cfg) {\n fail('Session vanished mid-publish — re-run `dashwise login`.');\n return 1;\n }\n const url = `${resolveApiUrl()}/api/modules/${mod.id}/publish/cli`;\n const form = new FormData();\n // Native `Blob` works in Node 18+; `Buffer` is array-buffer-like\n // so we wrap it before passing to FormData.\n const blob = new Blob([new Uint8Array(tarball.bytes)], { type: 'application/gzip' });\n form.set('file', blob, 'module.tar.gz');\n form.set('bump', bump);\n if (options.dryRun) form.set('dry_run', 'true');\n\n let res: Response;\n try {\n res = await fetch(url, {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n Authorization: `Bearer ${cfg.token}`,\n },\n body: form,\n });\n } catch (err) {\n fail(`Network error during upload: ${(err as Error).message}`);\n return 1;\n }\n\n const body = (await res.json().catch(() => null)) as unknown;\n if (!res.ok) {\n const env = body && typeof body === 'object' ? (body as Record<string, unknown>) : null;\n fail(\n `Publish failed (${res.status}${env?.code ? ` ${env.code}` : ''}): ${env?.message ?? '(no message)'}`,\n );\n if (env?.context) {\n out(JSON.stringify(env.context, null, 2));\n }\n return 1;\n }\n\n const result = body as PublishResponse | null;\n if (!result) {\n fail('Publish succeeded but the response body was empty or malformed.');\n return 1;\n }\n if (options.dryRun) {\n success(`Dry run OK — would publish ${code(`v${result.version}`)}`);\n } else {\n success(`Published ${code(mod.slug)} ${code(`v${result.version}`)}`);\n }\n info(`Bundle: ${code(result.bundle_url)}`);\n info(`Hash: ${dim(result.bundle_hash)}`);\n info(`Size: ${formatBytes(result.bytes_uploaded)}`);\n if (result.warnings.length > 0) {\n warn(`${result.warnings.length} warning${result.warnings.length === 1 ? '' : 's'}:`);\n for (const w of result.warnings) {\n out(` ${dim('•')} ${w}`);\n }\n }\n if (process.stdout.isTTY && !options.dryRun) outro('Done.');\n return 0;\n}\n\nfunction formatBytes(n: number): string {\n if (n < 1024) return `${n}B`;\n if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)}KB`;\n return `${(n / 1024 / 1024).toFixed(1)}MB`;\n}\n","/**\n * Tarball helper for `dashwise module publish`.\n *\n * Wraps the `tar` npm package with DashWise-specific defaults:\n * - gzip compression (server expects `.tar.gz`)\n * - sensible exclusion list (node_modules, .next, .git, ...)\n * - allowlist of files that should ALWAYS be included if present\n * (module.json, manifest.yaml, package.json, app/, server/, etc.)\n * - 100MB size cap (matches backend's `BUNDLE_TOO_LARGE` gate)\n *\n * Output is a `Uint8Array` buffer so callers can pipe it straight\n * into a `fetch` multipart upload without a temp file. The trade-off\n * is memory — but 100MB max is fine for any modern CLI host.\n */\n\nimport { existsSync, readdirSync, statSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport * as tar from 'tar';\n\n/**\n * Patterns that should NEVER be included in the published bundle.\n * Path semantics: a candidate path matches if any segment equals\n * the pattern (e.g. `node_modules` matches `foo/node_modules/bar`).\n *\n * Kept conservative: the backend's per-file policy gate is the\n * security boundary; this list is the UX layer that keeps tarballs\n * tractable and the upload step fast.\n */\nexport const DEFAULT_EXCLUDE_PATTERNS = [\n 'node_modules',\n '.next',\n '.git',\n '.turbo',\n '.dashwise',\n '.DS_Store',\n '.env',\n '.env.local',\n '.env.development.local',\n '.env.test.local',\n '.env.production.local',\n 'coverage',\n '.nyc_output',\n '.vitest-cache',\n '.idea',\n '.vscode',\n 'dist',\n 'build',\n] as const;\n\n/** Per-file size cap. Files larger than this are excluded with a warning. */\nconst PER_FILE_BYTE_LIMIT = 10 * 1024 * 1024; // 10MB\n/** Tarball total cap — matches backend BUNDLE_TOO_LARGE gate. */\nexport const MAX_TARBALL_BYTES = 100 * 1024 * 1024; // 100MB\n\nexport interface TarballResult {\n /** Gzipped tarball bytes ready to upload. */\n bytes: Uint8Array;\n /** Files included (relative paths from `cwd`). Sorted. */\n filesIncluded: string[];\n /** Files skipped + the reason. */\n warnings: string[];\n}\n\n/**\n * Pack `cwd` into a gzipped tarball.\n *\n * The pack walks `cwd` once, applies exclusion rules + per-file size\n * limits, and emits a buffer. We don't stream-to-disk because the\n * 100MB ceiling makes the in-memory path fine + lets the caller\n * `fetch(...)` without a temp file dance.\n *\n * `extraExclude` is appended to the defaults so callers can suppress\n * additional patterns (e.g. local secrets) without forking the list.\n */\nexport async function packTarball(opts: {\n cwd: string;\n extraExclude?: readonly string[];\n}): Promise<TarballResult> {\n if (!existsSync(opts.cwd)) {\n throw new Error(`packTarball: cwd not found at ${opts.cwd}`);\n }\n const excludeSet = new Set<string>([\n ...DEFAULT_EXCLUDE_PATTERNS,\n ...(opts.extraExclude ?? []),\n ]);\n const filesIncluded: string[] = [];\n const warnings: string[] = [];\n const candidates = walk(opts.cwd, excludeSet);\n for (const abs of candidates) {\n const rel = relative(opts.cwd, abs);\n const size = statSync(abs).size;\n if (size > PER_FILE_BYTE_LIMIT) {\n warnings.push(\n `${rel} skipped — ${formatBytes(size)} exceeds ${formatBytes(PER_FILE_BYTE_LIMIT)} per-file cap`,\n );\n continue;\n }\n filesIncluded.push(rel);\n }\n if (filesIncluded.length === 0) {\n throw new Error(\n `packTarball: nothing to pack in ${opts.cwd} (after applying exclude list)`,\n );\n }\n filesIncluded.sort();\n\n // The `tar.c` API streams chunks; collect them into one buffer.\n // We use the lower-level callback form so the result is a single\n // contiguous Uint8Array — the multipart upload step expects that.\n const chunks: Buffer[] = [];\n await new Promise<void>((resolveDone, rejectDone) => {\n const stream = tar.c(\n {\n gzip: true,\n cwd: opts.cwd,\n // Don't follow symlinks — bundle-local content only.\n follow: false,\n // Preserve the exact case of paths; the backend's per-file\n // policy gate keys off these.\n portable: true,\n },\n filesIncluded,\n );\n stream.on('data', (chunk: Buffer) => chunks.push(chunk));\n stream.on('error', rejectDone);\n stream.on('end', resolveDone);\n });\n const bytes = Buffer.concat(chunks);\n if (bytes.byteLength > MAX_TARBALL_BYTES) {\n throw new Error(\n `packTarball: tarball is ${formatBytes(bytes.byteLength)}, exceeds ${formatBytes(MAX_TARBALL_BYTES)} max`,\n );\n }\n return { bytes, filesIncluded, warnings };\n}\n\n// ── helpers ────────────────────────────────────────────────────────────\n\nfunction walk(root: string, excludeSet: Set<string>): string[] {\n const out: string[] = [];\n const stack: string[] = [root];\n while (stack.length > 0) {\n const dir = stack.pop();\n if (!dir) continue;\n let entries: import('node:fs').Dirent[];\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch {\n continue; // unreadable directory — silently skip\n }\n for (const entry of entries) {\n if (excludeSet.has(entry.name)) continue;\n const abs = join(dir, entry.name);\n if (entry.isDirectory()) {\n stack.push(abs);\n } else if (entry.isFile()) {\n out.push(abs);\n }\n // Skip symlinks + sockets + everything else.\n }\n }\n return out;\n}\n\nfunction formatBytes(n: number): string {\n if (n < 1024) return `${n}B`;\n if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)}KB`;\n return `${(n / 1024 / 1024).toFixed(1)}MB`;\n}\n\n// Test seam: expose internals for unit tests without making them\n// part of the public package surface.\nexport const __forTests = {\n walk,\n formatBytes,\n PER_FILE_BYTE_LIMIT,\n};\n","/**\n * `dashwise module pull-data` — export own-table data from the\n * owner-workspace installation to a local JSON file (default\n * `dashwise-data.json` in the project root).\n *\n * Useful for: seeding local dev with production-shaped data,\n * fixture generation, manual inspection. The output shape matches\n * what `db.<table>.list()` would return through the SDK — manifest\n * slugs as keys, NOT physical `field_<id>` names — so the data\n * can be reused as fixtures for unit tests or local API mocks.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { code, dim, fail, info, success, warn } from '../../lib/output.js';\n\nexport interface PullDataOptions {\n dir?: string;\n /** Max rows per table (1-1000, default 100). */\n limit?: number;\n /** Output path (default: `dashwise-data.json` in dir). */\n out?: string;\n}\n\ninterface PullDataResponse {\n module_slug: string;\n module_version: string | null;\n tables: Array<{\n slug: string;\n total_rows: number;\n rows: Array<Record<string, unknown>>;\n }>;\n}\n\nexport async function modulePullDataCommand(\n options: PullDataOptions,\n): Promise<number> {\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n fail(\n `No ${code('module.json')} found in ${code(projectRoot)}. Run \\`dashwise module init <slug>\\` first.`,\n );\n return 1;\n }\n let manifest: { module?: { slug?: string } };\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n } catch (err) {\n fail(`Could not parse ${code(manifestPath)}: ${(err as Error).message}`);\n return 1;\n }\n const slug = manifest.module?.slug;\n if (!slug) {\n fail(`${code('module.json')} is missing ${code('module.slug')}.`);\n return 1;\n }\n\n // Resolve slug → moduleId.\n let mod: { id: number };\n try {\n mod = await apiRequest<{ id: number }>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(slug)}`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n fail(`Module ${code(slug)} not found on the backend.`);\n return 1;\n }\n if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n fail(`Could not resolve module: ${(err as Error).message}`);\n return 1;\n }\n\n const limit = options.limit ?? 100;\n let res: PullDataResponse;\n try {\n res = await apiRequest<PullDataResponse>(\n 'GET',\n `/api/modules/${mod.id}/own-data?limit=${limit}`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 400) {\n fail(`Invalid request: ${err.message}`);\n return 1;\n }\n fail(`Could not pull data: ${(err as Error).message}`);\n return 1;\n }\n\n const outPath = options.out\n ? resolve(options.out)\n : join(projectRoot, 'dashwise-data.json');\n writeFileSync(outPath, JSON.stringify(res, null, 2) + '\\n', 'utf-8');\n\n let totalRows = 0;\n for (const t of res.tables) totalRows += t.rows.length;\n success(`Wrote ${totalRows} row${totalRows === 1 ? '' : 's'} across ${res.tables.length} table${res.tables.length === 1 ? '' : 's'} to ${code(outPath)}`);\n\n // Warn on truncation per table — useful when a table has many\n // more rows than the user grabbed.\n for (const t of res.tables) {\n if (t.total_rows > t.rows.length) {\n warn(\n `Table ${code(t.slug)} truncated: ${t.rows.length} of ${t.total_rows} rows (use ${code(`--limit ${Math.min(t.total_rows, 1000)}`)} to grab more).`,\n );\n }\n }\n if (res.tables.length === 0) {\n info(dim('No owned tables on this module. (Did you publish a manifest with `owns.tables`?)'));\n }\n return 0;\n}\n","/**\n * `dashwise module validate` — run the local `module.json` through\n * the backend's `POST /api/modules/manifest/validate` endpoint.\n *\n * Useful as a pre-publish sanity check: catches structural manifest\n * errors (bad field types, unknown table refs, etc.) before paying\n * the cost of a publish round-trip.\n *\n * Output is structured-by-default: bullet-listed issues on failure,\n * \"Manifest is valid\" on success. Exit code 0 / 1 mirrors the\n * underlying validation result.\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { code, dim, fail, out, success } from '../../lib/output.js';\n\nexport interface ValidateOptions {\n dir?: string;\n}\n\ninterface ValidateOkResponse {\n ok: true;\n manifest: unknown;\n}\n\ninterface ManifestIssue {\n path?: string;\n message?: string;\n}\n\nexport async function moduleValidateCommand(\n options: ValidateOptions,\n): Promise<number> {\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n fail(\n `No ${code('module.json')} found in ${code(projectRoot)}. Run \\`dashwise module init <slug>\\` first.`,\n );\n return 1;\n }\n let manifest: unknown;\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n } catch (err) {\n fail(`Could not parse ${code(manifestPath)}: ${(err as Error).message}`);\n return 1;\n }\n\n try {\n const res = await apiRequest<ValidateOkResponse>(\n 'POST',\n '/api/modules/manifest/validate',\n manifest,\n );\n if (res.ok) {\n success('Manifest is valid.');\n return 0;\n }\n // Defensive — the endpoint only returns `ok:true` on success;\n // anything else throws on the API side.\n fail(`Unexpected response shape: ${JSON.stringify(res)}`);\n return 1;\n } catch (err) {\n if (err instanceof ApiError && err.status === 400) {\n const issues = readIssues(err.context);\n if (issues.length > 0) {\n fail(`Manifest is invalid (${issues.length} issue${issues.length === 1 ? '' : 's'}):`);\n for (const issue of issues) {\n const path = issue.path ?? '(root)';\n const message = issue.message ?? '(no message)';\n out(` ${dim('•')} ${code(path)}: ${message}`);\n }\n } else {\n fail(`Manifest is invalid: ${err.message}`);\n }\n return 1;\n }\n if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n fail(`Could not validate manifest: ${(err as Error).message}`);\n return 1;\n }\n}\n\nfunction readIssues(context: Record<string, unknown> | undefined): ManifestIssue[] {\n if (!context) return [];\n const v = context['issues'];\n if (!Array.isArray(v)) return [];\n return v\n .map((entry) => {\n if (!entry || typeof entry !== 'object') return null;\n const e = entry as Record<string, unknown>;\n const issue: ManifestIssue = {};\n if (typeof e.path === 'string') issue.path = e.path;\n if (typeof e.message === 'string') issue.message = e.message;\n return issue;\n })\n .filter((x): x is ManifestIssue => x !== null);\n}\n","/**\n * `dashwise deps add <provider-slug>` — declare a cross-module dep in\n * `module.json#dependencies`.\n *\n * Two modes:\n * 1. Interactive (TTY default) — fetches the provider's published\n * `exposes` block from the backend, lets the user pick tables +\n * fields via `@clack/prompts.multiselect`, prompts for the\n * required `purpose` string.\n * 2. Non-interactive (`--table`, `--fields`, `--purpose` provided\n * OR not a TTY) — single-table add with no prompts. Multi-table\n * adds are done by re-running the command per table, OR by\n * hand-editing module.json (which `deps list` then displays\n * verbatim).\n *\n * Backend reachability is best-effort: if the provider can't be\n * found (network down, slug typo, provider deleted), interactive\n * mode falls back to a minimal \"manual\" path that asks the user to\n * type the table + field names verbatim.\n *\n * Spec: dashwise-devops-docs/plans/modules-sdk-query-v1.md §9.\n */\n\nimport {\n intro,\n isCancel,\n multiselect,\n outro,\n select,\n text,\n} from '@clack/prompts';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport {\n readManifestOrThrow,\n writeManifest,\n type ManifestDependency,\n type ManifestShape,\n} from '../../lib/manifest-io.js';\nimport { code, dim, fail, info, success, warn } from '../../lib/output.js';\n\nexport interface DepsAddOptions {\n dir?: string;\n /** Single-table add: required in non-interactive mode. */\n table?: string;\n /** Comma-separated field slugs for `--table`. */\n fields?: string;\n /** Human-readable purpose (10-500 chars, per manifest schema). */\n purpose?: string;\n /** SemVer range (default: `^<provider-current-version>` if backend reachable, else `^0.0.1`). */\n version?: string;\n /** Skip the confirmation step when replacing an existing dep declaration. */\n yes?: boolean;\n}\n\nconst MIN_PURPOSE_LEN = 10;\nconst MAX_PURPOSE_LEN = 500;\n\n/** Backend manifest_jsonb shape, only the parts the CLI needs. */\ninterface ProviderManifestSummary {\n module?: { slug?: string; name?: string; version?: string };\n exposes?: Array<{\n table: string;\n fields: string[];\n operations?: {\n list?: { allowed?: boolean };\n get?: { allowed?: boolean };\n search?: { allowed?: boolean };\n };\n visibility?: string;\n }>;\n}\n\ninterface ModuleByslugResponse {\n id: number;\n slug: string;\n name: string;\n current_version: string | null;\n}\n\ninterface VersionResponse {\n id: number;\n module_id: number;\n version: string;\n manifest_jsonb: ProviderManifestSummary;\n}\n\nexport async function depsAddCommand(\n providerSlug: string,\n options: DepsAddOptions,\n): Promise<number> {\n if (!providerSlug || typeof providerSlug !== 'string') {\n fail('Usage: `dashwise deps add <provider-slug>`');\n return 1;\n }\n // Module slugs are kebab-case (matches backend MODULE_SLUG_REGEX).\n if (!/^[a-z][a-z0-9-]*[a-z0-9]$/.test(providerSlug)) {\n fail(\n `Provider slug ${code(providerSlug)} is invalid. Module slugs are kebab-case (e.g. ${code('crm-app')}).`,\n );\n return 1;\n }\n\n let manifest;\n try {\n manifest = readManifestOrThrow(options.dir);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n // Refuse to self-depend (would be a no-op but confusing).\n if (manifest.module?.slug === providerSlug) {\n fail('A module cannot depend on itself.');\n return 1;\n }\n\n const isInteractive = process.stdout.isTTY;\n const hasAllNonInteractive =\n options.table !== undefined &&\n options.fields !== undefined &&\n options.purpose !== undefined;\n\n if (!isInteractive && !hasAllNonInteractive) {\n fail(\n `Non-interactive mode requires ${code('--table')}, ${code('--fields')}, and ${code('--purpose')}.`,\n );\n return 1;\n }\n\n // Fetch provider summary (best-effort — non-fatal in interactive mode).\n let providerSummary: ProviderManifestSummary | null = null;\n let resolvedVersion: string | null = null;\n try {\n const mod = await apiRequest<ModuleByslugResponse>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(providerSlug)}`,\n );\n if (mod.current_version) {\n const versions = await apiRequest<VersionResponse[]>(\n 'GET',\n `/api/modules/${mod.id}/versions`,\n );\n // Versions are returned newest-first per the controller spec; the\n // first one matching `current_version` is what's actually\n // installable. Fall back to versions[0] if no exact match.\n const current =\n versions.find((v) => v.version === mod.current_version) ??\n versions[0];\n if (current) {\n providerSummary = current.manifest_jsonb;\n resolvedVersion = current.version;\n }\n }\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n if (!isInteractive) {\n fail(\n `Provider ${code(providerSlug)} not found on the backend. Publish it first or check the slug.`,\n );\n return 1;\n }\n warn(\n `Provider ${code(providerSlug)} not found on the backend (404). You can still declare the dep manually.`,\n );\n } else if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n } else {\n warn(`Could not fetch provider summary: ${(err as Error).message}`);\n }\n }\n\n // Resolve the dep entry's fields.\n let entry: ManifestDependency;\n if (isInteractive) {\n intro(`Adding dependency on ${code(providerSlug)}`);\n const built = await collectInteractive(\n providerSlug,\n providerSummary,\n resolvedVersion,\n options,\n );\n if (built === null) {\n outro('Cancelled.');\n return 130;\n }\n entry = built;\n } else {\n // Non-interactive path: all required args are present per the\n // check above; we trust them + let the backend validate semantics\n // on the next publish.\n const fieldList = (options.fields ?? '')\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n if (fieldList.length === 0) {\n fail(`${code('--fields')} must list at least one field slug.`);\n return 1;\n }\n const purposeErr = validatePurpose(options.purpose!);\n if (purposeErr) {\n fail(purposeErr);\n return 1;\n }\n entry = {\n module: providerSlug,\n version: options.version ?? (resolvedVersion ? `^${resolvedVersion}` : '^0.0.1'),\n reads: [{ table: options.table!, fields: fieldList }],\n purpose: options.purpose!,\n };\n }\n\n // Merge with existing manifest.dependencies[].\n const deps: ManifestDependency[] = manifest.dependencies ?? [];\n const existingIdx = deps.findIndex((d) => d.module === providerSlug);\n if (existingIdx >= 0) {\n if (!options.yes && isInteractive) {\n const answer = await select({\n message: `Dep on ${providerSlug} already exists. Replace it?`,\n options: [\n { value: 'replace', label: 'Replace (loses prior reads/writes)' },\n { value: 'cancel', label: 'Cancel' },\n ],\n initialValue: 'replace',\n });\n if (isCancel(answer) || answer === 'cancel') {\n outro('Cancelled.');\n return 130;\n }\n }\n deps[existingIdx] = entry;\n } else {\n deps.push(entry);\n }\n manifest.dependencies = deps;\n\n try {\n writeManifest(manifest as ManifestShape, options.dir);\n } catch (err) {\n fail(`Could not write manifest: ${(err as Error).message}`);\n return 1;\n }\n\n success(\n `${existingIdx >= 0 ? 'Replaced' : 'Added'} dependency on ${code(providerSlug)}@${entry.version}.`,\n );\n info(`Reads: ${entry.reads.map((r) => `${code(r.table)} (${r.fields.join(', ')})`).join('; ')}`);\n info(`Run ${code('dashwise module generate')} to refresh typed wrappers.`);\n if (isInteractive) outro('Done.');\n return 0;\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────\n\ninterface NormalizedReadEntry {\n table: string;\n fields: string[];\n}\n\nasync function collectInteractive(\n providerSlug: string,\n summary: ProviderManifestSummary | null,\n resolvedVersion: string | null,\n options: DepsAddOptions,\n): Promise<ManifestDependency | null> {\n const reads: NormalizedReadEntry[] = [];\n\n if (summary && summary.exposes && summary.exposes.length > 0) {\n // Backend-assisted: present the actual exposes set.\n info(\n `Provider exposes ${summary.exposes.length} table${summary.exposes.length === 1 ? '' : 's'}.`,\n );\n // Filter to tables the provider actually allows `list` or `get` on\n // (others are visible-but-unreadable from a SDK perspective).\n const readableTables = summary.exposes.filter((e) => {\n const ops = e.operations;\n if (!ops) return true; // back-compat: no operations block = implicit allow\n return ops.list?.allowed === true || ops.get?.allowed === true;\n });\n if (readableTables.length === 0) {\n warn(\n `Provider ${code(providerSlug)} exposes tables but none are readable (operations.list / .get all denied).`,\n );\n return null;\n }\n\n const picked = await multiselect({\n message: 'Which tables do you want to read from?',\n options: readableTables.map((e) => ({\n value: e.table,\n label: `${e.table} ${dim(`(${e.fields.length} field${e.fields.length === 1 ? '' : 's'})`)}`,\n })),\n required: true,\n });\n if (isCancel(picked)) return null;\n\n for (const tableSlug of picked as string[]) {\n const exposeEntry = readableTables.find((e) => e.table === tableSlug)!;\n const fieldsPicked = await multiselect({\n message: `Fields to read from ${code(tableSlug)}:`,\n options: exposeEntry.fields.map((f) => ({ value: f, label: f })),\n required: true,\n initialValues: exposeEntry.fields, // pre-select all; user trims down\n });\n if (isCancel(fieldsPicked)) return null;\n reads.push({ table: tableSlug, fields: fieldsPicked as string[] });\n }\n } else {\n // Manual fallback when no backend summary is available.\n info('No provider summary available — enter table + fields manually.');\n const tableSlug = await text({\n message: 'Provider table slug to read from:',\n placeholder: 'contacts',\n validate: (v) =>\n /^[a-z][a-z0-9_]*[a-z0-9]$/.test(v) ? undefined : 'Table slugs are snake_case.',\n });\n if (isCancel(tableSlug)) return null;\n const fieldsStr = await text({\n message: 'Comma-separated field slugs:',\n placeholder: 'name, email, company',\n validate: (v) =>\n v.split(',').map((s) => s.trim()).filter(Boolean).length > 0\n ? undefined\n : 'At least one field required.',\n });\n if (isCancel(fieldsStr)) return null;\n reads.push({\n table: tableSlug as string,\n fields: (fieldsStr as string)\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean),\n });\n }\n\n // Purpose — manifest validator requires 10-500 chars.\n const initialPurpose = options.purpose ?? '';\n const purpose = await text({\n message: `Why does your module need this dependency? ${dim(`(${MIN_PURPOSE_LEN}-${MAX_PURPOSE_LEN} chars; shown to workspace admins at install consent)`)}`,\n placeholder: 'Look up assignee contact info when rendering tasks.',\n initialValue: initialPurpose,\n validate: (v) => validatePurpose(v) ?? undefined,\n });\n if (isCancel(purpose)) return null;\n\n // Version range — default to `^<resolved>` for stability.\n const defaultVersion =\n options.version ?? (resolvedVersion ? `^${resolvedVersion}` : '^0.0.1');\n const version = await text({\n message: `SemVer range to pin: ${dim('(npm-style; e.g. ^1.2.3, ~1.2.0, >=1.0.0)')}`,\n placeholder: defaultVersion,\n initialValue: defaultVersion,\n validate: (v) =>\n /^[\\^~]?[0-9]+\\.[0-9]+\\.[0-9]+(-[a-zA-Z0-9.-]+)?$/.test(v) ||\n /^(>=|<=|>|<|=)?[0-9]+\\.[0-9]+\\.[0-9]+(-[a-zA-Z0-9.-]+)?$/.test(v)\n ? undefined\n : 'Must be a npm-style semver range (e.g. ^1.2.3).',\n });\n if (isCancel(version)) return null;\n\n return {\n module: providerSlug,\n version: version as string,\n reads,\n purpose: purpose as string,\n };\n}\n\nfunction validatePurpose(purpose: string): string | null {\n if (typeof purpose !== 'string') return 'Purpose must be a string.';\n if (purpose.length < MIN_PURPOSE_LEN) {\n return `Purpose must be at least ${MIN_PURPOSE_LEN} characters; got ${purpose.length}.`;\n }\n if (purpose.length > MAX_PURPOSE_LEN) {\n return `Purpose must be at most ${MAX_PURPOSE_LEN} characters; got ${purpose.length}.`;\n }\n return null;\n}\n","/**\n * `dashwise deps check` — verify each declared dep still resolves\n * against a currently-published provider and that every field /\n * operation in the contract is still exposed.\n *\n * Exit code:\n * 0 — all deps healthy\n * 1 — at least one drift issue found\n *\n * Reports per-dep issues with a clear next step:\n * - PROVIDER_NOT_FOUND → the provider was deleted or renamed\n * - NO_MATCHING_VERSION → no published version satisfies the SemVer range\n * - FIELD_NOT_EXPOSED → consumer reads a field the provider no longer exposes\n * - OP_NOT_ALLOWED → consumer declares writes the provider blocks (writes opt-in)\n *\n * Backend reachability is required — `check` is an online command by\n * design. If the backend is unreachable, exit 1 with a clear message\n * (CI workflows can catch this + retry).\n *\n * Spec: dashwise-devops-docs/plans/modules-sdk-query-v1.md §9.\n */\n\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport {\n readManifestOrThrow,\n type ManifestDependency,\n} from '../../lib/manifest-io.js';\nimport { code, dim, fail, info, out, success, warn } from '../../lib/output.js';\n\nexport interface DepsCheckOptions {\n dir?: string;\n json?: boolean;\n}\n\ninterface ProviderManifestSummary {\n exposes?: Array<{\n table: string;\n fields: string[];\n operations?: Partial<\n Record<\n 'list' | 'get' | 'search' | 'create' | 'update' | 'delete',\n { allowed?: boolean }\n >\n >;\n }>;\n}\n\ninterface ModuleByslugResponse {\n id: number;\n slug: string;\n current_version: string | null;\n}\n\ninterface VersionResponse {\n id: number;\n version: string;\n manifest_jsonb: ProviderManifestSummary;\n}\n\ninterface Issue {\n /** Stable code so JSON consumers can branch. */\n code:\n | 'PROVIDER_NOT_FOUND'\n | 'NO_MATCHING_VERSION'\n | 'FIELD_NOT_EXPOSED'\n | 'TABLE_NOT_EXPOSED'\n | 'OP_NOT_ALLOWED'\n | 'BACKEND_UNREACHABLE';\n module: string;\n message: string;\n context?: Record<string, unknown>;\n}\n\nexport async function depsCheckCommand(options: DepsCheckOptions): Promise<number> {\n let manifest;\n try {\n manifest = readManifestOrThrow(options.dir);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n const deps: ManifestDependency[] = manifest.dependencies ?? [];\n if (deps.length === 0) {\n if (options.json) {\n out(JSON.stringify({ ok: true, deps: [], issues: [] }, null, 2));\n } else {\n info('No dependencies declared. Nothing to check.');\n }\n return 0;\n }\n\n const issues: Issue[] = [];\n const perDepStatus: Array<{ module: string; ok: boolean; resolved_version: string | null }> = [];\n\n for (const dep of deps) {\n let mod: ModuleByslugResponse;\n try {\n mod = await apiRequest<ModuleByslugResponse>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(dep.module)}`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n issues.push({\n code: 'PROVIDER_NOT_FOUND',\n module: dep.module,\n message: `Provider ${dep.module} not found on the backend. It may have been deleted or renamed.`,\n });\n perDepStatus.push({ module: dep.module, ok: false, resolved_version: null });\n continue;\n }\n if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n // Network / 500 / etc. — treat as fatal; we can't reason about\n // drift without an answer from the backend.\n issues.push({\n code: 'BACKEND_UNREACHABLE',\n module: dep.module,\n message: `Could not reach the backend: ${(err as Error).message}`,\n });\n perDepStatus.push({ module: dep.module, ok: false, resolved_version: null });\n continue;\n }\n\n // Pick the highest-matching version (newest-first per the\n // listVersions controller spec).\n let versions: VersionResponse[];\n try {\n versions = await apiRequest<VersionResponse[]>(\n 'GET',\n `/api/modules/${mod.id}/versions`,\n );\n } catch (err) {\n issues.push({\n code: 'BACKEND_UNREACHABLE',\n module: dep.module,\n message: `Could not list versions: ${(err as Error).message}`,\n });\n perDepStatus.push({ module: dep.module, ok: false, resolved_version: null });\n continue;\n }\n\n const matching = pickMatching(versions, dep.version);\n if (!matching) {\n issues.push({\n code: 'NO_MATCHING_VERSION',\n module: dep.module,\n message: `No published version satisfies ${dep.version}. Available: ${versions.map((v) => v.version).join(', ') || '(none)'}.`,\n context: { range: dep.version, available: versions.map((v) => v.version) },\n });\n perDepStatus.push({ module: dep.module, ok: false, resolved_version: null });\n continue;\n }\n\n // Drift checks against the matching version's manifest.\n const exposes = matching.manifest_jsonb.exposes ?? [];\n let depHealthy = true;\n\n for (const readEntry of dep.reads) {\n const exposeEntry = exposes.find((e) => e.table === readEntry.table);\n if (!exposeEntry) {\n issues.push({\n code: 'TABLE_NOT_EXPOSED',\n module: dep.module,\n message: `Table ${code(readEntry.table)} is no longer exposed by ${dep.module}@${matching.version}.`,\n context: { table: readEntry.table, resolved_version: matching.version },\n });\n depHealthy = false;\n continue;\n }\n const exposedFields = new Set(exposeEntry.fields);\n const missing = readEntry.fields.filter((f) => !exposedFields.has(f));\n if (missing.length > 0) {\n issues.push({\n code: 'FIELD_NOT_EXPOSED',\n module: dep.module,\n message: `Fields ${missing.map((f) => code(f)).join(', ')} on ${code(readEntry.table)} are no longer exposed by ${dep.module}@${matching.version}.`,\n context: {\n table: readEntry.table,\n missing,\n resolved_version: matching.version,\n },\n });\n depHealthy = false;\n }\n // Operation gate for list/get — we don't include search here since\n // the SDK doesn't expose it and the v1 plan doesn't either.\n const listAllowed = exposeEntry.operations?.list?.allowed !== false;\n const getAllowed = exposeEntry.operations?.get?.allowed !== false;\n if (!listAllowed && !getAllowed) {\n issues.push({\n code: 'OP_NOT_ALLOWED',\n module: dep.module,\n message: `Provider ${dep.module}@${matching.version} disallows both list AND get on ${code(readEntry.table)} — no reads possible.`,\n context: { table: readEntry.table, resolved_version: matching.version },\n });\n depHealthy = false;\n }\n }\n\n // Write-side drift (only flagged when consumer declared writes).\n for (const writeEntry of dep.writes ?? []) {\n const exposeEntry = exposes.find((e) => e.table === writeEntry.table);\n if (!exposeEntry) continue; // already flagged via reads loop\n for (const op of writeEntry.operations) {\n const gate = exposeEntry.operations?.[op as 'create' | 'update' | 'delete'];\n if (!gate || gate.allowed !== true) {\n issues.push({\n code: 'OP_NOT_ALLOWED',\n module: dep.module,\n message: `Write operation ${code(op)} on ${code(writeEntry.table)} is not allowed by ${dep.module}@${matching.version}.`,\n context: {\n table: writeEntry.table,\n operation: op,\n resolved_version: matching.version,\n },\n });\n depHealthy = false;\n }\n }\n }\n\n perDepStatus.push({\n module: dep.module,\n ok: depHealthy,\n resolved_version: matching.version,\n });\n }\n\n const ok = issues.length === 0;\n\n if (options.json) {\n out(\n JSON.stringify(\n { ok, deps: perDepStatus, issues },\n null,\n 2,\n ),\n );\n return ok ? 0 : 1;\n }\n\n // Human-readable output.\n for (const dep of perDepStatus) {\n if (dep.ok) {\n success(\n `${code(dep.module)} → ${dep.resolved_version ? `v${dep.resolved_version}` : dim('(no version)')}`,\n );\n } else {\n fail(`${code(dep.module)} ${dim('(drift detected)')}`);\n }\n }\n if (issues.length > 0) {\n out('');\n warn(`${issues.length} issue${issues.length === 1 ? '' : 's'}:`);\n for (const issue of issues) {\n out(` ${dim(`[${issue.code}]`)} ${issue.message}`);\n }\n out('');\n info(\n `Fix by removing/updating the dep (${code('dashwise deps remove <slug>')} then ${code('dashwise deps add <slug>')}) or by updating the provider.`,\n );\n } else {\n out('');\n success(`All ${perDepStatus.length} dependenc${perDepStatus.length === 1 ? 'y is' : 'ies are'} healthy.`);\n }\n return ok ? 0 : 1;\n}\n\n/**\n * Pick the newest version satisfying `range`. Range parsing is\n * intentionally minimal — covers `^x.y.z`, `~x.y.z`, `>=x.y.z`,\n * `<=x.y.z`, `>x.y.z`, `<x.y.z`, `=x.y.z`, and bare `x.y.z`. Full\n * SemVer support lives in the backend; this is a fail-soft heuristic\n * so check can give useful feedback even when offline tooling is the\n * canonical resolver.\n *\n * Caller passes `versions` in newest-first order (matches the\n * backend's `GET /:id/versions` contract).\n */\nfunction pickMatching(\n versions: VersionResponse[],\n range: string,\n): VersionResponse | null {\n for (const v of versions) {\n if (rangeSatisfied(v.version, range)) return v;\n }\n return null;\n}\n\nfunction rangeSatisfied(version: string, range: string): boolean {\n const vParts = parseSemver(version);\n if (!vParts) return false;\n const trimmed = range.trim();\n const opMatch = trimmed.match(/^(>=|<=|>|<|=|\\^|~)?(.+)$/);\n if (!opMatch) return false;\n const op = opMatch[1] ?? '=';\n const target = parseSemver(opMatch[2]);\n if (!target) return false;\n const cmp = compareSemver(vParts, target);\n switch (op) {\n case '=':\n return cmp === 0;\n case '>':\n return cmp > 0;\n case '<':\n return cmp < 0;\n case '>=':\n return cmp >= 0;\n case '<=':\n return cmp <= 0;\n case '^':\n // ^1.2.3 → >=1.2.3 <2.0.0 ; ^0.2.3 → >=0.2.3 <0.3.0 ; ^0.0.3 → >=0.0.3 <0.0.4\n if (cmp < 0) return false;\n if (target[0] > 0) return vParts[0] === target[0];\n if (target[1] > 0) return vParts[0] === 0 && vParts[1] === target[1];\n return vParts[0] === 0 && vParts[1] === 0 && vParts[2] === target[2];\n case '~':\n // ~1.2.3 → >=1.2.3 <1.3.0\n if (cmp < 0) return false;\n return vParts[0] === target[0] && vParts[1] === target[1];\n default:\n return false;\n }\n}\n\nfunction parseSemver(s: string): [number, number, number] | null {\n const m = s.trim().match(/^(\\d+)\\.(\\d+)\\.(\\d+)(?:-[a-zA-Z0-9.-]+)?$/);\n if (!m) return null;\n return [Number(m[1]), Number(m[2]), Number(m[3])];\n}\n\nfunction compareSemver(a: [number, number, number], b: [number, number, number]): number {\n for (let i = 0; i < 3; i++) {\n if (a[i] !== b[i]) return a[i] - b[i];\n }\n return 0;\n}\n\n/**\n * Test seam — expose internal helpers for unit tests without making\n * them part of the CLI's public surface. Same pattern as\n * `lib/tarball.ts#__forTests`.\n */\nexport const __forTests = {\n rangeSatisfied,\n pickMatching,\n parseSemver,\n compareSemver,\n};\n","/**\n * `dashwise deps list` — show declared cross-module dependencies.\n *\n * Pure-local read from `module.json#dependencies`. No backend call;\n * runs offline. For drift detection (does each declared dep still\n * resolve against an installed provider?) use `dashwise deps check`.\n *\n * Output shapes:\n * - Default: human-readable columns + per-dep `reads:` / `writes:`\n * summaries.\n * - `--json`: stable JSON array of `{ module, version, reads,\n * writes?, purpose }` — same shape as the manifest's\n * `dependencies[]` entries. Pipes cleanly into `jq`.\n *\n * Spec: dashwise-devops-docs/plans/modules-sdk-query-v1.md §9.\n */\n\nimport { readManifestOrThrow, type ManifestDependency } from '../../lib/manifest-io.js';\nimport { code, dim, fail, info, out } from '../../lib/output.js';\n\nexport interface DepsListOptions {\n dir?: string;\n json?: boolean;\n}\n\nexport async function depsListCommand(options: DepsListOptions): Promise<number> {\n let manifest;\n try {\n manifest = readManifestOrThrow(options.dir);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n const deps: ManifestDependency[] = manifest.dependencies ?? [];\n\n if (options.json) {\n // Stable, pipe-friendly. Empty deps list → empty array (not null);\n // jq consumers don't have to handle the absent-key case.\n out(JSON.stringify(deps, null, 2));\n return 0;\n }\n\n if (deps.length === 0) {\n info('No dependencies declared in module.json.');\n info(`Run ${code('dashwise deps add <provider-slug>')} to add one.`);\n return 0;\n }\n\n out(`${deps.length} dependenc${deps.length === 1 ? 'y' : 'ies'} declared:`);\n out('');\n for (const dep of deps) {\n out(` ${code(dep.module)}@${dep.version}`);\n out(` ${dim('purpose:')} ${dep.purpose}`);\n if (dep.reads.length > 0) {\n out(` ${dim('reads:')}`);\n for (const r of dep.reads) {\n out(` ${code(r.table)} → ${r.fields.join(', ')}`);\n }\n }\n if (dep.writes && dep.writes.length > 0) {\n out(` ${dim('writes:')}`);\n for (const w of dep.writes) {\n out(\n ` ${code(w.table)} → ${w.fields.join(', ')} (${w.operations.join('/')})`,\n );\n }\n }\n out('');\n }\n return 0;\n}\n","/**\n * `dashwise deps remove <provider-slug>` — delete the dep entry from\n * `module.json#dependencies`.\n *\n * Pure-local mutation. Idempotent: removing a slug that's not declared\n * is treated as a no-op + reported (exit 0). Confirmation prompt\n * unless `--yes` is passed.\n *\n * After successful removal, prints a reminder to re-run\n * `dashwise module generate` so the typed wrappers no longer reference\n * the removed dep. (Generated `deps.<member>` access becomes a\n * compile error in consumer code — that's the right surface to catch\n * stale references.)\n */\n\nimport { isCancel, select } from '@clack/prompts';\nimport {\n readManifestOrThrow,\n writeManifest,\n type ManifestDependency,\n} from '../../lib/manifest-io.js';\nimport { code, fail, info, success } from '../../lib/output.js';\n\nexport interface DepsRemoveOptions {\n dir?: string;\n /** Skip the confirmation prompt (CI / scripts). */\n yes?: boolean;\n}\n\nexport async function depsRemoveCommand(\n providerSlug: string,\n options: DepsRemoveOptions,\n): Promise<number> {\n if (!providerSlug || typeof providerSlug !== 'string') {\n fail('Usage: `dashwise deps remove <provider-slug>`');\n return 1;\n }\n\n let manifest;\n try {\n manifest = readManifestOrThrow(options.dir);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n const deps: ManifestDependency[] = manifest.dependencies ?? [];\n const target = deps.find((d) => d.module === providerSlug);\n if (!target) {\n // Idempotent — not an error. Mirrors `apt remove` / `npm uninstall`\n // semantics for \"wasn't installed anyway.\"\n info(`No dependency on ${code(providerSlug)} declared; nothing to remove.`);\n return 0;\n }\n\n if (!options.yes && process.stdout.isTTY) {\n const answer = await select({\n message: `Remove dependency on ${providerSlug}?`,\n options: [\n { value: 'go', label: 'Yes, remove it' },\n { value: 'cancel', label: 'No, keep it' },\n ],\n initialValue: 'go',\n });\n if (isCancel(answer) || answer === 'cancel') {\n info('Aborted.');\n return 130;\n }\n }\n\n manifest.dependencies = deps.filter((d) => d.module !== providerSlug);\n // Normalize: if the array became empty, drop the key entirely so the\n // manifest matches what `dashwise module init` emits for a fresh\n // module (no `dependencies` key at all).\n if ((manifest.dependencies as ManifestDependency[]).length === 0) {\n delete manifest.dependencies;\n }\n\n try {\n writeManifest(manifest, options.dir);\n } catch (err) {\n fail(`Could not write manifest: ${(err as Error).message}`);\n return 1;\n }\n\n success(`Removed dependency on ${code(providerSlug)}.`);\n info(`Run ${code('dashwise module generate')} to refresh typed wrappers.`);\n return 0;\n}\n","/**\n * `dashwise pull`\n *\n * P1-E2 (BaaS Phase 1, Bucket E sprint 2) — pull the canonical manifest\n * from the backend and write it to local `module.json`. Inverse of the\n * write-back-from-GET pattern used by schema-mutation commands; lets\n * users sync after dashboard-side schema edits OR after another tool\n * (DashAI, a teammate) mutated the backend.\n *\n * Per the manifest spec (`dashwise-devops-docs/plans/dashwise-manifest-spec.md`):\n * the manifest is a derived export of backend state; `pull` is the\n * primitive that materializes that derivation locally.\n *\n * Reuses the existing `GET /api/installations/:id/schema` endpoint —\n * `BaaS Phase 1 / E6` is a no-op for `dashwise pull`'s purposes; the\n * exporter primitive already exists with the right auth model\n * (local-flavor runtime token).\n *\n * Flags:\n * --dir <path> project root (default: cwd)\n * --dry-run fetch + diff; don't write\n *\n * Exit codes: 0 on success (synced or already in sync), 1 on any\n * failure (not logged in, no install cached, backend rejected, etc.).\n *\n * Future polish (not in P1-E2):\n * - --force / git-dirty check (defer until pull becomes routine\n * enough that workflow conflicts are realistic; for now git is\n * the safety net — local file is in a repo)\n * - rich diff rendering (terraform-plan style)\n */\n\nimport { ApiError, getInstallationSchema } from '../lib/api-client.js';\nimport { manifestPath, writeManifest, type ManifestShape } from '../lib/manifest-io.js';\nimport { loadSchemaCommandContext } from '../lib/schema-command-context.js';\nimport { code, dim, fail, info, success } from '../lib/output.js';\n\nexport interface PullOptions {\n dir?: string;\n dryRun?: boolean;\n}\n\nexport async function pullCommand(options: PullOptions): Promise<number> {\n let ctx: ReturnType<typeof loadSchemaCommandContext>;\n try {\n ctx = loadSchemaCommandContext({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n });\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n info(`Pulling manifest for installation ${ctx.entry.installationId}…`);\n\n let remoteManifest: Record<string, unknown>;\n try {\n const response = await getInstallationSchema(\n ctx.entry.installationId,\n ctx.requestOptions,\n );\n remoteManifest = response.manifest;\n } catch (err) {\n return surfacePullFailure(err);\n }\n\n // Compare local vs remote using the canonical JSON form the CLI\n // writes elsewhere (writeManifest's format). Object-equality via\n // JSON.stringify is fine here — the manifest is small + the\n // backend returns keys in a stable order (object spread in\n // schema-propose.service.ts:getManifest).\n const localJson = JSON.stringify(ctx.manifest, null, 2) + '\\n';\n const remoteJson = JSON.stringify(remoteManifest, null, 2) + '\\n';\n\n if (localJson === remoteJson) {\n success('Already in sync — local module.json matches backend.');\n return 0;\n }\n\n const localBytes = Buffer.byteLength(localJson, 'utf8');\n const remoteBytes = Buffer.byteLength(remoteJson, 'utf8');\n const delta = remoteBytes - localBytes;\n const deltaStr = delta === 0 ? '0 bytes' : `${delta > 0 ? '+' : ''}${delta} bytes`;\n\n if (options.dryRun) {\n info(\n `Drift detected (${deltaStr}). ${code('--dry-run')} — not writing.`,\n );\n info(`Run ${code('dashwise pull')} without ${code('--dry-run')} to apply.`);\n return 0;\n }\n\n try {\n writeManifest(remoteManifest as ManifestShape, ctx.projectRoot);\n } catch (err) {\n fail(`Failed to write ${manifestPath(ctx.projectRoot)}: ${(err as Error).message}`);\n return 1;\n }\n\n success(\n `Synced module.json from backend (${deltaStr}). ${dim(`Run \\`dashwise module generate\\` to refresh typed SDK if your watcher isn't running.`)}`,\n );\n return 0;\n}\n\n/**\n * Map a pull-time ApiError into a user-friendly message. Different\n * code set from the schema-mutation commands (no TABLE_SLUG_EXISTS etc.)\n * because pull is read-only — the failure modes are auth + connectivity.\n */\nfunction surfacePullFailure(err: unknown): number {\n if (err instanceof ApiError) {\n switch (err.code) {\n case 'UNAUTHENTICATED':\n fail(\n `Runtime token rejected. The cached token for this module may be expired — re-run \\`dashwise init <slug> --force\\` to mint a fresh one.`,\n );\n break;\n case 'SANDBOX_TOKEN_NOT_ACCEPTED':\n fail(\n `Schema-read endpoint requires a local-dev runtime token (kind=local). The cached token is the wrong kind — re-run \\`dashwise init <slug> --force\\`.`,\n );\n break;\n case 'INSTALL_MISMATCH':\n fail(\n `Runtime token is bound to a different installation than expected. The cached install id may be stale — re-run \\`dashwise init <slug> --force\\`.`,\n );\n break;\n case 'INSTALLATION_NOT_FOUND':\n fail(\n `The backend has no record of this installation. It may have been destroyed (GC, manual cleanup). Re-run \\`dashwise init <slug>\\` to provision a fresh one.`,\n );\n break;\n default:\n fail(`Backend rejected: ${err.code} ${err.status} — ${err.message}`);\n }\n return 1;\n }\n fail(`Pull failed: ${(err as Error).message}`);\n return 1;\n}\n","/**\n * `dashwise api-keys` — per-installation API key management.\n *\n * HH-CC-P1-C4 (BaaS Phase 1 Bucket C sprint 4). Pairs with the\n * backend (C1: minting endpoint, C2: runtime-guard recognition).\n *\n * Subcommands:\n * - `list` List API keys for the current module's install\n * - `create <name>` Mint a new key; prints the plaintext ONCE\n * - `revoke <key-id>` Soft-revoke a key (irreversible from the CLI)\n *\n * Auth: CLI bearer (JWT) — these are workspace-admin operations, NOT\n * runtime-data-plane operations. The runtime token cached in\n * `auth.json#modules[slug]` doesn't grant this permission; the user's\n * own login bearer does.\n *\n * Install resolution: from the current `module.json#module.slug` +\n * `auth.json#modules[<slug>].installationId`. Operates only on the\n * install currently bound to this project dir.\n */\n\nimport {\n ApiError,\n apiRequest as _apiRequest, // re-exported here only to keep imports tidy in tests\n createApiKey,\n listApiKeys,\n revokeApiKey,\n type ApiKeyPublic,\n type RequestOptions,\n} from '../lib/api-client.js';\nimport {\n readConfig,\n readModuleEntry,\n resolveApiUrl,\n} from '../lib/config.js';\nimport { readManifestOrThrow } from '../lib/manifest-io.js';\nimport { code, dim, fail, info, success, warn } from '../lib/output.js';\n\n// Silence unused-import lint — kept for symmetry with sibling commands\n// (some of which DO directly call apiRequest from this file).\nvoid _apiRequest;\n\ninterface CommonOptions {\n dir?: string;\n}\n\ninterface ResolvedContext {\n installationId: number;\n slug: string;\n requestOptions: RequestOptions;\n}\n\n/**\n * Shared setup: resolve the slug + install id from the current\n * project dir + auth.json, build a JWT-authed RequestOptions.\n *\n * Errors are thrown as plain `Error` instances; callers `catch` +\n * `fail(err.message)` + return 1.\n */\nfunction loadContext(opts: CommonOptions): ResolvedContext {\n const manifest = readManifestOrThrow(opts.dir);\n const slug = manifest.module?.slug;\n if (!slug) {\n throw new Error(\n `module.json has no module.slug — the manifest is malformed.`,\n );\n }\n const cfg = readConfig();\n if (!cfg) {\n throw new Error('Not logged in. Run `dashwise login` first.');\n }\n const entry = readModuleEntry(slug);\n if (!entry) {\n throw new Error(\n `No dev install cached for module \"${slug}\". Run \\`dashwise init ${slug} --force\\` to provision one.`,\n );\n }\n return {\n installationId: entry.installationId,\n slug,\n requestOptions: {\n baseUrl: resolveApiUrl(),\n auth: { token: cfg.token },\n },\n };\n}\n\n// ── list ─────────────────────────────────────────────────────────────\n\nexport interface ApiKeysListOptions extends CommonOptions {\n /** Include revoked keys in the output. Default: false (active only). */\n all?: boolean;\n json?: boolean;\n}\n\nexport async function apiKeysListCommand(\n options: ApiKeysListOptions,\n): Promise<number> {\n let ctx: ResolvedContext;\n try {\n ctx = loadContext(options);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n let keys: ApiKeyPublic[];\n try {\n const resp = await listApiKeys(ctx.installationId, ctx.requestOptions);\n keys = resp.api_keys;\n } catch (err) {\n return surfaceApiKeysError(err);\n }\n\n const filtered = options.all ? keys : keys.filter((k) => k.revoked_at === null);\n\n if (options.json) {\n process.stdout.write(`${JSON.stringify(filtered, null, 2)}\\n`);\n return 0;\n }\n\n if (filtered.length === 0) {\n info(\n options.all\n ? `No API keys (active or revoked) for ${code(ctx.slug)}.`\n : `No active API keys for ${code(ctx.slug)}. Run ${code('dashwise api-keys create <name>')} to mint one, or ${code('dashwise api-keys list --all')} to include revoked.`,\n );\n return 0;\n }\n\n info(`API keys for ${code(ctx.slug)} (install id=${ctx.installationId}):`);\n for (const k of filtered) {\n const status = formatKeyStatus(k);\n const lastUsed = k.last_used_at\n ? `last used ${formatRelative(new Date(k.last_used_at))}`\n : 'never used';\n process.stdout.write(\n ` ${code(`#${k.id}`)} ${k.name} ${dim(`dwk_${k.key_prefix}…`)} ${status} ${dim(`(${lastUsed})`)}\\n`,\n );\n }\n return 0;\n}\n\n// ── create ───────────────────────────────────────────────────────────\n\nexport interface ApiKeysCreateOptions extends CommonOptions {\n name?: string;\n /** Comma-separated. Mapped to backend's scopes array. */\n scopes?: string;\n /** ISO-8601 timestamp. Forwarded to backend. */\n expiresAt?: string;\n /** Print only the raw key on stdout (everything else to stderr).\n * Lets shell substitution work: KEY=$(dashwise api-keys create ... --raw-only) */\n rawOnly?: boolean;\n}\n\nexport async function apiKeysCreateCommand(\n nameArg: string | undefined,\n options: ApiKeysCreateOptions,\n): Promise<number> {\n const name = nameArg ?? options.name;\n if (!name) {\n fail('Usage: `dashwise api-keys create <name>` (e.g. `dashwise api-keys create production`)');\n return 1;\n }\n let ctx: ResolvedContext;\n try {\n ctx = loadContext(options);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n const body: { name: string; scopes?: string[]; expires_at?: string } = { name };\n if (options.scopes !== undefined) {\n body.scopes = options.scopes\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n }\n if (options.expiresAt !== undefined) {\n body.expires_at = options.expiresAt;\n }\n\n let resp;\n try {\n resp = await createApiKey(ctx.installationId, body, ctx.requestOptions);\n } catch (err) {\n return surfaceApiKeysError(err);\n }\n\n if (options.rawOnly) {\n // Stderr for chatter, stdout for the key. Lets shell capture\n // work cleanly: KEY=$(dashwise api-keys create prod --raw-only)\n process.stderr.write(\n `Created API key #${resp.api_key.id} (${resp.api_key.name}) for install ${ctx.installationId}.\\n`,\n );\n process.stdout.write(`${resp.raw_key}\\n`);\n return 0;\n }\n\n success(\n `Created API key ${code(`#${resp.api_key.id}`)} (${resp.api_key.name}) for ${code(ctx.slug)}.`,\n );\n info('');\n warn(\n 'This is the ONLY time the full key is displayed. Save it now — the backend stores a hash, not the plaintext.',\n );\n info('');\n process.stdout.write(` ${code(resp.raw_key)}\\n`);\n info('');\n info(`Use in a deployed module's env:`);\n info(` ${code(`DASHWISE_API_KEY=${resp.raw_key.slice(0, 12)}…`)}`);\n info(\n ` ${code(`DASHWISE_INSTALLATION_ID=${ctx.installationId}`)}`,\n );\n info(\n ` ${code(`DASHWISE_API_URL=${resolveApiUrl()}`)}`,\n );\n return 0;\n}\n\n// ── revoke ───────────────────────────────────────────────────────────\n\nexport interface ApiKeysRevokeOptions extends CommonOptions {\n yes?: boolean;\n}\n\nexport async function apiKeysRevokeCommand(\n keyIdArg: string | undefined,\n options: ApiKeysRevokeOptions,\n): Promise<number> {\n if (!keyIdArg) {\n fail('Usage: `dashwise api-keys revoke <key-id>` — id from `dashwise api-keys list`');\n return 1;\n }\n const keyId = Number.parseInt(keyIdArg, 10);\n if (!Number.isFinite(keyId) || keyId <= 0) {\n fail(`Invalid key id \"${keyIdArg}\" — expected a positive integer.`);\n return 1;\n }\n\n let ctx: ResolvedContext;\n try {\n ctx = loadContext(options);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n // For v1 we accept --yes only (no interactive prompt). Future\n // could prompt; for now the CLI is non-interactive-friendly by\n // default. A misclick on a single key id is recoverable (re-mint\n // takes seconds), so the friction-free path is right.\n if (!options.yes) {\n info(\n `Revoking API key #${keyId} for ${code(ctx.slug)} (install ${ctx.installationId}). Pass ${code('--yes')} to skip this confirmation in scripts.`,\n );\n }\n\n let resp;\n try {\n resp = await revokeApiKey(ctx.installationId, keyId, ctx.requestOptions);\n } catch (err) {\n return surfaceApiKeysError(err);\n }\n\n success(\n `Revoked API key #${resp.api_key.id} (${resp.api_key.name}). Future requests with this key will return 401.`,\n );\n return 0;\n}\n\n// ── error mapping ────────────────────────────────────────────────────\n\nfunction surfaceApiKeysError(err: unknown): number {\n if (err instanceof ApiError) {\n switch (err.code) {\n case 'UNAUTHENTICATED':\n fail(\n `Auth rejected by backend. Your CLI token may be stale — run ${code('dashwise login')} then retry.`,\n );\n return 1;\n case 'NOT_WORKSPACE_MEMBER':\n fail(\n `You're not a member of this installation's workspace. API-key management requires workspace membership.`,\n );\n return 1;\n case 'INSTALLATION_NOT_FOUND':\n fail(\n `Installation not found. It may have been destroyed; re-provision via ${code('dashwise init <slug>')}.`,\n );\n return 1;\n case 'API_KEY_NOT_FOUND':\n fail(\n `API key not found for this installation. Use ${code('dashwise api-keys list')} to see valid ids.`,\n );\n return 1;\n default:\n fail(`Backend rejected: ${err.code} ${err.status} — ${err.message}`);\n return 1;\n }\n }\n fail(`API-key operation failed: ${(err as Error).message}`);\n return 1;\n}\n\n// ── presentation helpers ─────────────────────────────────────────────\n\nfunction formatKeyStatus(k: ApiKeyPublic): string {\n if (k.revoked_at) return dim('[revoked]');\n if (k.expires_at && new Date(k.expires_at).getTime() <= Date.now()) {\n return dim('[expired]');\n }\n return dim('[active]');\n}\n\nfunction formatRelative(d: Date): string {\n const deltaMs = Date.now() - d.getTime();\n const sec = Math.floor(deltaMs / 1000);\n if (sec < 60) return `${sec}s ago`;\n const min = Math.floor(sec / 60);\n if (min < 60) return `${min}m ago`;\n const hr = Math.floor(min / 60);\n if (hr < 24) return `${hr}h ago`;\n const day = Math.floor(hr / 24);\n return `${day}d ago`;\n}\n","/**\n * `dashwise env export` — emit the env vars a deployed module needs\n * to authenticate against the DashWise data plane.\n *\n * HH-CC-P1-D1 (BaaS Phase 1 Bucket D sprint 1). Pairs with:\n * - P1-C1/C4: the API-key infrastructure that supplies\n * `DASHWISE_API_KEY` for production deploys.\n *\n * Default output (--format env): plain `KEY=value` lines suitable\n * for `.env`, Railway dashboard's \"raw env\" paste box, Vercel's\n * import-env, or any Docker-style env file.\n *\n * Other formats wrap the SAME values in platform-native syntax so\n * the user can pipe-copy without rewriting:\n *\n * --format json {\"KEY\": \"value\", ...}\n * --format railway `railway variables set KEY=value …` (single line)\n * --format vercel `vercel env add KEY production` (one per var)\n * --format fly `fly secrets set KEY=value …` (single line)\n *\n * Auth is the CLI bearer + the per-module runtime token's install id\n * (NOT the runtime token itself — that's local-dev-scoped). For the\n * `DASHWISE_API_KEY` slot the user has three options:\n *\n * - Default: emit a placeholder + a one-line hint to run\n * `dashwise api-keys create <name>` separately. Multi-export\n * re-uses the same key without polluting the key list.\n * - `--new-key <name>`: mint a fresh key + inline the plaintext\n * in the output. Convenient for first deploys.\n * - `--key dwk_...`: caller supplies a previously-minted key\n * (e.g. from a password manager). No backend round-trip.\n */\n\nimport { createApiKey, ApiError } from '../lib/api-client.js';\nimport { readConfig, readModuleEntry, resolveApiUrl } from '../lib/config.js';\nimport { readManifestOrThrow } from '../lib/manifest-io.js';\nimport { code, dim, fail, info, warn } from '../lib/output.js';\n\nexport type EnvExportFormat = 'env' | 'json' | 'railway' | 'vercel' | 'fly';\n\nexport interface EnvExportOptions {\n dir?: string;\n format?: EnvExportFormat;\n /** Mint a NEW API key with this name + inline it in the output. */\n newKey?: string;\n /** Use a previously-minted API key (paste plaintext). */\n key?: string;\n}\n\nconst PLACEHOLDER =\n '<run-`dashwise-api-keys-create-<name>`-and-paste-here>';\n\nexport async function envExportCommand(\n options: EnvExportOptions,\n): Promise<number> {\n const format: EnvExportFormat = options.format ?? 'env';\n if (!['env', 'json', 'railway', 'vercel', 'fly'].includes(format)) {\n fail(\n `Unknown --format \"${format}\". Allowed: env | json | railway | vercel | fly.`,\n );\n return 1;\n }\n if (options.newKey && options.key) {\n fail(\n `Pass either --new-key (mint fresh) or --key (paste existing). Not both.`,\n );\n return 1;\n }\n\n let manifest;\n try {\n manifest = readManifestOrThrow(options.dir);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n const slug = manifest.module?.slug;\n if (!slug) {\n fail('module.json has no module.slug — the manifest is malformed.');\n return 1;\n }\n const cfg = readConfig();\n if (!cfg) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n const entry = readModuleEntry(slug);\n if (!entry) {\n fail(\n `No dev install cached for module \"${slug}\". Run \\`dashwise init ${slug} --force\\` to provision one.`,\n );\n return 1;\n }\n\n const apiUrl = resolveApiUrl();\n const installationId = entry.installationId;\n\n // Resolve the API key slot.\n let apiKey: string;\n let apiKeyComment: string | null = null;\n if (options.key !== undefined) {\n if (!options.key.startsWith('dwk_')) {\n fail(`--key value must start with \\`dwk_\\` (got \"${options.key.slice(0, 8)}…\").`);\n return 1;\n }\n apiKey = options.key;\n apiKeyComment = '# DASHWISE_API_KEY supplied via --key';\n } else if (options.newKey !== undefined) {\n try {\n const resp = await createApiKey(\n installationId,\n { name: options.newKey },\n {\n baseUrl: apiUrl,\n auth: { token: cfg.token },\n },\n );\n apiKey = resp.raw_key;\n apiKeyComment = `# DASHWISE_API_KEY minted by --new-key (id=${resp.api_key.id}, name=\"${resp.api_key.name}\")`;\n // Emit a warning to stderr so even when stdout is captured to\n // a file, the user knows a key was just minted (visible in\n // their terminal).\n process.stderr.write(\n `${dim('[env export]')} Minted API key #${resp.api_key.id} (${resp.api_key.name}). The plaintext below is the ONLY time it's shown — save the file or paste it now.\\n`,\n );\n } catch (err) {\n if (err instanceof ApiError) {\n fail(`Failed to mint API key: ${err.code} ${err.status} — ${err.message}`);\n } else {\n fail(`Failed to mint API key: ${(err as Error).message}`);\n }\n return 1;\n }\n } else {\n apiKey = PLACEHOLDER;\n apiKeyComment =\n '# DASHWISE_API_KEY — run `dashwise api-keys create <name>` to mint one + paste here.';\n }\n\n // Single source of truth for the env shape. Other formats below\n // render this same set in their platform-native syntax.\n const entries: Array<{ key: string; value: string; comment?: string }> = [\n {\n key: 'DASHWISE_API_URL',\n value: apiUrl,\n comment: '# DashWise backend URL — same value the CLI is logged into.',\n },\n {\n key: 'NEXT_PUBLIC_DASHWISE_API_URL',\n value: apiUrl,\n comment:\n '# Client-side mirror — Next.js inlines NEXT_PUBLIC_* into the browser bundle so <AuthProvider> hits the right origin.',\n },\n {\n key: 'DASHWISE_INSTALLATION_ID',\n value: String(installationId),\n comment: `# Per-workspace install id for module \"${slug}\".`,\n },\n {\n key: 'DASHWISE_API_KEY',\n value: apiKey,\n ...(apiKeyComment !== null ? { comment: apiKeyComment } : {}),\n },\n ];\n\n process.stdout.write(render(entries, format));\n // Trailing newline for `env` / shell formats so subsequent prompt\n // appears on a fresh line.\n if (format !== 'json') process.stdout.write('\\n');\n\n // Friendly footer to stderr (so it doesn't pollute redirected\n // stdout). Suggests the next step.\n if (apiKey === PLACEHOLDER) {\n info('');\n info(\n `Next: ${code(`dashwise api-keys create <name>`)} → paste the plaintext into ${code('DASHWISE_API_KEY')}.`,\n );\n } else if (options.newKey !== undefined) {\n info('');\n warn(\n 'API key plaintext is shown ONLY once. Save the output of this command now.',\n );\n }\n return 0;\n}\n\nfunction render(\n entries: Array<{ key: string; value: string; comment?: string }>,\n format: EnvExportFormat,\n): string {\n switch (format) {\n case 'env': {\n const lines: string[] = [];\n for (const e of entries) {\n if (e.comment) lines.push(e.comment);\n lines.push(`${e.key}=${e.value}`);\n lines.push('');\n }\n return lines.join('\\n').trimEnd();\n }\n case 'json': {\n const obj: Record<string, string> = {};\n for (const e of entries) obj[e.key] = e.value;\n return JSON.stringify(obj, null, 2);\n }\n case 'railway': {\n // Railway CLI: `railway variables set KEY=value KEY2=value2`.\n // Single line so the user can pipe-copy.\n const parts = entries.map((e) => `${e.key}='${e.value.replace(/'/g, \"'\\\\''\")}'`);\n return `railway variables set ${parts.join(' ')}`;\n }\n case 'vercel': {\n // Vercel doesn't have a one-shot bulk set in `vercel env`.\n // Emit one line per var. Production scope by default; user\n // can edit if they want preview/development.\n const lines = entries.map(\n (e) =>\n `echo ${shellQuote(e.value)} | vercel env add ${e.key} production`,\n );\n return lines.join('\\n');\n }\n case 'fly': {\n // `fly secrets set KEY=value KEY2=value2`. Single command per\n // Fly's recommendation (sets are atomic — multi-var avoids\n // multiple machine restarts).\n const parts = entries.map((e) => `${e.key}=${shellQuote(e.value)}`);\n return `fly secrets set ${parts.join(' ')}`;\n }\n }\n}\n\n/**\n * Minimal POSIX-shell single-quote escape. Wraps the value in single\n * quotes + escapes embedded single quotes via `'\\''`. Safe for\n * direct interpolation into a shell command.\n */\nfunction shellQuote(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\n","/**\n * `dashwise query` — run typed queries against the local module's\n * installation via the @dashai/sdk query plane.\n *\n * Three modes:\n * --inline \"<expr>\" Evaluate a one-liner. `qb`, `deps`, `db` are\n * pre-bound to the local module's generated SDK.\n * Example:\n * dashwise query --inline \"qb.tasks.where({done:false}).count()\"\n * --file <path> Dynamic-import a .mjs/.js file. The file should\n * export a default that's either a Query, an\n * AggQuery, or a Promise.\n * Example file:\n * import { qb } from '@dashai/generated';\n * export default qb.tasks.where({done:false}).limit(20);\n * --repl Open a Node REPL with the generated SDK pre-bound.\n * Top-level await supported. Ctrl-D to exit.\n *\n * All three modes:\n * - Run in the current directory (must contain `module.json` +\n * `node_modules/@dashai/generated`).\n * - Load env from `.env.local` if present (matches the scaffold's\n * dev-loop convention); DASHWISE_API_URL / _INSTALLATION_ID /\n * _API_TOKEN must be set before the SDK can hit the backend.\n * - Print the result as pretty-printed JSON. `--json` flag emits\n * compact JSON for piping.\n *\n * v1 limits:\n * - --file accepts .mjs / .js only. .ts requires `tsx` which we\n * don't bundle yet. Workaround: `npx tsx <path>` directly.\n * - --inline expression must be valid JS (or `await`-friendly\n * pattern). TS syntax not supported in --inline either.\n *\n * Spec: dashwise-devops-docs/plans/modules-sdk-query-v1.md §6.3, §9.\n */\n\nimport { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join, resolve as pathResolve } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { manifestPath, readManifestOrThrow } from '../lib/manifest-io.js';\nimport { code, dim, fail, info, out } from '../lib/output.js';\n\nexport interface QueryCommandOptions {\n dir?: string;\n inline?: string;\n file?: string;\n repl?: boolean;\n json?: boolean;\n /**\n * Phase 5 `.explain()` flag (2026-05-19). When true, the runner\n * calls `.explain()` on the resulting Query/JoinedQuery/AggQuery\n * (returning the Postgres plan envelope) instead of `.execute()`.\n * No-op for `--repl` mode — REPL users call `.explain()` themselves.\n *\n * Backend MVP supports joined queries only; bare own/dep/view paths\n * reject server-side with EXPLAIN_NOT_SUPPORTED_YET. The CLI passes\n * the call through unchanged and surfaces the typed error to the\n * caller.\n */\n explain?: boolean;\n /**\n * Phase 6 streaming flag (2026-05-20). When true, the runner calls\n * `.stream()` instead of `.execute()` and prints rows incrementally\n * as JSON-lines (one row per line, terminated by `\\n`). Lets users\n * see progress on big queries + Ctrl-C cleanly midway. Mutually\n * exclusive with `--explain` (different ops) and `--repl` (REPL\n * users call `.stream()` themselves and use `for await`).\n *\n * `--json` is implied — streaming always emits JSON-lines, never\n * the pretty-printed result wrapper. Bare-array `--json` output is\n * what most users want anyway when piping into `jq`.\n */\n stream?: boolean;\n}\n\nexport async function queryCommand(options: QueryCommandOptions): Promise<number> {\n const projectRoot = pathResolve(options.dir ?? process.cwd());\n\n // Sanity: must be inside a module project.\n try {\n readManifestOrThrow(projectRoot);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n // Must have run `dashwise module generate` so @dashai/generated\n // exists. Surface the missing-package case with the right next step.\n const generatedPath = join(\n projectRoot,\n 'node_modules',\n '@dashai',\n 'generated',\n );\n if (!existsSync(generatedPath)) {\n fail(\n `No ${code('@dashai/generated')} in ${code('node_modules')}. Run ${code('dashwise module generate')} first.`,\n );\n return 1;\n }\n\n // Best-effort env loading from .env.local — matches what the\n // scaffold ships + what `dashwise module dev` would inject. The\n // generated SDK reads these via `process.env.DASHWISE_*` so we\n // hydrate `process.env` directly (vs. a richer dotenv parser —\n // the format is k=v lines, no quoting needed for the dev env).\n hydrateEnvFromDotenvLocal(projectRoot);\n\n // Exactly one mode flag must be set.\n const modes = [\n options.inline !== undefined ? 'inline' : null,\n options.file !== undefined ? 'file' : null,\n options.repl === true ? 'repl' : null,\n ].filter(Boolean);\n if (modes.length === 0) {\n fail('Pass one of: `--inline \"expr\"`, `--file <path>`, or `--repl`.');\n return 1;\n }\n if (modes.length > 1) {\n fail(`--inline / --file / --repl are mutually exclusive (got: ${modes.join(', ')}).`);\n return 1;\n }\n\n // Phase 5 (2026-05-19): --explain is meaningless with --repl (REPL\n // users call .explain() themselves). Reject the combo with a clear\n // message rather than silently ignoring.\n if (options.explain === true && options.repl === true) {\n fail('--explain has no effect with --repl. In the REPL, call `.explain()` directly on your builder.');\n return 1;\n }\n // Phase 6 streaming (2026-05-20): same logic for --stream + --repl.\n if (options.stream === true && options.repl === true) {\n fail('--stream has no effect with --repl. In the REPL, call `.stream()` directly + use `for await`.');\n return 1;\n }\n // --explain and --stream are different operations (return plan vs.\n // stream rows). Mutual exclusion prevents accidental misuse like\n // \"stream the explain plan\" which has no defined semantic.\n if (options.explain === true && options.stream === true) {\n fail('--explain and --stream are mutually exclusive — `.explain()` returns a single plan envelope; `.stream()` yields rows.');\n return 1;\n }\n const explain = options.explain === true;\n const stream = options.stream === true;\n\n if (options.repl) return runRepl(generatedPath);\n if (options.file !== undefined)\n return runFile(options.file, projectRoot, options.json === true, explain, stream);\n if (options.inline !== undefined)\n return runInline(\n options.inline,\n projectRoot,\n generatedPath,\n options.json === true,\n explain,\n stream,\n );\n // Unreachable per the modes check above.\n return 1;\n}\n\n// ── Mode: --inline ──────────────────────────────────────────────────────\n\n/**\n * Evaluate a one-liner expression with `qb`, `deps`, `db` in scope.\n *\n * Strategy: write a temp `.mjs` file that imports the generated SDK\n * + evaluates the expression as a default export, then dynamic-import\n * it. The temp file lives in tmpdir; cleaned up on the way out (or\n * left on disk if the process is killed — best-effort cleanup).\n *\n * Reason for temp-file vs. `new Function(...)`: dynamic import gives\n * us proper ESM semantics + module-resolution against `node_modules/@dashai/generated`,\n * which `new Function` doesn't. Cost is one syscall per invocation.\n */\nasync function runInline(\n expression: string,\n projectRoot: string,\n _generatedPath: string,\n jsonCompact: boolean,\n explain: boolean,\n stream: boolean,\n): Promise<number> {\n const tmpDir = mkdtempSync(join(tmpdir(), 'dashwise-query-'));\n const tmpFile = join(tmpDir, 'inline.mjs');\n // Strip a trailing semicolon if present so the embedded expression\n // is a valid value position.\n const cleanedExpr = expression.trim().replace(/;\\s*$/, '');\n const source = [\n \"import { qb, deps, db } from '@dashai/generated';\",\n `export default (async () => (${cleanedExpr}))();`,\n '',\n ].join('\\n');\n writeFileSync(tmpFile, source, 'utf-8');\n try {\n return await importAndPrint(tmpFile, projectRoot, jsonCompact, explain, stream);\n } finally {\n try {\n rmSync(tmpDir, { recursive: true, force: true });\n } catch {\n // Best-effort cleanup. tmp dirs get reaped by the OS.\n }\n }\n}\n\n// ── Mode: --file ────────────────────────────────────────────────────────\n\n/**\n * Run a `.mjs` / `.js` file via dynamic import. The file should\n * export a default that's a Query / AggQuery / Promise / value.\n *\n * `.ts` files are NOT supported in v1 — would require bundling `tsx`\n * or running through `node --import tsx`. Users can shell out via\n * `npx tsx <file>` directly for TS today.\n */\nasync function runFile(\n file: string,\n projectRoot: string,\n jsonCompact: boolean,\n explain: boolean,\n stream: boolean,\n): Promise<number> {\n const abs = pathResolve(projectRoot, file);\n if (!existsSync(abs)) {\n fail(`File not found: ${code(abs)}`);\n return 1;\n }\n if (!/\\.(mjs|js)$/.test(abs)) {\n fail(\n `Only .mjs / .js files are supported in v1. For .ts files, run ${code('npx tsx <file>')} directly. (Tracked: bundle tsx for native .ts support.)`,\n );\n return 1;\n }\n return importAndPrint(abs, projectRoot, jsonCompact, explain, stream);\n}\n\n// ── Mode: --repl ────────────────────────────────────────────────────────\n\n/**\n * Open an interactive Node REPL with the generated SDK pre-bound.\n *\n * Implementation: Node's built-in `repl` module. The generated SDK is\n * imported once at startup + its exports (`qb`, `deps`, `db`) are\n * added to the REPL's context object. Top-level await works because\n * Node's REPL has supported it since v12.\n *\n * Exit with `.exit` or Ctrl-D. Stack traces from query errors stay\n * in the REPL so users can keep iterating.\n */\nasync function runRepl(generatedPath: string): Promise<number> {\n let generated: Record<string, unknown>;\n try {\n generated = await dynamicImportFromPath(generatedPath);\n } catch (err) {\n fail(\n `Could not import ${code('@dashai/generated')}: ${(err as Error).message}`,\n );\n info(\n `Try running ${code('dashwise module generate')} to refresh the typed wrappers.`,\n );\n return 1;\n }\n\n info(`${code('dashwise query --repl')} — Node REPL with qb / deps / db pre-bound.`);\n info(`Try: ${code('await qb.<table>.execute()')} Ctrl-D to exit.`);\n out('');\n\n // Dynamic require for Node's repl module — keep it lazy so the\n // command's startup cost stays low for the inline/file modes.\n const repl = await import('node:repl');\n const server = repl.start({\n prompt: `${code('dashwise')}${dim('>')} `,\n useColors: true,\n useGlobal: false,\n });\n // Inject the generated SDK's exports into the REPL context so\n // users type `qb.tasks.execute()` without imports.\n for (const [key, value] of Object.entries(generated)) {\n Object.defineProperty(server.context, key, {\n configurable: false,\n enumerable: true,\n writable: false,\n value,\n });\n }\n\n return new Promise<number>((resolveExit) => {\n server.on('exit', () => {\n out(dim('Goodbye.'));\n resolveExit(0);\n });\n });\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────\n\n/**\n * Dynamic-import `file` (resolving from `projectRoot`'s\n * `node_modules`), await the default export if it's a Promise / Query\n * / AggQuery, and pretty-print the result.\n */\nasync function importAndPrint(\n file: string,\n projectRoot: string,\n jsonCompact: boolean,\n explain: boolean,\n stream: boolean,\n): Promise<number> {\n // Switch cwd so bare imports inside the file resolve against the\n // project's `node_modules` instead of the CLI's own. Saved + restored\n // around the import — defensive in case the consumer's code touches\n // process.cwd elsewhere.\n const originalCwd = process.cwd();\n try {\n process.chdir(projectRoot);\n const url = pathToFileURL(file).toString();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const mod: any = await import(url);\n let result = mod.default;\n // Default-export shapes we handle:\n // - Promise<T> → await it\n // - Query / AggQuery → .execute() (or .explain() if --explain,\n // or .stream() if --stream)\n // - Anything else → print as-is\n if (result && typeof result.then === 'function') {\n result = await result;\n }\n if (result && typeof result.toAst === 'function') {\n // Phase 6 streaming (2026-05-20): --stream takes precedence over\n // --execute (they're mutually exclusive at the option-parse level,\n // but ordering matters at dispatch time). Iterate the async\n // iterable + print one JSON-line per row so consumers can pipe\n // into jq / line-oriented tools.\n if (stream && typeof result.stream === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const iterable = result.stream() as AsyncIterable<unknown>;\n let rowCount = 0;\n for await (const row of iterable) {\n out(JSON.stringify(row));\n rowCount++;\n }\n // Emit a final summary on stderr so it doesn't pollute the\n // JSON-lines stdout stream. Consumers piping into jq see ONLY\n // the data; humans see \"streamed N rows\" at the bottom.\n if (!jsonCompact) {\n info(`Streamed ${rowCount} row${rowCount === 1 ? '' : 's'}.`);\n }\n return 0;\n }\n // Phase 5 `.explain()` (2026-05-19): if --explain was passed,\n // call .explain() instead of .execute(). All three builder\n // shapes (Query, JoinedQuery, AggQuery) expose .explain() since\n // the SDK slice landed alongside this CLI flag.\n if (explain && typeof result.explain === 'function') {\n result = await result.explain();\n } else if (typeof result.execute === 'function') {\n result = await result.execute();\n }\n }\n if (jsonCompact) {\n out(JSON.stringify(result));\n } else {\n out(JSON.stringify(result, null, 2));\n }\n return 0;\n } catch (err) {\n fail(`Query failed: ${(err as Error).message}`);\n if (process.env.DASHWISE_DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n return 1;\n } finally {\n process.chdir(originalCwd);\n }\n}\n\n/**\n * Resolve `@dashai/generated` from the project's node_modules and\n * dynamic-import its entry. Returns the module's exports object.\n */\nasync function dynamicImportFromPath(\n generatedDir: string,\n): Promise<Record<string, unknown>> {\n // Project-local @dashai/generated has `index.js` per the codegen\n // emitter; resolve directly rather than going through Node's package\n // resolution to keep the path deterministic.\n const entry = join(generatedDir, 'index.js');\n if (!existsSync(entry)) {\n throw new Error(`Expected ${entry} to exist. Did 'dashwise module generate' run?`);\n }\n const url = pathToFileURL(entry).toString();\n return (await import(url)) as Record<string, unknown>;\n}\n\n/**\n * Read `.env.local` from `projectRoot` and merge into `process.env`\n * without overwriting existing values. Supports `KEY=value` lines\n * + `#`-prefixed comments + blank lines — same dialect the scaffold's\n * `.env.local.example` uses. Robust enough for the dev-loop env.\n */\nfunction hydrateEnvFromDotenvLocal(projectRoot: string): void {\n const envFile = join(projectRoot, '.env.local');\n if (!existsSync(envFile)) return;\n const raw = readFileSync(envFile, 'utf-8');\n for (const line of raw.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (trimmed.length === 0 || trimmed.startsWith('#')) continue;\n const eq = trimmed.indexOf('=');\n if (eq <= 0) continue;\n const key = trimmed.slice(0, eq).trim();\n let value = trimmed.slice(eq + 1).trim();\n // Strip a single surrounding quote pair if present.\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n if (process.env[key] === undefined) {\n process.env[key] = value;\n }\n }\n}\n\n// Use manifestPath() from manifest-io so the import isn't tree-shaken\n// for unused-import lint without an actual call.\nvoid manifestPath;\n","/**\n * `dashwise module query-log` — read the per-module SDK query log.\n *\n * Hits `GET /api/modules/:moduleId/query-log?since=...&slow=...&limit=...`\n * (added in dashwise-backend Phase 6 slice 6.4). Workspace-member-\n * scoped on the server side — non-members get 403 NOT_A_WORKSPACE_MEMBER.\n *\n * Module resolution order:\n * 1. `--module <id-or-slug>` if provided\n * 2. `module.json#module.slug` in the current directory if present\n * 3. Otherwise fail with a \"which module?\" message\n *\n * Output: column-aligned table by default; pass `--json` for compact\n * JSON suitable for piping into `jq`.\n *\n * `--tail` polls every 5s for new entries (the last-seen `created_at`\n * becomes the next poll's `since` filter). Stops on Ctrl-C. Server\n * still enforces the 500-row response cap per poll, so very busy\n * modules may see \"(more entries above)\" between polls if log\n * volume exceeds 500/5s.\n */\n\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { readManifestOrThrow } from '../../lib/manifest-io.js';\nimport { code, dim, fail, info, out } from '../../lib/output.js';\n\nexport interface ModuleQueryLogOptions {\n /**\n * Module to read the log for. Accepts a numeric id (`123`) or a\n * slug (`my-module`). If omitted, falls back to the slug in the\n * current directory's `module.json`.\n */\n module?: string;\n /**\n * Filter to slow queries only (duration_ms > 500 — matches the\n * SDK/backend slow-query threshold).\n */\n slow?: boolean;\n /**\n * Filter rows where `created_at >= NOW() - <since>`. Duration\n * shorthand (`30m`, `1h`, `2d`, `7d`) or ISO 8601 timestamp.\n * Passed through to the backend's validator.\n */\n since?: string;\n /**\n * Max rows to fetch per call. Default 50; backend caps at 500.\n */\n limit?: number;\n /**\n * Poll for new entries every 5s. Stops on Ctrl-C. Mutually\n * exclusive with `--json` (tail mode prints the table format\n * incrementally).\n */\n tail?: boolean;\n /**\n * Emit compact JSON instead of the table. Useful for piping into\n * `jq` / scripting. Ignored when `--tail` is set.\n */\n json?: boolean;\n /**\n * Override project directory (for `module.json` slug lookup).\n * Defaults to `process.cwd()`. Only consulted when `--module` is\n * absent.\n */\n dir?: string;\n}\n\ninterface QueryLogRow {\n id: string;\n request_id: string;\n installation_id: number;\n module_id: number;\n endpoint: 'query' | 'explain';\n ast_hash: string | null;\n duration_ms: number;\n row_count: number | null;\n error_code: string | null;\n error_message: string | null;\n created_at: string;\n}\n\ninterface QueryLogResponse {\n entries: QueryLogRow[];\n count: number;\n}\n\ninterface ModuleByIdResponse {\n id: number;\n slug: string;\n}\n\nconst POLL_INTERVAL_MS = 5_000;\n\nexport async function moduleQueryLogCommand(\n options: ModuleQueryLogOptions,\n): Promise<number> {\n // Resolve the moduleId. The user can pass `--module <id-or-slug>`\n // or we infer from the current directory's manifest.\n let moduleId: number;\n try {\n moduleId = await resolveModuleId(options.module, options.dir);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n if (options.tail) {\n return runTail(moduleId, options);\n }\n return runOnce(moduleId, options);\n}\n\n// ── One-shot mode (default) ──────────────────────────────────────\n\nasync function runOnce(\n moduleId: number,\n options: ModuleQueryLogOptions,\n): Promise<number> {\n const params: Record<string, string> = {};\n if (options.slow) params.slow = 'true';\n if (options.since) params.since = options.since;\n if (typeof options.limit === 'number') params.limit = String(options.limit);\n const qs = new URLSearchParams(params).toString();\n const path = `/api/modules/${moduleId}/query-log${qs ? `?${qs}` : ''}`;\n\n let body: QueryLogResponse;\n try {\n body = await apiRequest<QueryLogResponse>('GET', path);\n } catch (err) {\n return handleApiError(err);\n }\n\n if (options.json) {\n out(JSON.stringify(body));\n return 0;\n }\n\n if (body.entries.length === 0) {\n info(\n options.slow\n ? 'No slow queries in the requested window.'\n : 'No query log entries in the requested window.',\n );\n return 0;\n }\n\n renderTable(body.entries);\n out('');\n info(`${body.count} ${body.count === 1 ? 'entry' : 'entries'}.`);\n return 0;\n}\n\n// ── --tail mode ──────────────────────────────────────────────────\n\nasync function runTail(\n moduleId: number,\n options: ModuleQueryLogOptions,\n): Promise<number> {\n // Initial fetch — use whatever filters the user passed plus a\n // reasonable starting window if `--since` wasn't set.\n const initialParams: Record<string, string> = {};\n if (options.slow) initialParams.slow = 'true';\n initialParams.since = options.since ?? '5m';\n if (typeof options.limit === 'number') initialParams.limit = String(options.limit);\n const initialQs = new URLSearchParams(initialParams).toString();\n\n info(`Tailing query log for module ${moduleId}. Ctrl-C to stop.`);\n out('');\n\n // Track the most-recent created_at across polls so we can fetch\n // strictly-new rows. The backend's `since` param does a NOW()-based\n // window, so we use a small overlap (2s) to ensure we don't miss\n // entries whose created_at lands between poll cycles. De-dup by\n // request_id locally to suppress overlap repeats.\n const seenIds = new Set<string>();\n let firstPoll = true;\n\n // Print headers once up front; subsequent polls append rows without\n // re-printing.\n printTableHeader();\n\n // Initial poll uses the user-specified since; subsequent polls use\n // a fixed 7s window (5s poll interval + 2s overlap).\n while (true) {\n try {\n const path = `/api/modules/${moduleId}/query-log?${firstPoll ? initialQs : buildTailParams(options)}`;\n const body = await apiRequest<QueryLogResponse>('GET', path);\n\n // Print rows in chronological order (response is DESC, reverse\n // for the tail's natural \"latest at bottom\" reading order).\n const newRows: QueryLogRow[] = [];\n for (const row of [...body.entries].reverse()) {\n if (seenIds.has(row.request_id)) continue;\n seenIds.add(row.request_id);\n newRows.push(row);\n }\n for (const row of newRows) {\n out(formatRow(row));\n }\n firstPoll = false;\n } catch (err) {\n // Don't crash the tail on transient errors — log + continue.\n info(dim(`(tail poll error: ${(err as Error).message})`));\n }\n await sleep(POLL_INTERVAL_MS);\n }\n}\n\nfunction buildTailParams(options: ModuleQueryLogOptions): string {\n const params: Record<string, string> = { since: '7s' };\n if (options.slow) params.slow = 'true';\n if (typeof options.limit === 'number') params.limit = String(options.limit);\n return new URLSearchParams(params).toString();\n}\n\n// ── Module-id resolution ─────────────────────────────────────────\n\nasync function resolveModuleId(\n moduleArg: string | undefined,\n dir: string | undefined,\n): Promise<number> {\n // 1. Explicit --module: numeric → use as-is; slug → lookup.\n if (moduleArg && moduleArg.length > 0) {\n const asInt = Number.parseInt(moduleArg, 10);\n if (Number.isFinite(asInt) && String(asInt) === moduleArg) {\n return asInt;\n }\n return lookupModuleIdBySlug(moduleArg);\n }\n // 2. Fall back to module.json in the project directory.\n const projectRoot = dir ?? process.cwd();\n try {\n const manifest = readManifestOrThrow(projectRoot);\n if (manifest?.module?.slug) {\n return lookupModuleIdBySlug(manifest.module.slug);\n }\n } catch {\n // Manifest absent or malformed — fall through to the error below.\n }\n throw new Error(\n `No module specified. Pass --module <id-or-slug> or run inside a module project directory containing module.json.`,\n );\n}\n\nasync function lookupModuleIdBySlug(slug: string): Promise<number> {\n const found = await apiRequest<ModuleByIdResponse>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(slug)}`,\n );\n if (!found || typeof found.id !== 'number') {\n throw new Error(`Module ${code(slug)} not found.`);\n }\n return found.id;\n}\n\n// ── Error handling ───────────────────────────────────────────────\n\nfunction handleApiError(err: unknown): number {\n if (err instanceof ApiError) {\n if (err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n if (err.status === 403) {\n fail(\n `Forbidden — you are not a member of this module's owner workspace. ` +\n `Use \\`dashwise workspace list\\` to see what you have access to.`,\n );\n return 1;\n }\n if (err.status === 404) {\n fail(`Module not found.`);\n return 1;\n }\n }\n fail(`Could not load query log: ${(err as Error).message}`);\n return 1;\n}\n\n// ── Table rendering ──────────────────────────────────────────────\n\n/**\n * Column widths chosen to fit a typical 80-col terminal plus a\n * little slack. ID is the bigint serialized as string (up to ~19\n * digits); we show only the last 8 for compactness — the request_id\n * is the real trace anchor anyway.\n */\nconst COL_WIDTHS = {\n time: 19, // \"YYYY-MM-DD HH:MM:SS\"\n endpoint: 7, // \"query\" | \"explain\"\n ms: 6, // \"12345\" with margin\n rows: 5,\n code: 18,\n request: 12, // first 12 chars of request_id (most are UUIDs)\n};\n\nfunction renderTable(entries: QueryLogRow[]): void {\n out('');\n printTableHeader();\n // Server returns DESC (newest first) — preserve that for one-shot\n // mode so the most-recent activity is at the top of the screen.\n for (const row of entries) {\n out(formatRow(row));\n }\n}\n\nfunction printTableHeader(): void {\n out(\n [\n 'TIME'.padEnd(COL_WIDTHS.time),\n 'ENDPT'.padEnd(COL_WIDTHS.endpoint),\n 'MS'.padStart(COL_WIDTHS.ms),\n 'ROWS'.padStart(COL_WIDTHS.rows),\n 'CODE'.padEnd(COL_WIDTHS.code),\n 'REQ',\n ].join(' '),\n );\n out(\n [\n '-'.repeat(COL_WIDTHS.time),\n '-'.repeat(COL_WIDTHS.endpoint),\n '-'.repeat(COL_WIDTHS.ms),\n '-'.repeat(COL_WIDTHS.rows),\n '-'.repeat(COL_WIDTHS.code),\n '-'.repeat(COL_WIDTHS.request),\n ].join(' '),\n );\n}\n\nfunction formatRow(row: QueryLogRow): string {\n const time = formatTimestamp(row.created_at);\n const endpoint = row.endpoint.padEnd(COL_WIDTHS.endpoint);\n const ms = String(row.duration_ms).padStart(COL_WIDTHS.ms);\n const rows =\n row.row_count === null ? '—'.padStart(COL_WIDTHS.rows) : String(row.row_count).padStart(COL_WIDTHS.rows);\n const errCode = row.error_code ?? '';\n const codeCol = errCode\n ? code(errCode).padEnd(COL_WIDTHS.code + (code(errCode).length - errCode.length))\n : 'OK'.padEnd(COL_WIDTHS.code);\n const req = row.request_id.slice(0, COL_WIDTHS.request);\n return [time, endpoint, ms, rows, codeCol, dim(req)].join(' ');\n}\n\nfunction formatTimestamp(iso: string): string {\n // YYYY-MM-DD HH:MM:SS for compact display; preserves UTC if the\n // input is Z-suffixed. We deliberately don't convert to local TZ\n // here so log entries are reproducible across consumers in\n // different timezones.\n return iso.slice(0, 19).replace('T', ' ');\n}\n\n// ── Misc ─────────────────────────────────────────────────────────\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/**\n * `dashwise module action-log` — read the per-installation server-action\n * audit log (cross-module + own-module dispatches).\n *\n * Hits `GET /api/modules/runtime/installations/:installationId/action-log`\n * (added in dashwise-backend Phase 7 slice 7.5a). Workspace-member-scoped\n * server-side — non-members get 403 NOT_A_WORKSPACE_MEMBER.\n *\n * **Why per-installation, not per-module**: cross-module dispatches are\n * events between TWO installations. The audit row keys by\n * installation id (not module id). The CLI surfaces either side\n * (`--role caller` for outbound; `--role provider` for inbound) so\n * authors can debug both directions from the same command.\n *\n * The user provides `--installation <id>` directly. A `--module <slug>`\n * convenience that resolves to the user's default-workspace\n * installation is a planned follow-up; it needs a new backend\n * \"list-installations-by-module-in-workspace\" endpoint.\n *\n * Output: column-aligned table by default; pass `--json` for compact\n * JSON suitable for piping into `jq`.\n *\n * `--tail` polls every 5s for new entries (last-seen `created_at`\n * becomes the next poll's `since` filter). Stops on Ctrl-C. Server\n * still enforces the 500-row response cap per poll.\n */\n\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { code, dim, fail, info, out } from '../../lib/output.js';\n\nexport interface ModuleActionLogOptions {\n /**\n * Installation to read the log for (numeric id). Mutually exclusive\n * with `module` — exactly one must be set. (Validated by the CLI\n * binder; the action handler treats both as optional + checks.)\n */\n installation?: number;\n /**\n * Module slug — resolves to the caller's accessible installation\n * via `GET /api/modules/by-slug/:slug/my-installation`. Convenience\n * for the common case where the user has one workspace's\n * installation; multi-workspace authors should use `--installation`\n * with an explicit id (or `dashwise workspace use <slug>` to fix\n * the default).\n */\n module?: string;\n /**\n * Which side of cross-module dispatches to query.\n * - `caller` (default) → outbound actions THIS installation invoked\n * - `provider` → inbound actions OTHER modules invoked on THIS installation\n */\n role?: 'caller' | 'provider';\n /**\n * Filter to slow actions only (elapsed_ms > 500 — matches the\n * SDK/backend slow threshold). Uses the partial slow-action index.\n */\n slow?: boolean;\n /**\n * Filter rows where `created_at >= NOW() - <since>`. Duration\n * shorthand (`30m`, `1h`, `2d`, `7d`) or ISO 8601 timestamp.\n */\n since?: string;\n /** Filter to cross-module dispatches only (cross_module=true rows). */\n crossModuleOnly?: boolean;\n /** Max rows per call. Default 50; backend caps at 500. */\n limit?: number;\n /**\n * Poll every 5s for new entries. Stops on Ctrl-C. Mutually exclusive\n * with `--json` (tail mode prints incrementally as rows arrive).\n */\n tail?: boolean;\n /** Compact JSON instead of the table. Ignored when `--tail` is set. */\n json?: boolean;\n}\n\ninterface ActionLogRow {\n id: string;\n request_id: string;\n caller_installation_id: number;\n caller_module_slug: string;\n caller_user_id: number | null;\n provider_installation_id: number;\n provider_module_slug: string;\n action_name: string;\n input_hash: string;\n output_hash: string | null;\n ok: boolean;\n error_code: string | null;\n elapsed_ms: number;\n cross_module: boolean;\n created_at: string;\n}\n\ninterface ActionLogResponse {\n entries: ActionLogRow[];\n count: number;\n}\n\nconst POLL_INTERVAL_MS = 5_000;\n\nexport async function moduleActionLogCommand(\n options: ModuleActionLogOptions,\n): Promise<number> {\n // Validate mutually-exclusive scope flags.\n if (options.installation === undefined && options.module === undefined) {\n fail('Must pass either `--installation <id>` or `--module <slug>`.');\n return 1;\n }\n if (options.installation !== undefined && options.module !== undefined) {\n fail('`--installation` and `--module` are mutually exclusive — pass one or the other.');\n return 1;\n }\n\n // If --module was passed, resolve to an installation id.\n let installationId = options.installation;\n if (installationId === undefined && options.module !== undefined) {\n try {\n const resolved = await apiRequest<{ installation_id: number; module_slug: string }>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(options.module)}/my-installation`,\n );\n installationId = resolved.installation_id;\n } catch (err) {\n return mapAndPrintError(err, options.json);\n }\n }\n if (options.tail) {\n return runTail(installationId as number, options);\n }\n return runOnce(installationId as number, options);\n}\n\n// ── One-shot mode ────────────────────────────────────────────────\n\nasync function runOnce(installationId: number, options: ModuleActionLogOptions): Promise<number> {\n const params: Record<string, string> = {};\n if (options.role !== undefined) params.role = options.role;\n if (options.slow) params.slow = 'true';\n if (options.crossModuleOnly) params.cross_module_only = 'true';\n if (options.since !== undefined) params.since = options.since;\n if (options.limit !== undefined) params.limit = String(options.limit);\n\n let response: ActionLogResponse;\n try {\n response = await apiRequest<ActionLogResponse>(\n 'GET',\n `/api/modules/runtime/installations/${installationId}/action-log?${new URLSearchParams(params).toString()}`,\n );\n } catch (err) {\n return mapAndPrintError(err, options.json);\n }\n\n if (options.json) {\n out(JSON.stringify(response));\n return 0;\n }\n\n printTable(response.entries);\n if (response.entries.length === 0) {\n info('No entries.');\n }\n return 0;\n}\n\n// ── Tail mode ────────────────────────────────────────────────────\n\nasync function runTail(installationId: number, options: ModuleActionLogOptions): Promise<number> {\n if (options.json) {\n fail('`--tail` and `--json` are mutually exclusive.');\n return 1;\n }\n info(`Tailing action log for installation ${code(String(installationId))} every 5s. Ctrl-C to stop.`);\n\n let lastSeen: string | undefined;\n const printed = new Set<string>();\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const params: Record<string, string> = {};\n if (options.role !== undefined) params.role = options.role;\n if (options.slow) params.slow = 'true';\n if (options.crossModuleOnly) params.cross_module_only = 'true';\n if (lastSeen !== undefined) params.since = lastSeen;\n else if (options.since !== undefined) params.since = options.since;\n params.limit = String(options.limit ?? 100);\n\n try {\n const response = await apiRequest<ActionLogResponse>(\n 'GET',\n `/api/modules/runtime/installations/${installationId}/action-log?${new URLSearchParams(params).toString()}`,\n );\n // Backend returns rows newest-first; we want oldest-first when\n // tailing so the user reads down the page. Reverse + dedup by id.\n const fresh = response.entries.filter((e) => !printed.has(e.id)).reverse();\n if (fresh.length > 0) {\n for (const entry of fresh) {\n printed.add(entry.id);\n printRow(entry);\n }\n // Update since-anchor to the newest row we just printed.\n lastSeen = fresh[fresh.length - 1].created_at;\n }\n } catch (err) {\n // Tail mode swallows transient errors + keeps polling. Fatal\n // (401/403) drops out so the user knows to re-login.\n if (err instanceof ApiError && (err.status === 401 || err.status === 403)) {\n return mapAndPrintError(err, false);\n }\n dim(`(tail: transient error — ${(err as Error).message})`);\n }\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n}\n\n// ── Output ───────────────────────────────────────────────────────\n\nfunction printTable(rows: ActionLogRow[]): void {\n if (rows.length === 0) {\n out('');\n out(' (no entries)');\n out('');\n return;\n }\n const widths = {\n time: 19,\n elapsed: 5,\n cross: 5,\n caller: 18,\n action: 22,\n code: 18,\n };\n out('');\n out(\n `${'TIME'.padEnd(widths.time)} ${'MS'.padStart(widths.elapsed)} ${'CROSS'.padEnd(widths.cross)} ${'CALLER'.padEnd(widths.caller)} ${'ACTION'.padEnd(widths.action)} ${'CODE'.padEnd(widths.code)}`,\n );\n out(\n `${'-'.repeat(widths.time)} ${'-'.repeat(widths.elapsed)} ${'-'.repeat(widths.cross)} ${'-'.repeat(widths.caller)} ${'-'.repeat(widths.action)} ${'-'.repeat(widths.code)}`,\n );\n for (const r of rows) {\n printRow(r);\n }\n out('');\n info(`${rows.length} entr${rows.length === 1 ? 'y' : 'ies'}.`);\n}\n\nfunction printRow(r: ActionLogRow): void {\n const time = r.created_at.slice(0, 19).replace('T', ' ');\n const cross = r.cross_module ? code('yes') : dim(' no');\n const codeCol = r.ok ? dim('-') : code(r.error_code ?? 'ERROR');\n out(\n `${time.padEnd(19)} ${String(r.elapsed_ms).padStart(5)} ${cross.padEnd(5)} ${r.caller_module_slug.padEnd(18)} ${r.action_name.padEnd(22)} ${codeCol}`,\n );\n}\n\nfunction mapAndPrintError(err: unknown, json: boolean | undefined): number {\n if (err instanceof ApiError) {\n if (err.status === 401) {\n const msg = 'Not logged in. Run `dashwise login` first.';\n if (json) out(JSON.stringify({ ok: false, error: { code: 'NOT_LOGGED_IN', message: msg } }));\n else fail(msg);\n return 1;\n }\n if (err.status === 403) {\n const msg = 'Workspace-member access required for this installation.';\n if (json) out(JSON.stringify({ ok: false, error: { code: 'FORBIDDEN', message: msg } }));\n else fail(msg);\n return 1;\n }\n if (err.status === 404) {\n const msg = 'Installation not found.';\n if (json) out(JSON.stringify({ ok: false, error: { code: 'INSTALLATION_NOT_FOUND', message: msg } }));\n else fail(msg);\n return 1;\n }\n }\n const msg = `Could not fetch action log: ${(err as Error).message}`;\n if (json) out(JSON.stringify({ ok: false, error: { code: 'FETCH_FAILED', message: (err as Error).message } }));\n else fail(msg);\n return 1;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/lib/config.ts","../src/lib/api-client.ts","../src/lib/output.ts","../src/lib/manifest-io.ts","../src/lib/scaffold.ts","../src/lib/workspaces.ts","../src/commands/module/init.ts","../src/lib/schema-command-context.ts","../src/commands/module/destroy-dev-install.ts","../src/commands/module/reset-dev-install.ts","../src/lib/field-spec.ts","../src/commands/table/create.ts","../src/commands/table/delete.ts","../src/commands/field/add.ts","../src/commands/field/remove.ts","../src/commands/field/set-type.ts","../src/commands/dev.ts","../src/lib/connect-status.ts","../src/lib/manifest-poll.ts","../src/commands/login.ts","../src/commands/logout.ts","../src/commands/profile.ts","../src/commands/workspace.ts","../src/commands/module/clone.ts","../src/commands/module/connect-git.ts","../src/commands/module/convert.ts","../src/commands/module/export.ts","../src/commands/module/register.ts","../src/commands/module/generate.ts","../src/commands/module/dev.ts","../src/commands/module/diff.ts","../src/bin.ts","../src/commands/module/list.ts","../src/commands/module/publish.ts","../src/lib/tarball.ts","../src/commands/module/pull-data.ts","../src/commands/module/validate.ts","../src/commands/deps/add.ts","../src/commands/deps/check.ts","../src/commands/deps/list.ts","../src/commands/deps/remove.ts","../src/commands/deps/connect.ts","../src/commands/uses/bind.ts","../src/commands/uses/add.ts","../src/lib/uses-types.ts","../src/commands/pull.ts","../src/commands/api-keys.ts","../src/commands/origins.ts","../src/commands/env-export.ts","../src/commands/query.ts","../src/commands/module/query-log.ts","../src/commands/module/action-log.ts"],"names":["c","out","code","join","existsSync","readFileSync","writeFileSync","select","isCancel","intro","resolve","readdirSync","mkdirSync","outro","workspace","resolvePath","manifestPath","exitCode","text","walk","statSync","deriveSlug","basename","rmSync","dirname","fsWatch","relative","formatBytes","reportConnectStatus","loadContext","statusChip","list","parseOps","pathResolve","sleep","POLL_INTERVAL_MS","runTail","runOnce","msg","destroyDevInstallCommand","resetDevInstallCommand","tableCreateCommand","tableDeleteCommand","fieldAddCommand","fieldRemoveCommand","fieldSetTypeCommand"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAuHO,SAAS,SAAA,GAAoB;A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B","file":"bin.js","sourcesContent":["/**\n * Local CLI configuration — persisted to\n * `$XDG_CONFIG_HOME/dashwise/auth.json` (defaults to\n * `~/.config/dashwise/auth.json` on Linux/macOS and the equivalent\n * `%APPDATA%\\dashwise\\auth.json` on Windows).\n *\n * Contents:\n * - `apiUrl` — backend root, e.g. `http://localhost:3000`\n * - `token` — raw `dwc_*` CLI token (the secret)\n * - `tokenId` — DB id of the `cli_tokens` row (so `dashwise\n * logout` can call DELETE precisely)\n * - `user` — cached profile for fast `dashwise profile`\n * (refreshed on `dashwise login` + on demand)\n * - `workspaceSlug` — default workspace selected via\n * `dashwise workspace use <slug>`\n *\n * Permissions: chmod 0600 on write — the file holds a long-lived\n * bearer credential. Best-effort on Windows (the API tolerates\n * `EPERM` on the chmod call there).\n */\n\nimport {\n chmodSync,\n existsSync,\n mkdirSync,\n readFileSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from 'node:fs';\nimport { homedir, platform } from 'node:os';\nimport { join } from 'node:path';\n\nexport interface CliConfig {\n /** Backend base URL — e.g. `http://localhost:3000`. */\n apiUrl: string;\n /** Raw CLI token (`dwc_<...>`). */\n token: string;\n /** DB id of the matching `cli_tokens` row. Used by `logout`. */\n tokenId: number;\n /** Cached user identity. */\n user: {\n id: number;\n email: string;\n username: string;\n firstName: string;\n lastName: string;\n };\n /** Optional default workspace slug. */\n workspaceSlug?: string;\n /**\n * P1-C (identity collapse) — per-module local-dev install metadata,\n * keyed by the module's slug (matches `module.json#module.slug`).\n *\n * Written by `dashwise init` / `dashwise module register` after\n * `POST /api/installations/dev` mints a scoped `dwk_` API key. Read\n * by `@dashai/sdk`'s `createDevClient({ moduleSlug })` to authenticate\n * against the local-dev install. Each entry is independent — entries\n * for other modules survive any single module's destroy / re-init.\n *\n * Field semantics:\n * - `apiKey` — the raw `dwk_*` key the SDK sends as `Authorization:\n * Bearer <apiKey>` on every data + schema request. Minted against\n * the kind='local' install, so the own-table plane grants the\n * developer self-access without explicit grant rows (see P1-C4).\n * - `apiKeyId` — DB id of the `module_api_keys` row. Used to revoke\n * precisely (`dashwise api-keys revoke`) and to surface in status.\n * - `installationId` — numeric install id the key binds to.\n * - `expiresAt` — ISO timestamp; informational only. Expiry is\n * enforced server-side; the CLI can warn when nearing it.\n *\n * Legacy tolerance: the pre-P1-C shape carried `runtimeToken` (a\n * 90-day JWT) instead of `apiKey`. Entries written by an older CLI\n * are still parsed — `runtimeToken` is kept optional here so the\n * self-heal path in `dashwise dev` can detect a legacy entry, mint a\n * `dwk_` key, and rewrite the entry in the new shape.\n */\n modules?: Record<string, CliConfigModuleEntry>;\n}\n\n/**\n * Per-module entry within `CliConfig.modules`. See `modules` field above.\n *\n * `apiKey` / `apiKeyId` are the canonical (P1-C) fields. `runtimeToken`\n * is a legacy field retained ONLY for read-tolerance + self-heal — new\n * writes never set it.\n */\nexport interface CliConfigModuleEntry {\n /** Raw `dwk_*` API key. Canonical P1-C credential. */\n apiKey: string;\n /** DB id of the `module_api_keys` row (for `dashwise api-keys revoke`). */\n apiKeyId: number;\n /** Numeric install id the key binds to. */\n installationId: number;\n /** ISO timestamp; informational only. */\n expiresAt: string;\n /**\n * @deprecated Legacy 90-day runtime JWT (pre-P1-C). Present only in\n * `auth.json` files written by an older CLI. Read-tolerated so the\n * self-heal path can upgrade the entry to an `apiKey`; never written\n * by current code.\n */\n runtimeToken?: string;\n}\n\nconst FILE_NAME = 'auth.json';\nconst DIR_NAME = 'dashwise';\n\n/**\n * Resolve the config directory using XDG conventions.\n *\n * 1. `$XDG_CONFIG_HOME/dashwise/` if set\n * 2. `~/.config/dashwise/` on Linux/macOS\n * 3. `%APPDATA%\\dashwise\\` on Windows (via env)\n *\n * Mirrors `dashwise` projects on common platforms; matches what\n * users would expect from other CLIs (gh, npm, etc.).\n */\nexport function configDir(): string {\n if (process.env.XDG_CONFIG_HOME) {\n return join(process.env.XDG_CONFIG_HOME, DIR_NAME);\n }\n if (platform() === 'win32' && process.env.APPDATA) {\n return join(process.env.APPDATA, DIR_NAME);\n }\n return join(homedir(), '.config', DIR_NAME);\n}\n\nexport function configPath(): string {\n return join(configDir(), FILE_NAME);\n}\n\n/**\n * Read the saved config, or `null` if no file exists. Throws if the\n * file exists but is malformed JSON — the caller decides whether to\n * surface as \"run `dashwise login` again\" or as a hard error.\n */\nexport function readConfig(): CliConfig | null {\n const path = configPath();\n if (!existsSync(path)) return null;\n const raw = readFileSync(path, 'utf-8');\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n throw new Error(\n `Failed to parse ${path}: ${(err as Error).message}. Run \\`dashwise login\\` to recreate it.`,\n );\n }\n if (!isPlausibleConfig(parsed)) {\n throw new Error(\n `Config at ${path} is missing required fields. Run \\`dashwise login\\` to recreate it.`,\n );\n }\n return parsed;\n}\n\n/**\n * Write the config atomically (via temp + rename) with 0600 perms.\n * Creates the parent dir if missing.\n */\nexport function writeConfig(config: CliConfig): void {\n const dir = configDir();\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n const path = configPath();\n const tmp = `${path}.tmp.${process.pid}`;\n writeFileSync(tmp, JSON.stringify(config, null, 2) + '\\n', 'utf-8');\n try {\n chmodSync(tmp, 0o600);\n } catch {\n // Windows + some FUSE FS don't support chmod; best-effort.\n }\n // Atomic rename — readers see either the old config or the new\n // one, never a partial write.\n renameSync(tmp, path);\n}\n\n/**\n * Remove the config file (`dashwise logout`). Idempotent — no error\n * if the file already doesn't exist.\n */\nexport function deleteConfig(): void {\n const path = configPath();\n if (!existsSync(path)) return;\n rmSync(path);\n}\n\n/**\n * Resolve the API URL the CLI should talk to.\n * Priority: explicit `DASHWISE_API_URL` env → saved config → default.\n */\nexport function resolveApiUrl(): string {\n const fromEnv = process.env.DASHWISE_API_URL?.trim();\n if (fromEnv) return fromEnv.replace(/\\/+$/, '');\n const cfg = safeReadConfig();\n if (cfg?.apiUrl) return cfg.apiUrl.replace(/\\/+$/, '');\n return 'http://localhost:3000';\n}\n\n/**\n * Convenience: read the saved token if the file exists + is valid.\n * Returns `null` if the user isn't logged in.\n */\nexport function readSavedToken(): string | null {\n const cfg = safeReadConfig();\n return cfg?.token ?? null;\n}\n\nfunction safeReadConfig(): CliConfig | null {\n try {\n return readConfig();\n } catch {\n return null;\n }\n}\n\nfunction isPlausibleConfig(v: unknown): v is CliConfig {\n if (!v || typeof v !== 'object') return false;\n const c = v as Record<string, unknown>;\n if (typeof c.apiUrl !== 'string') return false;\n if (typeof c.token !== 'string') return false;\n if (typeof c.tokenId !== 'number') return false;\n if (!c.user || typeof c.user !== 'object') return false;\n const u = c.user as Record<string, unknown>;\n if (typeof u.id !== 'number') return false;\n if (typeof u.email !== 'string') return false;\n // HH-CC-LDI-6: `modules` is optional and forgiving — entries with\n // wrong shape are silently ignored at read time, mirroring the\n // SDK's reader. Strict per-entry validation would force CLI\n // crashes on partial writes (e.g. interrupt mid-init).\n if (c.modules !== undefined) {\n if (typeof c.modules !== 'object' || c.modules === null) return false;\n }\n return true;\n}\n\n/**\n * HH-CC-LDI-6 — record a module's local-dev install in `auth.json`.\n *\n * Atomic: reads, mutates, writes. If `dashwise init` is interrupted\n * after the API call but before this returns, the install row exists\n * server-side without local persistence — the user has to re-init or\n * use the future `dashwise module recover-dev-install` command (LDI-9).\n *\n * Throws if there's no saved config (the user isn't logged in).\n * Callers should check `isLoggedIn()` first and surface a clear\n * \"run `dashwise login` first\" error.\n */\nexport function upsertModuleEntry(\n slug: string,\n entry: CliConfigModuleEntry,\n): void {\n const cfg = readConfig();\n if (!cfg) {\n throw new Error(\n 'No CLI config file. Run `dashwise login` first to create one.',\n );\n }\n const next: CliConfig = {\n ...cfg,\n modules: {\n ...(cfg.modules ?? {}),\n [slug]: entry,\n },\n };\n writeConfig(next);\n}\n\n/**\n * HH-CC-LDI-6 — read a module's local-dev entry, or `null` if none\n * has been provisioned. Returns `null` when the user isn't logged in.\n */\nexport function readModuleEntry(slug: string): CliConfigModuleEntry | null {\n const cfg = safeReadConfig();\n if (!cfg?.modules) return null;\n return cfg.modules[slug] ?? null;\n}\n\n/**\n * HH-CC-LDI-6 — remove a module's entry (used by future LDI-9\n * `dashwise module destroy-dev-install`). Idempotent — no-op when\n * the entry doesn't exist or the user isn't logged in.\n */\nexport function removeModuleEntry(slug: string): void {\n const cfg = safeReadConfig();\n if (!cfg?.modules || !(slug in cfg.modules)) return;\n const { [slug]: _removed, ...rest } = cfg.modules;\n void _removed;\n const next: CliConfig = {\n ...cfg,\n modules: Object.keys(rest).length > 0 ? rest : undefined,\n };\n writeConfig(next);\n}\n\n/**\n * Return current file mode bits (for diagnostics). Returns `null`\n * on any failure (file missing, permission denied, etc.).\n */\nexport function configFileMode(): number | null {\n try {\n const s = statSync(configPath());\n return s.mode & 0o777;\n } catch {\n return null;\n }\n}\n\n/** Confirm a saved config exists (for `whoami` short-circuit). */\nexport function isLoggedIn(): boolean {\n return readSavedToken() !== null;\n}\n\n/** Convenience helper used by tests + diagnostic commands. */\nexport function configSummary(): {\n path: string;\n exists: boolean;\n mode: number | null;\n} {\n return {\n path: configPath(),\n exists: existsSync(configPath()),\n mode: configFileMode(),\n };\n}\n\n// Helpers above intentionally exported individually — no default\n// export so tree-shake at the `bin.ts` level remains effective.\n","/**\n * Thin HTTP client for the DashWise backend, tailored for the CLI's\n * call patterns.\n *\n * Three shapes of authenticated request emerge in the CLI:\n * 1. **Public** — `dashwise login` device-code start/poll (no token yet)\n * 2. **CLI token (`Bearer dwc_*`)** — every command after login\n * 3. **One-off Bearer** — internal use during the login flow\n * (we don't have a saved token while polling)\n *\n * The class is intentionally small + dependency-free (uses\n * `globalThis.fetch`). Error envelopes from the backend\n * (`{ code, message, retriable, context }`) are surfaced as typed\n * `ApiError`s so command code can branch on `err.code`.\n */\n\nimport { resolveApiUrl, readSavedToken } from './config.js';\n\nexport interface ApiErrorEnvelope {\n code?: string;\n message?: string;\n retriable?: boolean;\n context?: Record<string, unknown>;\n}\n\nexport class ApiError extends Error {\n readonly status: number;\n readonly code: string;\n readonly context: Record<string, unknown> | undefined;\n readonly retriable: boolean;\n\n constructor(status: number, envelope: ApiErrorEnvelope | null, fallbackMessage: string) {\n const code = envelope?.code ?? codeFromStatus(status);\n const message = envelope?.message ?? fallbackMessage;\n super(message);\n this.name = 'ApiError';\n this.status = status;\n this.code = code;\n this.context = envelope?.context;\n this.retriable = envelope?.retriable ?? status >= 500;\n }\n}\n\nexport interface RequestOptions {\n /**\n * Auth mode:\n * - `'auto'` (default) — `Bearer <saved-token>` if one exists,\n * else no header.\n * - `'public'` — no Authorization header (used by the device-code\n * endpoints which authenticate via the device_code itself).\n * - `{ token: 'dwc_...' }` — explicit token (used during login\n * polling before we save the file).\n */\n auth?: 'auto' | 'public' | { token: string };\n\n /** Override the base URL (testing / `--api-url` flag). */\n baseUrl?: string;\n\n /** Extra request headers (rare — diagnostic plumbing). */\n headers?: Record<string, string>;\n}\n\n/**\n * Make a JSON request. Returns the parsed body (`T`) or throws an\n * `ApiError`. 204 responses return `undefined`.\n */\nexport async function apiRequest<T = unknown>(\n method: string,\n path: string,\n body?: unknown,\n options: RequestOptions = {},\n): Promise<T> {\n const baseUrl = (options.baseUrl ?? resolveApiUrl()).replace(/\\/+$/, '');\n const url = `${baseUrl}${path.startsWith('/') ? path : `/${path}`}`;\n\n const headers: Record<string, string> = {\n Accept: 'application/json',\n ...(options.headers ?? {}),\n };\n if (body !== undefined) {\n headers['Content-Type'] = 'application/json';\n }\n const authMode = options.auth ?? 'auto';\n if (authMode === 'auto') {\n const saved = readSavedToken();\n if (saved) headers['Authorization'] = `Bearer ${saved}`;\n } else if (typeof authMode === 'object' && authMode.token) {\n headers['Authorization'] = `Bearer ${authMode.token}`;\n }\n\n let res: Response;\n try {\n res = await fetch(url, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n } catch (err) {\n // Network-level failure — DNS, ECONNREFUSED, TLS, etc. Surface\n // as an ApiError with a stable code so callers can branch.\n throw new ApiError(0, { code: 'NETWORK_ERROR', message: (err as Error).message }, 'Network error');\n }\n\n if (res.status === 204) {\n return undefined as T;\n }\n\n const contentType = res.headers.get('content-type') ?? '';\n let parsed: unknown = null;\n if (contentType.includes('application/json')) {\n try {\n parsed = await res.json();\n } catch {\n parsed = null;\n }\n } else if (res.status >= 400) {\n // Non-JSON error body — still want a stable error shape.\n try {\n parsed = { message: await res.text() };\n } catch {\n parsed = null;\n }\n }\n\n if (!res.ok) {\n throw new ApiError(res.status, asEnvelope(parsed), `HTTP ${res.status}`);\n }\n return parsed as T;\n}\n\nfunction asEnvelope(v: unknown): ApiErrorEnvelope | null {\n if (!v || typeof v !== 'object') return null;\n const env = v as Record<string, unknown>;\n const out: ApiErrorEnvelope = {};\n if (typeof env.code === 'string') out.code = env.code;\n if (typeof env.message === 'string') out.message = env.message;\n if (typeof env.retriable === 'boolean') out.retriable = env.retriable;\n if (env.context && typeof env.context === 'object') {\n out.context = env.context as Record<string, unknown>;\n }\n return out;\n}\n\nfunction codeFromStatus(status: number): string {\n if (status === 401) return 'UNAUTHENTICATED';\n if (status === 403) return 'FORBIDDEN';\n if (status === 404) return 'NOT_FOUND';\n if (status === 0) return 'NETWORK_ERROR';\n if (status >= 500) return 'INTERNAL_ERROR';\n return 'HTTP_ERROR';\n}\n\n// ── HH-CC-LDI-6: typed wrapper for POST /api/installations/dev ────────\n\n/**\n * Shape returned by `POST /api/installations/dev` — matches the\n * backend's `DevInstallationController.createDevInstallation` envelope.\n * See `dashwise-backend/src/modules/modules/installation/dev-installation.controller.ts`.\n *\n * P1-C (identity collapse): the endpoint now mints a scoped `dwk_` API\n * key against the fresh kind='local' install instead of a 90-day\n * runtime JWT. `runtime_token` / `runtime_token_expires_at` are GONE\n * (no back-compat). `tables_applied` reports how many manifest\n * `owns.tables` were materialized when a `manifest` was pushed (0 when\n * absent or empty).\n */\nexport interface DevInstallationResponse {\n installation: {\n id: number;\n kind: 'sandbox' | 'local' | 'production';\n workspace_id: number;\n module_id: number;\n module_version_id: number;\n application_id: number;\n installed_on: string;\n };\n module: {\n id: number;\n slug: string;\n name: string;\n };\n /** Raw `dwk_*` API key minted against the local install. Shown once. */\n api_key: string;\n /** DB id of the `module_api_keys` row. */\n api_key_id: number;\n /** ISO-8601 expiry of the minted key (default LOCAL_DEV_TOKEN_TTL_DAYS). */\n api_key_expires_at: string;\n /** Count of `manifest.owns.tables` materialized (0 when no manifest sent). */\n tables_applied: number;\n}\n\n/**\n * Create a local-dev module installation + mint a scoped `dwk_` API key.\n *\n * Called by `dashwise init` / `dashwise module register` after the user\n * picks a workspace + slug + name. The returned `api_key` is persisted\n * into `auth.json#modules[<slug>]` via `upsertModuleEntry`; the SDK's\n * `createDevClient({ moduleSlug })` reads from there on every dev server\n * boot, and the schema commands send it as `Authorization: Bearer`.\n *\n * P1-C C2: when `manifest` (the full `module.json`, schema_version 2) is\n * supplied, the backend runs `parseManifest` (422 MANIFEST_INVALID with\n * `issues[]` on failure) and materializes `manifest.owns.tables` into the\n * fresh draft install via the schema-propose/apply path — closing the\n * convert→register gap where `owns.tables` used to be dropped. The count\n * comes back as `tables_applied`.\n *\n * Errors (surfaced as `ApiError` with the backend's `code` field):\n * - 403 — caller is not a member of the target workspace.\n * - 409 SLUG_ALREADY_EXISTS — a module with this slug exists. The\n * user should pick a different slug or run `dashwise module\n * destroy-dev-install` first (LDI-9).\n * - 422 MANIFEST_INVALID — the pushed manifest failed validation;\n * `context.issues[]` carries the per-path problems.\n * - 503 RUNTIME_DATA_API_DISABLED — `BUILDER_SESSION_TOKEN_SECRET`\n * unset on the backend. Operator-side issue, not a user issue.\n */\nexport async function createDevInstallation(\n body: {\n slug: string;\n name: string;\n description?: string;\n workspaceId: number;\n /**\n * HH-CC-FUP-2 — `module_kind` from the scaffold's `module.json`.\n * Without forwarding it the backend's draft manifest gets no\n * `module_kind`, `SchemaProposeService.getManifest()` falls back\n * to `'ai_builder'`, and that wrong value rewrites the local\n * module.json on the first watcher tick.\n */\n moduleKind?: 'ai_builder' | 'hand_authored' | 'custom';\n /**\n * P1-C C2 — the full local `module.json` object (schema_version 2).\n * When present, the backend materializes `owns.tables` into the\n * fresh draft install. Optional: `dashwise init` scaffolds an empty\n * draft (omits it), while `dashwise module register` sends the\n * existing manifest so a converted app's tables land server-side.\n */\n manifest?: Record<string, unknown>;\n },\n options: RequestOptions = {},\n): Promise<DevInstallationResponse> {\n return apiRequest<DevInstallationResponse>(\n 'POST',\n '/api/installations/dev',\n body,\n options,\n );\n}\n\n/**\n * HH-CC-LDI-9 — destroy a local-dev installation.\n *\n * Maps to `DELETE /api/installations/dev/:installationId`. The\n * backend (`DevInstallationService.destroy`) tears down the install\n * row + its application tile, and conditionally drops the module\n * if it was a dev-only artifact (no other installs, never published).\n *\n * Returns `{ installation_id, module_id, module_also_dropped }`.\n *\n * Errors (`ApiError`):\n * - 404 `INSTALLATION_NOT_FOUND` — install id doesn't exist.\n * - 403 `INSTALLATION_KIND_NOT_LOCAL` — refuses non-local installs.\n * - 403 `NOT_WORKSPACE_MEMBER` — caller isn't in the install's workspace.\n */\nexport interface DestroyDevInstallationResponse {\n installation_id: number;\n module_id: number;\n module_also_dropped: boolean;\n}\n\nexport async function destroyDevInstallation(\n installationId: number,\n options: RequestOptions = {},\n): Promise<DestroyDevInstallationResponse> {\n return apiRequest<DestroyDevInstallationResponse>(\n 'DELETE',\n `/api/installations/dev/${installationId}`,\n undefined,\n options,\n );\n}\n\n// ── HH-CC-P1-C1/C4 + P1-C: per-installation scoped API keys ──────────\n\n/**\n * One (source/table/operation) grant on a scoped `dwk_` key. Mirrors\n * the backend's `ApiKeyGrantDto`\n * (`installation/api-keys/dto/api-keys.dto.ts`).\n *\n * - `source: 'module'` → a table the module owns\n * (`manifest.owns.tables[].slug`), named via `tableSlug`.\n * - `source: 'datahub'` → a shared Data Hub table (`tableId`) or an\n * entire database (`applicationId`). The backend requires exactly\n * one of those two for a datahub grant.\n *\n * `operations` lists the verbs to allow (own-table `list`/`get` both\n * collapse to `read` server-side).\n */\nexport interface ApiKeyGrantInput {\n source: 'module' | 'datahub';\n tableId?: number;\n applicationId?: number;\n tableSlug?: string;\n operations: Array<'create' | 'read' | 'update' | 'delete'>;\n}\n\n/**\n * A materialized grant row as returned in list/create responses — one\n * row per (scope, operation). Fields mirror the `module_api_key_grants`\n * entity. Defensive/optional so an older backend that doesn't yet echo\n * grants doesn't break parsing.\n */\nexport interface ApiKeyGrantRow {\n source: 'module' | 'datahub';\n table_id: number | null;\n application_id: number | null;\n table_slug: string | null;\n operation: 'create' | 'read' | 'update' | 'delete';\n}\n\n/**\n * Shape returned by the API-keys endpoints. Mirrors `ApiKeyPublic`\n * from the backend controller. NEVER contains the hash or raw key\n * (those are POST-time-only).\n *\n * P1-C: `grants` is the scoped-access surface the backend now returns;\n * `scopes` / `enforcement_mode` are legacy/optional (the identity-\n * collapse migration drops `enforcement_mode` server-side — kept\n * optional here so the CLI parses both old and new payloads).\n */\nexport interface ApiKeyPublic {\n id: number;\n installation_id: number;\n module_id: number;\n name: string;\n key_prefix: string;\n created_by_user_id: number;\n created_at: string;\n last_used_at: string | null;\n expires_at: string | null;\n revoked_at: string | null;\n /** P1-C — scoped grant rows (one per scope×operation). */\n grants?: ApiKeyGrantRow[];\n /** @deprecated Legacy coarse scope strings; may be absent post-P1-C. */\n scopes?: string[];\n /** @deprecated Removed by the identity-collapse migration. */\n enforcement_mode?: 'legacy_full' | 'scoped';\n}\n\n/** Response from `POST /api/installations/:id/api-keys`. */\nexport interface CreateApiKeyResponse {\n api_key: ApiKeyPublic;\n /** Plaintext key. Backend returns this ONCE; never stored. */\n raw_key: string;\n}\n\nexport async function createApiKey(\n installationId: number,\n body: {\n name: string;\n /** P1-C scoped grants → backend `ApiKeyGrantDto[]`. */\n grants?: ApiKeyGrantInput[];\n expires_at?: string;\n },\n options: RequestOptions = {},\n): Promise<CreateApiKeyResponse> {\n return apiRequest<CreateApiKeyResponse>(\n 'POST',\n `/api/installations/${installationId}/api-keys`,\n body,\n options,\n );\n}\n\nexport async function listApiKeys(\n installationId: number,\n options: RequestOptions = {},\n): Promise<{ api_keys: ApiKeyPublic[] }> {\n return apiRequest<{ api_keys: ApiKeyPublic[] }>(\n 'GET',\n `/api/installations/${installationId}/api-keys`,\n undefined,\n options,\n );\n}\n\nexport async function revokeApiKey(\n installationId: number,\n keyId: number,\n options: RequestOptions = {},\n): Promise<{ api_key: ApiKeyPublic }> {\n return apiRequest<{ api_key: ApiKeyPublic }>(\n 'DELETE',\n `/api/installations/${installationId}/api-keys/${keyId}`,\n undefined,\n options,\n );\n}\n\n// ── Phase 2 W3: SSO callback-origin allowlist ────────────────────────\n//\n// The install's `allowed_origins_jsonb` — a full-replace list of extra\n// origins the SSO start-url endpoint accepts as a callback destination.\n// `kind='local'` installs implicitly allow localhost; these are the\n// stored extras (https-only for non-localhost entries; the backend\n// validates). User-JWT + workspace-admin routes; the CLI resolves the\n// install id from `auth.json#modules[slug]` so the user never types it.\n\n/** Response envelope for GET/PUT `/api/installations/:id/origins`. */\nexport interface InstallationOriginsResponse {\n allowed_origins: string[];\n}\n\n/** `GET /api/installations/:id/origins` — read the current allowlist. */\nexport async function getOrigins(\n installationId: number,\n options: RequestOptions = {},\n): Promise<InstallationOriginsResponse> {\n return apiRequest<InstallationOriginsResponse>(\n 'GET',\n `/api/installations/${installationId}/origins`,\n undefined,\n options,\n );\n}\n\n/**\n * `PUT /api/installations/:id/origins` — full-replace the allowlist.\n * The caller reads the current list, edits it, and writes the whole\n * thing back (there is no add/remove endpoint — the `dashwise origins`\n * subcommands do the read-modify-write on the client side).\n */\nexport async function setOrigins(\n installationId: number,\n allowedOrigins: string[],\n options: RequestOptions = {},\n): Promise<InstallationOriginsResponse> {\n return apiRequest<InstallationOriginsResponse>(\n 'PUT',\n `/api/installations/${installationId}/origins`,\n { allowed_origins: allowedOrigins },\n options,\n );\n}\n\n// ── HH-CC-LDI-8: schema-mutation endpoints (mirrors LDI-4 controller) ──\n\n/** FieldDef body shape — open enough to carry `options`, `target`, etc. */\nexport interface FieldDefBody {\n slug: string;\n type: string;\n required?: boolean;\n options?: string[];\n target?: string;\n default?: unknown;\n}\n\n/**\n * Common response shape from `propose_*` endpoints — the LDI-4\n * controller strips the in-memory `sdk` blob, so the wire payload is\n * just the operation result + sdk_regen metadata.\n */\nexport interface SchemaOpResponse {\n table_slug: string;\n physical_table_id: number;\n manifest_version: number;\n sdk_regen: { hash: string; ms: number };\n /** Present on proposeField responses (add / update / remove). */\n operation_applied?: 'add' | 'update' | 'remove';\n}\n\nexport interface DropTableResponse {\n table_slug: string;\n dropped: boolean;\n manifest_version: number;\n sdk_regen: { hash: string; ms: number };\n}\n\n// ── Phase 2 wire protocol: schema mutations on /api/module-api ───────\n//\n// These target the install-agnostic module-API schema plane. There is\n// NO installation id in the URL — the backend resolves the install from\n// the `dwk_` key in the Authorization header (which the caller passes\n// via `options.auth`). Auth policy (Phase-1 C3 minus the URL id): the\n// key's install IS the install; mutations require a kind='local'\n// install (else SCHEMA_LOCKED); reads are allowed for any api_key.\n\n/** `POST /api/module-api/schema/tables` — create a table. */\nexport async function createTable(\n body: {\n slug: string;\n fields: FieldDefBody[];\n indexes?: Array<{ fields: string[]; unique?: boolean }>;\n },\n options: RequestOptions = {},\n): Promise<SchemaOpResponse> {\n return apiRequest<SchemaOpResponse>(\n 'POST',\n `/api/module-api/schema/tables`,\n body,\n options,\n );\n}\n\n/** `DELETE /api/module-api/schema/tables/:tableSlug` — drop a table. */\nexport async function dropTable(\n tableSlug: string,\n options: RequestOptions = {},\n): Promise<DropTableResponse> {\n return apiRequest<DropTableResponse>(\n 'DELETE',\n `/api/module-api/schema/tables/${tableSlug}`,\n undefined,\n options,\n );\n}\n\n/** `POST /api/module-api/schema/fields` — add a field. */\nexport async function addField(\n body: { table_slug: string; field: FieldDefBody },\n options: RequestOptions = {},\n): Promise<SchemaOpResponse> {\n return apiRequest<SchemaOpResponse>(\n 'POST',\n `/api/module-api/schema/fields`,\n body,\n options,\n );\n}\n\n/** `PATCH /api/module-api/schema/fields/:tableSlug/:fieldSlug` — update. */\nexport async function updateField(\n tableSlug: string,\n fieldSlug: string,\n body: Omit<FieldDefBody, 'slug'>,\n options: RequestOptions = {},\n): Promise<SchemaOpResponse> {\n return apiRequest<SchemaOpResponse>(\n 'PATCH',\n `/api/module-api/schema/fields/${tableSlug}/${fieldSlug}`,\n body,\n options,\n );\n}\n\n/**\n * `GET /api/module-api/schema` — read the current draft manifest. Used\n * post-mutation to write the new state back to local `module.json`\n * (HH-CC-LDI-8 REST-first / write-back-from-GET model).\n */\nexport async function getInstallationSchema(\n options: RequestOptions = {},\n): Promise<{ manifest: Record<string, unknown> }> {\n return apiRequest<{ manifest: Record<string, unknown> }>(\n 'GET',\n `/api/module-api/schema`,\n undefined,\n options,\n );\n}\n\n/** `DELETE /api/module-api/schema/fields/:tableSlug/:fieldSlug` — remove. */\nexport async function removeField(\n tableSlug: string,\n fieldSlug: string,\n options: RequestOptions = {},\n): Promise<SchemaOpResponse> {\n return apiRequest<SchemaOpResponse>(\n 'DELETE',\n `/api/module-api/schema/fields/${tableSlug}/${fieldSlug}`,\n undefined,\n options,\n );\n}\n\n// ── P3-C: cross-module dependency connect surface (D3 + D4) ───────────\n//\n// Phase 3 (modules-platform-v2) reworks cross-module deps from\n// \"resolve-or-reject at install\" to \"park-not-reject\": a declared dep\n// that can't bind (no provider install, version mismatch, exposes/action\n// gap) is PARKED as a `module_dependencies` row with `status='unbound'`\n// instead of failing the install. These endpoints let a workspace member\n// inspect + a workspace admin (re-)connect those rows.\n//\n// All routes are workspace-scoped and authenticate with the user's CLI\n// bearer (JWT) — NOT the module's `dwk_` key (that's the runtime data\n// plane). The install id is resolved by the CLI from\n// `auth.json#modules[<slug>].installationId`; the user never types it.\n\n/**\n * One dependency status/reason enum value. Mirrors the SDK's\n * `DepUnboundReason` + the backend's `module_dependencies.unbound_reason`.\n * Kept as a widened `string` on the wire type so a new backend reason\n * doesn't break CLI parsing; the CLI renders whatever it gets.\n */\nexport type DependencyStatus = 'resolved' | 'unbound';\n\n/**\n * One row from `GET /api/installations/:id/dependencies` (D4). Shape per\n * the pinned Phase-3 contract:\n * `{ slug, range, status, reason, provider:{installation_id, version} | null, contract_summary }`\n *\n * `provider` is populated only when `status='resolved'`; `reason` only\n * when `status='unbound'`. `contract_summary` is an opaque snapshot blob\n * the CLI surfaces verbatim (tables/fields/actions the bound contract\n * covers) — typed loosely so a backend shape change doesn't break the CLI.\n */\nexport interface InstallationDependency {\n slug: string;\n /**\n * Declared semver range. `null` for a legacy row whose range can't be\n * recovered — matches the backend `DependencyConnectView.range`\n * (`string | null`). Render with a `?? '*'` fallback.\n */\n range: string | null;\n status: DependencyStatus;\n reason?: string | null;\n provider?: {\n installation_id: number;\n version: string;\n } | null;\n contract_summary?: Record<string, unknown> | null;\n}\n\n/**\n * `GET /api/installations/:installationId/dependencies` (D4) — the\n * connect surface. Workspace-member auth. Returns one entry per declared\n * dep with its live resolved/unbound status.\n */\nexport async function getInstallationDependencies(\n installationId: number,\n options: RequestOptions = {},\n): Promise<InstallationDependency[]> {\n return apiRequest<InstallationDependency[]>(\n 'GET',\n `/api/installations/${installationId}/dependencies`,\n undefined,\n options,\n );\n}\n\n/**\n * `POST /api/installations/:installationId/dependencies/:providerSlug/bind`\n * (D4) — re-run single-dep resolution, snapshot the contract, flip the\n * row to `status='resolved'`. Workspace-admin auth.\n *\n * Body `{ provider_installation_id? }` is optional — omit to let the\n * backend pick the workspace's provider install; pass it to disambiguate\n * when more than one candidate exists.\n *\n * On failure the backend returns **409** with the park reason as the\n * error `code` (`MISSING_DEPENDENCY`, `DEPENDENCY_VERSION_MISMATCH`,\n * `EXPOSES_MISSING`, `EXPOSES_PRIVATE`, `ACTION_NOT_EXPOSED`,\n * `PROVIDER_NOT_PRODUCTION`, …) — surfaced here as an `ApiError`; the row\n * stays `unbound`.\n */\nexport async function bindDependency(\n installationId: number,\n providerSlug: string,\n body: { provider_installation_id?: number } = {},\n options: RequestOptions = {},\n): Promise<InstallationDependency> {\n return apiRequest<InstallationDependency>(\n 'POST',\n `/api/installations/${installationId}/dependencies/${providerSlug}/bind`,\n body,\n options,\n );\n}\n\n/**\n * `POST /api/installations/:installationId/dependencies/:providerSlug/unbind`\n * (D4) — NULL the provider ref + contract, flip the row to\n * `status='unbound'` with reason `MANUALLY_UNBOUND`. Workspace-admin auth.\n */\nexport async function unbindDependency(\n installationId: number,\n providerSlug: string,\n options: RequestOptions = {},\n): Promise<InstallationDependency> {\n return apiRequest<InstallationDependency>(\n 'POST',\n `/api/installations/${installationId}/dependencies/${providerSlug}/unbind`,\n undefined,\n options,\n );\n}\n\n/**\n * One entry in the D3 \"needs report\" `modules[]` array. Shape per the\n * pinned contract:\n * `{ slug, range, status, reason?, provider_installed_version? }`\n */\nexport interface NeedsReportModule {\n slug: string;\n /**\n * Declared semver range. `null` for a row with no recoverable range —\n * matches the backend `NeedsReportModuleEntry.range` (`string | null`).\n */\n range: string | null;\n status: DependencyStatus;\n reason?: string;\n provider_installed_version?: string;\n}\n\n/**\n * One entry in the D3 needs report's `tables[]` array (Phase 4 U3). The\n * workspace-table `uses` counterpart to {@link NeedsReportModule}. Present\n * everywhere the report exists — install/attach responses AND the dry-run\n * preview (`GET /api/modules/:id/needs`). The `would_*` statuses appear\n * ONLY in the dry-run preview (they describe what auto-match WOULD do);\n * install/attach responses carry the settled `bound`/`unbound`/`declined`.\n */\nexport interface NeedsReportTable {\n uses_slug: string;\n /** The manifest `ops` the module declares on this workspace-table slot. */\n ops: Array<'create' | 'read' | 'update' | 'delete'>;\n /** `create` | `require` | `optional` — default `require`. */\n if_missing: 'create' | 'require' | 'optional';\n /**\n * Settled or dry-run status:\n * - `bound` / `unbound` / `declined` — the persisted binding state.\n * - `would_create` / `would_bind` / `would_park` — dry-run only\n * (what install-time auto-match WOULD do for this slot).\n */\n status:\n | 'bound'\n | 'unbound'\n | 'declined'\n | 'would_create'\n | 'would_bind'\n | 'would_park';\n /** Machine reason when unbound/would_park (the uses-plane vocabulary). */\n reason?: string;\n /** The connected / candidate workspace table, when there is one. */\n table?: { id: number; name: string };\n /** Auto-computed declared→physical field map (would_bind preview). */\n auto_field_map?: Record<string, number>;\n /** Declared required fields with no compatible physical match. */\n missing_required?: string[];\n}\n\n/**\n * The D3 \"needs report\". Phase 4 populates `tables[]` (the workspace-table\n * `uses` binding half) everywhere the report exists — alongside the\n * cross-module `modules[]` half.\n */\nexport interface NeedsReport {\n modules: NeedsReportModule[];\n tables: NeedsReportTable[];\n}\n\n/**\n * `GET /api/modules/:moduleId/needs?workspace_id=N` (D3) — a DRY-RUN\n * preview of what WOULD happen if this module were installed into\n * workspace N: which deps would resolve vs park (and why). User-JWT,\n * workspace-member auth. Statuses reflect the would-be install outcome,\n * NOT a persisted `module_dependencies` row.\n */\nexport async function getModuleNeeds(\n moduleId: number,\n workspaceId: number,\n options: RequestOptions = {},\n): Promise<NeedsReport> {\n return apiRequest<NeedsReport>(\n 'GET',\n `/api/modules/${moduleId}/needs?workspace_id=${encodeURIComponent(String(workspaceId))}`,\n undefined,\n options,\n );\n}\n\n// ── P4-C: workspace-table `uses` binding surface (U4) ─────────────────\n//\n// Phase 4 (modules-platform-v2) adds the `uses` plane — a module reads +\n// writes a WORKSPACE table the workspace already owns (the declared,\n// portable counterpart to the ad-hoc numeric Data Hub bridge, and the\n// workspace-table sibling of cross-module `deps`). A module DECLARES an\n// abstract contract in `module.json#uses[].tables[]` (slug + fields +\n// abstract types + ops); each slot is BOUND to a physical workspace table\n// via a `field_map` (declared field → physical field id). The binding IS\n// the grant on the runtime plane.\n//\n// These endpoints let a workspace member inspect + a workspace admin\n// (re-)connect those `module_table_bindings` rows. All routes are\n// workspace-scoped and authenticate with the user's CLI bearer (JWT) —\n// NOT the module's `dwk_` key (that's the runtime data plane). The\n// install id is resolved by the CLI from\n// `auth.json#modules[<slug>].installationId`; the user never types it.\n\n/**\n * Binding status vocabulary on the wire. Mirrors the backend's\n * `module_table_bindings.status` — but typed as a widened union with a\n * `string` escape so a new backend value never breaks CLI parsing.\n * - `bound` — a workspace table is connected + field-mapped.\n * - `unbound` — parked (never bound / ambiguous / no match / table\n * trashed / ops widened pending consent / manually unbound).\n * - `declined` — an admin explicitly declined an optional-needs slot.\n */\nexport type BindingStatus = 'bound' | 'unbound' | 'declined';\n\n/**\n * One row from `GET /api/installations/:id/bindings` (U4). Shape per the\n * pinned Phase-4 contract:\n * `{ uses_slug, purpose, ops, consented_ops, status, reason,\n * table:{id,name}|null, field_map, missing_fields:[] }`\n *\n * - `ops` — the manifest-declared operations for this slot.\n * - `consented_ops` — what the admin consented to at bind time. The\n * ENFORCED set at runtime is `ops ∩ consented_ops`.\n * - `table` — the connected workspace table (populated iff `bound`).\n * - `field_map` — declared-field-slug → physical-field-id (iff `bound`).\n * - `missing_fields` — declared required fields not satisfiable on the\n * bound table (drives the \"re-map\"/\"re-bind\" nudge).\n * - `reason` — machine reason (uses-plane vocabulary) iff `unbound`.\n */\nexport interface InstallationBinding {\n uses_slug: string;\n /** Author-declared explanation of why the module needs this table. */\n purpose?: string | null;\n ops: Array<'create' | 'read' | 'update' | 'delete'>;\n consented_ops: Array<'create' | 'read' | 'update' | 'delete'>;\n status: BindingStatus;\n reason?: string | null;\n table?: { id: number; name: string } | null;\n field_map?: Record<string, number> | null;\n missing_fields?: string[];\n}\n\n/**\n * One candidate from `GET /api/installations/:id/bindings/:usesSlug/candidates`\n * (U4). Shape per the pinned Phase-4 contract:\n * `{ table_id, name, match_score, auto_field_map, missing_required:[] }`\n *\n * Candidates are the target workspace's non-module tables scored against\n * the slot's required-field coverage. `auto_field_map` is what the server\n * would use if this candidate is bound without an explicit `--map`;\n * `missing_required` lists declared required fields the candidate can't\n * satisfy (a non-empty list means binding this candidate would leave a\n * gap the admin must map by hand).\n */\nexport interface BindingCandidate {\n table_id: number;\n name: string;\n /** Higher = better auto-match (slugified-name equality + coverage). */\n match_score: number;\n auto_field_map: Record<string, number>;\n missing_required: string[];\n}\n\n/**\n * `GET /api/installations/:installationId/bindings` (U4) — the workspace-\n * table binding surface. Workspace-member auth. Returns one entry per\n * declared `uses` slot with its live bound/unbound/declined status.\n */\nexport async function getInstallationBindings(\n installationId: number,\n options: RequestOptions = {},\n): Promise<InstallationBinding[]> {\n return apiRequest<InstallationBinding[]>(\n 'GET',\n `/api/installations/${installationId}/bindings`,\n undefined,\n options,\n );\n}\n\n/**\n * `GET /api/installations/:installationId/bindings/:usesSlug/candidates`\n * (U4) — the ranked list of workspace tables that could satisfy a slot.\n * Workspace-member auth. Used by `dashwise bind <slug>` to present a pick\n * list (interactive) or to auto-resolve a `--table <name>` to its id.\n */\nexport async function getBindingCandidates(\n installationId: number,\n usesSlug: string,\n options: RequestOptions = {},\n): Promise<BindingCandidate[]> {\n return apiRequest<BindingCandidate[]>(\n 'GET',\n `/api/installations/${installationId}/bindings/${encodeURIComponent(usesSlug)}/candidates`,\n undefined,\n options,\n );\n}\n\n/**\n * `PUT /api/installations/:installationId/bindings/:usesSlug` (U4) —\n * (re-)bind a slot. Workspace-admin auth. Two body shapes (mutually\n * exclusive):\n * - `{ table_id, field_map? }` — bind to an existing workspace table.\n * The server validates workspace + non-module ownership + required\n * coverage + type compat, auto-completes any unmapped fields by name\n * match, and sets `consented_ops = current manifest ops`.\n * - `{ create: true }` — materialize a plain user-owned Data Hub table\n * from the manifest fields spec, then bind to it with full consent.\n *\n * On failure the backend returns a typed error (`code` on the envelope):\n * `NOT_WORKSPACE_ADMIN`, `TABLE_NOT_IN_WORKSPACE`, `TABLE_IS_MODULE_MANAGED`,\n * `MISSING_REQUIRED_FIELDS`, `FIELD_TYPE_INCOMPATIBLE`, `DECLINE_NOT_ALLOWED`\n * (for a `decline` on a require-need), etc. — surfaced as `ApiError`.\n */\nexport async function putBinding(\n installationId: number,\n usesSlug: string,\n body:\n | { table_id: number; field_map?: Record<string, number> }\n | { create: true },\n options: RequestOptions = {},\n): Promise<InstallationBinding> {\n return apiRequest<InstallationBinding>(\n 'PUT',\n `/api/installations/${installationId}/bindings/${encodeURIComponent(usesSlug)}`,\n body,\n options,\n );\n}\n\n/**\n * `POST /api/installations/:installationId/bindings/:usesSlug/unbind` (U4)\n * — NULL the table ref + field_map, flip the row to `status='unbound'`\n * with reason `MANUALLY_UNBOUND`. Workspace-admin auth. Runtime reads/\n * writes then return `USES_UNBOUND` until the slot is bound again.\n */\nexport async function unbindBinding(\n installationId: number,\n usesSlug: string,\n options: RequestOptions = {},\n): Promise<InstallationBinding> {\n return apiRequest<InstallationBinding>(\n 'POST',\n `/api/installations/${installationId}/bindings/${encodeURIComponent(usesSlug)}/unbind`,\n undefined,\n options,\n );\n}\n\n/**\n * `POST /api/installations/:installationId/bindings/:usesSlug/decline` (U4)\n * — mark an OPTIONAL-needs slot `status='declined'` (the module runs\n * without it). Workspace-admin auth. Declining a `require`-need slot is\n * rejected with `DECLINE_NOT_ALLOWED` (surfaced as an `ApiError`).\n */\nexport async function declineBinding(\n installationId: number,\n usesSlug: string,\n options: RequestOptions = {},\n): Promise<InstallationBinding> {\n return apiRequest<InstallationBinding>(\n 'POST',\n `/api/installations/${installationId}/bindings/${encodeURIComponent(usesSlug)}/decline`,\n undefined,\n options,\n );\n}\n\n// ── P4-C: workspace-table introspection (the `uses add --from-table` on-ramp) ──\n\n/** One physical field on a workspace table, as returned by introspection. */\nexport interface WorkspaceTableField {\n /** Physical field id — the value that lands in a binding's `field_map`. */\n id: number;\n slug: string;\n /** Human name (what a `--map <usesField>=<name>` override references). */\n name?: string;\n /** Physical field type (text | long_text | number | … | link_row | formula). */\n type: string;\n required?: boolean;\n}\n\n/**\n * Result of introspecting a workspace table by name for the reverse\n * on-ramp. `table_id` anchors the subsequent bind; `fields[]` carries the\n * physical types the CLI folds into abstract `uses` types.\n */\nexport interface WorkspaceTableIntrospection {\n table_id: number;\n name: string;\n slug: string;\n fields: WorkspaceTableField[];\n}\n\n/** Minimal `GET /api/tables/:id` shape the introspection helper needs. */\ninterface TableResponse {\n id: number;\n name: string;\n application_id: number;\n}\n\n/** Minimal `GET /api/fields/table/:tableId` element shape. */\ninterface FieldResponse {\n id: number;\n name: string;\n type: string;\n is_required?: boolean;\n}\n\n/**\n * Local re-implementation of the CLI's kebab slugifier (kept in sync with\n * `commands/uses/add.ts#slugify`). Backend fields expose only a human\n * `name`, no slug; the `uses` contract needs kebab field slugs, so we\n * derive one from the name. A `--map` override can reference either the\n * derived slug OR the raw `name` (both are indexed by the bind command).\n */\nfunction slugifyFieldName(name: string): string {\n return name\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '');\n}\n\n/**\n * Introspect an existing WORKSPACE table by its NUMERIC id, returning its\n * physical fields + types. Powers `dashwise uses add --from-table <id>`\n * (fold physical types → abstract `uses` contract) and the `dashwise bind\n * --map` override path (resolve `<usesField>=<physicalName>` → field id).\n *\n * Implemented over two EXISTING workspace-member-authed routes —\n * `GET /api/tables/:id` (name) + `GET /api/fields/table/:tableId` (fields)\n * — because there is no installation-scoped `uses/introspect` route in the\n * backend (the pinned U4 contract never specified one). The bearer's\n * workspace membership is enforced by `TableAccessGuard` on both routes.\n *\n * SCOPE (P4 review retarget): this resolves by numeric id only. Resolving\n * a table by NAME within the install's workspace — with the server-side\n * non-module + ambiguity checks the removed route promised — needs either\n * a backend introspection route or a workspace-tables listing that exposes\n * `module_id` (neither exists today); that name→id on-ramp is tracked\n * separately (task_2f6a4cc2). A non-numeric `tableRef` is rejected here\n * with `NON_NUMERIC_TABLE_REF` so the caller can pass the id.\n *\n * Module-managed tables are NOT filtered here (the fields route doesn't\n * expose `module_id`); a mistaken module-table id is rejected downstream\n * by the bind path's `TABLE_IS_MODULE_MANAGED` guard.\n *\n * Errors: `NON_NUMERIC_TABLE_REF` (a name was passed — pass the id),\n * plus the underlying `ApiError` (`NOT_FOUND` / `UNAUTHENTICATED` /\n * `NOT_WORKSPACE_MEMBER`) from the two GETs.\n */\nexport async function introspectWorkspaceTable(\n // Retained for call-site compatibility (both callers pass the context's\n // installationId) and for the future name→id resolution that will scope\n // the lookup to this install's workspace. Unused by the id-only path.\n _installationId: number,\n tableNameOrId: string,\n options: RequestOptions = {},\n): Promise<WorkspaceTableIntrospection> {\n const ref = String(tableNameOrId).trim();\n const asNumber = Number(ref);\n if (!Number.isInteger(asNumber) || asNumber <= 0 || String(asNumber) !== ref) {\n // A non-numeric argument is a table NAME. Name→id resolution isn't\n // available client-side (see the scope note above) — surface a typed,\n // actionable error instead of guessing.\n const message = `\"${ref}\" is not a numeric table id. Pass the workspace table's numeric id (find it in the Dashwise UI URL, or via \\`GET /api/tables/application/:applicationId\\`). Resolving a table by name is not yet supported by this command.`;\n throw new ApiError(0, { code: 'NON_NUMERIC_TABLE_REF', message }, message);\n }\n\n const table = await apiRequest<TableResponse>(\n 'GET',\n `/api/tables/${asNumber}`,\n undefined,\n options,\n );\n const rawFields = await apiRequest<FieldResponse[]>(\n 'GET',\n `/api/fields/table/${asNumber}`,\n undefined,\n options,\n );\n\n const fields: WorkspaceTableField[] = rawFields.map((f) => ({\n id: f.id,\n slug: slugifyFieldName(f.name),\n name: f.name,\n type: f.type,\n ...(f.is_required !== undefined ? { required: f.is_required } : {}),\n }));\n\n return {\n table_id: table.id,\n name: table.name,\n slug: slugifyFieldName(table.name),\n fields,\n };\n}\n\n/** Minimal shape from `GET /api/modules/by-slug/:slug` the CLI needs. */\nexport interface ModuleBySlugResponse {\n id: number;\n slug: string;\n name: string;\n current_version: string | null;\n}\n\n/**\n * `GET /api/modules/by-slug/:slug` — resolve a module's numeric id from\n * its slug. CLI-bearer auth. Used by commands that need the module id\n * (e.g. to apply a draft manifest) but only know the slug from module.json.\n */\nexport async function getModuleBySlug(\n slug: string,\n options: RequestOptions = {},\n): Promise<ModuleBySlugResponse> {\n return apiRequest<ModuleBySlugResponse>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(slug)}`,\n undefined,\n options,\n );\n}\n\n/**\n * `PUT /api/modules/:moduleId/draft/manifest` — validate + apply a full\n * manifest to the module's origin draft installation (materializes\n * physical tables/fields; Phase 4: reconciles `uses` bindings — new slots\n * park, removed slots drop). CLI-bearer auth. 400 MANIFEST_INVALID with a\n * structured `issues[]` on validation failure (surfaced as `ApiError`).\n *\n * The response echoes the applied manifest + apply metadata; callers that\n * only care about success can ignore the shape (typed loosely).\n */\nexport async function applyDraftManifest(\n moduleId: number,\n manifest: Record<string, unknown>,\n options: RequestOptions = {},\n): Promise<Record<string, unknown>> {\n return apiRequest<Record<string, unknown>>(\n 'PUT',\n `/api/modules/${moduleId}/draft/manifest`,\n manifest,\n options,\n );\n}\n","/**\n * Output formatting helpers — colors via picocolors (zero deps,\n * tiny). All output goes through these so the CLI has a consistent\n * voice + we can later add `--no-color` / `--json` modes by editing\n * one file.\n */\n\nimport pc from 'picocolors';\n\nexport function success(msg: string): void {\n process.stderr.write(`${pc.green('✓')} ${msg}\\n`);\n}\n\nexport function info(msg: string): void {\n process.stderr.write(`${pc.cyan('ℹ')} ${msg}\\n`);\n}\n\nexport function warn(msg: string): void {\n process.stderr.write(`${pc.yellow('⚠')} ${msg}\\n`);\n}\n\nexport function fail(msg: string): void {\n process.stderr.write(`${pc.red('✗')} ${msg}\\n`);\n}\n\n/** Plain text to stdout — for command output that should be pipe-able. */\nexport function out(msg: string): void {\n process.stdout.write(`${msg}\\n`);\n}\n\n/** Print a `key: value` pair, key bold and right-padded. */\nexport function kv(key: string, value: string, padTo = 14): void {\n const padded = key.padEnd(padTo);\n process.stdout.write(`${pc.bold(padded)} ${value}\\n`);\n}\n\n/** Highlight CLI commands or paths in inline text. */\nexport function code(s: string): string {\n return pc.cyan(s);\n}\n\n/** Dim secondary info (timestamps, helper hints). */\nexport function dim(s: string): string {\n return pc.dim(s);\n}\n\nexport { pc };\n","/**\n * Shared `module.json` I/O for CLI commands.\n *\n * Several commands need to read + mutate the local manifest\n * (`connect-git`, `deps add / remove`, future `module fields add`,\n * etc.). Inlining the read/write/JSON-parse dance in every command\n * leaks formatting choices (2-space indent, trailing newline) and\n * makes file-level invariants harder to enforce. This helper is the\n * single chokepoint.\n *\n * Properties:\n * - Tolerates an absent file with a typed null return.\n * - Throws a typed error (with file path) on parse failure.\n * - Writes are atomic-ish: same write pattern as the rest of the\n * CLI (one `writeFileSync`, no temp file — manifest is small +\n * local; partial writes only matter for ~256-byte regions and\n * fsync ordering on local disk).\n * - Preserves 2-space indent + trailing newline so `git diff` after\n * a CLI mutation shows only the actual change.\n * - Generic over the manifest shape — callers cast to their needed\n * shape since the manifest schema is owned by the backend.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\n\n/**\n * Reasonably-permissive shape covering what CLI commands care about.\n * The backend validator owns the full schema; we only narrow what we\n * need to read/write here.\n */\nexport interface ManifestShape {\n schema_version?: number;\n module?: {\n slug?: string;\n name?: string;\n version?: string;\n [k: string]: unknown;\n };\n module_kind?: string;\n owns?: { tables?: Array<{ slug?: string; [k: string]: unknown }> };\n dependencies?: ManifestDependency[];\n /** Phase 4 (modules-platform-v2) — WORKSPACE-table `uses` contracts. */\n uses?: ManifestUses;\n exposes?: Array<Record<string, unknown>>;\n repository?: Record<string, unknown>;\n [k: string]: unknown;\n}\n\nexport interface ManifestDependency {\n module: string;\n version: string;\n reads: Array<{ table: string; fields: string[] }>;\n writes?: Array<{ table: string; fields: string[]; operations: string[] }>;\n purpose: string;\n}\n\n/**\n * Phase 4 (modules-platform-v2) manifest `uses` block — a sibling of\n * `owns` / `dependencies` / `exposes`. Declares WORKSPACE tables the\n * module wants to read/write (the workspace already owns them; they are\n * NOT the module's own tables and NOT another module's tables). Each\n * entry is an ABSTRACT contract that gets BOUND to a physical workspace\n * table at install/bind time via a `field_map`.\n *\n * The backend's manifest validator owns the full schema; we narrow only\n * what the CLI reads/writes. `if_missing` defaults to `'require'`.\n */\nexport interface ManifestUses {\n tables: ManifestUsesTable[];\n}\n\nexport interface ManifestUsesTable {\n /** kebab-case slot slug (dep-grammar); unique across owns + uses. */\n slug: string;\n /** Optional author-facing explanation (shown to admins at bind/consent). */\n purpose?: string;\n /** Non-empty subset of create|read|update|delete. */\n ops: Array<'create' | 'read' | 'update' | 'delete'>;\n /** >=1 declared field the contract needs. */\n fields: ManifestUsesField[];\n /**\n * What happens when auto-match can't bind:\n * - `create` — materialize a plain user-owned Data Hub table.\n * - `require` — park until an admin binds (default).\n * - `optional` — park, but an admin may `decline` it.\n */\n if_missing?: 'create' | 'require' | 'optional';\n}\n\nexport interface ManifestUsesField {\n /** kebab-case field slug; unique per table. */\n slug: string;\n /**\n * The ABSTRACT type(s) the field can be — the physical bound field must\n * be compatible (text accepts text|long_text|email|url, etc.). Excludes\n * link_row / formula / ai (no cross-plane links in v1).\n */\n types: string[];\n /** Whether the contract requires this field to be present + mapped. */\n required?: boolean;\n}\n\n/**\n * Resolve the manifest path inside `dir` (defaults to `process.cwd()`).\n * Pure path math — does not touch the filesystem.\n */\nexport function manifestPath(dir?: string): string {\n return join(resolve(dir ?? process.cwd()), 'module.json');\n}\n\n/**\n * Read + parse `module.json` from `dir`. Returns `null` when the file\n * doesn't exist (so callers can branch on \"not a module directory\" vs\n * \"broken manifest\"). Throws with a clear message on parse failure.\n */\nexport function readManifest<T extends ManifestShape = ManifestShape>(dir?: string): T | null {\n const path = manifestPath(dir);\n if (!existsSync(path)) return null;\n const raw = readFileSync(path, 'utf-8');\n try {\n return JSON.parse(raw) as T;\n } catch (err) {\n throw new Error(\n `Failed to parse ${path}: ${(err as Error).message}. Fix or delete the file and re-run.`,\n );\n }\n}\n\n/**\n * Write `manifest` back to `module.json` in `dir`. Uses the canonical\n * 2-space indent + trailing newline so subsequent commits show only\n * the intended diff. Caller is responsible for any structural\n * validation — this helper is a dumb serializer.\n */\nexport function writeManifest(manifest: ManifestShape, dir?: string): void {\n const path = manifestPath(dir);\n writeFileSync(path, JSON.stringify(manifest, null, 2) + '\\n', 'utf-8');\n}\n\n/**\n * Convenience: read the manifest or throw a CLI-friendly error if\n * either the file is missing or unparseable. Use from commands that\n * REQUIRE a manifest to function (most of them).\n */\nexport function readManifestOrThrow<T extends ManifestShape = ManifestShape>(dir?: string): T {\n const manifest = readManifest<T>(dir);\n if (!manifest) {\n throw new Error(\n `No module.json found in ${resolve(dir ?? process.cwd())}. Run \\`dashwise module init\\` first or pass \\`--dir <path>\\`.`,\n );\n }\n return manifest;\n}\n","/**\n * Inline scaffold for `dashwise module init`. Each function returns\n * the file content for a single file in the target project tree.\n *\n * Kept inline (no template-files dir) because the scaffold is small\n * + benefits from having the runtime values (slug, name) interpolated\n * in TS rather than via a separate templating engine. When the\n * scaffold grows beyond ~10 files OR starts to differ meaningfully\n * between AI-built / hand-authored / custom flavors, splitting to\n * `templates/<flavor>/` becomes worth it.\n */\n\nexport type ScaffoldKind = 'hand_authored' | 'custom';\n\n/**\n * HH-CC-P1-D2 — supported `--deploy-target` values. When set, the\n * scaffold emits the matching platform config file (`railway.json`,\n * `vercel.json`, or `fly.toml`) so the project lands as a one-shot\n * deploy-ready repo. Default (omitted) writes no platform file —\n * the repo stays clean and the user can add one later by hand.\n */\nexport const DEPLOY_TARGETS = ['railway', 'vercel', 'fly'] as const;\nexport type DeployTarget = (typeof DEPLOY_TARGETS)[number];\n\nexport function isDeployTarget(value: string): value is DeployTarget {\n return (DEPLOY_TARGETS as readonly string[]).includes(value);\n}\n\nexport interface ScaffoldOptions {\n slug: string;\n name: string;\n /** Module flavor — `hand_authored` (simple isolate-runtime) or `custom` (full Next.js + machine runtime). */\n kind?: ScaffoldKind;\n /** Optional Git repository URL — populates `module.json#repository.url`. */\n repositoryUrl?: string;\n}\n\nexport function manifestJson(opts: ScaffoldOptions): string {\n const kind = opts.kind ?? 'hand_authored';\n // Seed one example `items` table so the scaffold ships a working\n // end-to-end data-plane slice (paired with `app/api/items/route.ts`,\n // which calls `db.items.list()` / `db.items.create()`). This gives\n // Scenario-A authors a concrete, runnable example instead of an empty\n // manifest + blank page.\n //\n // (An earlier version shipped an empty `tables: []` to avoid an\n // \"I didn't create that\" surprise. Dogfood feedback flipped that\n // trade: a first-run example that actually runs is worth more than a\n // pristine-but-empty manifest. Delete the `items` table + its route\n // once you add your own tables via `dashwise table create`.)\n const manifest: Record<string, unknown> = {\n schema_version: 2,\n module: {\n slug: opts.slug,\n name: opts.name,\n version: '0.0.1',\n },\n module_kind: kind,\n owns: {\n tables: [\n {\n slug: 'items',\n name: 'Items',\n fields: [\n { slug: 'title', type: 'text' },\n { slug: 'done', type: 'boolean' },\n ],\n },\n ],\n },\n };\n if (kind === 'custom') {\n manifest.runtime = {\n type: 'nextjs',\n kind: 'machine',\n machine_size: 'shared-cpu-1x',\n server_actions: true,\n };\n }\n if (opts.repositoryUrl) {\n manifest.repository = { type: 'git', url: opts.repositoryUrl };\n }\n return JSON.stringify(manifest, null, 2) + '\\n';\n}\n\nexport function packageJson(opts: ScaffoldOptions): string {\n return (\n JSON.stringify(\n {\n name: opts.slug,\n version: '0.0.1',\n private: true,\n type: 'module',\n scripts: {\n dev: 'dashwise module dev',\n 'dev:next': 'next dev',\n 'dashwise:generate': 'dashwise module generate',\n build: 'next build',\n start: 'next start',\n },\n dependencies: {\n '@dashai/sdk': '^2.0.0',\n next: '^15.0.0',\n react: '^19.0.0',\n 'react-dom': '^19.0.0',\n },\n devDependencies: {\n '@types/node': '^22.0.0',\n '@types/react': '^19.0.0',\n '@types/react-dom': '^19.0.0',\n typescript: '^5.5.0',\n },\n },\n null,\n 2,\n ) + '\\n'\n );\n}\n\nexport function tsconfigJson(): string {\n return (\n JSON.stringify(\n {\n compilerOptions: {\n target: 'ES2022',\n lib: ['dom', 'dom.iterable', 'ES2022'],\n module: 'ESNext',\n moduleResolution: 'Bundler',\n jsx: 'preserve',\n strict: true,\n skipLibCheck: true,\n resolveJsonModule: true,\n esModuleInterop: true,\n isolatedModules: true,\n allowJs: false,\n noEmit: true,\n incremental: true,\n plugins: [{ name: 'next' }],\n paths: { '@/*': ['./*'] },\n },\n include: ['next-env.d.ts', '**/*.ts', '**/*.tsx', '.next/types/**/*.ts'],\n exclude: ['node_modules'],\n },\n null,\n 2,\n ) + '\\n'\n );\n}\n\nexport function nextConfig(): string {\n return `/** @type {import(\"next\").NextConfig} */\n//\n// Phase 2 two-var contract: the deploy env supplies exactly\n// DASHWISE_API_URL + DASHWISE_API_KEY. The browser needs the API URL\n// too (the SDK's <AuthProvider> calls /api/auth/sessions/me on it), so\n// we DERIVE NEXT_PUBLIC_DASHWISE_API_URL here from DASHWISE_API_URL at\n// build/start time — you never set the NEXT_PUBLIC_ var yourself. If\n// you already have one set (e.g. a custom setup), it wins.\nconst apiUrl = process.env.DASHWISE_API_URL;\n\nconst nextConfig = {\n // Required for the platform-hosted (per-install Lambda) runtime: the\n // injected wrapper probes [.next/standalone/server.js, server.js] and\n // exit(1)s the cold start if neither exists. Without this the built\n // Lambda FATALs. Harmless for local \\`next dev\\` / \\`next start\\`.\n output: 'standalone',\n typescript: { ignoreBuildErrors: true },\n eslint: { ignoreDuringBuilds: true },\n env: {\n NEXT_PUBLIC_DASHWISE_API_URL:\n process.env.NEXT_PUBLIC_DASHWISE_API_URL ?? apiUrl,\n },\n};\nexport default nextConfig;\n`;\n}\n\nexport function nextEnvDts(): string {\n return `/// <reference types=\"next\" />\n/// <reference types=\"next/image-types/global\" />\n`;\n}\n\nexport function gitignore(): string {\n return [\n '# Dependencies',\n '/node_modules',\n '',\n '# Generated by Next.js',\n '/.next',\n '/out',\n '',\n '# Production',\n '/build',\n '',\n '# Misc',\n '.DS_Store',\n '*.log',\n '',\n '# Env',\n '.env',\n '.env.local',\n '.env.*.local',\n '',\n '# Editor',\n '.vscode/',\n '.idea/',\n '',\n '# DashWise-generated SDK output is regenerable from module.json',\n '# (run `dashwise module generate`); keep it out of source control.',\n '/node_modules/@dashai/generated/',\n '',\n ].join('\\n');\n}\n\n/**\n * HH-CC-FUP-5: `apiUrl` accepts the CLI's saved API URL so a scaffold\n * created after `dashwise login https://api.dashwise.net` doesn't lie\n * about where it expects the backend to be. Falls back to localhost:3000\n * for offline scaffolds (no login yet).\n */\nconst SCAFFOLD_DEFAULT_API_URL = 'http://localhost:3000';\n\nexport function envLocalExample(apiUrl: string = SCAFFOLD_DEFAULT_API_URL): string {\n return [\n '# Copy to .env.local + fill in real values.',\n '# Phase 2 two-var contract: exactly these two vars. `dashwise dev`',\n '# auto-injects both from ~/.config/dashwise/auth.json — you only need',\n '# to edit this file if you point at a non-default backend or run',\n '# `next dev` standalone.',\n '#',\n '# The browser needs the API URL too; next.config derives',\n '# NEXT_PUBLIC_DASHWISE_API_URL from DASHWISE_API_URL, so you never set',\n '# it yourself.',\n `DASHWISE_API_URL=${apiUrl}`,\n '# Scoped `dwk_` API key — mint with `dashwise api-keys create <name>`',\n '# for deploys; `dashwise dev` injects the local-dev key automatically.',\n 'DASHWISE_API_KEY=',\n '',\n ].join('\\n');\n}\n\nexport function envLocal(apiUrl: string = SCAFFOLD_DEFAULT_API_URL): string {\n return [\n '# Local dev config — auto-generated by `dashwise module init`.',\n `# Backend URL pinned to your logged-in CLI config (${apiUrl}). Gitignored;`,\n '# safe to edit. `dashwise dev` (the unified loop) auto-injects the',\n '# Phase 2 two-var contract — DASHWISE_API_URL + the per-module `dwk_`',\n '# DASHWISE_API_KEY — from ~/.config/dashwise/auth.json, so you',\n '# typically don\\'t need to set either here.',\n '#',\n '# The browser needs the API URL too; next.config derives',\n '# NEXT_PUBLIC_DASHWISE_API_URL from DASHWISE_API_URL automatically.',\n '# There is no DASHWISE_INSTALLATION_ID — the API key resolves the',\n '# install server-side.',\n `DASHWISE_API_URL=${apiUrl}`,\n '# Scoped `dwk_` key. Left blank; `dashwise dev` injects the local-dev',\n '# key. For a standalone `next dev`, paste one from `dashwise api-keys',\n '# create <name>`.',\n 'DASHWISE_API_KEY=',\n '',\n ].join('\\n');\n}\n\nexport function appLayoutTsx(opts: ScaffoldOptions): string {\n return `export const metadata = {\n title: ${JSON.stringify(opts.name)},\n description: ${JSON.stringify(`DashWise module: ${opts.slug}`)},\n};\n\nexport default function RootLayout({ children }: { children: React.ReactNode }) {\n return (\n <html lang=\"en\">\n <body style={{ margin: 0, fontFamily: 'system-ui, sans-serif' }}>{children}</body>\n </html>\n );\n}\n`;\n}\n\nexport function appPageTsx(opts: ScaffoldOptions): string {\n return `export default function Page() {\n return (\n <main style={{ minHeight: '100dvh', display: 'grid', placeItems: 'center', padding: 32 }}>\n <div style={{ maxWidth: 560, textAlign: 'center' }}>\n <h1 style={{ fontSize: 28, marginBottom: 8 }}>${escapeHtml(opts.name)}</h1>\n <p style={{ color: '#475569' }}>\n Module slug: <code>${escapeHtml(opts.slug)}</code>\n </p>\n <p style={{ marginTop: 24, color: '#64748b', fontSize: 14 }}>\n Run <code>dashwise module dev</code> to start the watch loop.\n <br />\n Edit <code>module.json</code> to add tables; regenerated types\n land in <code>@dashai/generated</code>.\n </p>\n </div>\n </main>\n );\n}\n`;\n}\n\nexport function readme(opts: ScaffoldOptions): string {\n const kind = opts.kind ?? 'hand_authored';\n if (kind === 'custom') {\n return readmeCustom(opts);\n }\n return readmeHandAuthored(opts);\n}\n\nfunction readmeHandAuthored(opts: ScaffoldOptions): string {\n return `# ${opts.name}\n\nA DashWise module (hand-authored). Slug: \\`${opts.slug}\\`.\n\n## Get started\n\n\\`\\`\\`bash\nnpm install\ndashwise dev # one command: watcher + Next.js dev together,\n # auth env vars auto-injected from your CLI config\n\\`\\`\\`\n\nIf you'd rather run the two halves in separate terminals (e.g. to attach a\ndebugger to Next), use the legacy two-terminal flow:\n\n\\`\\`\\`bash\ndashwise module generate # produces node_modules/@dashai/generated/\ndashwise module dev # watch module.json + auto-regenerate\nnpm run dev:next # plain Next.js dev server (in another terminal)\n\\`\\`\\`\n\n## Project layout\n\n| Path | What |\n| --- | --- |\n| \\`module.json\\` | Manifest. Declares tables, dependencies, runtime config. |\n| \\`app/\\` | Next.js App Router. Edit freely. |\n| \\`node_modules/@dashai/generated/\\` | Auto-generated typed wrappers. **Do not edit by hand** — regenerated by \\`dashwise module generate\\`. |\n\n## Imports\n\n\\`\\`\\`ts\nimport { db } from '@dashai/generated';\nimport type { ItemsRow } from '@dashai/generated';\n\n// runtime types + errors\nimport { createClient, type Where } from '@dashai/sdk';\n\\`\\`\\`\n`;\n}\n\nfunction readmeCustom(opts: ScaffoldOptions): string {\n return `# ${opts.name}\n\nA **custom DashWise module** — a full Next.js App Router app that\nruns in a per-installation Fly Machine (P7 substrate). Authenticated\nvia the DashWise NestJS backend through \\`@dashai/sdk/auth\\`.\n\nSlug: \\`${opts.slug}\\`.\n\n## Get started\n\n\\`\\`\\`bash\nnpm install\ndashwise dev # one command: watcher + Next.js dev together,\n # auth env vars auto-injected from your CLI config\n\\`\\`\\`\n\nIf you'd rather run the two halves in separate terminals (e.g. to attach a\ndebugger to Next), use the legacy two-terminal flow:\n\n\\`\\`\\`bash\ndashwise module generate # produces node_modules/@dashai/generated/\ndashwise module dev # watch + regen on module.json save (terminal 1)\nnpm run dev:next # next dev on :3000 (terminal 2)\n\\`\\`\\`\n\n## Architecture\n\n- **\\`module.json\\`** — manifest (\\`module_kind: 'custom'\\`, \\`runtime.kind: 'machine'\\`).\n- **\\`middleware.ts\\`** — \\`withAuth\\` from \\`@dashai/sdk/auth/middleware\\`. Redirects unauthenticated requests through the DashWise SSO flow.\n- **\\`app/layout.tsx\\`** — wraps the tree in \\`<AuthProvider>\\` from \\`@dashai/sdk/auth/client\\`.\n- **\\`app/page.tsx\\`** — public landing (allowlisted in \\`middleware.ts\\`).\n- **\\`app/dashboard/page.tsx\\`** — Server Component requiring a valid session via \\`getServerSession()\\`.\n- **\\`app/api/auth/callback/route.ts\\`** — exchanges the SSO one-time code for a session cookie (uses \\`exchangeCode()\\` from the SDK).\n- **\\`app/api/auth/sign-in/route.ts\\`** — one entry point that calls the backend's \\`POST /api/module-api/sso/start-url\\` (authenticated with your \\`dwk_\\` key) and 302s the browser to the returned \\`redirect_url\\`. Same path in dev + prod.\n- **\\`app/api/auth/sign-out/route.ts\\`** — clears the session cookie + tells the backend to revoke.\n\n## Imports\n\n\\`\\`\\`ts\n// Data:\nimport { db } from '@dashai/generated';\n\n// Auth (server, e.g. inside a Server Component or route handler):\nimport { getServerSession, exchangeCode, signOut } from '@dashai/sdk/auth/server';\n\n// Auth (client, inside a Client Component):\n'use client';\nimport { useSession, SignOutButton, AuthProvider } from '@dashai/sdk/auth/client';\n\n// Runtime types + errors:\nimport { type Where, RowNotFoundError } from '@dashai/sdk';\n\\`\\`\\`\n\n## Publish\n\n\\`\\`\\`bash\ndashwise module validate # local lint\ndashwise module publish --bump patch\n\\`\\`\\`\n\n## Adding UI blocks\n\nThe scaffold pre-installs two shadcn/ui primitives (\\`Button\\`, \\`Card\\`) plus the\ncanonical Tailwind 4 + theme-tokens setup. To add more components:\n\n\\`\\`\\`bash\n# shadcn/ui base (free):\nnpx shadcn@latest add input badge dialog dropdown-menu\n\n# shadcn-studio blocks (free at https://shadcnstudio.com):\nnpx shadcn@latest add @shadcn-studio/hero-section-01\n\n# shadcn-studio Pro blocks (requires \\$EMAIL + \\$LICENSE_KEY env vars):\nnpx shadcn@latest add @ss-components/dashboard-shell-01\n\\`\\`\\`\n\nIf you're using Claude Code or another IDE that supports the shadcn-studio MCP,\ntrigger \\`/cui\\` (create new UI) or \\`/rui\\` (refine existing UI) to walk through\nthe canonical block-discovery flow.\n\n## Deploying elsewhere (custom domain)\n\nThe scaffolded SSO flow works on any domain. The \\`/api/auth/sign-in\\`\nroute sends its own public origin as the \\`callback_url\\` to the backend;\nthe backend accepts it as long as the origin is on your installation's\nallowlist. Local dev (\\`http://localhost:<port>\\`) is allowlisted\nautomatically for \\`kind='local'\\` installs.\n\nFor a deployed custom domain (e.g. \\`https://mymodule.example.com\\`), add\nit to the allowlist:\n\n\\`\\`\\`bash\ndashwise origins add https://mymodule.example.com\ndashwise origins list # confirm\n\\`\\`\\`\n\nThat's it — no middleware changes, no separate token scheme. The single\n\\`dwk_\\` \\`DASHWISE_API_KEY\\` drives both the data plane and the SSO\nstart-url call.\n`;\n}\n\n// ── Custom-flavor templates ──────────────────────────────────────────\n\nexport function middlewareTs(): string {\n return `// Next.js middleware — gates every route on the DashWise session cookie.\n// Public routes (and /api/auth/*) bypass the redirect; everything else\n// 302s through the SSO flow when no \\`dashwise.session\\` cookie is set.\nimport { withAuth } from '@dashai/sdk/auth/middleware';\n\nexport default withAuth({\n // \\`/sign-in-error\\` is public so unauthenticated visitors can actually\n // see the polished SSO error page — otherwise a sign-in failure would\n // redirect-loop trying to re-authenticate.\n publicPaths: ['/', '/about', '/sign-in-error'],\n loginPath: '/api/auth/sign-in',\n});\n\nexport const config = {\n matcher: ['/((?!_next/static|_next/image|favicon.ico|public/).*)'],\n};\n`;\n}\n\nexport function appLayoutCustomTsx(opts: ScaffoldOptions): string {\n return `import './globals.css';\nimport { AuthProvider } from '@dashai/sdk/auth/client';\nimport { ThemeProvider } from '@/components/theme-provider';\n\nexport const metadata = {\n title: ${JSON.stringify(opts.name)},\n description: ${JSON.stringify(`DashWise custom module: ${opts.slug}`)},\n};\n\nexport default function RootLayout({ children }: { children: React.ReactNode }) {\n return (\n <html lang=\"en\" suppressHydrationWarning>\n <body className=\"antialiased\">\n <ThemeProvider\n attribute=\"class\"\n defaultTheme=\"system\"\n enableSystem\n disableTransitionOnChange\n >\n {/* sessionEndpoint points at the same-origin /api/auth/session\n route so the host-scoped session cookie is actually sent —\n a cross-origin fetch to the API would drop it (D8). */}\n <AuthProvider sessionEndpoint=\"/api/auth/session\">{children}</AuthProvider>\n </ThemeProvider>\n </body>\n </html>\n );\n}\n`;\n}\n\nexport function appPageCustomTsx(opts: ScaffoldOptions): string {\n return `// Public landing page — listed in middleware.ts publicPaths.\n//\n// First-run experience for unauthenticated visitors: hero with the\n// module name + tagline, a \"Sign in with DashWise\" button that kicks\n// off the SSO flow (via /api/auth/sign-in), and a feature card\n// describing what the module does. After signing in, the user lands\n// on /dashboard (Server Component, session-validated).\n//\n// Styling: shadcn/ui primitives (\\`<Button>\\`, \\`<Card>\\`) on Tailwind 4\n// theme tokens. Add more blocks via \\`npx shadcn add @shadcn-studio/...\\`\n// (see README's \"Adding UI blocks\" section).\nimport Link from 'next/link';\nimport { LogIn, LayoutDashboard } from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from '@/components/ui/card';\n\nexport default function Page() {\n return (\n <main className=\"flex min-h-dvh flex-col items-center justify-center gap-12 px-6 py-16\">\n <section className=\"flex max-w-2xl flex-col items-center gap-6 text-center\">\n <h1 className=\"text-balance text-4xl font-semibold tracking-tight sm:text-5xl\">\n ${escapeHtml(opts.name)}\n </h1>\n <p className=\"text-balance text-lg text-muted-foreground\">\n A DashWise module. Sign in with your DashWise account to access the\n dashboard and start using the workspace's data through the typed SDK.\n </p>\n <div className=\"flex flex-wrap items-center justify-center gap-3\">\n <Button asChild size=\"lg\">\n <Link href=\"/api/auth/sign-in?return_to=/dashboard\">\n <LogIn aria-hidden=\"true\" />\n Sign in with DashWise\n </Link>\n </Button>\n <Button asChild variant=\"ghost\" size=\"lg\">\n <Link href=\"/dashboard\">\n <LayoutDashboard aria-hidden=\"true\" />\n Go to dashboard\n </Link>\n </Button>\n </div>\n </section>\n\n <Card className=\"w-full max-w-2xl\">\n <CardHeader>\n <CardTitle>What you can do here</CardTitle>\n <CardDescription>\n This is a custom DashWise module — a full Next.js app authenticated\n against the DashWise SSO. Edit \\`app/page.tsx\\` to replace this\n landing page; everything else is yours to customize.\n </CardDescription>\n </CardHeader>\n <CardContent className=\"text-sm text-muted-foreground\">\n <ul className=\"space-y-2\">\n <li>\n Edit <code className=\"rounded bg-muted px-1.5 py-0.5\">module.json</code>\n {' '}to declare tables, dependencies, and runtime config.\n </li>\n <li>\n Run <code className=\"rounded bg-muted px-1.5 py-0.5\">dashwise dev</code>\n {' '}for a one-command local loop with auth env vars auto-injected.\n </li>\n <li>\n Import typed table clients from{' '}\n <code className=\"rounded bg-muted px-1.5 py-0.5\">@dashai/generated</code>\n {' '}— the SDK regenerates on every manifest save.\n </li>\n </ul>\n </CardContent>\n </Card>\n </main>\n );\n}\n`;\n}\n\nexport function appDashboardPageTsx(): string {\n return `import { getServerSession } from '@dashai/sdk/auth/server';\nimport { redirect } from 'next/navigation';\nimport { LogOut, ShieldCheck } from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from '@/components/ui/card';\n\n/**\n * Auth-gated Server Component. The middleware ensures the user has\n * a session cookie before this page renders; \\`getServerSession()\\`\n * validates the cookie against the backend's \\`/api/auth/sessions/me\\`\n * endpoint, returning the decoded \\`Session\\` (or \\`null\\` if stale).\n *\n * On a successful render, this is the polished session card — replace\n * the contents with whatever your module actually needs to show.\n */\nexport default async function Dashboard() {\n const session = await getServerSession();\n if (!session) {\n redirect('/api/auth/sign-in?return_to=/dashboard');\n }\n return (\n <main className=\"mx-auto flex min-h-dvh max-w-3xl flex-col gap-6 px-6 py-12\">\n <header className=\"flex items-start justify-between gap-4\">\n <div>\n <h1 className=\"text-2xl font-semibold tracking-tight\">Dashboard</h1>\n <p className=\"text-sm text-muted-foreground\">\n You're signed in. This page is rendered as a Server Component and\n validates the session cookie on every request.\n </p>\n </div>\n <form action=\"/api/auth/sign-out\" method=\"POST\">\n <Button variant=\"outline\" size=\"sm\" type=\"submit\">\n <LogOut aria-hidden=\"true\" />\n Sign out\n </Button>\n </form>\n </header>\n\n <Card>\n <CardHeader>\n <CardTitle className=\"flex items-center gap-2\">\n <ShieldCheck className=\"size-5 text-primary\" aria-hidden=\"true\" />\n Session\n </CardTitle>\n <CardDescription>\n Decoded from the \\`dashwise.session\\` cookie via{' '}\n <code className=\"rounded bg-muted px-1.5 py-0.5\">getServerSession()</code>.\n </CardDescription>\n </CardHeader>\n <CardContent className=\"space-y-3 text-sm\">\n <Row label=\"Email\" value={session.user.email} />\n <Row label=\"User ID\" value={String(session.user.id)} />\n <Row label=\"Workspace\" value={String(session.workspaceId)} />\n <Row label=\"Role\" value={session.role} />\n {session.installationId !== undefined && (\n <Row\n label=\"Installation\"\n value={\n session.moduleSlug\n ? \\`\\${session.installationId} (\\${session.moduleSlug})\\`\n : String(session.installationId)\n }\n />\n )}\n </CardContent>\n </Card>\n\n <Card>\n <CardHeader>\n <CardTitle>Next steps</CardTitle>\n <CardDescription>\n Replace this dashboard with your module's actual UI.\n </CardDescription>\n </CardHeader>\n <CardContent className=\"space-y-2 text-sm text-muted-foreground\">\n <p>\n <strong className=\"text-foreground\">1.</strong> Edit{' '}\n <code className=\"rounded bg-muted px-1.5 py-0.5\">module.json</code>{' '}\n to add tables, dependencies, and exposed actions.\n </p>\n <p>\n <strong className=\"text-foreground\">2.</strong> Import typed clients\n from{' '}\n <code className=\"rounded bg-muted px-1.5 py-0.5\">@dashai/generated</code>{' '}\n (regenerated on every manifest save).\n </p>\n <p>\n <strong className=\"text-foreground\">3.</strong> Run{' '}\n <code className=\"rounded bg-muted px-1.5 py-0.5\">dashwise module publish --bump patch</code>{' '}\n when you're ready to ship.\n </p>\n </CardContent>\n </Card>\n </main>\n );\n}\n\nfunction Row({ label, value }: { label: string; value: string }) {\n return (\n <div className=\"flex items-baseline justify-between gap-4 border-b border-border/50 pb-2 last:border-0 last:pb-0\">\n <span className=\"text-muted-foreground\">{label}</span>\n <span className=\"font-mono text-sm\">{value}</span>\n </div>\n );\n}\n`;\n}\n\nexport function appApiAuthSignInTs(): string {\n return `// /api/auth/sign-in — kick off the SSO flow (one path, dev + prod).\n//\n// Reads \\`?return_to=\\` from the caller (defaults to '/'), then asks the\n// DashWise backend for a redirect URL by calling the module-API\n// server-side start endpoint:\n//\n// POST /api/module-api/sso/start-url\n// Authorization: Bearer <DASHWISE_API_KEY> (the module's dwk_ key)\n// { \"callback_url\": \"<this module>/api/auth/callback?return_to=...\" }\n//\n// The backend resolves the install from the key (no installation id in\n// the request), validates the callback_url origin against the install's\n// allowlist (kind='local' installs implicitly allow localhost), and\n// returns { redirect_url, expires_in_seconds }. We 302 the browser to\n// redirect_url, which runs the existing main-app SSO flow and ends in a\n// 302 back to callback_url?code=<one-time>. The /api/auth/callback route\n// exchanges that code for a session cookie.\n//\n// No dev-vs-prod branching, no installation id, no dev-session id — the\n// single dwk_ key drives both local dev and production.\nimport { NextResponse } from 'next/server';\nimport { getPublicOrigin } from '@/lib/request-origin';\n\nexport async function GET(request: Request) {\n const url = new URL(request.url);\n const returnTo = url.searchParams.get('return_to') ?? '/';\n const apiBaseUrl = process.env.DASHWISE_API_URL;\n const apiKey = process.env.DASHWISE_API_KEY;\n\n if (!apiBaseUrl) {\n return new NextResponse('DASHWISE_API_URL must be set in the environment', {\n status: 500,\n });\n }\n if (!apiKey) {\n return new NextResponse(\n 'DASHWISE_API_KEY must be set in the environment. Run \\`dashwise dev\\` ' +\n '(local) or paste a key from \\`dashwise api-keys create\\` (deployed).',\n { status: 500 },\n );\n }\n\n // Absolute callback URL so the backend knows which host to bounce back\n // to. \\`getPublicOrigin\\` reads \\`X-Forwarded-Host\\` when present so the\n // URL points at the public domain, not the internal Node origin behind\n // reverse proxies (Railway/Vercel/Fly). The callback path is fixed at\n // /api/auth/callback by SDK convention; we tuck \\`return_to\\` onto it so\n // the callback route can resume the user's original destination.\n const moduleOrigin = getPublicOrigin(request);\n const callback = new URL('/api/auth/callback', moduleOrigin);\n callback.searchParams.set('return_to', returnTo);\n\n let res: Response;\n try {\n res = await fetch(\\`\\${apiBaseUrl}/api/module-api/sso/start-url\\`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n Authorization: \\`Bearer \\${apiKey}\\`,\n },\n body: JSON.stringify({ callback_url: callback.toString() }),\n });\n } catch (err) {\n const target = new URL('/sign-in-error', moduleOrigin);\n target.searchParams.set('code', 'server_error');\n target.searchParams.set('description', (err as Error).message);\n return NextResponse.redirect(target);\n }\n\n if (!res.ok) {\n // The backend rejected the start (bad key, callback origin not\n // allowlisted, install missing). Surface a real error page instead\n // of a raw 4xx.\n const body = (await res.json().catch(() => null)) as\n | { code?: string; message?: string }\n | null;\n const target = new URL('/sign-in-error', moduleOrigin);\n target.searchParams.set('code', body?.code ?? 'invalid_request');\n if (body?.message) target.searchParams.set('description', body.message);\n return NextResponse.redirect(target);\n }\n\n const body = (await res.json().catch(() => null)) as\n | { redirect_url?: string }\n | null;\n if (!body?.redirect_url) {\n const target = new URL('/sign-in-error', moduleOrigin);\n target.searchParams.set('code', 'server_error');\n target.searchParams.set(\n 'description',\n 'start-url response missing redirect_url',\n );\n return NextResponse.redirect(target);\n }\n return NextResponse.redirect(body.redirect_url);\n}\n`;\n}\n\nexport function appApiAuthCallbackTs(): string {\n return `// /api/auth/callback — receives \\`?code=&return_to=\\` from the\n// DashWise SSO start endpoint OR \\`?error=&error_description=\\` if the\n// SSO flow failed. Two paths:\n//\n// 1. Success path: exchange \\`?code\\` for a session cookie via\n// \\`exchangeCode()\\`, then redirect to \\`return_to\\`.\n// 2. Error path: SSO returned \\`?error=\\` — redirect to the polished\n// sign-in-error page so the user sees a real error UI instead of\n// a raw 4xx page. The error code maps to known SSO error codes\n// (e.g. \\`access_denied\\`, \\`server_error\\`, \\`invalid_request\\`).\nimport { NextResponse } from 'next/server';\nimport { exchangeCode } from '@dashai/sdk/auth/server';\nimport { getPublicOrigin } from '@/lib/request-origin';\n\nexport async function GET(request: Request) {\n const url = new URL(request.url);\n // Resolve the public origin once — all redirects below are\n // back to this module, and behind a reverse proxy url.origin is\n // the internal Node origin (localhost:<PORT>), not the public host.\n const publicOrigin = getPublicOrigin(request);\n const error = url.searchParams.get('error');\n if (error) {\n const target = new URL('/sign-in-error', publicOrigin);\n target.searchParams.set('code', error);\n const description = url.searchParams.get('error_description');\n if (description) target.searchParams.set('description', description);\n return NextResponse.redirect(target);\n }\n const code = url.searchParams.get('code');\n const returnTo = url.searchParams.get('return_to') ?? '/';\n if (!code) {\n const target = new URL('/sign-in-error', publicOrigin);\n target.searchParams.set('code', 'missing_code');\n return NextResponse.redirect(target);\n }\n try {\n await exchangeCode(code); // sets the dashwise.session cookie\n } catch (err) {\n const target = new URL('/sign-in-error', publicOrigin);\n target.searchParams.set('code', 'exchange_failed');\n target.searchParams.set('description', (err as Error).message);\n return NextResponse.redirect(target);\n }\n return NextResponse.redirect(new URL(returnTo, publicOrigin));\n}\n`;\n}\n\nexport function appApiAuthSignOutTs(): string {\n return `// /api/auth/sign-out — best-effort backend revoke + cookie clear,\n// then redirect to / so the browser actually navigates somewhere\n// after the form POST. A 204 here would leave the user staring at\n// /dashboard with stale-rendered HTML — the cookie WAS cleared but\n// they'd think nothing happened. 303 See Other forces the browser\n// to follow with GET (not re-POST), landing on the public '/' page.\nimport { NextResponse } from 'next/server';\nimport { signOut } from '@dashai/sdk/auth/server';\nimport { getPublicOrigin } from '@/lib/request-origin';\n\nexport async function POST(request: Request) {\n await signOut();\n // Build the redirect against the public origin so we don't land\n // the user on \\`http://localhost:<PORT>/\\` when running behind a\n // reverse proxy (Railway/Vercel/Fly).\n return NextResponse.redirect(new URL('/', getPublicOrigin(request)), 303);\n}\n`;\n}\n\n/**\n * `app/api/items/route.ts` — a minimal example data-plane route that\n * exercises the generated SDK end-to-end against the seeded `items`\n * table (declared in `module.json#owns.tables`). GET lists rows, POST\n * creates one. Delete this file (and the `items` table) once you've\n * added your own tables via `dashwise table create`.\n *\n * Imports from `@dashai/generated` — the typed client the CLI's watcher\n * materializes into `node_modules/@dashai/generated/` on every manifest\n * save. Run `dashwise dev` (or `dashwise module generate`) first, or the\n * import won't resolve.\n */\nexport function appApiItemsRouteTs(): string {\n return `// Example data-plane route — lists + creates rows in the seeded\n// \\`items\\` table via the generated typed SDK. Delete this (and the\n// \\`items\\` table in module.json) once you add your own tables.\n//\n// \\`db\\` comes from @dashai/generated, regenerated on every module.json\n// save by \\`dashwise dev\\`. Run it (or \\`dashwise module generate\\`) first.\nimport { NextResponse } from 'next/server';\nimport { db } from '@dashai/generated';\n\nexport async function GET() {\n const page = await db.items.list({ limit: 50 });\n return NextResponse.json(page.rows);\n}\n\nexport async function POST(request: Request) {\n const body = (await request.json().catch(() => null)) as\n | { title?: unknown; done?: unknown }\n | null;\n const title = typeof body?.title === 'string' ? body.title : '';\n if (!title) {\n return NextResponse.json(\n { error: 'title is required (string)' },\n { status: 400 },\n );\n }\n const done = typeof body?.done === 'boolean' ? body.done : false;\n const row = await db.items.create({ title, done });\n return NextResponse.json(row, { status: 201 });\n}\n`;\n}\n\nexport function appApiAuthSessionTs(): string {\n return `// /api/auth/session — SAME-ORIGIN session probe for client components.\n//\n// D8: the browser's <AuthProvider> can't read the session by calling the\n// cross-origin DashWise API directly, because the \\`dashwise.session\\`\n// cookie is host-scoped to THIS module's origin and is never sent to\n// \\`api.dashwise.net\\`. So <AuthProvider sessionEndpoint=\"/api/auth/session\">\n// hits this route (same origin → the cookie IS sent); we validate it\n// server-side via \\`getServerSession()\\` (which forwards the cookie to the\n// API for us) and return the fully-enriched session — or \\`null\\` — as JSON.\n//\n// \\`getServerSession()\\` already merges the RBAC slice, so the client\n// receives \\`rbacRoles\\` / \\`rbacPermissions\\` and skips a second fetch.\nimport { NextResponse } from 'next/server';\nimport { getServerSession } from '@dashai/sdk/auth/server';\n\nexport async function GET() {\n const session = await getServerSession();\n // Always 200 — \\`null\\` is a valid \"not signed in\" answer the client\n // maps to \\`unauthenticated\\`. \\`no-store\\` so a stale signed-in body is\n // never served to a signed-out user after sign-out.\n return NextResponse.json(session, {\n headers: { 'Cache-Control': 'no-store' },\n });\n}\n`;\n}\n\nexport function packageJsonCustom(opts: ScaffoldOptions): string {\n return (\n JSON.stringify(\n {\n name: opts.slug,\n version: '0.0.1',\n private: true,\n type: 'module',\n scripts: {\n dev: 'dashwise module dev',\n 'dev:next': 'next dev',\n 'dashwise:generate': 'dashwise module generate',\n build: 'next build',\n start: 'next start',\n },\n dependencies: {\n '@dashai/sdk': '^2.0.0',\n next: '^15.0.0',\n react: '^19.0.0',\n 'react-dom': '^19.0.0',\n // Styling system — same shadcn + Tailwind 4 stack as the\n // main DashWise frontend, so look-and-feel stays consistent\n // and module authors can add more blocks via the\n // shadcn-studio MCP (`npx shadcn add @shadcn-studio/...`).\n tailwindcss: '^4',\n '@tailwindcss/postcss': '^4',\n 'tw-animate-css': '^1.4.0',\n shadcn: '^4.0.8',\n 'radix-ui': '^1.4.3',\n 'class-variance-authority': '^0.7.1',\n clsx: '^2.1.1',\n 'tailwind-merge': '^3.5.0',\n 'lucide-react': '^0.577.0',\n 'next-themes': '^0.4.6',\n },\n devDependencies: {\n '@types/node': '^22.0.0',\n '@types/react': '^19.0.0',\n '@types/react-dom': '^19.0.0',\n typescript: '^5.5.0',\n },\n },\n null,\n 2,\n ) + '\\n'\n );\n}\n\n// ── shadcn + Tailwind 4 stack (custom scaffold) ──────────────────────\n//\n// These templates mirror the configuration the main `dashwise-frontend`\n// uses, so visual + UX consistency is preserved across the dashboard\n// and scaffolded modules. The stack: Tailwind 4 (no config file —\n// config lives in `globals.css` via `@import \"tailwindcss\"`), shadcn\n// New York style, oklch theme tokens, lucide icons, next-themes for\n// the dark-mode toggle.\n//\n// Module authors who want more blocks add them via the shadcn-studio\n// MCP workflow: `/cui` for new blocks, `/rui` for refines (see the\n// scaffold's README for the canonical pointer).\n\n/**\n * `components.json` — shadcn config. Pins the style + base color so\n * `npx shadcn add` produces the same look as the rest of the DashWise\n * ecosystem. The two registries (`@shadcn-studio` free + `@ss-components`\n * Pro) are declared so module authors can pull blocks from either\n * without re-running init.\n */\nexport function componentsJson(): string {\n return (\n JSON.stringify(\n {\n $schema: 'https://ui.shadcn.com/schema.json',\n style: 'new-york',\n rsc: true,\n tsx: true,\n tailwind: {\n config: '',\n css: 'app/globals.css',\n baseColor: 'neutral',\n cssVariables: true,\n prefix: '',\n },\n iconLibrary: 'lucide',\n rtl: false,\n aliases: {\n components: '@/components',\n utils: '@/lib/utils',\n ui: '@/components/ui',\n lib: '@/lib',\n hooks: '@/hooks',\n },\n registries: {\n '@shadcn-studio': 'https://shadcnstudio.com/r/{name}.json',\n '@ss-components': {\n url: 'https://shadcnstudio.com/r/components/{name}.json',\n params: {\n email: '${EMAIL}',\n license_key: '${LICENSE_KEY}',\n },\n },\n },\n },\n null,\n 2,\n ) + '\\n'\n );\n}\n\n/**\n * `postcss.config.mjs` — Tailwind 4's PostCSS plugin entry. No other\n * plugins needed; the rest of the build is Next.js's defaults.\n */\nexport function postcssConfigMjs(): string {\n return `const config = {\n plugins: {\n \"@tailwindcss/postcss\": {},\n },\n};\n\nexport default config;\n`;\n}\n\n/**\n * `app/globals.css` — Tailwind 4 entry + oklch theme tokens.\n *\n * Tailwind 4 has no `tailwind.config.ts`; config lives here via the\n * `@import \"tailwindcss\"` directive + CSS custom properties. The\n * `:root` block defines the light theme; `.dark` overrides it. Tokens\n * are copied verbatim from the main dashwise-frontend so module authors\n * who later read the frontend code see the same names.\n */\nexport function globalsCss(): string {\n return `@import \"tailwindcss\";\n@import \"tw-animate-css\";\n@import \"shadcn/tailwind.css\";\n\n@custom-variant dark (&:is(.dark *));\n\n:root {\n --background: oklch(1 0 0);\n --foreground: oklch(0.14 0 0);\n --card: oklch(1 0 0);\n --card-foreground: oklch(0.14 0 0);\n --popover: oklch(1 0 0);\n --popover-foreground: oklch(0.14 0 0);\n --primary: oklch(0.2 0 0);\n --primary-foreground: oklch(0.99 0 0);\n --secondary: oklch(0.97 0 0);\n --secondary-foreground: oklch(0.2 0 0);\n --muted: oklch(0.97 0 0);\n --muted-foreground: oklch(0.56 0 0);\n --accent: oklch(0.97 0 0);\n --accent-foreground: oklch(0.2 0 0);\n --destructive: oklch(0.58 0.24 28.48);\n --border: oklch(0.92 0 0);\n --input: oklch(0.92 0 0);\n --ring: oklch(0.71 0 0);\n --radius: 0.625rem;\n\n --font-sans:\n ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,\n \"Segoe UI\", Roboto, \"Helvetica Neue\", Arial, sans-serif;\n --font-mono:\n ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas,\n \"Liberation Mono\", \"Courier New\", monospace;\n}\n\n.dark {\n --background: oklch(0.14 0 0);\n --foreground: oklch(0.99 0 0);\n --card: oklch(0.2 0 0);\n --card-foreground: oklch(0.99 0 0);\n --popover: oklch(0.2 0 0);\n --popover-foreground: oklch(0.99 0 0);\n --primary: oklch(0.92 0 0);\n --primary-foreground: oklch(0.2 0 0);\n --secondary: oklch(0.27 0 0);\n --secondary-foreground: oklch(0.99 0 0);\n --muted: oklch(0.27 0 0);\n --muted-foreground: oklch(0.71 0 0);\n --accent: oklch(0.27 0 0);\n --accent-foreground: oklch(0.99 0 0);\n --destructive: oklch(0.7 0.19 22.23);\n --border: oklch(0.27 0 0);\n --input: oklch(0.27 0 0);\n --ring: oklch(0.56 0 0);\n}\n\n* {\n border-color: var(--border);\n}\n\nbody {\n background-color: var(--background);\n color: var(--foreground);\n font-family: var(--font-sans);\n}\n`;\n}\n\n/**\n * `lib/utils.ts` — the canonical \\`cn()\\` helper that shadcn components\n * import. Combines \\`clsx\\` (conditional class composition) with\n * \\`tailwind-merge\\` (resolves conflicting Tailwind utilities, e.g.\n * \\`px-2 px-4\\` → \\`px-4\\`).\n */\nexport function libUtilsTs(): string {\n return `import { clsx, type ClassValue } from \"clsx\";\nimport { twMerge } from \"tailwind-merge\";\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n`;\n}\n\n/**\n * \\`lib/request-origin.ts\\` — resolve the **public** origin of an\n * incoming request, respecting reverse-proxy headers.\n *\n * Used by the three \\`/api/auth/*\\` route handlers when building\n * redirect URLs. Behind a reverse proxy (Railway, Vercel, Fly,\n * Cloudflare, an nginx in front of a Node container, etc.)\n * \\`new URL(request.url).origin\\` reports the *internal* origin the\n * Node process is bound to — usually \\`http://localhost:<PORT>\\` —\n * not the public host the browser actually hit. Building the SSO\n * \\`return_to\\` against that internal origin sends the browser to\n * localhost after the round-trip and breaks sign-in entirely.\n */\nexport function libRequestOriginTs(): string {\n return `/**\n * Resolve the **public** origin of an incoming request.\n *\n * Behind a reverse proxy (Railway, Vercel, Fly, Cloudflare, an\n * nginx in front of a Node container, etc.) \\`new URL(request.url)\\`\n * reports the *internal* origin the Node process is bound to —\n * usually \\`http://localhost:<PORT>\\` — not the public URL the\n * browser hit. The proxy preserves the public origin in\n * \\`X-Forwarded-*\\` headers; we read those first.\n *\n * Falls back to \\`new URL(request.url).origin\\` for local dev where\n * there's no proxy in front of Next.js.\n *\n * Both \\`x-forwarded-proto\\` and \\`x-forwarded-host\\` can be\n * comma-separated when multiple proxies chain; the leftmost entry\n * is the original client-facing one per RFC 7239 conventions.\n */\nexport function getPublicOrigin(request: Request): string {\n const forwardedProto = request.headers.get('x-forwarded-proto');\n const forwardedHost = request.headers.get('x-forwarded-host');\n if (forwardedProto && forwardedHost) {\n const proto = forwardedProto.split(',')[0].trim();\n const host = forwardedHost.split(',')[0].trim();\n return \\`\\${proto}://\\${host}\\`;\n }\n return new URL(request.url).origin;\n}\n`;\n}\n\n/**\n * \\`components/ui/button.tsx\\` — vendored from the dashwise-frontend's\n * canonical button (which itself came from shadcn New York). Vendored\n * (vs running \\`npx shadcn add\\` in a post-install) so the scaffold\n * doesn't need network access at install time.\n */\nexport function componentsUiButtonTsx(): string {\n return `import * as React from \"react\";\nimport { cva, type VariantProps } from \"class-variance-authority\";\nimport { Slot } from \"radix-ui\";\n\nimport { cn } from \"@/lib/utils\";\n\nconst buttonVariants = cva(\n \"inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n {\n variants: {\n variant: {\n default: \"bg-primary text-primary-foreground hover:bg-primary/90\",\n destructive:\n \"bg-destructive text-white hover:bg-destructive/90\",\n outline:\n \"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground\",\n secondary:\n \"bg-secondary text-secondary-foreground hover:bg-secondary/80\",\n ghost:\n \"hover:bg-accent hover:text-accent-foreground\",\n link: \"text-primary underline-offset-4 hover:underline\",\n },\n size: {\n default: \"h-9 px-4 py-2 has-[>svg]:px-3\",\n sm: \"h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5\",\n lg: \"h-10 rounded-md px-6 has-[>svg]:px-4\",\n icon: \"size-9\",\n },\n },\n defaultVariants: {\n variant: \"default\",\n size: \"default\",\n },\n },\n);\n\nfunction Button({\n className,\n variant = \"default\",\n size = \"default\",\n asChild = false,\n ...props\n}: React.ComponentProps<\"button\"> &\n VariantProps<typeof buttonVariants> & {\n asChild?: boolean;\n }) {\n const Comp = asChild ? Slot.Root : \"button\";\n return (\n <Comp\n data-slot=\"button\"\n className={cn(buttonVariants({ variant, size, className }))}\n {...props}\n />\n );\n}\n\nexport { Button, buttonVariants };\n`;\n}\n\n/**\n * \\`components/ui/card.tsx\\` — vendored from the dashwise-frontend. Same\n * rationale as button.tsx.\n */\nexport function componentsUiCardTsx(): string {\n return `import * as React from \"react\";\n\nimport { cn } from \"@/lib/utils\";\n\nfunction Card({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card\"\n className={cn(\n \"flex flex-col gap-6 rounded-xl border bg-card py-6 text-card-foreground shadow-sm\",\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction CardHeader({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-header\"\n className={cn(\n \"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6\",\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction CardTitle({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-title\"\n className={cn(\"leading-none font-semibold\", className)}\n {...props}\n />\n );\n}\n\nfunction CardDescription({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-description\"\n className={cn(\"text-sm text-muted-foreground\", className)}\n {...props}\n />\n );\n}\n\nfunction CardContent({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-content\"\n className={cn(\"px-6\", className)}\n {...props}\n />\n );\n}\n\nfunction CardFooter({ className, ...props }: React.ComponentProps<\"div\">) {\n return (\n <div\n data-slot=\"card-footer\"\n className={cn(\"flex items-center px-6\", className)}\n {...props}\n />\n );\n}\n\nexport { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };\n`;\n}\n\n/**\n * \\`components/theme-provider.tsx\\` — thin re-export of the next-themes\n * provider, marked \\`\"use client\"\\`. Layout wraps in this so the\n * \\`.dark\\` class can be applied to \\`<html>\\` based on system preference\n * or explicit user toggle.\n */\nexport function componentsThemeProviderTsx(): string {\n return `\"use client\";\n\nimport { ThemeProvider as NextThemesProvider } from \"next-themes\";\n\nexport function ThemeProvider({\n children,\n ...props\n}: React.ComponentProps<typeof NextThemesProvider>) {\n return <NextThemesProvider {...props}>{children}</NextThemesProvider>;\n}\n`;\n}\n\n/**\n * \\`app/sign-in-error/page.tsx\\` — the SSO error landing.\n *\n * Reached via redirect from /api/auth/callback when the SSO flow\n * returns \\`?error=\\` or when code exchange fails. Renders a polished\n * error UI with the SSO error code (plain-English when known) + a\n * \"Try again\" button that retries the sign-in flow.\n *\n * Listed in middleware.ts publicPaths so unauthenticated visitors can\n * actually reach the error page (otherwise the redirect would loop).\n */\nexport function appSignInErrorPageTsx(): string {\n return `import Link from 'next/link';\nimport { AlertTriangle, RefreshCw } from 'lucide-react';\nimport { Button } from '@/components/ui/button';\nimport {\n Card,\n CardContent,\n CardDescription,\n CardHeader,\n CardTitle,\n} from '@/components/ui/card';\n\nconst ERROR_MESSAGES: Record<string, string> = {\n access_denied:\n \"You declined the sign-in request. To use this module, you'll need to authorize it on the DashWise sign-in page.\",\n server_error:\n 'The DashWise sign-in server returned an internal error. This is usually transient — try again in a moment.',\n invalid_request:\n 'The sign-in request was malformed. This is almost always a configuration bug — check that DASHWISE_API_URL and DASHWISE_API_KEY are set correctly and the callback origin is allowlisted (run \"dashwise origins add <url>\").',\n missing_code:\n 'The callback URL was missing the expected exchange code. This usually means the SSO flow was interrupted.',\n exchange_failed:\n \"The exchange code couldn't be redeemed for a session. The code may have expired (they're single-use and short-lived) — try signing in again.\",\n};\n\ninterface SignInErrorPageProps {\n searchParams: Promise<{ code?: string; description?: string }>;\n}\n\nexport default async function SignInErrorPage({ searchParams }: SignInErrorPageProps) {\n const params = await searchParams;\n const errorCode = params.code ?? 'unknown';\n const friendlyMessage = ERROR_MESSAGES[errorCode];\n return (\n <main className=\"flex min-h-dvh items-center justify-center px-6 py-12\">\n <Card className=\"w-full max-w-lg\">\n <CardHeader>\n <div className=\"flex items-start gap-3\">\n <div className=\"rounded-full bg-destructive/10 p-2\">\n <AlertTriangle className=\"size-5 text-destructive\" aria-hidden=\"true\" />\n </div>\n <div className=\"flex-1\">\n <CardTitle>Sign-in failed</CardTitle>\n <CardDescription>\n The DashWise SSO flow couldn't complete.\n </CardDescription>\n </div>\n </div>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <div className=\"space-y-1\">\n <div className=\"text-xs uppercase tracking-wide text-muted-foreground\">\n Error code\n </div>\n <code className=\"block rounded bg-muted px-2 py-1 text-sm\">\n {errorCode}\n </code>\n </div>\n {friendlyMessage && (\n <p className=\"text-sm text-muted-foreground\">{friendlyMessage}</p>\n )}\n {params.description && (\n <div className=\"space-y-1\">\n <div className=\"text-xs uppercase tracking-wide text-muted-foreground\">\n Detail\n </div>\n <p className=\"text-sm text-muted-foreground\">{params.description}</p>\n </div>\n )}\n <div className=\"flex flex-wrap gap-2 pt-2\">\n <Button asChild>\n <Link href=\"/api/auth/sign-in?return_to=/dashboard\">\n <RefreshCw aria-hidden=\"true\" />\n Try again\n </Link>\n </Button>\n <Button asChild variant=\"ghost\">\n <Link href=\"/\">Back to landing</Link>\n </Button>\n </div>\n </CardContent>\n </Card>\n </main>\n );\n}\n`;\n}\n\nfunction escapeHtml(s: string): string {\n return s\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"');\n}\n\n/**\n * Canonical module-slug regex — kebab-case only (P1-C C5).\n *\n * `^[a-z][a-z0-9-]*[a-z0-9]$`: starts with a letter, ends with a letter\n * or digit, hyphen-separated in between. Single-char slugs (`a`) are\n * allowed by the trailing-optional shape below. Underscores are NO\n * LONGER accepted — kebab slugs are the dependency-capable identity\n * from birth (module deps + `dwk_` grants key off `owns.tables[].slug`\n * which follows the same rule). Rejecting `_` at authoring time avoids\n * minting an install whose slug the manifest validator would later\n * refuse.\n */\nexport const MODULE_SLUG_REGEX = /^[a-z]([a-z0-9-]*[a-z0-9])?$/;\n\n/** Slug validation — kebab-case, matching the manifest schema's regex. */\nexport function isValidSlug(slug: string): boolean {\n return MODULE_SLUG_REGEX.test(slug);\n}\n\n/**\n * A one-line, actionable reason a slug is invalid — used by `init` /\n * `register` so the user gets more than \"doesn't match a regex\". Calls\n * out the two most common mistakes (underscores, trailing hyphen)\n * explicitly.\n */\nexport function slugValidationMessage(slug: string): string {\n if (slug.includes('_')) {\n const suggestion = slug.replace(/_/g, '-').replace(/^-+|-+$/g, '');\n return (\n `Slug \"${slug}\" uses underscores — module slugs must be kebab-case ` +\n `(letters, digits, hyphens; e.g. \"${suggestion || 'my-module'}\"). ` +\n `Rename it and retry.`\n );\n }\n return `Slug \"${slug}\" must be kebab-case — match /^[a-z][a-z0-9-]*[a-z0-9]$/ (a leading letter, then letters/digits/hyphens, no trailing hyphen).`;\n}\n\n// ── HH-CC-FUP-5: agent-facing scaffold docs ───────────────────────────\n//\n// CLAUDE.md + spec.md + agent-log.md ship with every scaffold so AI\n// coding agents (Claude Code, Cursor, etc.) inherit the spec-first +\n// log-every-change discipline used in the dashwise-backend codebase\n// without the author having to write any of it themselves. The bodies\n// are kept short on purpose — pointers to the canonical docs\n// (`building-modules.md`, manifest schema) instead of duplicating\n// content that drifts.\n\nexport function claudeMd(opts: ScaffoldOptions): string {\n const isCustom = (opts.kind ?? 'hand_authored') === 'custom';\n return `# CLAUDE.md — ${opts.name}\n\nInstructions for AI coding agents (Claude Code, Cursor, etc.) working\nin this DashWise module. Read this before making changes.\n\n## What this module is\n\nA DashWise ${isCustom ? '**custom Next.js** module (full app runtime, machine-class)' : '**hand-authored simple** module (isolate runtime)'} authored against \\`@dashai/sdk\\`.\nModule slug: \\`${opts.slug}\\`.\n\nDashWise calls apps \"modules\". A module is a Next.js app + a\nmanifest (\\`module.json\\`) declaring the tables it owns, modules it\ndepends on, and actions it exposes. The DashWise backend hosts the\ndata plane + auth; this module ships UI + business logic.\n\n## Spec-first, log-every-change\n\nThis scaffold mirrors the dashwise-backend convention:\n\n- **\\`spec.md\\`** is the source of truth for what this module does —\n tables, fields, API contracts, business rules, error cases. Update\n it BEFORE writing code that changes behavior. If a behavior isn't\n in \\`spec.md\\`, it isn't real yet.\n- **\\`agent-log.md\\`** is an append-only log of every meaningful\n change. Every commit that touches \\`module.json\\`, \\`spec.md\\`, a\n schema mutation, or a public surface MUST add an entry. Format:\n\n \\`\\`\\`\n ## YYYY-MM-DD HH:MM — <author or agent name>\n\n **Change:** one-line summary\n **Files:** comma-separated list of files\n **Reason:** why this change was necessary\n **Spec impact:** none | updated spec.md §<section>\n \\`\\`\\`\n\n Reverse chronological (newest first).\n\n## Schema changes go through the CLI, not by hand\n\n\\`module.json\\` is the manifest. The backend has its own copy that\nthe runtime data plane uses. To keep them in sync, mutate via the\nCLI — \\`dashwise table create\\`, \\`dashwise field add\\`, etc. —\nwhich calls the schema endpoints and rewrites the local\n\\`module.json\\` from the backend's response. Hand-edits to\n\\`module.json\\` won't sync until the next CLI mutation picks them up.\n\nCommon commands:\n\n\\`\\`\\`\ndashwise table create <slug> --field <slug:type[:required]>\ndashwise table delete <slug>\ndashwise field add <table> <slug:type[:required]>\ndashwise field remove <table> <slug>\ndashwise field set-type <table> <slug> <type>\n\\`\\`\\`\n\nAllowed field types: \\`text\\`, \\`long_text\\`, \\`number\\`, \\`boolean\\`,\n\\`date\\`, \\`datetime\\`, \\`single_select\\`, \\`multi_select\\`,\n\\`link_row\\`, \\`file\\`, \\`multi_file\\`, \\`email\\`, \\`url\\`,\n\\`phone\\`, \\`formula\\`, \\`ai\\`.\n\n## Read + write data via the generated SDK\n\nThe CLI's watcher regenerates typed clients into\n\\`node_modules/@dashai/generated/\\` every time \\`module.json\\` changes.\nImport from there:\n\n\\`\\`\\`ts\nimport { db, qb } from '@dashai/generated';\n\n// Simple CRUD\nconst rows = await db.<table>.list();\nawait db.<table>.create({ /* fields */ });\n\n// Query builder (joins, aggregates)\nconst stats = await qb.from('<table>').where({ /* ... */ }).execute();\n\\`\\`\\`\n\nThe data plane authenticates via the per-module scoped \\`dwk_\\` API key\ncached in \\`~/.config/dashwise/auth.json#modules[${opts.slug}]\\` after\n\\`dashwise init\\` provisions the dev install. \\`dashwise dev\\` injects it\nas \\`DASHWISE_API_KEY\\` into the Next.js child env automatically. The\nkey binds the install server-side — there is no \\`DASHWISE_INSTALLATION_ID\\`.\n\n## Auth in dev mode\n\n\\`dashwise dev\\` registers a dev-mode SSO session with the backend so\nworkspace members can sign into the locally-running module via DashWise\nSSO. The scaffold's \\`/api/auth/sign-in\\` route is a single path: it\ncalls \\`POST /api/module-api/sso/start-url\\` with your \\`dwk_\\` key and\nfollows the returned \\`redirect_url\\` — the same code runs in dev and in\nproduction, with no installation id or dev-session id in the request.\n\nIn Server Components: \\`await getServerSession()\\` (from\n\\`@dashai/sdk/auth/server\\`).\nIn Client Components: \\`useSession()\\` (from\n\\`@dashai/sdk/auth/client\\`), wrapped in \\`<AuthProvider>\\` (already\nin \\`app/layout.tsx\\`).\n\n## Local dev lifecycle\n\n\\`\\`\\`\ndashwise login # one-time, opens browser\ndashwise init [slug] # scaffold + provision dev install\ndashwise dev # watcher + next dev, auth env auto-injected\ndashwise module destroy-dev-install # tear down when done (cleans backend + auth.json)\n\\`\\`\\`\n\n## Engineering bar\n\n- **No hacks, shortcuts, or temporary \"quick fixes\" as final\n implementations.** If something needs work, leave it as a stub and\n open an issue / TODO with a clear name — don't bury a workaround.\n- **No silent error swallowing.** Catch what you can handle; surface\n what you can't. Tests should assert error codes, not just status.\n- **No untyped \\`any\\`.** The generated SDK gives you types — use\n them. If you need an escape hatch, add a \\`@ts-expect-error\\` with\n a comment explaining why.\n- **No secrets in code or env files.** Use \\`runtime.secrets[]\\` in\n \\`module.json\\`; values are encrypted at rest and resolved at\n runtime.\n\n## Pointers\n\n- Full walkthrough — \\`@dashai/cli\\`'s [building-modules.md](https://github.com/Intuize/dashwise-cli/blob/main/docs/building-modules.md).\n- Manifest schema — \\`@dashai/sdk/dist/manifest/schema.d.ts\\` (generated from the backend Zod source of truth).\n- Query plane reference — same docs, \\`Query AST v1 wire format\\` section.\n`;\n}\n\nexport function specMd(opts: ScaffoldOptions): string {\n return `# ${opts.name} — Spec\n\n> Living document. Source of truth for what this module does. Update\n> this BEFORE changing code that changes behavior — see CLAUDE.md.\n\n## Notion\n\n(link to ticket / design doc here, or remove this section)\n\n## Overview\n\nOne-sentence description of what this module does, who uses it, and\nwhat tables it owns.\n\n## Database schema\n\n| Table | Columns | Notes |\n|---|---|---|\n| \\`items\\` | \\`title:text\\`, \\`done:boolean\\` | seeded example — edit or replace; \\`dashwise table create <slug> --field <slug:type>\\` adds more |\n\n## API / contract\n\n| Method | Path | Auth | Purpose |\n|---|---|---|---|\n| GET | \\`/api/items\\` | dwk_ (server-side) | list \\`items\\` rows via \\`db.items.list()\\` |\n| POST | \\`/api/items\\` | dwk_ (server-side) | create an \\`items\\` row via \\`db.items.create()\\` |\n\n## Business rules\n\n- (RBAC, validation, domain logic.)\n\n## Dependencies\n\nModules this module reads from + which tables/actions:\n\n- (none yet — declare in \\`module.json#dependencies[]\\`)\n\n## Exposed tables + actions\n\nTables or server-actions this module makes available to other\nmodules:\n\n- (none yet)\n\n## Error cases\n\n- (what can go wrong + how it's handled)\n\n## Decisions\n\n- (architectural choices + the trade-offs that drove them)\n\n## Open questions\n\n- (anything blocking implementation)\n`;\n}\n\nexport function agentLogMd(opts: ScaffoldOptions): string {\n return `# Agent Log — ${opts.name}\n\nAppend-only log of meaningful changes to this module. Every commit\nthat touches \\`module.json\\`, \\`spec.md\\`, a schema, or a public\nsurface MUST add an entry here in the same change.\n\nFormat (reverse chronological, newest first):\n\n\\`\\`\\`\n## YYYY-MM-DD HH:MM — <author or agent name>\n\n**Change:** one-line summary\n**Files:** comma-separated list of files\n**Reason:** why this change was necessary\n**Spec impact:** none | updated spec.md §<section>\n\n(optional: longer context, verification steps, decisions deferred)\n\\`\\`\\`\n\n---\n\n## ${new Date().toISOString().slice(0, 10)} — dashwise module init\n\n**Change:** Scaffolded module \\`${opts.slug}\\` via \\`dashwise module init\\`.\n**Files:** entire scaffold (\\`module.json\\`, \\`app/\\`, \\`components/\\`, ...).\n**Reason:** initial scaffold.\n**Spec impact:** seeded \\`spec.md\\` template — fill in before first\nschema mutation.\n`;\n}\n\n// ── HH-CC-P1-D2: deploy-target platform config templates ──────────────\n//\n// When `dashwise init` is run with `--deploy-target <platform>`, the\n// scaffold emits a single platform config file. These templates are\n// intentionally minimal — they cover the build/start contract and\n// reasonable defaults for a Next.js custom module; the operator still\n// pushes env vars via `dashwise env export --format <platform> | sh`\n// (P1-D1). Default (no flag) emits no file — the repo stays clean.\n//\n// Templates are deliberately copy-paste-able for the simple module\n// flavor too, since all three platforms can host plain Node services.\n\n/**\n * Railway picks up `railway.json` for build/deploy config. The schema\n * is documented at <https://docs.railway.com/reference/config-as-code>.\n * Nixpacks is Railway's default builder for Node — it autodetects\n * Next.js from `package.json` so we don't need to spell out build/start\n * commands; the `restartPolicyType` line is the one tweak worth making\n * since the default is `ALWAYS`, which masks crash loops.\n *\n * Env vars are NOT set here — Railway reads them from its dashboard or\n * via `railway variables set` (which is what `dashwise env export\n * --format railway` produces).\n */\nexport function railwayJson(_opts: ScaffoldOptions): string {\n return (\n JSON.stringify(\n {\n $schema: 'https://railway.com/railway.schema.json',\n build: {\n builder: 'NIXPACKS',\n },\n deploy: {\n restartPolicyType: 'ON_FAILURE',\n restartPolicyMaxRetries: 3,\n },\n },\n null,\n 2,\n ) + '\\n'\n );\n}\n\n/**\n * Vercel auto-detects Next.js from `package.json` and doesn't strictly\n * need a `vercel.json` — but emitting one declares \"this repo is\n * Vercel-ready\" and gives the author a hook for future overrides\n * (rewrites, headers, regions, etc.) without a second commit later.\n *\n * Env vars are NOT inlined here — Vercel reads them from its dashboard\n * or via `vercel env add` (which is what `dashwise env export --format\n * vercel` produces).\n */\nexport function vercelJson(_opts: ScaffoldOptions): string {\n return (\n JSON.stringify(\n {\n $schema: 'https://openapi.vercel.sh/vercel.json',\n framework: 'nextjs',\n },\n null,\n 2,\n ) + '\\n'\n );\n}\n\n/**\n * Fly's `fly.toml` is more involved — it carries the app name + region\n * + machine sizing. We seed `app = \"<slug>\"` from the module slug; if\n * the slug is already taken globally on fly.io, the author will hit a\n * clear \"name taken\" error from `fly launch` and can edit this file.\n *\n * `primary_region = \"iad\"` is Fly's recommended default for US-East\n * latency; reasonable for the typical DashWise install (api.dashwise.net\n * is also US-East). Authors targeting other regions should edit this.\n *\n * `auto_stop_machines = \"stop\"` + `min_machines_running = 0` keeps cost\n * down for low-traffic modules — Fly will spin up on first request.\n * Authors who want always-on can flip `min_machines_running = 1`.\n *\n * Env vars (DASHWISE_API_KEY etc.) are NOT inlined here — they go in\n * Fly secrets via `fly secrets set` (`dashwise env export --format\n * fly` produces those).\n */\nexport function flyToml(opts: ScaffoldOptions): string {\n return `# fly.toml — generated by \\`dashwise init --deploy-target fly\\`.\n# Run \\`fly launch --no-deploy --copy-config\\` to register this app with\n# Fly; the launcher will read this file and prompt for anything missing.\n#\n# Edit \\`app\\` if the slug is already taken globally on fly.io.\n# Edit \\`primary_region\\` for non-US-East deploys (https://fly.io/docs/reference/regions/).\n\napp = \"${opts.slug}\"\nprimary_region = \"iad\"\n\n[build]\n\n[http_service]\n internal_port = 3000\n force_https = true\n auto_stop_machines = \"stop\"\n auto_start_machines = true\n min_machines_running = 0\n processes = [\"app\"]\n\n[[vm]]\n cpu_kind = \"shared\"\n cpus = 1\n memory_mb = 256\n`;\n}\n","/**\n * HH-CC-LDI-6 — workspace selection helpers used across commands\n * that need to scope an operation to one workspace (`dashwise init`,\n * `dashwise dev`, future `dashwise module status`, etc.).\n *\n * Two resolution paths emerge from the existing CLI:\n *\n * - **Non-interactive** (CI, scripted) — caller passes `--workspace\n * <slug-or-id>`. We validate against the user's accessible\n * workspaces; throw on miss. Auto-pick if the user has exactly\n * one workspace.\n *\n * - **Interactive** (TTY, no `--workspace` flag) — when the user\n * has multiple workspaces and `interactive: true` is passed, we\n * prompt with @clack's `select`. Otherwise we throw with the\n * same \"re-run with --workspace\" error as the non-interactive\n * path.\n *\n * The split exists because `dashwise dev` was designed for\n * scripting (errors loudly with a re-run hint) and `dashwise init`\n * is designed for interactive onboarding (asks the user to pick).\n * One function, two policies via the `interactive` flag.\n */\n\nimport { isCancel, select } from '@clack/prompts';\nimport { apiRequest } from './api-client.js';\n\nexport interface WorkspaceSummary {\n id: number;\n name: string;\n slug: string;\n}\n\n/**\n * Resolve which workspace an operation should target.\n *\n * Resolution order:\n * 1. If `flag` is set → match it against the user's workspaces by\n * slug (preferred) or numeric id; throw if no match.\n * 2. Else if the user has exactly one workspace → auto-pick it.\n * 3. Else if `interactive` and we're in a TTY → prompt with @clack.\n * 4. Else → throw with a \"re-run with --workspace\" hint.\n *\n * `apiToken` is taken explicitly (not from saved config) so callers\n * can pass an in-memory token during the login flow or a per-call\n * override token. Most callers pass `readSavedToken()`.\n */\nexport async function selectWorkspace(opts: {\n apiUrl: string;\n apiToken: string;\n flag?: string;\n interactive: boolean;\n}): Promise<WorkspaceSummary> {\n const workspaces = await apiRequest<WorkspaceSummary[]>(\n 'GET',\n '/api/workspaces',\n undefined,\n { baseUrl: opts.apiUrl, auth: { token: opts.apiToken } },\n );\n if (workspaces.length === 0) {\n throw new Error(\n 'No workspaces found for your account. Create a workspace at the DashWise dashboard first.',\n );\n }\n\n // Flag path — caller provided a slug or id.\n if (opts.flag !== undefined) {\n return matchWorkspaceOrThrow(workspaces, opts.flag);\n }\n\n // Single workspace — auto-pick. Same behavior in both modes.\n if (workspaces.length === 1) {\n return workspaces[0]!;\n }\n\n // Multiple workspaces — interactive prompt OR throw.\n if (opts.interactive && process.stdout.isTTY) {\n const choice = await select({\n message: 'Which workspace should this module live in?',\n options: workspaces.map((w) => ({\n value: w.slug,\n label: w.name,\n hint: `slug=${w.slug}, id=${w.id}`,\n })),\n });\n if (isCancel(choice)) {\n throw new Error('Aborted.');\n }\n const picked = workspaces.find((w) => w.slug === choice);\n if (!picked) {\n // Shouldn't happen — @clack returns one of the options we\n // gave it — but defensive guard so a TS narrowing failure\n // doesn't surface as a stack trace.\n throw new Error(`Internal error: selection \"${String(choice)}\" did not match any workspace.`);\n }\n return picked;\n }\n\n // Non-interactive multi-workspace case — throw with the re-run hint.\n const list = workspaces\n .map((w) => ` - ${w.slug} (id=${w.id}, name=\"${w.name}\")`)\n .join('\\n');\n throw new Error(\n `You have ${workspaces.length} workspaces. Re-run with --workspace <slug-or-id> to pick one:\\n${list}`,\n );\n}\n\n/**\n * Match a `--workspace` flag value against the workspace list.\n *\n * Accepts either a slug (preferred) or a numeric id as a string.\n * Throws if there's no match — surfacing the list helps users\n * notice typos.\n *\n * Exported for tests; not part of the typical command surface.\n */\nexport function matchWorkspaceOrThrow(\n workspaces: WorkspaceSummary[],\n flag: string,\n): WorkspaceSummary {\n const asNumber = Number.parseInt(flag, 10);\n const isNumeric = !Number.isNaN(asNumber) && String(asNumber) === flag;\n const match = isNumeric\n ? workspaces.find((w) => w.id === asNumber)\n : workspaces.find((w) => w.slug === flag);\n if (!match) {\n const list = workspaces.map((w) => ` - ${w.slug} (id=${w.id})`).join('\\n');\n throw new Error(`No workspace matching --workspace=${flag}. Available:\\n${list}`);\n }\n return match;\n}\n","/**\n * `dashwise module init <slug>` — scaffold a new DashWise module\n * project in a fresh directory.\n *\n * As of 2026-05-18, the DEFAULT scaffold is the full Next.js custom-\n * module scaffold — a real Next.js 16 app with `middleware.ts`,\n * `/api/auth/*` routes, an `<AuthProvider>` wrap, and a protected\n * `app/dashboard/page.tsx` example. Authentication + workspace\n * context are wired against the DashWise NestJS backend out of the\n * box (per the v1 plan in\n * `dashwise-devops-docs/plans/module-authoring-platform.md`).\n *\n * Files emitted by the default (`custom` kind):\n *\n * module.json — manifest (schema_version 2)\n * package.json — deps on @dashai/sdk + next + react\n * tsconfig.json\n * next.config.mjs\n * next-env.d.ts\n * .gitignore — ignores node_modules + .next + .dashwise/\n * .env.local.example — DASHWISE_* var template\n * middleware.ts — uses withAuth() from @dashai/sdk/auth/middleware\n * app/layout.tsx — wraps {children} in <AuthProvider>\n * app/page.tsx — public landing\n * app/dashboard/page.tsx — protected route using getServerSession()\n * app/api/auth/sign-in/route.ts — kicks off DashWise SSO redirect\n * app/api/auth/callback/route.ts — exchanges one-time code for cookie\n * app/api/auth/sign-out/route.ts — clears cookie + tells backend\n * README.md — getting-started + auth flow explainer\n *\n * For the legacy minimal scaffold (no Next.js auth wiring — purely\n * hand-authored simple-module runtime), pass `--simple`:\n *\n * dashwise module init my-mod --simple\n *\n * This emits 9 files (no middleware, no /api/auth/*, no dashboard).\n * The `--simple` flag is permanent — some module use cases (public\n * data viewers, demo modules) genuinely don't need auth.\n *\n * `--custom` is kept as a back-compat alias for the default and is\n * silently deprecated. New code should not pass either flag for the\n * full scaffold — just `dashwise module init <slug>`.\n *\n * Refuses to overwrite an existing non-empty directory unless\n * `--force` is passed. Does NOT run `npm install` automatically —\n * surfaces the next-step commands at the end of the run.\n */\n\nimport { existsSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { intro, isCancel, outro, text } from '@clack/prompts';\nimport {\n appApiAuthCallbackTs,\n appApiAuthSessionTs,\n appApiAuthSignInTs,\n appApiItemsRouteTs,\n agentLogMd,\n appApiAuthSignOutTs,\n appDashboardPageTsx,\n appLayoutCustomTsx,\n appLayoutTsx,\n appPageCustomTsx,\n appPageTsx,\n appSignInErrorPageTsx,\n claudeMd,\n componentsJson,\n componentsThemeProviderTsx,\n componentsUiButtonTsx,\n componentsUiCardTsx,\n DEPLOY_TARGETS,\n type DeployTarget,\n envLocal,\n envLocalExample,\n flyToml,\n gitignore,\n globalsCss,\n isDeployTarget,\n isValidSlug,\n libRequestOriginTs,\n libUtilsTs,\n manifestJson,\n middlewareTs,\n nextConfig,\n nextEnvDts,\n packageJson,\n packageJsonCustom,\n postcssConfigMjs,\n railwayJson,\n readme,\n slugValidationMessage,\n specMd,\n type ScaffoldKind,\n tsconfigJson,\n vercelJson,\n} from '../../lib/scaffold.js';\nimport { code, dim, fail, info, success, warn } from '../../lib/output.js';\nimport {\n ApiError,\n createDevInstallation,\n type DevInstallationResponse,\n} from '../../lib/api-client.js';\nimport {\n isLoggedIn,\n readConfig,\n resolveApiUrl,\n upsertModuleEntry,\n} from '../../lib/config.js';\nimport { selectWorkspace } from '../../lib/workspaces.js';\n\nexport interface InitOptions {\n /** Override the target directory (defaults to `./<slug>`). */\n dir?: string;\n /** Overwrite an existing non-empty directory. */\n force?: boolean;\n /** Human-readable module name (default: derive from slug). */\n name?: string;\n /**\n * Use the legacy minimal scaffold (hand-authored simple module —\n * no Next.js auth wiring). Default before 2026-05-18; opt-in now.\n * Mutually exclusive with `custom`; if both are passed, an error\n * is raised before any files are written.\n */\n simple?: boolean;\n /**\n * @deprecated Back-compat alias for the default (full Next.js +\n * auth wiring). New code should call `init` without flags.\n *\n * Kept for back-compat across the v0.x.y series. Will be removed\n * in a future major version. When passed alongside `--simple`,\n * raises an error (mutually exclusive).\n */\n custom?: boolean;\n /** Optional Git repository URL to write into module.json#repository. */\n git?: string;\n /**\n * HH-CC-LDI-6 — skip the provisioning phase (no `POST /api/installations/dev`\n * call, no `auth.json#modules[slug]` write). The local scaffold is\n * created as before; the resulting module has no dev install backing it,\n * so `dashwise dev` / SDK data-plane calls will fail with\n * `UnauthenticatedError` until you run a future\n * `dashwise module provision-dev-install` (LDI-9) or re-run\n * `dashwise init --force`.\n *\n * Commander maps the CLI flag `--no-provision` to `provision: false`;\n * this option is therefore typed as `provision?: boolean` with\n * `undefined` (default) meaning \"provision if logged in\".\n */\n provision?: boolean;\n /**\n * HH-CC-LDI-6 — target workspace slug or numeric id. When omitted +\n * interactive (TTY), the CLI prompts; when omitted + non-interactive\n * (CI), throws if the user has more than one workspace.\n */\n workspace?: string;\n /**\n * HH-CC-LDI-6 — module description forwarded to the backend's\n * `POST /api/installations/dev` request. No effect when\n * `--no-provision`. Defaults to undefined.\n */\n description?: string;\n /**\n * HH-CC-P1-D2 — when set, the scaffold emits the matching platform\n * config file (`railway.json` / `vercel.json` / `fly.toml`) alongside\n * the rest of the scaffold so the project lands as a one-shot\n * deploy-ready repo. Default (undefined) writes no platform file.\n *\n * Validated at the top of `moduleInitCommand` before any files are\n * written; an invalid value fails fast with exit code 1.\n */\n deployTarget?: DeployTarget;\n}\n\nexport async function moduleInitCommand(\n slugArg: string | undefined,\n options: InitOptions,\n): Promise<number> {\n intro('Scaffolding a new DashWise module');\n\n // Resolve slug — prompt if not provided.\n let slug = slugArg;\n if (!slug && process.stdout.isTTY) {\n const answer = await text({\n message: 'Module slug?',\n placeholder: 'tasks',\n validate: (v) => (isValidSlug(v) ? undefined : slugValidationMessage(v)),\n });\n if (isCancel(answer)) {\n fail('Aborted.');\n return 130;\n }\n slug = answer;\n }\n if (!slug) {\n fail('Usage: `dashwise module init <slug>`');\n return 1;\n }\n if (!isValidSlug(slug)) {\n fail(slugValidationMessage(slug));\n return 1;\n }\n\n // Derive a default human name from the slug if --name wasn't given.\n const name = options.name ?? humanizeSlug(slug);\n const dir = resolve(options.dir ?? slug);\n\n if (existsSync(dir)) {\n const entries = readdirSync(dir);\n if (entries.length > 0 && !options.force) {\n fail(\n `Directory ${code(dir)} is not empty. Pass ${code('--force')} to scaffold anyway (existing files will be overwritten).`,\n );\n return 1;\n }\n }\n\n // Resolve scaffold kind. As of 2026-05-18 the default is `'custom'`\n // (the full Next.js + auth scaffold); `--simple` opts back to the\n // legacy minimal scaffold; `--custom` is a back-compat no-op alias.\n //\n // Mutually-exclusive flags are caught here before any files are\n // written so the user gets a clean failure instead of \"scaffolded\n // simple but you also passed --custom, which one wins?\".\n if (options.simple && options.custom) {\n fail(\n `Cannot pass both ${code('--simple')} and ${code('--custom')} — they're mutually exclusive. ${code('--simple')} selects the legacy minimal scaffold; the default (no flag) is the full Next.js scaffold (formerly ${code('--custom')}).`,\n );\n return 1;\n }\n\n // HH-CC-P1-D2: validate --deploy-target before any files are written.\n // Commander's `.choices(...)` already enforces the allowlist at the\n // CLI boundary, but the library entry (moduleInitCommand) is reached\n // from tests + future callers without commander, so we re-check here\n // to keep the contract honest.\n if (\n options.deployTarget !== undefined &&\n !isDeployTarget(options.deployTarget)\n ) {\n fail(\n `Invalid --deploy-target ${code(options.deployTarget)} — must be one of ${DEPLOY_TARGETS.map((t) => code(t)).join(', ')}.`,\n );\n return 1;\n }\n\n const kind: ScaffoldKind = options.simple ? 'hand_authored' : 'custom';\n const scaffoldOpts = {\n slug,\n name,\n kind,\n ...(options.git !== undefined ? { repositoryUrl: options.git } : {}),\n };\n\n // HH-CC-FUP-5: pin the scaffold's .env.local to whatever backend\n // the CLI is currently pointed at (from saved login config or\n // $DASHWISE_API_URL or --api-url). Pre-FUP-5 every scaffold got\n // a hard-coded `http://localhost:3000`, which was wrong for anyone\n // running against api.dashwise.net (the common case once login\n // shipped). `resolveApiUrl()` falls back to `http://localhost:3000`\n // if nothing is set, preserving the old behavior for offline\n // scaffolds.\n const scaffoldApiUrl = resolveApiUrl();\n\n // Common files (both flavors).\n const files: Array<[string, string]> = [\n ['module.json', manifestJson(scaffoldOpts)],\n ['tsconfig.json', tsconfigJson()],\n ['next.config.mjs', nextConfig()],\n ['next-env.d.ts', nextEnvDts()],\n ['.gitignore', gitignore()],\n ['.env.local.example', envLocalExample(scaffoldApiUrl)],\n ['.env.local', envLocal(scaffoldApiUrl)],\n ['README.md', readme(scaffoldOpts)],\n // HH-CC-FUP-5: agent-facing docs ship with every scaffold so AI\n // coding agents (Claude Code, Cursor, etc.) have the spec + log\n // discipline + SDK pointers loaded into context from byte one.\n ['CLAUDE.md', claudeMd(scaffoldOpts)],\n ['spec.md', specMd(scaffoldOpts)],\n ['agent-log.md', agentLogMd(scaffoldOpts)],\n // Example data-plane route (both flavors) — exercises the generated\n // SDK against the seeded `items` table. Ships for simple + custom\n // since both produce `@dashai/generated`.\n ['app/api/items/route.ts', appApiItemsRouteTs()],\n ];\n\n // Flavor-specific files.\n if (kind === 'custom') {\n // Custom Next.js app with auth wiring + shadcn/Tailwind 4 stack.\n // The shadcn config + base primitives (button, card) are vendored\n // rather than installed via `npx shadcn add` so the scaffold has\n // no network dependency at first run.\n files.push(\n ['package.json', packageJsonCustom(scaffoldOpts)],\n ['middleware.ts', middlewareTs()],\n ['components.json', componentsJson()],\n ['postcss.config.mjs', postcssConfigMjs()],\n ['app/globals.css', globalsCss()],\n ['lib/utils.ts', libUtilsTs()],\n ['lib/request-origin.ts', libRequestOriginTs()],\n ['components/theme-provider.tsx', componentsThemeProviderTsx()],\n ['components/ui/button.tsx', componentsUiButtonTsx()],\n ['components/ui/card.tsx', componentsUiCardTsx()],\n ['app/layout.tsx', appLayoutCustomTsx(scaffoldOpts)],\n ['app/page.tsx', appPageCustomTsx(scaffoldOpts)],\n ['app/dashboard/page.tsx', appDashboardPageTsx()],\n ['app/sign-in-error/page.tsx', appSignInErrorPageTsx()],\n ['app/api/auth/sign-in/route.ts', appApiAuthSignInTs()],\n ['app/api/auth/callback/route.ts', appApiAuthCallbackTs()],\n ['app/api/auth/sign-out/route.ts', appApiAuthSignOutTs()],\n // D8: same-origin session probe that <AuthProvider> hits so the\n // host-scoped session cookie is actually sent.\n ['app/api/auth/session/route.ts', appApiAuthSessionTs()],\n );\n } else {\n // Hand-authored simple module (isolate runtime).\n files.push(\n ['package.json', packageJson(scaffoldOpts)],\n ['app/layout.tsx', appLayoutTsx(scaffoldOpts)],\n ['app/page.tsx', appPageTsx(scaffoldOpts)],\n );\n }\n\n // HH-CC-P1-D2: optional platform config file. Default (no\n // --deploy-target) writes nothing — the repo stays clean and the\n // author can add a platform file later by hand. When set, the file\n // is written alongside the rest of the scaffold; pairs with\n // `dashwise env export --format <platform>` (P1-D1) for the full\n // deploy loop.\n if (options.deployTarget !== undefined) {\n switch (options.deployTarget) {\n case 'railway':\n files.push(['railway.json', railwayJson(scaffoldOpts)]);\n break;\n case 'vercel':\n files.push(['vercel.json', vercelJson(scaffoldOpts)]);\n break;\n case 'fly':\n files.push(['fly.toml', flyToml(scaffoldOpts)]);\n break;\n }\n }\n\n // We intentionally don't run `npm install` here — the user might\n // want to inspect what we wrote first OR run it in their own shell\n // with their preferred package manager.\n for (const [relPath, content] of files) {\n const absPath = join(dir, relPath);\n const parentDir = join(absPath, '..');\n if (!existsSync(parentDir)) {\n mkdirSync(parentDir, { recursive: true });\n }\n writeFileSync(absPath, content, 'utf-8');\n }\n\n success(\n `Scaffolded ${code(slug)} (${kind === 'custom' ? 'custom Next.js' : 'simple module'}) in ${code(dir)}`,\n );\n\n // HH-CC-LDI-6: provisioning phase. After the scaffold lands, talk\n // to the backend to create a real local-dev install + mint a\n // runtime token. Cache the token in `auth.json#modules[slug]` so\n // `dashwise dev` + `@dashai/sdk`'s `createDevClient({ moduleSlug })`\n // can pick it up. Failures here DON'T roll back the scaffold —\n // the user can re-run `dashwise init --force` later (or, once\n // LDI-9 ships, `dashwise module provision-dev-install`).\n let devInstall: DevInstallationResponse | null = null;\n const wantsProvision = options.provision !== false; // default = true\n if (wantsProvision) {\n // FUP-2: forward the scaffold's module_kind so the backend stamps\n // it on the draft manifest at provision time. `kind` here is the\n // ScaffoldKind we just resolved above (custom | hand_authored).\n devInstall = await tryProvisionDevInstall({\n slug,\n name,\n description: options.description,\n workspaceFlag: options.workspace,\n moduleKind: kind,\n });\n } else {\n info(\n `Skipping provisioning (${code('--no-provision')}). ${dim(\"Run with provisioning later to enable `dashwise dev` data-plane.\")}`,\n );\n }\n\n info(`Next steps:`);\n process.stdout.write(`\n ${dim('1.')} ${code(`cd ${dir}`)}\n ${dim('2.')} ${code('npm install')}\n ${dim('3.')} ${code('dashwise dev')} ${dim('# one command: watcher + next dev, auth auto-injected')}\n\n ${dim(' (or, for the two-terminal flow:')}\n ${dim(' dashwise module generate')} ${dim('# materialize typed wrappers')}\n ${dim(' dashwise module dev')} ${dim('# watch + auto-regenerate')}\n ${dim(' npm run dev:next # next dev on :3000)')}\n${\n devInstall\n ? `\n ${dim(`Dev installation id=${devInstall.installation.id}; API key expires ${devInstall.api_key_expires_at}.`)}\n`\n : ''\n}`);\n outro('Happy authoring.');\n return 0;\n}\n\n/**\n * HH-CC-LDI-6 — provisioning sub-flow for `dashwise init`.\n *\n * Returns the API response on success, or `null` on a recoverable\n * failure (not logged in, network error, backend down). All failures\n * are surfaced to the user with `warn(...)` so they know what to fix;\n * the parent caller continues with a successful scaffold.\n *\n * Errors that should be unrecoverable (slug conflict, kind mismatch,\n * any 4xx from the backend) are surfaced as warnings too — the user\n * can re-init with a different slug or destroy the conflicting\n * install (LDI-9) without losing their local scaffold.\n *\n * Exported as an internal because the integration is hard to unit-\n * test through `moduleInitCommand` (intro/outro/text prompts +\n * filesystem). Tests that need to exercise this path can call this\n * function directly.\n */\nasync function tryProvisionDevInstall(args: {\n slug: string;\n name: string;\n description?: string;\n workspaceFlag?: string;\n /**\n * FUP-2: scaffold's `module_kind`. Stamped on the backend's draft\n * manifest at create time so the first getManifest() read returns\n * this value instead of falling back to `'ai_builder'`.\n */\n moduleKind?: 'ai_builder' | 'hand_authored' | 'custom';\n}): Promise<DevInstallationResponse | null> {\n if (!isLoggedIn()) {\n warn(\n `Not logged in — skipping dev-install provisioning. Run ${code('dashwise login')} then ${code(`dashwise init ${args.slug} --force`)} to retry.`,\n );\n return null;\n }\n const cfg = readConfig();\n if (!cfg) {\n // Defense — isLoggedIn() returned true so cfg should exist; if\n // it doesn't, the file got removed between the two reads. Treat\n // as not-logged-in.\n warn('CLI config disappeared mid-init. Skipping provisioning.');\n return null;\n }\n\n let workspace;\n try {\n workspace = await selectWorkspace({\n apiUrl: resolveApiUrl(),\n apiToken: cfg.token,\n flag: args.workspaceFlag,\n interactive: true,\n });\n } catch (err) {\n warn(`Workspace selection failed: ${(err as Error).message}`);\n return null;\n }\n info(\n `Provisioning dev install in workspace ${code(workspace.slug)} (id=${workspace.id})…`,\n );\n\n let response: DevInstallationResponse;\n try {\n response = await createDevInstallation(\n {\n slug: args.slug,\n name: args.name,\n ...(args.description !== undefined ? { description: args.description } : {}),\n workspaceId: workspace.id,\n ...(args.moduleKind !== undefined ? { moduleKind: args.moduleKind } : {}),\n },\n { baseUrl: resolveApiUrl(), auth: { token: cfg.token } },\n );\n } catch (err) {\n if (err instanceof ApiError) {\n surfaceProvisionApiError(err, args.slug);\n return null;\n }\n warn(`Provisioning failed: ${(err as Error).message}`);\n return null;\n }\n\n // Persist the API key. If THIS step fails (disk full, permissions,\n // etc.) we MUST tell the user the key so they can recover manually —\n // the server-side install was created and there's no point in\n // re-creating it.\n try {\n upsertModuleEntry(args.slug, {\n apiKey: response.api_key,\n apiKeyId: response.api_key_id,\n installationId: response.installation.id,\n expiresAt: response.api_key_expires_at,\n });\n } catch (err) {\n warn(\n `Provisioned successfully (installation id=${response.installation.id}) but failed to cache the API key: ${(err as Error).message}\\n` +\n ` API key (save this manually): ${response.api_key}\\n` +\n ` Key expires: ${response.api_key_expires_at}`,\n );\n return response;\n }\n\n success(\n `Provisioned dev install id=${response.installation.id}. API key cached in your CLI config.`,\n );\n return response;\n}\n\n/**\n * Map a known `ApiError.code` to a user-friendly recovery hint.\n * Anything unmapped falls back to printing the raw envelope.\n */\nfunction surfaceProvisionApiError(err: ApiError, slug: string): void {\n switch (err.code) {\n case 'UNAUTHENTICATED':\n warn(\n `Auth rejected by backend. Your CLI token may be stale — run ${code('dashwise login')} then ${code(`dashwise init ${slug} --force`)}.`,\n );\n return;\n case 'FORBIDDEN':\n warn(\n `Not authorized to create a module in that workspace. Confirm you're a member at the DashWise dashboard.`,\n );\n return;\n case 'SLUG_ALREADY_EXISTS':\n // The backend's POST /api/installations/dev maps the upstream\n // createDraft 409 ConflictException to this code; the user\n // either picks a different slug or, once LDI-9 ships,\n // destroys the existing install.\n warn(\n `A module with slug ${code(slug)} already exists. Pick a different slug, or destroy the existing dev install (LDI-9 coming soon) and re-run.`,\n );\n return;\n case 'RUNTIME_DATA_API_DISABLED':\n warn(\n `Backend has the local-dev API turned off (BUILDER_SESSION_TOKEN_SECRET unset). Contact the operator.`,\n );\n return;\n default:\n warn(\n `Provisioning failed (${err.code} ${err.status}): ${err.message}`,\n );\n }\n}\n\n/** Convert `tasks-app` → `Tasks app` for a friendly default name. */\nfunction humanizeSlug(slug: string): string {\n const words = slug.replace(/[-_]/g, ' ').split(/\\s+/).filter(Boolean);\n if (words.length === 0) return slug;\n const first = words[0];\n const cap = first.charAt(0).toUpperCase() + first.slice(1);\n return [cap, ...words.slice(1)].join(' ');\n}\n","/**\n * HH-CC-LDI-8 — shared setup for `dashwise table` / `dashwise field`\n * commands.\n *\n * Each schema-mutation command needs the same six things:\n *\n * 1. The project root (containing `module.json`)\n * 2. The current manifest (parsed) + the raw bytes (for rollback)\n * 3. The module's slug\n * 4. The CLI's saved config (apiUrl + bearer + ...)\n * 5. The per-module dev install entry (`auth.json#modules[slug]`)\n * — runtime token + installation id\n * 6. A `RequestOptions` ready to pass to the api-client helpers\n *\n * `loadSchemaCommandContext()` centralises that — commands stay\n * focused on the operation itself instead of repeating the setup\n * boilerplate.\n *\n * Errors at any step throw a user-readable `Error` (no stack trace\n * surface area); commands catch + `fail(err.message)` + return 1.\n */\n\nimport { readFileSync } from 'node:fs';\nimport { join, resolve as resolvePath } from 'node:path';\nimport type { RequestOptions } from './api-client.js';\nimport {\n readConfig,\n readModuleEntry,\n resolveApiUrl,\n type CliConfig,\n type CliConfigModuleEntry,\n} from './config.js';\nimport {\n readManifestOrThrow,\n type ManifestShape,\n} from './manifest-io.js';\n\nexport interface SchemaCommandContext {\n projectRoot: string;\n manifestPath: string;\n manifest: ManifestShape;\n /** Verbatim file bytes — preserved so commands that want to do\n * edit-first-with-rollback have something to restore from. */\n manifestRawBytes: string;\n slug: string;\n cfg: CliConfig;\n entry: CliConfigModuleEntry;\n /**\n * Pre-built RequestOptions targeting the per-module `dwk_` API key.\n * Pass directly to api-client helpers (createTable, addField, etc.).\n * Uses the bound install's API key, NOT the CLI bearer — the Phase 2\n * module-API schema endpoints (`/api/module-api/schema/*`) resolve the\n * install from the key (no id in the URL); mutations require the key's\n * install to be kind='local' (else SCHEMA_LOCKED), reads are allowed\n * for any api_key.\n */\n requestOptions: RequestOptions;\n}\n\n/**\n * Load + validate the four prerequisites for any schema-mutation\n * command. Throws on any missing piece with a clear \"how to fix\"\n * error message.\n */\nexport function loadSchemaCommandContext(opts: {\n dir?: string;\n}): SchemaCommandContext {\n const projectRoot = resolvePath(opts.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n\n // Use readManifestOrThrow for a typed \"doesn't exist / unreadable\"\n // failure mode; capture the raw bytes for potential rollback paths.\n const manifest = readManifestOrThrow<ManifestShape>(projectRoot);\n const manifestRawBytes = readFileSync(manifestPath, 'utf-8');\n\n const slug = manifest.module?.slug;\n if (!slug) {\n throw new Error(\n `module.json at ${manifestPath} has no module.slug — the manifest is malformed.`,\n );\n }\n\n const cfg = readConfig();\n if (!cfg) {\n throw new Error('Not logged in. Run `dashwise login` first.');\n }\n\n const entry = readModuleEntry(slug);\n if (!entry) {\n throw new Error(\n `No dev install cached for module \"${slug}\". Run \\`dashwise init ${slug} --force\\` to provision one.`,\n );\n }\n\n // P1-C C3: schema mutations authenticate with the module's `dwk_` API\n // key. `resolveSchemaAuthToken` prefers the canonical `apiKey`; it\n // tolerates a legacy entry that only has `runtimeToken` by throwing a\n // clear \"run dashwise dev / init\" pointer (the self-heal path in\n // `dashwise dev` upgrades legacy entries to an API key).\n const token = resolveSchemaAuthToken(entry, slug);\n\n return {\n projectRoot,\n manifestPath,\n manifest,\n manifestRawBytes,\n slug,\n cfg,\n entry,\n requestOptions: {\n baseUrl: resolveApiUrl(),\n auth: { token },\n },\n };\n}\n\n/**\n * Resolve the Bearer token schema commands send. Canonical is the\n * `dwk_` `apiKey`. A pre-P1-C entry may carry only the legacy\n * `runtimeToken` (a 90-day JWT the backend no longer accepts on the\n * schema plane) — in that case we throw a clear pointer rather than\n * sending a credential the backend will 401. Running `dashwise dev`\n * once upgrades the entry (it mints an API key + rewrites auth.json).\n */\nfunction resolveSchemaAuthToken(\n entry: CliConfigModuleEntry,\n slug: string,\n): string {\n if (entry.apiKey) return entry.apiKey;\n throw new Error(\n `The cached credential for \"${slug}\" is a legacy runtime token, which the ` +\n `schema endpoints no longer accept. Run \\`dashwise dev\\` once (it mints a ` +\n `dwk_ API key and updates your config), or \\`dashwise init ${slug} --force\\` ` +\n `to re-provision.`,\n );\n}\n","/**\n * `dashwise module destroy-dev-install [--module <slug>]`\n *\n * HH-CC-LDI-9 — tear down the local-dev install for a module. Reads\n * the current module's slug from `module.json` by default; pass\n * `--module <slug>` to target a different one (useful when the\n * project directory's manifest is gone but the auth.json entry\n * still lingers).\n *\n * Sequence:\n * 1. Resolve slug + install id from auth.json#modules[slug].\n * 2. DELETE /api/installations/dev/:id (audited as\n * DESTROY_DEV_INSTALLATION on the backend).\n * 3. Remove the auth.json#modules[slug] entry.\n *\n * If the backend returns 404 INSTALLATION_NOT_FOUND, we still clean\n * up the local auth.json entry — the install is gone on the server\n * already, no point in leaving a dangling token client-side.\n */\n\nimport { isCancel, confirm } from '@clack/prompts';\nimport { resolve as resolvePath } from 'node:path';\nimport {\n ApiError,\n destroyDevInstallation,\n} from '../../lib/api-client.js';\nimport {\n readConfig,\n readModuleEntry,\n removeModuleEntry,\n resolveApiUrl,\n} from '../../lib/config.js';\nimport { readManifest } from '../../lib/manifest-io.js';\nimport { code, fail, info, success, warn } from '../../lib/output.js';\n\nexport interface DestroyDevInstallOptions {\n dir?: string;\n /** Override the module slug (default: read from local module.json). */\n module?: string;\n /** Skip the confirmation prompt — for CI. */\n yes?: boolean;\n}\n\nexport async function destroyDevInstallCommand(\n options: DestroyDevInstallOptions,\n): Promise<number> {\n // ── 1. Resolve slug ────────────────────────────────────────────────\n let slug = options.module;\n if (!slug) {\n const projectRoot = resolvePath(options.dir ?? process.cwd());\n const manifest = (() => {\n try {\n return readManifest(projectRoot);\n } catch {\n return null;\n }\n })();\n slug = manifest?.module?.slug;\n if (!slug) {\n fail(\n `No module slug — pass ${code('--module <slug>')} or run from a directory with a valid module.json.`,\n );\n return 1;\n }\n }\n\n // ── 2. Find the cached install id ──────────────────────────────────\n const cfg = readConfig();\n if (!cfg) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n const entry = readModuleEntry(slug);\n if (!entry) {\n warn(\n `No cached dev install for ${code(slug)} in auth.json. Nothing to do.`,\n );\n return 0;\n }\n\n // ── 3. Confirm (skipped with --yes) ────────────────────────────────\n if (!options.yes && process.stdout.isTTY) {\n const choice = await confirm({\n message: `Destroy dev install ${code(`${slug} (id=${entry.installationId})`)}? Tables and rows will be soft-deleted (recoverable for 30 days via dashboard trash).`,\n });\n if (isCancel(choice) || !choice) {\n info('Aborted.');\n return 130;\n }\n }\n\n // ── 4. DELETE on backend ───────────────────────────────────────────\n let backendCleaned = false;\n try {\n const response = await destroyDevInstallation(entry.installationId, {\n baseUrl: resolveApiUrl(),\n auth: { token: cfg.token },\n });\n backendCleaned = true;\n success(\n `Destroyed dev install ${code(`${slug} (id=${response.installation_id})`)}${\n response.module_also_dropped\n ? ' — module also dropped (no other installs, unpublished).'\n : ' (module kept — other installs reference it or it has a published version).'\n }`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.code === 'INSTALLATION_NOT_FOUND') {\n // Already gone server-side; clean up the local entry anyway.\n warn(\n `Install ${entry.installationId} not found on the backend — already destroyed elsewhere. Cleaning up local cache.`,\n );\n backendCleaned = true;\n } else {\n return surfaceDestroyError(err);\n }\n }\n\n // ── 5. Clean up auth.json ──────────────────────────────────────────\n if (backendCleaned) {\n try {\n removeModuleEntry(slug);\n info(`Removed ${code(slug)} entry from auth.json.`);\n } catch (err) {\n warn(\n `Backend cleanup succeeded but failed to update auth.json: ${(err as Error).message}. Edit ${code('~/.config/dashwise/auth.json')} manually to remove the ${code(`modules[\"${slug}\"]`)} entry.`,\n );\n }\n }\n\n return 0;\n}\n\nfunction surfaceDestroyError(err: unknown): number {\n if (err instanceof ApiError) {\n switch (err.code) {\n case 'INSTALLATION_KIND_NOT_LOCAL':\n fail(\n `Refusing to destroy: the install isn't kind=local (it may have been promoted to production). Use the dashboard's uninstall flow instead.`,\n );\n break;\n case 'NOT_WORKSPACE_MEMBER':\n fail(\n `You're not a member of the install's workspace. Contact a workspace admin.`,\n );\n break;\n case 'UNAUTHENTICATED':\n fail(\n `Auth rejected by backend — your CLI bearer may be stale. Re-run ${code('dashwise login')} and try again.`,\n );\n break;\n default:\n fail(`Backend rejected: ${err.code} ${err.status} — ${err.message}`);\n }\n return 1;\n }\n fail(`Unexpected error: ${(err as Error).message}`);\n return 1;\n}\n","/**\n * `dashwise module reset-dev-install`\n *\n * HH-CC-LDI-9 — destroy + re-create the local-dev install for the\n * current module. Useful when:\n * - Test data has accumulated and you want a clean slate\n * - The cached runtime token has been compromised + you want a\n * fresh one without the LDI-9.x rotate-token endpoint\n * - Schema is in a wedged state and you want to start over from\n * the local module.json\n *\n * Implementation: composes `destroyDevInstallCommand` +\n * `moduleInitCommand({ provision: true, force: true })`. Both phases\n * are interactive in a TTY (with `--yes` to skip prompts).\n *\n * If destroy fails the reset bails — we don't want to provision a\n * second install while a stale one still exists (the backend would\n * 409 SLUG_ALREADY_EXISTS anyway).\n */\n\nimport { resolve as resolvePath } from 'node:path';\nimport { destroyDevInstallCommand } from './destroy-dev-install.js';\nimport { moduleInitCommand } from './init.js';\nimport { readManifest } from '../../lib/manifest-io.js';\nimport { code, fail, info } from '../../lib/output.js';\n\nexport interface ResetDevInstallOptions {\n dir?: string;\n /** Override the module slug (default: from local module.json). */\n module?: string;\n /** Target workspace for re-provisioning (passed to init). */\n workspace?: string;\n /** Skip confirmation prompts in both destroy + init phases. */\n yes?: boolean;\n}\n\nexport async function resetDevInstallCommand(\n options: ResetDevInstallOptions,\n): Promise<number> {\n // We need both a slug AND the module's display name (init re-uses\n // these on re-create). Read once from module.json so destroy + init\n // both agree on the target.\n const projectRoot = resolvePath(options.dir ?? process.cwd());\n const manifest = (() => {\n try {\n return readManifest(projectRoot);\n } catch {\n return null;\n }\n })();\n\n const slug = options.module ?? manifest?.module?.slug;\n if (!slug) {\n fail(\n `No module slug — pass ${code('--module <slug>')} or run from a directory with a valid module.json.`,\n );\n return 1;\n }\n const name = manifest?.module?.name ?? slug;\n\n // ── Phase 1: destroy ──────────────────────────────────────────────\n info(`Resetting dev install for ${code(slug)} — phase 1/2: destroy…`);\n const destroyExit = await destroyDevInstallCommand({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n module: slug,\n ...(options.yes !== undefined ? { yes: options.yes } : {}),\n });\n if (destroyExit !== 0) {\n fail(\n `Destroy phase failed (exit ${destroyExit}); aborting reset. Fix the underlying error and re-run.`,\n );\n return destroyExit;\n }\n\n // ── Phase 2: re-init / provision ──────────────────────────────────\n info(`Reset phase 2/2: re-provisioning…`);\n return moduleInitCommand(slug, {\n name,\n ...(options.dir !== undefined ? { dir: options.dir } : { dir: projectRoot }),\n // `--force` so init doesn't refuse to overwrite the existing\n // module.json (we're keeping the local scaffold; only the\n // backend install is being recreated).\n force: true,\n // Keep the current scaffold layout — don't try to detect or\n // change `simple` vs `custom`. The user can re-init manually\n // with `dashwise init` if they want to swap scaffolds.\n provision: true,\n ...(options.workspace !== undefined ? { workspace: options.workspace } : {}),\n });\n}\n","/**\n * HH-CC-LDI-8 — parse `--field <slug>:<type>[:flags]` syntax for\n * `dashwise table create` / `dashwise field add`.\n *\n * Grammar (regular):\n *\n * spec := <slug> ':' <type> [ ':' <flag> (',' <flag>)* ]\n * slug := snake_case, ^[a-z][a-z0-9_]*[a-z0-9]$\n * type := one of FIELD_TYPES (defined here to avoid a backend\n * import; kept in sync with manifest-schema.ts on the\n * server side)\n * flag := 'required' | 'unique' (v1 — extend as needed)\n *\n * Examples:\n * \"title:text\" → { slug:'title', type:'text' }\n * \"title:text:required\" → { slug:'title', type:'text', required:true }\n * \"tags:multi_select:required\" → { slug:'tags', type:'multi_select', required:true }\n *\n * For field types that need extra config (`single_select` / `multi_select`\n * with `options`, `link_row` with `target`, `formula` with `formula`,\n * `ai` with `prompt`), use `--field-json '{...}'` instead — the JSON\n * shape mirrors `FieldDefBody` from `api-client.ts`. This split keeps\n * the simple syntax actually simple while still supporting the rich\n * cases.\n *\n * Pure function — easy to unit-test. No I/O.\n */\n\nimport type { FieldDefBody } from './api-client.js';\n\n/**\n * Closed set of field types the backend accepts. Mirrors\n * `dashwise-backend/src/modules/modules/manifest/manifest-schema.ts:FIELD_TYPES`.\n * Kept here to avoid a backend dep; backend's manifest validator is\n * still the source of truth at apply-time.\n */\nexport const FIELD_TYPES = [\n 'text',\n 'long_text',\n 'number',\n 'boolean',\n 'date',\n 'datetime',\n 'single_select',\n 'multi_select',\n 'link_row',\n 'file',\n 'multi_file',\n 'email',\n 'url',\n 'phone',\n 'formula',\n 'ai',\n] as const;\nexport type FieldType = (typeof FIELD_TYPES)[number];\n\nconst SLUG_REGEX = /^[a-z][a-z0-9_]*[a-z0-9]$/;\nconst KNOWN_FLAGS = new Set(['required', 'unique']);\n\n/**\n * Parse a single `--field <slug>:<type>[:flags]` spec into a FieldDef\n * body. Throws with a clear error message if any part is malformed —\n * callers surface to the user via `fail()`.\n */\nexport function parseFieldSpec(spec: string): FieldDefBody {\n const parts = spec.split(':');\n if (parts.length < 2) {\n throw new FieldSpecError(\n `Field spec ${quote(spec)} is malformed — expected ${quote('<slug>:<type>[:flags]')}.`,\n );\n }\n const [slug, type, ...flagParts] = parts;\n\n if (!SLUG_REGEX.test(slug!)) {\n throw new FieldSpecError(\n `Field slug ${quote(slug!)} must match ${quote(SLUG_REGEX.source)} (snake_case, 2+ chars).`,\n );\n }\n\n if (!(FIELD_TYPES as readonly string[]).includes(type!)) {\n throw new FieldSpecError(\n `Field type ${quote(type!)} is not a known type. Allowed: ${FIELD_TYPES.join(', ')}.`,\n );\n }\n\n const result: FieldDefBody = { slug: slug!, type: type! };\n\n if (flagParts.length > 0) {\n // Flags are comma-separated within a single colon segment OR\n // each flag is its own colon segment. We accept both for\n // ergonomics: `name:text:required,unique` and\n // `name:text:required:unique` both parse the same.\n const flags = flagParts\n .flatMap((segment) => segment.split(','))\n .map((f) => f.trim())\n .filter((f) => f.length > 0);\n\n for (const flag of flags) {\n if (!KNOWN_FLAGS.has(flag)) {\n throw new FieldSpecError(\n `Unknown flag ${quote(flag)} in field spec ${quote(spec)}. Known flags: ${[...KNOWN_FLAGS].join(', ')}. For options/target/default, use ${quote('--field-json')} instead.`,\n );\n }\n if (flag === 'required') result.required = true;\n // `unique` is a table-level index concern, not a field-level\n // attribute on FieldDef — we accept the flag for forward\n // compat with `dashwise table create --field foo:text:unique`\n // but turning it into a table-level unique index belongs in\n // the calling command. Silently dropped here; the command\n // handler reads it from the raw spec if it cares.\n }\n }\n\n // Types that need options / target / formula / prompt can't be\n // expressed in the simple syntax — direct the user to --field-json.\n // We validate post-flag-parse so the type check fires before the\n // options check (better error ordering for the user).\n if (\n (type === 'single_select' || type === 'multi_select') &&\n result.options === undefined\n ) {\n throw new FieldSpecError(\n `Type ${quote(type)} requires an ${quote('options')} list. Use ${quote('--field-json')} for this field — e.g. ${quote(`'{\"slug\":\"${slug}\",\"type\":\"${type}\",\"options\":[\"a\",\"b\"]}'`)}.`,\n );\n }\n if (type === 'link_row' && result.target === undefined) {\n throw new FieldSpecError(\n `Type ${quote('link_row')} requires a ${quote('target')}. Use ${quote('--field-json')}.`,\n );\n }\n if (type === 'formula' || type === 'ai') {\n throw new FieldSpecError(\n `Type ${quote(type)} requires extra config (${quote('formula')} or ${quote('prompt')}). Use ${quote('--field-json')}.`,\n );\n }\n\n return result;\n}\n\n/**\n * Parse a `--field-json '<json>'` value into a FieldDef body. Just a\n * thin wrapper around `JSON.parse` with shape validation against\n * `FieldDefBody`. Pure function.\n */\nexport function parseFieldJson(json: string): FieldDefBody {\n let parsed: unknown;\n try {\n parsed = JSON.parse(json);\n } catch (err) {\n throw new FieldSpecError(\n `--field-json value is not valid JSON: ${(err as Error).message}`,\n );\n }\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new FieldSpecError('--field-json must be a JSON object.');\n }\n const o = parsed as Record<string, unknown>;\n if (typeof o.slug !== 'string' || !SLUG_REGEX.test(o.slug)) {\n throw new FieldSpecError(\n `--field-json missing or invalid ${quote('slug')}. Must match ${quote(SLUG_REGEX.source)}.`,\n );\n }\n if (typeof o.type !== 'string' || !(FIELD_TYPES as readonly string[]).includes(o.type)) {\n throw new FieldSpecError(\n `--field-json missing or invalid ${quote('type')}. Allowed: ${FIELD_TYPES.join(', ')}.`,\n );\n }\n // The rest of the fields are best-effort — the backend's manifest\n // validator is the final authority on what shapes are accepted.\n // Cast through unknown because Record<string, unknown> doesn't\n // structurally narrow to FieldDefBody (we've validated slug + type\n // above, which is enough for the runtime path).\n return o as unknown as FieldDefBody;\n}\n\nexport class FieldSpecError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'FieldSpecError';\n }\n}\n\nfunction quote(s: string): string {\n return `\\`${s}\\``;\n}\n","/**\n * `dashwise table create <slug> --field <spec>... [--field-json <json>...]`\n *\n * HH-CC-LDI-8 — create a new table in the current module's manifest +\n * materialize it as a physical Postgres table in the dev installation.\n *\n * Flow (REST-first / write-back-from-GET):\n * 1. Load context (manifest slug, `dwk_` key, install id for logging).\n * 2. Parse `--field` + `--field-json` flags into a FieldDef array.\n * 3. POST /api/module-api/schema/tables (key resolves the install).\n * 4. GET /api/module-api/schema to fetch the new manifest.\n * 5. Write the response to local module.json.\n *\n * No local-mutation logic — the backend's `SchemaProposeService`\n * is the source of truth for the manifest shape after the operation.\n * If the POST succeeds but the GET fails, local module.json is left\n * stale; `dashwise dev` reconciles on next startup.\n */\n\nimport { writeManifest, type ManifestShape } from '../../lib/manifest-io.js';\nimport {\n ApiError,\n createTable,\n getInstallationSchema,\n type FieldDefBody,\n} from '../../lib/api-client.js';\nimport { loadSchemaCommandContext } from '../../lib/schema-command-context.js';\nimport {\n FieldSpecError,\n parseFieldJson,\n parseFieldSpec,\n} from '../../lib/field-spec.js';\nimport { code, fail, info, success, warn } from '../../lib/output.js';\n\nexport interface TableCreateOptions {\n dir?: string;\n field?: string[];\n fieldJson?: string[];\n}\n\nexport async function tableCreateCommand(\n slug: string | undefined,\n options: TableCreateOptions,\n): Promise<number> {\n if (!slug) {\n fail('Usage: `dashwise table create <slug> --field <slug>:<type>[:required] [...]`');\n return 1;\n }\n\n // ── 1. Build the FieldDef array from --field + --field-json flags ──\n const fields: FieldDefBody[] = [];\n try {\n for (const spec of options.field ?? []) {\n fields.push(parseFieldSpec(spec));\n }\n for (const json of options.fieldJson ?? []) {\n fields.push(parseFieldJson(json));\n }\n } catch (err) {\n if (err instanceof FieldSpecError) {\n fail(err.message);\n return 1;\n }\n throw err;\n }\n if (fields.length === 0) {\n fail(\n `At least one field is required. Use ${code('--field <slug>:<type>')} (repeatable) or ${code(\"--field-json '{...}'\")} for fields with options/target/default.`,\n );\n return 1;\n }\n\n // Detect duplicate slugs within the input (the backend also rejects\n // but a local check gives a clearer error than the round-trip).\n const seen = new Set<string>();\n for (const f of fields) {\n if (seen.has(f.slug)) {\n fail(`Duplicate field slug ${code(f.slug)} in --field flags.`);\n return 1;\n }\n seen.add(f.slug);\n }\n\n // ── 2. Load command context ────────────────────────────────────────\n let ctx: ReturnType<typeof loadSchemaCommandContext>;\n try {\n ctx = loadSchemaCommandContext({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n });\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n // ── 3. POST /api/installations/:id/schema/tables ───────────────────\n info(`Creating table ${code(slug)} in installation ${ctx.entry.installationId}…`);\n try {\n const result = await createTable(\n { slug, fields },\n ctx.requestOptions,\n );\n success(\n `Created table ${code(slug)} (physical_table_id=${result.physical_table_id}, manifest_version=${result.manifest_version})`,\n );\n } catch (err) {\n return surfaceFailure(err);\n }\n\n // ── 4. GET /schema + write back to local module.json ───────────────\n return syncLocalManifest(ctx);\n}\n\n/**\n * After a successful schema mutation, fetch the new server-side\n * manifest and write it to local `module.json`. Shared by every\n * schema-mutation command.\n *\n * Failure here is non-fatal — the mutation already succeeded\n * server-side, the local file just gets stale. We surface a warning\n * + tell the user to retry via `dashwise module reconcile` (future\n * LDI-9 sub-command) OR they can re-run their next `dashwise dev`\n * which will pick up the latest manifest automatically.\n */\nexport async function syncLocalManifest(\n ctx: ReturnType<typeof loadSchemaCommandContext>,\n): Promise<number> {\n try {\n const { manifest } = await getInstallationSchema(ctx.requestOptions);\n writeManifest(manifest as ManifestShape, ctx.projectRoot);\n return 0;\n } catch (err) {\n if (err instanceof ApiError) {\n warn(\n `Schema sync to local module.json failed (${err.code} ${err.status}): ${err.message}. The mutation succeeded server-side; re-run your next command to retry the local sync.`,\n );\n } else {\n warn(\n `Schema sync to local module.json failed: ${(err as Error).message}. The mutation succeeded server-side.`,\n );\n }\n // Exit 0 — the operation succeeded, only the local sync didn't.\n return 0;\n }\n}\n\n/**\n * Translate an ApiError from a schema-mutation REST call into a\n * user-facing failure message. Reused by every table/field command\n * since they all surface the same set of codes from\n * `SchemaProposeService → InstallationSchemaController.mapServiceError`.\n */\nexport function surfaceFailure(err: unknown): number {\n if (err instanceof ApiError) {\n switch (err.code) {\n case 'TABLE_SLUG_EXISTS':\n fail(`A table with this slug already exists in the manifest.`);\n break;\n case 'FIELD_SLUG_EXISTS':\n fail(`A field with this slug already exists on the table.`);\n break;\n case 'TABLE_NOT_FOUND':\n fail(`Table not found in the manifest.`);\n break;\n case 'FIELD_NOT_FOUND':\n fail(`Field not found on the table.`);\n break;\n case 'UNAUTHENTICATED':\n fail(\n `API key rejected by backend. The cached key may be expired or revoked — re-run \\`dashwise init <slug> --force\\` to mint a fresh one.`,\n );\n break;\n case 'SCHEMA_LOCKED':\n fail(\n `Schema mutations require a local-dev install (kind=local). The cached API key belongs to a non-local install — schema is locked. Run \\`dashwise init <slug> --force\\` for a local dev install.`,\n );\n break;\n case 'INSTALL_MISMATCH':\n fail(\n `API key is bound to a different installation than the URL. The cached install id may be stale — re-run \\`dashwise init <slug> --force\\`.`,\n );\n break;\n default:\n fail(`Backend rejected: ${err.code} ${err.status} — ${err.message}`);\n }\n return 1;\n }\n fail(`Unexpected error: ${(err as Error).message}`);\n return 1;\n}\n","/**\n * `dashwise table delete <slug>`\n *\n * HH-CC-LDI-8 — drop a table from the current module. Calls\n * `DELETE /api/module-api/schema/tables/:tableSlug` (the `dwk_` key\n * resolves the install), which (via the backend's `applyManifestDelta`)\n * soft-deletes the physical table — recoverable for 30 days through the\n * dashboard's trash.\n *\n * Same REST-first / write-back-from-GET pattern as `table create`.\n */\n\nimport { dropTable } from '../../lib/api-client.js';\nimport { loadSchemaCommandContext } from '../../lib/schema-command-context.js';\nimport { code, fail, info, success } from '../../lib/output.js';\nimport { surfaceFailure, syncLocalManifest } from './create.js';\n\nexport interface TableDeleteOptions {\n dir?: string;\n}\n\nexport async function tableDeleteCommand(\n slug: string | undefined,\n options: TableDeleteOptions,\n): Promise<number> {\n if (!slug) {\n fail('Usage: `dashwise table delete <slug>`');\n return 1;\n }\n\n let ctx: ReturnType<typeof loadSchemaCommandContext>;\n try {\n ctx = loadSchemaCommandContext({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n });\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n info(`Dropping table ${code(slug)} from installation ${ctx.entry.installationId}…`);\n try {\n const result = await dropTable(slug, ctx.requestOptions);\n success(\n `Dropped table ${code(slug)} (manifest_version=${result.manifest_version}). Physical table soft-deleted; recoverable for 30 days via the dashboard's trash.`,\n );\n } catch (err) {\n return surfaceFailure(err);\n }\n\n return syncLocalManifest(ctx);\n}\n","/**\n * `dashwise field add <table-slug> <field-spec>`\n *\n * HH-CC-LDI-8 — add a new field to an existing table. The field spec\n * uses the same `<slug>:<type>[:flags]` syntax as `dashwise table\n * create --field`, OR the `--field-json '{...}'` escape hatch for\n * options/target/default.\n *\n * Examples:\n * dashwise field add tasks title:text:required\n * dashwise field add tasks done:boolean\n * dashwise field add tasks priority --field-json '{\"slug\":\"priority\",\"type\":\"single_select\",\"options\":[\"low\",\"medium\",\"high\"]}'\n *\n * REST-first / write-back-from-GET pattern (same as `table create`).\n */\n\nimport { addField } from '../../lib/api-client.js';\nimport { loadSchemaCommandContext } from '../../lib/schema-command-context.js';\nimport {\n FieldSpecError,\n parseFieldJson,\n parseFieldSpec,\n} from '../../lib/field-spec.js';\nimport { code, fail, info, success } from '../../lib/output.js';\nimport { surfaceFailure, syncLocalManifest } from '../table/create.js';\n\nexport interface FieldAddOptions {\n dir?: string;\n fieldJson?: string;\n}\n\nexport async function fieldAddCommand(\n tableSlug: string | undefined,\n fieldSpec: string | undefined,\n options: FieldAddOptions,\n): Promise<number> {\n if (!tableSlug) {\n fail(\n 'Usage: `dashwise field add <table-slug> <field-slug>:<type>[:required]` or `dashwise field add <table-slug> --field-json \\'{...}\\'`',\n );\n return 1;\n }\n\n // The field can come from either the positional `<spec>` arg OR\n // `--field-json`. Exactly one must be supplied; both would be\n // ambiguous (which wins?).\n const hasPositional = fieldSpec !== undefined;\n const hasJson = options.fieldJson !== undefined;\n if (!hasPositional && !hasJson) {\n fail(\n `Pass either a field spec (e.g. ${code('title:text:required')}) or ${code('--field-json')} with the field's JSON definition.`,\n );\n return 1;\n }\n if (hasPositional && hasJson) {\n fail(\n `Pass only ONE of the field spec or ${code('--field-json')} — they're mutually exclusive.`,\n );\n return 1;\n }\n\n let field;\n try {\n field = hasJson\n ? parseFieldJson(options.fieldJson!)\n : parseFieldSpec(fieldSpec!);\n } catch (err) {\n if (err instanceof FieldSpecError) {\n fail(err.message);\n return 1;\n }\n throw err;\n }\n\n let ctx: ReturnType<typeof loadSchemaCommandContext>;\n try {\n ctx = loadSchemaCommandContext({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n });\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n info(\n `Adding field ${code(`${tableSlug}.${field.slug}`)} (${field.type}) to installation ${ctx.entry.installationId}…`,\n );\n try {\n const result = await addField(\n { table_slug: tableSlug, field },\n ctx.requestOptions,\n );\n success(\n `Added field ${code(`${tableSlug}.${field.slug}`)} (manifest_version=${result.manifest_version})`,\n );\n } catch (err) {\n return surfaceFailure(err);\n }\n\n return syncLocalManifest(ctx);\n}\n","/**\n * `dashwise field remove <table-slug> <field-slug>`\n *\n * HH-CC-LDI-8 — remove a field from a table. The backend's\n * `proposeField(operation='remove')` includes the M2-C-FIX\n * cascading-index-cleanup: any index referencing the removed field\n * is trimmed, and if the index becomes empty it's dropped entirely.\n *\n * REST-first / write-back-from-GET pattern.\n */\n\nimport { removeField } from '../../lib/api-client.js';\nimport { loadSchemaCommandContext } from '../../lib/schema-command-context.js';\nimport { code, fail, info, success } from '../../lib/output.js';\nimport { surfaceFailure, syncLocalManifest } from '../table/create.js';\n\nexport interface FieldRemoveOptions {\n dir?: string;\n}\n\nexport async function fieldRemoveCommand(\n tableSlug: string | undefined,\n fieldSlug: string | undefined,\n options: FieldRemoveOptions,\n): Promise<number> {\n if (!tableSlug || !fieldSlug) {\n fail('Usage: `dashwise field remove <table-slug> <field-slug>`');\n return 1;\n }\n\n let ctx: ReturnType<typeof loadSchemaCommandContext>;\n try {\n ctx = loadSchemaCommandContext({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n });\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n info(\n `Removing field ${code(`${tableSlug}.${fieldSlug}`)} from installation ${ctx.entry.installationId}…`,\n );\n try {\n const result = await removeField(\n tableSlug,\n fieldSlug,\n ctx.requestOptions,\n );\n success(\n `Removed field ${code(`${tableSlug}.${fieldSlug}`)} (manifest_version=${result.manifest_version})`,\n );\n } catch (err) {\n return surfaceFailure(err);\n }\n\n return syncLocalManifest(ctx);\n}\n","/**\n * `dashwise field set-type <table-slug> <field-slug> <new-type>`\n *\n * HH-CC-LDI-8 — change an existing field's type. Maps to\n * `PATCH /api/module-api/schema/fields/:tableSlug/:fieldSlug` (the\n * `dwk_` key resolves the install) with the new type passed in the body.\n *\n * Lossy type changes (text → number with non-numeric data; multi_select\n * → single_select with multi-value rows) are deferred to v1.1 per\n * `local-dev-installs-v1.md` §8.2 — the backend's manifest validator\n * rejects the unsafe cases today; v1.1 adds a structured\n * `RETYPE_UNSAFE` precheck.\n *\n * REST-first / write-back-from-GET pattern.\n */\n\nimport { updateField } from '../../lib/api-client.js';\nimport { loadSchemaCommandContext } from '../../lib/schema-command-context.js';\nimport { FIELD_TYPES } from '../../lib/field-spec.js';\nimport { code, fail, info, success } from '../../lib/output.js';\nimport { surfaceFailure, syncLocalManifest } from '../table/create.js';\n\nexport interface FieldSetTypeOptions {\n dir?: string;\n}\n\nexport async function fieldSetTypeCommand(\n tableSlug: string | undefined,\n fieldSlug: string | undefined,\n newType: string | undefined,\n options: FieldSetTypeOptions,\n): Promise<number> {\n if (!tableSlug || !fieldSlug || !newType) {\n fail(\n 'Usage: `dashwise field set-type <table-slug> <field-slug> <new-type>`',\n );\n return 1;\n }\n if (!(FIELD_TYPES as readonly string[]).includes(newType)) {\n fail(\n `Type ${code(newType)} is not a known type. Allowed: ${FIELD_TYPES.join(', ')}.`,\n );\n return 1;\n }\n\n let ctx: ReturnType<typeof loadSchemaCommandContext>;\n try {\n ctx = loadSchemaCommandContext({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n });\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n info(\n `Setting type of ${code(`${tableSlug}.${fieldSlug}`)} → ${code(newType)} on installation ${ctx.entry.installationId}…`,\n );\n try {\n const result = await updateField(\n tableSlug,\n fieldSlug,\n { type: newType },\n ctx.requestOptions,\n );\n success(\n `Updated ${code(`${tableSlug}.${fieldSlug}`)} → ${code(newType)} (manifest_version=${result.manifest_version})`,\n );\n } catch (err) {\n return surfaceFailure(err);\n }\n\n return syncLocalManifest(ctx);\n}\n","/**\n * `dashwise dev` — the one-command local dev loop.\n *\n * What it does:\n * 1. Verifies the developer has run `dashwise login` (i.e. the auth.json\n * config file exists). Bails with a clear pointer otherwise.\n * 2. Resolves the Phase 2 two-var contract (`DASHWISE_API_URL` +\n * `DASHWISE_API_KEY`, plus the `NEXT_PUBLIC_DASHWISE_API_URL`\n * client mirror) from (a) explicit flags, (b) existing env vars,\n * (c) the saved CLI config + per-module `dwk_` key — and injects\n * them into BOTH child processes' env so the SDK can authenticate\n * without the developer ever touching `.env.local`. It does NOT\n * inject any installation id, CLI bearer, or dev-session id.\n * 3. Spawns two children:\n * - `dashwise module dev` — manifest watcher + SDK regen loop\n * - `next dev` — Next.js dev server\n * Both stdout/stderr streams are line-prefixed with `[sdk]` and\n * `[next]` so a single terminal can show both subsystems' output\n * without confusion.\n * 4. Forwards SIGINT/SIGTERM to both children, waits for them to exit,\n * then exits itself with the worst child's exit code (so CI catches\n * a crash on either side).\n *\n * Why two child processes rather than running `module dev` in-process:\n * - Symmetric output prefixing — same code path handles both.\n * - Signal isolation — Ctrl-C is forwarded cleanly to both, neither\n * can interfere with the other's shutdown by throwing async.\n * - Failure isolation — a crash in `module dev`'s generator can't\n * take down `next dev` or vice versa; users see a clear \"[sdk]\n * exited with code 1, [next] still running\" line.\n *\n * The Next.js process gets spawned via `npx next dev` (or the project's\n * own `dev:next` script if present), which avoids hard-coding a path\n * to the user's local node_modules.\n */\n\nimport { spawn, type ChildProcess } from 'node:child_process';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { resolve as resolvePath } from 'node:path';\nimport { ApiError, apiRequest, createApiKey } from '../lib/api-client.js';\nimport { reportConnectStatus } from '../lib/connect-status.js';\nimport {\n readConfig,\n readModuleEntry,\n upsertModuleEntry,\n type CliConfigModuleEntry,\n} from '../lib/config.js';\nimport { readManifest } from '../lib/manifest-io.js';\nimport {\n startManifestPollLoop,\n type ManifestPollHandle,\n} from '../lib/manifest-poll.js';\nimport { code, dim, fail, info, success, warn } from '../lib/output.js';\n\nexport interface DevCommandOptions {\n /** Project directory containing `module.json`. Defaults to cwd. */\n dir?: string;\n /**\n * Run against an already-installed module instead of registering a\n * dev session.\n *\n * When set to a real installation id (numeric), `dashwise dev` skips\n * dev-session registration; that installation must already exist in\n * your workspace and the browser SSO resolves through it.\n *\n * When NOT set (the default), `dashwise dev` registers a dev session\n * with the backend so workspace members can sign into the locally-\n * running module and the main-app FE dev banner works. Phase 2: the\n * id is no longer injected into the child env — the scaffold's\n * sign-in route authenticates to /api/module-api/sso/start-url with\n * the module's `dwk_` key.\n */\n installationId?: string;\n /**\n * Override the `DASHWISE_API_URL` env var passed to children.\n * Defaults to the saved CLI config's `apiUrl`.\n */\n apiUrl?: string;\n /**\n * Port for `next dev`. Defaults to 3000 — used both for the child\n * spawn AND for computing the default dev-session callback origin\n * (`http://localhost:<port>`).\n */\n port?: number;\n /**\n * Workspace to scope the dev session to. Either a numeric id (`'42'`)\n * or a slug (`'my-workspace'`). When omitted, defaults to the user's\n * primary workspace if they have only one; errors out asking for an\n * explicit `--workspace` if they have multiple.\n *\n * Only relevant when using dev-mode SSO (the default — ignored if\n * `--installation-id` is passed).\n */\n workspace?: string;\n /**\n * Additional callback origins to allowlist on the dev session, beyond\n * the default `http://localhost:<port>`. Repeatable.\n *\n * Example: `--callback-origin https://myapp.local` for custom-domain\n * local dev. Each origin must be a fully-qualified http(s) URL.\n *\n * Only relevant when using dev-mode SSO.\n */\n callbackOrigin?: string[];\n /**\n * Skip the Next.js dev server — only run the manifest watcher.\n * Useful if the developer is running `next dev` separately for\n * some reason (e.g. they want a debugger attached to it).\n */\n sdkOnly?: boolean;\n /**\n * Skip the manifest watcher — only run `next dev`. Symmetric escape\n * hatch to `--sdk-only`.\n */\n nextOnly?: boolean;\n /**\n * HH-CC-P1-E3 — disable the backend manifest poll loop. Without this\n * flag, `dashwise dev` periodically fetches `/api/installations/:id/\n * schema` + writes to local `module.json` if the backend has\n * advanced (dashboard edits, AI builder mutations, teammate\n * commands). With `--no-remote-poll`, the watcher only reacts to\n * local file changes (CLI-driven mutations).\n *\n * Use when actively hand-editing module.json and don't want the\n * watcher clobbering your in-progress edits. The hand-edit-doesn't-\n * get-clobbered logic in `manifest-poll.ts` makes this rarely\n * needed in practice, but the escape hatch is here.\n */\n noRemotePoll?: boolean;\n /**\n * HH-CC-P1-E3 — backend manifest poll interval in seconds. Default\n * `5`. Ignored when `--no-remote-poll` is set.\n */\n remotePollIntervalSec?: number;\n}\n\n/**\n * Default port for the scaffolded Next.js dev server. Used both for\n * the `--port` default AND for computing the default callback origin\n * passed to `POST /api/auth/dev/sessions`. Single source of truth —\n * if the user overrides one without the other, the dev session's\n * allowlist won't match the actual dev server origin and SSO fails\n * with `INVALID_RETURN_TO`.\n */\nconst DEFAULT_NEXT_PORT = 3000;\n\n/**\n * ANSI-styled prefix prepended to every line of a child's output.\n * Colors are kept faint so a long dev session doesn't strain the eye.\n *\n * `[sdk]` is cyan-ish, `[next]` is magenta-ish — they map cleanly to\n * the two subsystems and stay distinguishable on dark + light terminals.\n */\nconst PREFIX_SDK = `\\x1b[36m[sdk]\\x1b[0m `;\nconst PREFIX_NEXT = `\\x1b[35m[next]\\x1b[0m `;\n// HH-CC-P1-E3 — backend manifest poll loop's log prefix. Yellow so\n// it's visually distinct from sdk (cyan) and next (magenta).\nconst PREFIX_POLL = `\\x1b[33m[poll]\\x1b[0m `;\n/** Default backend-manifest poll interval, seconds. */\nconst DEFAULT_REMOTE_POLL_INTERVAL_SEC = 5;\n/** Minimum poll interval — avoid hammering the backend. */\nconst MIN_REMOTE_POLL_INTERVAL_SEC = 1;\n\nexport async function devCommand(\n options: DevCommandOptions,\n): Promise<number> {\n if (options.sdkOnly && options.nextOnly) {\n fail(\n `Cannot pass both ${code('--sdk-only')} and ${code('--next-only')} — they're mutually exclusive.`,\n );\n return 1;\n }\n\n const projectRoot = resolvePath(options.dir ?? process.cwd());\n const manifestPath = `${projectRoot}/module.json`;\n if (!existsSync(manifestPath)) {\n fail(`No ${code('module.json')} found in ${code(projectRoot)}.`);\n info(`Run ${code('dashwise module init <slug>')} to scaffold a new module first.`);\n return 1;\n }\n\n // HH-CC-LDI-7: read the manifest to learn this module's slug, so we\n // can look up its per-module runtime token from auth.json#modules[slug].\n // Failing to parse the manifest isn't fatal — `module dev` will catch\n // it downstream with a clearer error message. We just lose the\n // runtime-token injection in that case.\n const manifestSlug = (() => {\n try {\n return readManifest(projectRoot)?.module?.slug;\n } catch {\n return undefined;\n }\n })();\n\n // ── 1. Auth resolution ───────────────────────────────────────────────\n // Saved config is the source of truth; --api-url / env can override\n // individual fields. Refuse to start if no auth at all — the dev\n // server would just 401 on every request.\n const savedConfig = (() => {\n try {\n return readConfig();\n } catch {\n // Corrupt config — treat as if not logged in. The login command\n // will surface the real error if re-run.\n return null;\n }\n })();\n\n const apiToken = process.env.DASHWISE_API_TOKEN ?? savedConfig?.token;\n if (!apiToken) {\n fail(`Not authenticated. Run ${code('dashwise login')} first.`);\n info(\n 'The unified dev loop reads your CLI token from ~/.config/dashwise/auth.json ' +\n 'and injects it into both child processes so the SDK can authenticate ' +\n 'without you editing .env.local.',\n );\n return 1;\n }\n const apiUrl =\n options.apiUrl ??\n process.env.DASHWISE_API_URL ??\n savedConfig?.apiUrl ??\n 'http://localhost:3000';\n // HH-CC-FUP-7: port resolution + collision handling.\n // - User passed --port <N>: try exactly N. If taken, fail fast with\n // the next free port suggested in the error message (don't auto-\n // reassign — explicit user intent is preserved).\n // - User didn't pass --port: probe DEFAULT_NEXT_PORT upward until we\n // find a free port (capped at PORT_PROBE_LIMIT attempts) so a\n // stray process on :3000 doesn't crash `dashwise dev` for users\n // who don't care about the specific port.\n //\n // The chosen port flows into BOTH the dev session's callback origin\n // (registered with the backend before next dev starts) AND the\n // child's --port arg. They MUST agree, otherwise SSO callbacks\n // 404 against the wrong port.\n let port: number;\n try {\n port = await resolveDevPort(options.port);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n // ── 2. Resolve auth mode ─────────────────────────────────────────────\n // Three paths, in priority order:\n //\n // (a) `--installation-id <id>` (or `DASHWISE_INSTALLATION_ID` env)\n // — prod-like mode against an already-installed module. No dev\n // session is registered.\n //\n // (b) `DASHWISE_DEV_SESSION_ID` env set (e.g. for testing) — assume\n // an existing dev session; skip registration.\n //\n // (c) Default — register a fresh dev session with the backend +\n // revoke on graceful shutdown. The session powers the main-app\n // FE dev banner and the local install's SSO context.\n //\n // Phase 2: the dev session id is NO LONGER injected into the child\n // env — the scaffold's sign-in route authenticates to\n // /api/module-api/sso/start-url with the module's `dwk_` key instead\n // of branching on a dev-session env var. Registration still happens\n // so the FE banner + local-install SSO keep working.\n const explicitInstallationId =\n options.installationId ?? process.env.DASHWISE_INSTALLATION_ID;\n const reuseDevSessionId = process.env.DASHWISE_DEV_SESSION_ID;\n\n // P1-C: per-module API-key lookup. We read it BEFORE the auth-mode\n // branching below so the path can branch on its presence — but we\n // don't make the key gate dev-session setup. The two are orthogonal:\n // the dev session powers SSO sign-in callbacks for end users hitting\n // the running module; the API key powers the SDK's data-plane +\n // schema calls. Both can be active simultaneously.\n //\n // SELF-HEAL: `resolveModuleApiKey` upgrades a legacy `runtimeToken`-\n // only entry (written by a pre-P1-C CLI) to a `dwk_` key by minting\n // one via POST /api/installations/:id/api-keys + rewriting auth.json.\n let moduleEntry =\n manifestSlug !== undefined ? readModuleEntry(manifestSlug) : null;\n const healed =\n manifestSlug !== undefined\n ? await resolveModuleApiKey(manifestSlug, moduleEntry, apiUrl, apiToken)\n : null;\n if (healed) moduleEntry = healed;\n // The `dwk_` key the SDK uses. Env override wins (mirrors every other\n // field), then the cached/healed entry's key.\n const apiKeyEnv = process.env.DASHWISE_API_KEY ?? moduleEntry?.apiKey;\n\n let installationIdEnv: string | undefined;\n let revokeDevSession: (() => Promise<void>) | undefined;\n\n if (explicitInstallationId && explicitInstallationId !== 'local') {\n installationIdEnv = explicitInstallationId;\n } else if (reuseDevSessionId) {\n // A dev session id was pre-supplied (test / CI harness) — assume it\n // already exists on the backend; skip registration + revocation.\n } else {\n // Default — register a dev session.\n let workspaceContext: { id: number; name: string; slug: string };\n try {\n workspaceContext = await resolveTargetWorkspace(apiUrl, apiToken, options.workspace);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n const callbackOrigins = computeCallbackOrigins(port, options.callbackOrigin ?? []);\n try {\n const session = await registerDevSession(apiUrl, apiToken, {\n target_workspace_id: workspaceContext.id,\n callback_origins: callbackOrigins,\n });\n revokeDevSession = () => revokeDevSessionBestEffort(apiUrl, apiToken, session.id);\n info(` ${dim('dev session')} ${session.id}`);\n info(` ${dim('workspace')} ${workspaceContext.name} (id=${workspaceContext.id}, slug=${workspaceContext.slug})`);\n info(` ${dim('callbacks')} ${callbackOrigins.join(', ')}`);\n info(` ${dim('expires')} ${session.expires_at}`);\n } catch (err) {\n if (err instanceof ApiError) {\n fail(`Failed to register dev session: ${err.code} — ${err.message}`);\n } else {\n fail(`Failed to register dev session: ${(err as Error).message}`);\n }\n return 1;\n }\n }\n\n // ── 3. Build child env ───────────────────────────────────────────────\n // Inherit the parent's env so user-set vars (e.g. NEXT_TELEMETRY_DISABLED,\n // NODE_OPTIONS) flow through unchanged. Overlay the Phase 2 two-var\n // contract so the SDK + scaffold can read them — these win over\n // anything the user set in .env.local because Next.js loads .env.local\n // AFTER process.env.\n //\n // Phase 2 wire protocol: the child gets EXACTLY the two-var contract\n // plus its client-side mirror:\n // - DASHWISE_API_URL — server-side backend base URL\n // - NEXT_PUBLIC_DASHWISE_API_URL — client mirror (browser bundle;\n // the scaffold's next.config normally derives this, but injecting\n // it here means `dashwise dev` works even before a rebuild)\n // - DASHWISE_API_KEY — the scoped `dwk_` data-plane cred\n //\n // We NO LONGER inject DASHWISE_INSTALLATION_ID (the key binds the\n // install server-side; there is no install id in any URL),\n // DASHWISE_API_TOKEN (the CLI bearer must never leak into the module\n // runtime), DASHWISE_RUNTIME_TOKEN (retired), or DASHWISE_DEV_SESSION_ID\n // (the scaffold's sign-in route now hits the key-authenticated\n // /api/module-api/sso/start-url instead of branching on a dev-session\n // env var). The dev session itself is still registered above so the\n // main-app FE dev banner + the local install's SSO context work.\n const childEnv: Record<string, string | undefined> = {\n ...process.env,\n DASHWISE_API_URL: apiUrl,\n NEXT_PUBLIC_DASHWISE_API_URL: apiUrl,\n ...(apiKeyEnv !== undefined ? { DASHWISE_API_KEY: apiKeyEnv } : {}),\n };\n\n // ── 4. Pre-flight banner ─────────────────────────────────────────────\n info(`Dev loop starting — Ctrl-C to stop.`);\n info(` ${dim('api')} ${apiUrl}`);\n if (installationIdEnv !== undefined) {\n info(` ${dim('installation')} ${installationIdEnv} (prod-mode SSO)`);\n } else {\n info(` ${dim('mode')} dev (dev SSO session registered)`);\n }\n // The CLI bearer stays the credential for dev-session registration +\n // any self-heal key mint (both CLI-token operations) — it is NOT\n // injected into the child env (see childEnv above).\n info(` ${dim('cli token')} ${maskedToken(apiToken)} ${dim(`(from ${apiToken === savedConfig?.token ? '~/.config/dashwise/auth.json' : '$DASHWISE_API_TOKEN'})`)}`);\n // P1-C: surface the API-key source so developers know which credential\n // the SDK will pick up. Three observable states:\n // - cached: per-module `dwk_` key in auth.json (the happy path)\n // - env: DASHWISE_API_KEY explicit override\n // - missing: no key; data-plane + schema calls will fail with\n // UnauthenticatedError. Surface a hint to run `dashwise init`.\n if (apiKeyEnv !== undefined) {\n const source =\n process.env.DASHWISE_API_KEY === apiKeyEnv\n ? '$DASHWISE_API_KEY'\n : `~/.config/dashwise/auth.json#modules[${manifestSlug}]`;\n const installId = moduleEntry?.installationId;\n info(\n ` ${dim('api key')} ${maskedToken(apiKeyEnv)} ${dim(`(from ${source}${installId ? `, install id=${installId}` : ''})`)}`,\n );\n } else if (manifestSlug !== undefined && installationIdEnv === undefined) {\n // No API key + no explicit install id → the SDK's data plane will\n // 401 on every call. Print a one-line hint so the dev knows why;\n // don't block the dev loop because SSO + scaffolding still work\n // without it.\n warn(\n `No API key cached for module ${code(manifestSlug)}. ` +\n `Data-plane calls (db, qb) will fail with UnauthenticatedError. ` +\n `Run ${code(`dashwise init ${manifestSlug} --force`)} to provision a dev install + cache a key.`,\n );\n }\n info('');\n\n // ── 3b. Connect-status summary (P3 deps + P4 uses bindings) ─────────\n // Best-effort: surface which declared cross-module deps + workspace-\n // table `uses` slots are connected vs parked, so a manifest push that\n // lands new declarations shows their park state up-front (the \"tables\n // half\" of the needs report, next to the deps half). Uses the CLI\n // bearer (these are workspace-scoped surfaces, not the runtime key).\n // Any failure is swallowed inside the reporter — never blocks the loop.\n if (moduleEntry !== null && manifestSlug !== undefined) {\n await reportConnectStatus({\n installationId: moduleEntry.installationId,\n moduleSlug: manifestSlug,\n requestOptions: { baseUrl: apiUrl, auth: { token: apiToken } },\n });\n }\n\n // ── 4. Spawn children ────────────────────────────────────────────────\n const children: { name: string; child: ChildProcess; prefix: string }[] = [];\n\n if (!options.nextOnly) {\n const sdkChild = spawnSdkWatcher(projectRoot, childEnv);\n children.push({ name: 'sdk', child: sdkChild, prefix: PREFIX_SDK });\n }\n if (!options.sdkOnly) {\n // Always pass `port` (default DEFAULT_NEXT_PORT, overridden by\n // --port). This ensures the actual dev server port matches the\n // dev session's callback origin allowlist computed above.\n const nextChild = spawnNextDev(projectRoot, childEnv, port);\n children.push({ name: 'next', child: nextChild, prefix: PREFIX_NEXT });\n }\n\n // ── 5. Wire output multiplexing ──────────────────────────────────────\n for (const { child, prefix } of children) {\n pipeWithPrefix(child.stdout, process.stdout, prefix);\n pipeWithPrefix(child.stderr, process.stderr, prefix);\n }\n\n // ── 5b. Backend manifest poll loop (HH-CC-P1-E3) ────────────────────\n // Fetches `GET /api/module-api/schema` periodically and writes\n // module.json when the backend has advanced. The sdk-watcher child\n // then picks up the file change + regenerates @dashai/generated.\n //\n // Gated on: a per-module `dwk_` API key being available (no key =\n // no auth = can't poll — C3 allows schema READS for any api_key), and\n // the user not opting out via `--no-remote-poll`. Also disabled when\n // `--sdk-only` is set without any next dev — the poll loop is only\n // valuable when the dev server is also running.\n let manifestPoll: ManifestPollHandle | null = null;\n const pollEntry = moduleEntry; // capture for null-narrowing (moduleEntry is `let`)\n const enablePoll =\n !options.noRemotePoll &&\n pollEntry !== null &&\n apiKeyEnv !== undefined &&\n manifestSlug !== undefined;\n if (enablePoll && pollEntry !== null) {\n const intervalSec = Math.max(\n MIN_REMOTE_POLL_INTERVAL_SEC,\n options.remotePollIntervalSec ?? DEFAULT_REMOTE_POLL_INTERVAL_SEC,\n );\n manifestPoll = startManifestPollLoop({\n manifestPath,\n requestOptions: {\n baseUrl: apiUrl,\n // The `dwk_` key resolves the install server-side.\n auth: { token: apiKeyEnv },\n },\n intervalMs: intervalSec * 1000,\n onUpdate: (msg) => {\n process.stdout.write(`${PREFIX_POLL}${msg}\\n`);\n },\n onError: (err) => {\n // Persistent failures should be visible but not noisy — write\n // to stderr through the [poll] prefix and keep going.\n process.stderr.write(`${PREFIX_POLL}${err.message}\\n`);\n },\n });\n info(\n ` ${dim('poll')} backend manifest every ${intervalSec}s ${dim('(--no-remote-poll to disable)')}`,\n );\n info('');\n }\n\n // ── 6. Signal forwarding + exit aggregation ─────────────────────────\n let shuttingDown = false;\n const forwardSignal = (sig: NodeJS.Signals) => {\n if (shuttingDown) return;\n shuttingDown = true;\n // Stop the poll loop first so no late writes race with shutdown.\n if (manifestPoll) {\n manifestPoll.stop();\n manifestPoll = null;\n }\n info(`\\nReceived ${sig}, stopping children…`);\n for (const { child } of children) {\n if (child.exitCode === null && child.signalCode === null) {\n child.kill(sig);\n }\n }\n // Best-effort revoke the dev session — fire-and-forget so we\n // don't delay shutdown if the API is slow. If the request fails\n // (offline, backend down, etc.) the dev session naturally expires\n // in 24h, so the leftover is harmless.\n if (revokeDevSession) {\n revokeDevSession().catch(() => {\n /* swallowed — best-effort */\n });\n }\n };\n process.on('SIGINT', () => forwardSignal('SIGINT'));\n process.on('SIGTERM', () => forwardSignal('SIGTERM'));\n\n // Wait for each child's exit. Aggregate exit codes — if either fails\n // non-zero (and we didn't kill it intentionally), surface the worst\n // code so CI catches a crash.\n const results = await Promise.all(\n children.map(\n ({ name, child }) =>\n new Promise<{ name: string; code: number; killed: boolean }>(\n (resolveExit) => {\n child.on('exit', (exitCode, signal) => {\n const killed = signal !== null;\n const finalCode =\n exitCode ?? (killed ? 0 : 1); // signal-only exit treated as clean\n resolveExit({ name, code: finalCode, killed });\n });\n },\n ),\n ),\n );\n\n // If ANY child exits non-zero AND wasn't killed by our signal forward,\n // kill the others so we don't leave orphans. Then aggregate.\n const crashed = results.find((r) => !r.killed && r.code !== 0);\n if (crashed && !shuttingDown) {\n warn(`[${crashed.name}] exited with code ${crashed.code} — stopping others.`);\n for (const { child } of children) {\n if (child.exitCode === null && child.signalCode === null) {\n child.kill('SIGTERM');\n }\n }\n }\n\n // Stop the poll loop in case shutdown was triggered by a child\n // crash rather than a signal (forwardSignal already stops it on\n // SIGINT/SIGTERM, but a crashed `next dev` reaches here without\n // going through forwardSignal — idempotent stop() handles both).\n if (manifestPoll) {\n manifestPoll.stop();\n manifestPoll = null;\n }\n\n const exitCode = Math.max(0, ...results.map((r) => r.code));\n if (exitCode === 0) {\n success('Dev loop stopped cleanly.');\n }\n return exitCode;\n}\n\n// ── Internals ───────────────────────────────────────────────────────────\n\n/**\n * Spawn `dashwise module dev` as a child. We re-exec the same CLI binary\n * via `process.execPath` + `process.argv[1]` so we never depend on the\n * binary being on $PATH (npm-install-globally is common but not\n * universal; pnpm workspace setups can put the bin in a non-PATH\n * directory).\n *\n * The child inherits stdio for stdin (so a future interactive-prompt\n * inside `module dev` could still work), but stdout/stderr are piped so\n * we can prefix the lines.\n */\nfunction spawnSdkWatcher(\n projectRoot: string,\n env: Record<string, string | undefined>,\n): ChildProcess {\n const child = spawn(\n process.execPath,\n [process.argv[1]!, 'module', 'dev', '--dir', projectRoot],\n {\n cwd: projectRoot,\n env,\n stdio: ['ignore', 'pipe', 'pipe'],\n },\n );\n return child;\n}\n\n/**\n * Spawn `next dev`. We prefer the project's `dev:next` npm script (which\n * the scaffold writes out) so the dev experience stays consistent with\n * what a user gets when running `npm run dev:next` directly. Falls back\n * to `npx next dev` if no script is defined.\n *\n * Pass `--port` explicitly if the caller asked, otherwise let Next pick\n * its default (3000 by default; Next falls forward to 3001/3002/...\n * when the port is taken — our local backend usually owns 3000).\n */\nfunction spawnNextDev(\n projectRoot: string,\n env: Record<string, string | undefined>,\n port: number | undefined,\n): ChildProcess {\n const portArgs = port !== undefined ? ['--', '--port', String(port)] : [];\n const hasDevNextScript = hasNpmScript(projectRoot, 'dev:next');\n // npm/yarn/pnpm differ on how they locate `next` — the safest cross-tool\n // path is to delegate to the project's own package manager via `npm run\n // dev:next`. If the script is missing, fall back to `npx next dev`.\n const [cmd, args] = hasDevNextScript\n ? ['npm', ['run', 'dev:next', ...portArgs]]\n : ['npx', ['next', 'dev', ...(port !== undefined ? ['--port', String(port)] : [])]];\n\n const child = spawn(cmd, args, {\n cwd: projectRoot,\n env,\n stdio: ['ignore', 'pipe', 'pipe'],\n // Windows requires `shell: true` for `npm` / `npx` because they're\n // `.cmd` shims, not real binaries.\n shell: process.platform === 'win32',\n });\n return child;\n}\n\n/**\n * Read the project's `package.json` and check whether the named script\n * exists. Returns false on any error (missing package.json, malformed\n * JSON, etc.) — the caller falls back to npx in that case.\n */\nfunction hasNpmScript(projectRoot: string, scriptName: string): boolean {\n try {\n const pkgPath = `${projectRoot}/package.json`;\n if (!existsSync(pkgPath)) return false;\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8')) as {\n scripts?: Record<string, string>;\n };\n return typeof pkg.scripts?.[scriptName] === 'string';\n } catch {\n return false;\n }\n}\n\n/**\n * Pipe a child's readable stream into our output stream, prefixing each\n * line with the given prefix. Uses line-buffered prefixing: partial\n * lines (no trailing newline) get prefixed too so e.g. spinner output\n * still surfaces — but if a child emits a stream of \\r-overwrites for a\n * fancy progress bar, the prefix collapses correctly because we re-emit\n * the partial line as-is.\n *\n * Edge case: if the stream is null (child was spawned without piping),\n * silently no-op. Real spawn calls above always pipe both, so this is\n * defence-in-depth.\n */\nfunction pipeWithPrefix(\n src: NodeJS.ReadableStream | null,\n dst: NodeJS.WritableStream,\n prefix: string,\n): void {\n if (!src) return;\n let leftover = '';\n src.on('data', (chunk: Buffer | string) => {\n const text = typeof chunk === 'string' ? chunk : chunk.toString('utf-8');\n const combined = leftover + text;\n const lines = combined.split('\\n');\n leftover = lines.pop() ?? '';\n for (const line of lines) {\n dst.write(`${prefix}${line}\\n`);\n }\n });\n src.on('end', () => {\n if (leftover.length > 0) {\n dst.write(`${prefix}${leftover}\\n`);\n }\n });\n}\n\n/**\n * Mask a bearer token for log display. Shows the prefix (so users can\n * recognize WHICH token is being used — `dwc_*` vs JWT etc.) and a\n * 4-char tail (for distinguishing between two tokens at a glance) but\n * never the middle.\n */\nfunction maskedToken(token: string): string {\n if (token.length <= 12) return '****';\n const prefix = token.slice(0, 4);\n const tail = token.slice(-4);\n return `${prefix}…${tail}`;\n}\n\n/**\n * P1-C SELF-HEAL — upgrade a legacy `auth.json#modules[slug]` entry that\n * only has a `runtimeToken` (written by a pre-identity-collapse CLI) to\n * one that has a `dwk_` `apiKey`, by minting a key against the install\n * and rewriting the entry. Idempotent + best-effort:\n *\n * - No entry, OR entry already has `apiKey`, OR a `DASHWISE_API_KEY`\n * env override is set → nothing to heal, returns `null` (caller\n * keeps using the existing entry / env).\n * - Legacy entry (has `runtimeToken`, no `apiKey`) → mint via\n * POST /api/installations/:id/api-keys (CLI-bearer authed), persist\n * the new shape, message the user, return the upgraded entry.\n * - Mint fails (install gone, offline, backend down) → message the\n * user with a recovery pointer and return `null`; the dev loop\n * continues (SSO + scaffolding still work). A destroyed install is\n * recovered by `dashwise init <slug> --force` (a clean re-register).\n *\n * Returns the upgraded entry when a heal happened, else `null`.\n */\nasync function resolveModuleApiKey(\n slug: string,\n entry: CliConfigModuleEntry | null,\n apiUrl: string,\n cliBearer: string,\n): Promise<CliConfigModuleEntry | null> {\n // Env override present, or nothing cached, or the entry is already on\n // the new shape → no heal needed.\n if (process.env.DASHWISE_API_KEY) return null;\n if (!entry) return null;\n if (entry.apiKey) return null;\n // Only heal a genuinely-legacy entry (had a runtime token). A\n // shapeless/partial entry with neither field can't be healed here —\n // the user needs to re-provision.\n if (!entry.runtimeToken) return null;\n\n info(\n `Upgrading cached credentials for ${code(slug)} to a ${code('dwk_')} API key ` +\n `(the local runtime token format was retired)…`,\n );\n let minted;\n try {\n minted = await createApiKey(\n entry.installationId,\n { name: 'local-dev' },\n { baseUrl: apiUrl, auth: { token: cliBearer } },\n );\n } catch (err) {\n if (err instanceof ApiError && err.code === 'INSTALLATION_NOT_FOUND') {\n warn(\n `Could not upgrade credentials for ${code(slug)}: its dev install no longer exists. ` +\n `Run ${code(`dashwise init ${slug} --force`)} to re-provision (a clean re-register).`,\n );\n return null;\n }\n const reason = err instanceof ApiError ? `${err.code}: ${err.message}` : (err as Error).message;\n warn(\n `Could not upgrade credentials for ${code(slug)} (${reason}). ` +\n `Data-plane calls may fail; run ${code(`dashwise init ${slug} --force`)} to refresh.`,\n );\n return null;\n }\n\n const upgraded: CliConfigModuleEntry = {\n apiKey: minted.raw_key,\n apiKeyId: minted.api_key.id,\n installationId: entry.installationId,\n expiresAt: minted.api_key.expires_at ?? entry.expiresAt,\n };\n try {\n upsertModuleEntry(slug, upgraded);\n } catch (err) {\n // Minted but couldn't persist — surface the key so the dev can\n // recover, but still use it for this session.\n warn(\n `Minted a new API key for ${code(slug)} but failed to cache it: ${(err as Error).message}\\n` +\n ` API key (save manually): ${minted.raw_key}`,\n );\n }\n success(`Upgraded ${code(slug)} to a dwk_ API key (id=${minted.api_key.id}).`);\n return upgraded;\n}\n\n// ── Dev-Mode SSO session lifecycle ──────────────────────────────────────\n\ninterface WorkspaceListItem {\n id: number;\n name: string;\n slug: string;\n}\n\ninterface DevSessionApiResponse {\n id: string;\n target_workspace_id: number;\n allowed_callback_origins: string[];\n expires_at: string;\n}\n\n/**\n * Compute the dev session's allowed callback origins. Defaults to the\n * dev server's bind URL (`http://localhost:<port>`); the user can add\n * more via `--callback-origin <url>` (repeatable).\n *\n * Backend validates each entry is a well-formed http(s) URL — we do\n * NOT pre-validate here; let the BE's error response (with code\n * `INVALID_CALLBACK_ORIGIN`) be the source of truth.\n */\nfunction computeCallbackOrigins(port: number, extra: string[]): string[] {\n const def = `http://localhost:${port}`;\n // De-dup: prevent the BE from rejecting a list with redundant\n // entries (the BE doesn't reject — it stores them as-is — but\n // sending unique values is the kinder client behavior).\n return Array.from(new Set([def, ...extra]));\n}\n\n/**\n * HH-CC-FUP-7 — port resolution + collision handling.\n *\n * Two modes depending on whether the user passed `--port`:\n *\n * - **Explicit `--port N`** (caller intent is \"use exactly N\"):\n * probe N once. If taken, throw a friendly error suggesting the\n * next free port the user could try. Do NOT auto-reassign — the\n * user picked a specific port for a reason (URL-shaped scripts,\n * bookmarks, hosts file entries, etc.).\n *\n * - **No --port** (caller doesn't care): probe DEFAULT_NEXT_PORT\n * upward until we find a free port, capped at PORT_PROBE_LIMIT\n * attempts. Mirrors Next.js's own \"port already in use, trying\n * 3001\" UX, but done up-front so the dev session's callback\n * origin matches the port that next dev will actually bind to.\n *\n * The chosen port becomes the dev session's `callback_origins[0]`\n * (`http://localhost:<port>`) AND the `--port` arg passed to next dev.\n * If they didn't agree, SSO callbacks would land on the wrong port.\n */\nconst PORT_PROBE_LIMIT = 10;\n\nexport async function resolveDevPort(\n requested: number | undefined,\n): Promise<number> {\n if (requested !== undefined) {\n if (await isPortFree(requested)) return requested;\n const suggestion = await findFirstFreePort(requested + 1, PORT_PROBE_LIMIT);\n const suggestionHint =\n suggestion !== null\n ? `Try \\`dashwise dev --port ${suggestion}\\`.`\n : `No free port found between ${requested + 1} and ${requested + PORT_PROBE_LIMIT} either — check what's listening with \\`lsof -i :${requested}\\`.`;\n throw new Error(\n `Port ${requested} is already in use. ${suggestionHint}`,\n );\n }\n const found = await findFirstFreePort(DEFAULT_NEXT_PORT, PORT_PROBE_LIMIT);\n if (found === null) {\n throw new Error(\n `No free port found between ${DEFAULT_NEXT_PORT} and ${DEFAULT_NEXT_PORT + PORT_PROBE_LIMIT - 1}. ` +\n `Free a port (e.g. \\`lsof -i :${DEFAULT_NEXT_PORT}\\`) or pass \\`--port <N>\\` explicitly.`,\n );\n }\n return found;\n}\n\n/**\n * True if no process is listening on the given port on any local\n * interface. Implemented by attempting to bind a transient server\n * to 0.0.0.0:port; if that succeeds we close immediately and the\n * port is free. EADDRINUSE → port is taken. Any other error → treat\n * as unknown / not-free (safer than assuming free).\n */\nasync function isPortFree(port: number): Promise<boolean> {\n const { createServer } = await import('node:net');\n return new Promise<boolean>((resolve) => {\n const server = createServer();\n server.once('error', () => {\n // Common error codes here: EADDRINUSE (port taken), EACCES\n // (privileged port under 1024). Either way the port isn't\n // usable for `next dev`, so report not-free.\n resolve(false);\n });\n server.once('listening', () => {\n server.close(() => resolve(true));\n });\n server.listen(port, '0.0.0.0');\n });\n}\n\n/**\n * Probe ports `start..start+limit-1` and return the first one that's\n * free, or null if none are. Sequential probe (cheap — sub-ms per port\n * locally; user-visible latency stays negligible).\n */\nasync function findFirstFreePort(\n start: number,\n limit: number,\n): Promise<number | null> {\n for (let i = 0; i < limit; i++) {\n const port = start + i;\n if (await isPortFree(port)) return port;\n }\n return null;\n}\n\n/**\n * Resolve the target workspace for the dev session, given the\n * optional `--workspace` flag. Three paths:\n *\n * - Flag is numeric → treat as id, fetch by id.\n * - Flag is non-numeric → treat as slug, look up.\n * - Flag absent → list user's workspaces. If exactly 1, auto-pick.\n * If 0, error. If >1, error with a list so the user can pick.\n *\n * Returns `{ id, name, slug }` for the chosen workspace.\n */\nasync function resolveTargetWorkspace(\n apiUrl: string,\n apiToken: string,\n flag: string | undefined,\n): Promise<{ id: number; name: string; slug: string }> {\n const workspaces = await apiRequest<WorkspaceListItem[]>(\n 'GET',\n '/api/workspaces',\n undefined,\n { baseUrl: apiUrl, auth: { token: apiToken } },\n );\n if (workspaces.length === 0) {\n throw new Error(\n 'No workspaces found for your account. Create a workspace at the DashWise dashboard first.',\n );\n }\n if (flag === undefined) {\n if (workspaces.length === 1) {\n return workspaces[0];\n }\n const list = workspaces.map((w) => ` - ${w.slug} (id=${w.id}, name=\"${w.name}\")`).join('\\n');\n throw new Error(\n `You have ${workspaces.length} workspaces. Re-run with --workspace <slug-or-id> to pick one:\\n${list}`,\n );\n }\n const asNumber = Number.parseInt(flag, 10);\n const isNumeric = !Number.isNaN(asNumber) && String(asNumber) === flag;\n const match = isNumeric\n ? workspaces.find((w) => w.id === asNumber)\n : workspaces.find((w) => w.slug === flag);\n if (!match) {\n const list = workspaces.map((w) => ` - ${w.slug} (id=${w.id})`).join('\\n');\n throw new Error(\n `No workspace matching --workspace=${flag}. Available:\\n${list}`,\n );\n }\n return match;\n}\n\n/**\n * `POST /api/auth/dev/sessions`. CLI-token authenticated. Returns the\n * dev session row the SDK keys off of.\n */\nasync function registerDevSession(\n apiUrl: string,\n apiToken: string,\n body: { target_workspace_id: number; callback_origins: string[] },\n): Promise<DevSessionApiResponse> {\n return apiRequest<DevSessionApiResponse>(\n 'POST',\n '/api/auth/dev/sessions',\n body,\n { baseUrl: apiUrl, auth: { token: apiToken } },\n );\n}\n\n/**\n * `DELETE /api/auth/dev/sessions/:id`. Best-effort — errors are\n * swallowed by the caller. If the call fails (offline, BE down,\n * CLI token revoked since registration), the session naturally\n * expires within 24h so leaving it is harmless.\n */\nasync function revokeDevSessionBestEffort(\n apiUrl: string,\n apiToken: string,\n id: string,\n): Promise<void> {\n await apiRequest<void>(\n 'DELETE',\n `/api/auth/dev/sessions/${encodeURIComponent(id)}`,\n undefined,\n { baseUrl: apiUrl, auth: { token: apiToken } },\n );\n}\n","/**\n * Shared \"connect status\" reporter — the combined deps (P3) + workspace-\n * table `uses` (P4) park/bind summary.\n *\n * P3 introduced the cross-module dependency connect surface (D4): a\n * declared dep parks `unbound` until a provider is installed + bound.\n * P4 adds the workspace-table `uses` binding surface (U4): a declared\n * `uses` slot parks until an admin binds a workspace table to it. Both\n * are \"declared here, connected separately\" states a developer needs to\n * SEE — especially right after a manifest push, when new declarations\n * land parked.\n *\n * This helper fetches both surfaces for one installation and prints a\n * compact, scannable summary (green ● bound/resolved, yellow ○ unbound).\n * It is BEST-EFFORT by contract: any failure (old backend without the\n * endpoints, stale token, offline) is swallowed to a one-line hint — a\n * status probe must never break the caller (e.g. `dashwise dev` startup).\n *\n * Used by `dashwise dev` at startup so the \"tables half\" of the needs\n * report shows up next to the deps half, exactly as the P3 deps output\n * does after a push.\n */\n\nimport {\n ApiError,\n getInstallationBindings,\n getInstallationDependencies,\n type InstallationBinding,\n type InstallationDependency,\n type RequestOptions,\n} from './api-client.js';\nimport { code, dim, info, out, pc } from './output.js';\n\nexport interface ConnectStatusOptions {\n installationId: number;\n moduleSlug: string;\n requestOptions: RequestOptions;\n}\n\n/**\n * Fetch + print the combined deps + uses connect status for an\n * installation. Never throws; never changes an exit code. Prints nothing\n * (beyond an optional single hint) when there are no declarations or the\n * surfaces are unreachable.\n */\nexport async function reportConnectStatus(\n opts: ConnectStatusOptions,\n): Promise<void> {\n const [deps, bindings] = await Promise.all([\n safeGet(() =>\n getInstallationDependencies(opts.installationId, opts.requestOptions),\n ),\n safeGet(() =>\n getInstallationBindings(opts.installationId, opts.requestOptions),\n ),\n ]);\n\n // Both unreachable (or genuinely empty) → nothing useful to show.\n if (deps === null && bindings === null) return;\n const depList = deps ?? [];\n const bindList = bindings ?? [];\n if (depList.length === 0 && bindList.length === 0) return;\n\n const unboundDeps = depList.filter((d) => d.status === 'unbound').length;\n const unboundUses = bindList.filter((b) => b.status === 'unbound').length;\n\n info(\n `Connect status for ${code(opts.moduleSlug)} ${dim(\n `(${depList.length} dep${depList.length === 1 ? '' : 's'}, ${bindList.length} uses slot${bindList.length === 1 ? '' : 's'})`,\n )}:`,\n );\n\n for (const d of depList) renderDep(d);\n for (const b of bindList) renderBinding(b);\n\n const hints: string[] = [];\n if (unboundDeps > 0) {\n hints.push(\n `${code('dashwise deps bind <provider-slug>')} once the provider is installed`,\n );\n }\n if (unboundUses > 0) {\n hints.push(`${code('dashwise bind <uses-slug> --table <name>')} to connect a table`);\n }\n if (hints.length > 0) {\n info(`Connect parked items with ${hints.join('; ')}.`);\n }\n out('');\n}\n\nfunction renderDep(d: InstallationDependency): void {\n if (d.status === 'resolved') {\n const providerLine = d.provider\n ? ` ${dim(`→ install #${d.provider.installation_id} @ v${d.provider.version}`)}`\n : '';\n out(` ${pc.green('● resolved')} ${dim('dep')} ${code(d.slug)}@${d.range ?? '*'}${providerLine}`);\n } else {\n out(\n ` ${pc.yellow('○ unbound')} ${dim('dep')} ${code(d.slug)}@${d.range ?? '*'} ${dim(`reason: ${d.reason ?? '(unspecified)'}`)}`,\n );\n }\n}\n\nfunction renderBinding(b: InstallationBinding): void {\n if (b.status === 'bound') {\n const tableLine = b.table ? ` ${dim(`→ ${b.table.name} (id ${b.table.id})`)}` : '';\n out(` ${pc.green('● bound')} ${dim('uses')} ${code(b.uses_slug)}${tableLine}`);\n } else if (b.status === 'declined') {\n out(` ${pc.dim('⊘ declined')} ${dim('uses')} ${code(b.uses_slug)}`);\n } else {\n out(\n ` ${pc.yellow('○ unbound')} ${dim('uses')} ${code(b.uses_slug)} ${dim(`reason: ${b.reason ?? '(unspecified)'}`)}`,\n );\n }\n}\n\n/**\n * Run an api-client getter, returning its result or `null` on ANY\n * failure. A 404 / old-backend / auth blip must degrade to \"no data\" so\n * the combined report still shows whatever half is reachable.\n */\nasync function safeGet<T>(fn: () => Promise<T[]>): Promise<T[] | null> {\n try {\n return await fn();\n } catch (err) {\n // Swallow — best-effort. (An ApiError or a network error both just\n // mean \"this half is unavailable right now\".)\n void (err as ApiError);\n return null;\n }\n}\n","/**\n * Backend manifest polling loop. Used by `dashwise dev` to auto-sync\n * local `module.json` whenever the backend canonical manifest changes\n * (P1-E3 — BaaS Phase 1, Bucket E sprint 3).\n *\n * Decoupled from `dev.ts` so it's:\n * 1. Testable in isolation (vitest can mock the api-client + assert\n * write-on-change behavior without spawning child processes).\n * 2. Reusable — future commands (`dashwise watch`, `dashwise mcp`,\n * etc.) can drop the same loop in without copy-paste.\n *\n * Design notes:\n *\n * - Polling cadence: setTimeout (not setInterval) chained from the\n * tick handler. This guarantees ≥`intervalMs` between consecutive\n * tick STARTS — never overlaps if a tick takes longer than the\n * interval (slow network, big manifest). setInterval would queue up\n * ticks under contention.\n *\n * - Initial baseline: read the local file BEFORE starting the loop.\n * First poll only writes if the backend differs from THAT baseline.\n * Prevents a write-storm on dev-start when the file already matches\n * the backend.\n *\n * - Failure handling: a single tick failure (network blip, backend\n * 500, expired token) logs via `onError` and keeps the loop\n * running. Persistent failures should be surfaced via UI by the\n * caller — the loop itself never gives up.\n *\n * - Stop semantics: the returned stop function is idempotent + cancels\n * any in-flight setTimeout. In-flight HTTP requests are NOT aborted\n * (no AbortController plumbing yet); they complete to no-op.\n */\n\nimport { readFileSync, writeFileSync, existsSync } from 'node:fs';\nimport { ApiError, getInstallationSchema } from './api-client.js';\nimport type { RequestOptions } from './api-client.js';\n\nexport interface ManifestPollOptions {\n manifestPath: string;\n /**\n * Request options carrying the `dwk_` key (`auth: { token }`). The\n * key resolves the install server-side — Phase 2's module-API schema\n * route (`GET /api/module-api/schema`) has no install id in the URL.\n */\n requestOptions: RequestOptions;\n intervalMs: number;\n /** Called when the backend manifest changes + we wrote locally. */\n onUpdate?: (msg: string) => void;\n /** Called on a single-tick failure. Loop keeps running. */\n onError?: (err: Error) => void;\n}\n\nexport interface ManifestPollHandle {\n /** Idempotent stop. Cancels any pending setTimeout. */\n stop: () => void;\n /** True until stop() is called. */\n isRunning: () => boolean;\n}\n\n/**\n * Start polling the backend canonical manifest. Returns a handle to\n * stop the loop. Loop begins on the NEXT tick (after `intervalMs`),\n * not immediately — `dashwise dev` already has the current local\n * state from its initial read; no point fetching again right away.\n *\n * Callers SHOULD invoke `handle.stop()` on shutdown. The loop will\n * otherwise run until process exit (which is fine for `dashwise dev`\n * but not for tests that need clean teardown).\n */\nexport function startManifestPollLoop(\n opts: ManifestPollOptions,\n): ManifestPollHandle {\n const {\n manifestPath,\n requestOptions,\n intervalMs,\n onUpdate,\n onError,\n } = opts;\n\n let lastSeenJson: string = existsSync(manifestPath)\n ? readFileSync(manifestPath, 'utf-8')\n : '';\n let timer: NodeJS.Timeout | null = null;\n let stopped = false;\n\n const tick = async (): Promise<void> => {\n if (stopped) return;\n try {\n const { manifest } = await getInstallationSchema(requestOptions);\n const remoteJson = JSON.stringify(manifest, null, 2) + '\\n';\n // Re-read the local file every tick — a hand-edit or another\n // CLI command (e.g. `dashwise table create` in another terminal)\n // might have changed it under us. If local == remote, no write.\n // If local != remote BUT remote == lastSeen, also no write —\n // the user's hand-edit is the latest and we shouldn't clobber\n // it (they can explicitly `dashwise pull` to discard).\n const currentLocal = existsSync(manifestPath)\n ? readFileSync(manifestPath, 'utf-8')\n : '';\n if (remoteJson === currentLocal) {\n lastSeenJson = remoteJson;\n } else if (remoteJson !== lastSeenJson) {\n // Backend advanced. Write through.\n writeFileSync(manifestPath, remoteJson, 'utf-8');\n lastSeenJson = remoteJson;\n if (onUpdate) {\n const delta =\n Buffer.byteLength(remoteJson, 'utf8') -\n Buffer.byteLength(currentLocal, 'utf8');\n const deltaStr =\n delta === 0\n ? '0 bytes'\n : `${delta > 0 ? '+' : ''}${delta} bytes`;\n onUpdate(\n `Backend manifest changed — synced to module.json (${deltaStr}).`,\n );\n }\n }\n // Else: backend == lastSeen but local has drifted (hand-edit).\n // Don't clobber — the user owns their working copy.\n } catch (err) {\n if (onError) {\n const message =\n err instanceof ApiError\n ? `${err.code} (HTTP ${err.status}): ${err.message}`\n : (err as Error).message;\n onError(new Error(message));\n }\n } finally {\n if (!stopped) {\n timer = setTimeout(() => void tick(), intervalMs);\n }\n }\n };\n\n // Schedule first tick after `intervalMs`. Don't poll immediately —\n // the caller already has the local state.\n timer = setTimeout(() => void tick(), intervalMs);\n\n return {\n stop: (): void => {\n if (stopped) return;\n stopped = true;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n },\n isRunning: (): boolean => !stopped,\n };\n}\n","/**\n * `dashwise login` — OAuth 2.0 Device Authorization Grant.\n *\n * Flow:\n * 1. POST /api/auth/cli/device-code → get `userCode` + `verificationUri`\n * 2. Display the code + URL; offer to open the browser\n * 3. Poll /api/auth/cli/poll on the published interval until the\n * user approves (or denies / it expires)\n * 4. On `approved`, save the returned token to ~/.config/dashwise/auth.json\n * 5. Fetch /api/auth/me to confirm + cache user identity\n *\n * UX: clack spinner during the poll loop; explicit prompts when\n * something needs the user's attention (e.g. opening the browser).\n * Non-interactive mode (`--no-prompt`) skips browser-open + just\n * prints the URL.\n */\n\nimport { cancel, intro, isCancel, log, outro, select, spinner } from '@clack/prompts';\nimport open from 'open';\nimport { ApiError, apiRequest } from '../lib/api-client.js';\nimport type {\n AuthMeResponse,\n CliDeviceCodeResponse,\n CliPollResponse,\n} from '../lib/backend-types.js';\nimport { resolveApiUrl, writeConfig, type CliConfig } from '../lib/config.js';\nimport { code, dim, fail, info, success } from '../lib/output.js';\n\nexport interface LoginOptions {\n /** Override the backend URL for this login (`--api-url`). */\n apiUrl?: string;\n /** Skip the \"open in browser\" prompt; just print the URL. */\n noPrompt?: boolean;\n /** Token name to suggest to the backend (shown in `me/cli-tokens`). */\n name?: string;\n}\n\nconst DEFAULT_TOKEN_NAME = 'dashwise-cli';\n\nexport async function loginCommand(options: LoginOptions): Promise<number> {\n const apiUrl = (options.apiUrl ?? resolveApiUrl()).replace(/\\/+$/, '');\n intro(`Logging into ${code(apiUrl)}`);\n\n // 1. Kick off the device-code grant.\n let dc: CliDeviceCodeResponse;\n try {\n dc = await apiRequest<CliDeviceCodeResponse>(\n 'POST',\n '/api/auth/cli/device-code',\n {\n name: options.name ?? DEFAULT_TOKEN_NAME,\n },\n { auth: 'public', baseUrl: apiUrl },\n );\n } catch (err) {\n fail(formatApiError('Could not start login flow', err));\n return 1;\n }\n\n log.message(\n [\n `Open the verification URL and confirm the code:`,\n ``,\n ` URL: ${code(dc.verificationUriComplete)}`,\n ` Code: ${code(dc.userCode)}`,\n ``,\n dim(\n `Code expires in ${formatSeconds(dc.expiresIn)}. The CLI will keep polling until you approve.`,\n ),\n ].join('\\n'),\n );\n\n // 2. Offer to open the browser (skipped in non-interactive mode).\n if (!options.noPrompt && process.stdout.isTTY) {\n const choice = await select({\n message: 'Open the verification URL in your browser?',\n options: [\n { value: 'open', label: 'Open now' },\n { value: 'skip', label: 'I’ll open it manually' },\n ],\n initialValue: 'open',\n });\n if (isCancel(choice)) {\n cancel('Login cancelled.');\n return 130; // SIGINT-equivalent exit code\n }\n if (choice === 'open') {\n try {\n await open(dc.verificationUriComplete);\n } catch (err) {\n info(`Could not open browser automatically (${(err as Error).message}). Open the URL above manually.`);\n }\n }\n }\n\n // 3. Poll until approved / denied / expired / overall deadline.\n const sp = spinner();\n sp.start('Waiting for approval');\n const overallDeadline = Date.now() + dc.expiresIn * 1000;\n let outcome: CliPollResponse | null = null;\n // Use 1s sleeps + let the backend's `slow_down` response push us\n // back if we exceed the published interval. Cheap; no need to be\n // clever with the polling cadence.\n const pollIntervalMs = Math.max(1000, dc.interval * 1000);\n\n pollLoop: while (Date.now() < overallDeadline) {\n let res: CliPollResponse;\n try {\n res = await apiRequest<CliPollResponse>(\n 'POST',\n '/api/auth/cli/poll',\n { deviceCode: dc.deviceCode },\n { auth: 'public', baseUrl: apiUrl },\n );\n } catch (err) {\n sp.stop(`Poll failed: ${(err as Error).message}`);\n fail('Poll failed mid-flight; you can re-run `dashwise login` to retry.');\n return 1;\n }\n switch (res.status) {\n case 'pending':\n case 'slow_down':\n await sleep(pollIntervalMs);\n continue pollLoop;\n case 'denied':\n sp.stop('Login denied by user.');\n cancel('Aborted.');\n return 1;\n case 'expired':\n sp.stop('Login code expired.');\n fail('The code expired before approval. Run `dashwise login` again.');\n return 1;\n case 'approved':\n outcome = res;\n break pollLoop;\n }\n }\n\n if (!outcome) {\n sp.stop('Timed out waiting for approval.');\n fail('Login took too long to be approved. Run `dashwise login` again.');\n return 1;\n }\n\n if (!outcome.token || !outcome.tokenId) {\n // Shouldn't happen on a fresh approval — but guard anyway.\n sp.stop('Approval received but token missing from response.');\n fail(\n 'Approval received but the backend did not return a token. Run `dashwise logout` then `dashwise login` to retry.',\n );\n return 1;\n }\n\n // 4. Confirm the token works + cache the profile.\n let me: AuthMeResponse;\n try {\n me = await apiRequest<AuthMeResponse>('GET', '/api/auth/me', undefined, {\n auth: { token: outcome.token },\n baseUrl: apiUrl,\n });\n } catch (err) {\n sp.stop('Approval accepted but profile fetch failed.');\n fail(formatApiError('Could not load user profile', err));\n return 1;\n }\n\n const cfg: CliConfig = {\n apiUrl,\n token: outcome.token,\n tokenId: outcome.tokenId,\n user: {\n id: me.id,\n email: me.email,\n username: me.username,\n firstName: me.first_name,\n lastName: me.last_name,\n },\n };\n writeConfig(cfg);\n sp.stop('Approved.');\n success(`Logged in as ${code(me.email)}`);\n outro('You can now run `dashwise profile`, `dashwise workspace list`, etc.');\n return 0;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction formatSeconds(seconds: number): string {\n if (seconds < 60) return `${seconds}s`;\n const minutes = Math.round(seconds / 60);\n return `${minutes}m`;\n}\n\nfunction formatApiError(prefix: string, err: unknown): string {\n if (err instanceof ApiError) {\n return `${prefix}: ${err.message} (code: ${err.code}, status: ${err.status})`;\n }\n if (err instanceof Error) return `${prefix}: ${err.message}`;\n return `${prefix}: ${String(err)}`;\n}\n","/**\n * `dashwise logout` — clear the local credentials and best-effort\n * revoke the server-side token row.\n *\n * Behavior:\n * 1. Read the saved config; if there's no token, exit 0 with an\n * info message (idempotent).\n * 2. Call `DELETE /api/auth/cli-tokens/:id` to revoke the row.\n * 404 / 403 / network errors are tolerated — the local file is\n * cleared regardless. We never want a server-side hiccup to\n * keep stale credentials on disk.\n * 3. Delete the local config file.\n */\n\nimport { apiRequest } from '../lib/api-client.js';\nimport { deleteConfig, readConfig } from '../lib/config.js';\nimport { code, info, success, warn } from '../lib/output.js';\n\nexport async function logoutCommand(): Promise<number> {\n let cfg;\n try {\n cfg = readConfig();\n } catch {\n // Corrupt file — clearing it is precisely what `logout` should do.\n deleteConfig();\n success('Cleared a corrupted local credential file.');\n return 0;\n }\n if (!cfg) {\n info('Already logged out (no saved credentials).');\n return 0;\n }\n\n // Best-effort server-side revocation.\n try {\n await apiRequest(\n 'DELETE',\n `/api/auth/cli-tokens/${cfg.tokenId}`,\n undefined,\n { auth: { token: cfg.token }, baseUrl: cfg.apiUrl },\n );\n } catch (err) {\n warn(\n `Could not revoke the server-side token (${(err as Error).message}). Local credentials cleared anyway.`,\n );\n }\n\n deleteConfig();\n success(`Logged out ${code(cfg.user.email)}`);\n return 0;\n}\n","/**\n * `dashwise profile` — show the current user + (briefly) workspaces.\n *\n * Reads the saved config first so the basic identity prints\n * instantly; then makes a live `/api/auth/me` call to refresh the\n * cached profile (network errors are tolerated — we fall back to\n * the cached values and warn).\n *\n * Output is plain key/value to stdout so the command is pipeable\n * (e.g. `dashwise profile | grep email`). For machine-readable\n * output a future `--json` flag is the right call.\n */\n\nimport { ApiError, apiRequest } from '../lib/api-client.js';\nimport type { AuthMeResponse, WorkspaceListItem } from '../lib/backend-types.js';\nimport { readConfig, writeConfig } from '../lib/config.js';\nimport { code, dim, fail, info, kv, out, warn } from '../lib/output.js';\n\nexport interface ProfileOptions {\n /** Emit the profile + workspaces as a single JSON object instead of human-readable kv pairs. */\n json?: boolean;\n}\n\nexport async function profileCommand(options: ProfileOptions = {}): Promise<number> {\n const cfg = readConfig();\n if (!cfg) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'NOT_LOGGED_IN', message: 'Run `dashwise login` first.' } }));\n } else {\n fail('Not logged in. Run `dashwise login` first.');\n }\n return 1;\n }\n\n // Refresh identity. Tolerate transient network errors.\n let me: AuthMeResponse | null = null;\n let refreshError: string | null = null;\n try {\n me = await apiRequest<AuthMeResponse>('GET', '/api/auth/me');\n } catch (err) {\n if (err instanceof ApiError && err.status === 401) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'TOKEN_INVALID', message: 'Saved token is no longer valid.' } }));\n } else {\n fail('Saved token is no longer valid. Run `dashwise login` again.');\n }\n return 1;\n }\n refreshError = (err as Error).message;\n if (!options.json) {\n warn(\n `Could not refresh profile from the server (${refreshError}). Showing cached values.`,\n );\n }\n }\n\n if (me) {\n // Persist any drift between cached + server values.\n const refreshed = {\n ...cfg,\n user: {\n id: me.id,\n email: me.email,\n username: me.username,\n firstName: me.first_name,\n lastName: me.last_name,\n },\n };\n writeConfig(refreshed);\n }\n const u = (me ?? toMe(cfg.user));\n\n // Workspace list — best-effort.\n let workspaces: WorkspaceListItem[] = [];\n let workspaceError: string | null = null;\n try {\n const fetched = await apiRequest<WorkspaceListItem[]>(\n 'GET',\n '/api/workspaces',\n );\n workspaces = Array.isArray(fetched) ? fetched : [];\n } catch (err) {\n workspaceError = (err as Error).message;\n }\n\n if (options.json) {\n out(\n JSON.stringify({\n ok: true,\n user: {\n id: u.id,\n username: u.username,\n email: u.email,\n first_name: u.first_name,\n last_name: u.last_name,\n },\n default_workspace: cfg.workspaceSlug ?? null,\n workspaces,\n api_url: cfg.apiUrl,\n ...(refreshError ? { profile_refresh_error: refreshError } : {}),\n ...(workspaceError ? { workspaces_error: workspaceError } : {}),\n }),\n );\n return 0;\n }\n\n out('');\n kv('User ID', `${u.id}`);\n kv('Username', u.username);\n kv('Email', u.email);\n kv('Name', `${u.first_name} ${u.last_name}`.trim() || dim('(not set)'));\n\n out('');\n if (workspaceError) {\n warn(\n `Could not list workspaces (${workspaceError}). Try \\`dashwise workspace list\\`.`,\n );\n } else if (workspaces.length === 0) {\n info('No workspaces yet.');\n } else {\n kv('Workspaces', `${workspaces.length}`);\n for (const w of workspaces) {\n const slug = w.slug ?? `id:${w.id}`;\n const role = w.role ?? w.permissions ?? '';\n const star = cfg.workspaceSlug === slug ? code(' (default)') : '';\n out(` - ${slug}${role ? dim(` [${role}]`) : ''}${star} ${dim(w.name)}`);\n }\n }\n\n out('');\n kv('API URL', cfg.apiUrl);\n return 0;\n}\n\nfunction toMe(cached: { id: number; email: string; username: string; firstName: string; lastName: string }): AuthMeResponse {\n return {\n id: cached.id,\n email: cached.email,\n username: cached.username,\n first_name: cached.firstName,\n last_name: cached.lastName,\n is_staff: false,\n is_active: true,\n date_joined: '',\n };\n}\n","/**\n * `dashwise workspace list` — list workspaces the user belongs to.\n * `dashwise workspace use <slug>` — set the default workspace (saved\n * to ~/.config/dashwise/auth.json).\n *\n * The \"default workspace\" is consumed by subsequent commands\n * (`module init`, `module publish`, etc.) so the user doesn't have\n * to pass `--workspace <slug>` every time. Persists across\n * `dashwise` invocations until `workspace use` is called again.\n */\n\nimport { ApiError, apiRequest } from '../lib/api-client.js';\nimport type { WorkspaceListItem } from '../lib/backend-types.js';\nimport { readConfig, writeConfig } from '../lib/config.js';\nimport { code, dim, fail, info, kv, out, success } from '../lib/output.js';\n\nexport interface WorkspaceListOptions {\n json?: boolean;\n}\n\nexport async function workspaceListCommand(options: WorkspaceListOptions = {}): Promise<number> {\n const cfg = readConfig();\n if (!cfg) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'NOT_LOGGED_IN', message: 'Run `dashwise login` first.' } }));\n } else {\n fail('Not logged in. Run `dashwise login` first.');\n }\n return 1;\n }\n let workspaces: WorkspaceListItem[];\n try {\n workspaces = await apiRequest<WorkspaceListItem[]>('GET', '/api/workspaces');\n } catch (err) {\n if (err instanceof ApiError && err.status === 401) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'TOKEN_INVALID', message: 'Saved token is no longer valid.' } }));\n } else {\n fail('Saved token is no longer valid. Run `dashwise login` again.');\n }\n return 1;\n }\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'FETCH_FAILED', message: (err as Error).message } }));\n } else {\n fail(`Could not list workspaces: ${(err as Error).message}`);\n }\n return 1;\n }\n if (options.json) {\n out(\n JSON.stringify({\n ok: true,\n default_workspace: cfg.workspaceSlug ?? null,\n workspaces: Array.isArray(workspaces) ? workspaces : [],\n }),\n );\n return 0;\n }\n if (!Array.isArray(workspaces) || workspaces.length === 0) {\n info('No workspaces yet.');\n return 0;\n }\n out('');\n for (const w of workspaces) {\n const slug = w.slug ?? `id:${w.id}`;\n const role = w.role ?? w.permissions ?? '';\n const isDefault = cfg.workspaceSlug === slug;\n const marker = isDefault ? code(' *') : ' ';\n out(`${marker} ${slug.padEnd(28)} ${dim(w.name)}${role ? dim(` [${role}]`) : ''}`);\n }\n out('');\n if (cfg.workspaceSlug) {\n info(`Default workspace: ${code(cfg.workspaceSlug)}`);\n } else {\n info('No default workspace set. Use `dashwise workspace use <slug>` to set one.');\n }\n return 0;\n}\n\nexport async function workspaceUseCommand(slug: string): Promise<number> {\n const cfg = readConfig();\n if (!cfg) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n if (typeof slug !== 'string' || slug.length === 0) {\n fail('Usage: `dashwise workspace use <slug>`');\n return 1;\n }\n // Validate the slug exists + the user has access. Avoids the\n // footgun of setting a default to a workspace the user can't\n // actually use.\n let workspaces: WorkspaceListItem[] = [];\n try {\n workspaces = await apiRequest<WorkspaceListItem[]>('GET', '/api/workspaces');\n } catch (err) {\n fail(`Could not validate the workspace (${(err as Error).message}).`);\n return 1;\n }\n const match = workspaces.find(\n (w) => w.slug === slug || `id:${w.id}` === slug || String(w.id) === slug,\n );\n if (!match) {\n fail(`Workspace ${code(slug)} not found in your accessible workspaces.`);\n out('');\n info('Run `dashwise workspace list` to see what you can choose.');\n return 1;\n }\n const matchedSlug = match.slug ?? `id:${match.id}`;\n writeConfig({ ...cfg, workspaceSlug: matchedSlug });\n success(`Default workspace set to ${code(matchedSlug)}`);\n kv('Name', match.name);\n if (match.role ?? match.permissions) {\n kv('Role', String(match.role ?? match.permissions));\n }\n return 0;\n}\n","/**\n * `dashwise module clone <slug>` — bring a published module's\n * source into a local directory.\n *\n * Two flavors based on what's available on the backend:\n *\n * 1. **Git mode** — when the module's published manifest carries\n * `repository.url`, we shell out to `git clone` to fetch the\n * source. This is the recommended path: full file history,\n * branch awareness, future `git pull` for updates.\n *\n * 2. **Manifest-only mode** — when no `repository.url` is set,\n * we write the published manifest into a fresh directory plus\n * a minimal scaffold (.gitignore, package.json, README) so the\n * user has a workable starting point. They can then layer\n * their own app code on top + run `dashwise module dev`.\n *\n * Refuses to write into a non-empty directory unless `--force` is\n * passed.\n */\n\nimport { spawnSync } from 'node:child_process';\nimport { existsSync, mkdirSync, readdirSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { gitignore, packageJson, packageJsonCustom } from '../../lib/scaffold.js';\nimport { code, dim, fail, info, out, success, warn } from '../../lib/output.js';\n\ninterface SourceMetadataResponse {\n module_slug: string;\n module_name: string;\n current_version: string | null;\n repository_url: string | null;\n manifest: Record<string, unknown> | null;\n}\n\nexport interface CloneOptions {\n /** Target directory (default: `./<slug>`). */\n dir?: string;\n /** Overwrite an existing non-empty directory. */\n force?: boolean;\n /** Skip git clone even when repository.url is set (use manifest mode). */\n noGit?: boolean;\n}\n\nexport async function moduleCloneCommand(\n slug: string,\n options: CloneOptions,\n): Promise<number> {\n if (!slug) {\n fail('Usage: `dashwise module clone <slug>`');\n return 1;\n }\n\n let meta: SourceMetadataResponse;\n try {\n meta = await apiRequest<SourceMetadataResponse>(\n 'GET',\n `/api/modules/${encodeURIComponent(slug)}/source-tarball`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n fail(`Module ${code(slug)} not found.`);\n return 1;\n }\n if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n if (err instanceof ApiError && err.status === 403) {\n fail(`No access to module ${code(slug)}. You must be a member of its owner workspace.`);\n return 1;\n }\n fail(`Could not fetch module metadata: ${(err as Error).message}`);\n return 1;\n }\n\n const target = resolve(options.dir ?? slug);\n\n // Refuse to overwrite an existing non-empty directory unless --force.\n if (existsSync(target)) {\n const entries = readdirSync(target);\n if (entries.length > 0 && !options.force) {\n fail(\n `Directory ${code(target)} is not empty. Pass ${code('--force')} to clone anyway.`,\n );\n return 1;\n }\n }\n\n // Decide between git mode + manifest-only fallback.\n const wantGit = !options.noGit && meta.repository_url !== null;\n if (wantGit) {\n return cloneViaGit(meta, target);\n }\n\n if (meta.repository_url !== null && options.noGit) {\n info(`--no-git: skipping git clone for ${code(meta.repository_url)}; writing manifest-only scaffold.`);\n } else {\n info(`Module ${code(slug)} has no ${code('repository.url')}; writing manifest-only scaffold.`);\n }\n return cloneViaManifest(slug, meta, target);\n}\n\n/**\n * Shell out to `git clone <url> <target>`. Inherits stdio so the\n * user sees git's progress + error messages directly. Returns 0 on\n * success, propagating git's exit code on failure.\n */\nfunction cloneViaGit(meta: SourceMetadataResponse, target: string): number {\n const repoUrl = meta.repository_url!;\n info(`Cloning ${code(repoUrl)} into ${code(target)}...`);\n const result = spawnSync('git', ['clone', repoUrl, target], {\n stdio: 'inherit',\n });\n if (result.error) {\n fail(`Failed to invoke git: ${result.error.message}`);\n return 1;\n }\n if (result.status !== 0) {\n fail(`git clone exited with status ${result.status}.`);\n return result.status ?? 1;\n }\n success(`Cloned ${code(meta.module_slug)} from ${code(repoUrl)}.`);\n if (meta.current_version) {\n info(`Current published version: ${code(`v${meta.current_version}`)}`);\n }\n return 0;\n}\n\n/**\n * Fallback when no Git URL is available: lay down `module.json` +\n * `.gitignore` + `package.json` + `README.md` so the user has a\n * starting point. The user has to recreate `app/` themselves —\n * we don't have access to the original source (no Git URL).\n */\nfunction cloneViaManifest(\n slug: string,\n meta: SourceMetadataResponse,\n target: string,\n): number {\n if (!meta.manifest) {\n fail(\n `Module ${code(slug)} has no published manifest yet (publish at least one version first).`,\n );\n return 1;\n }\n\n mkdirSync(target, { recursive: true });\n\n // Inspect the manifest to pick the right scaffold flavor.\n const manifestObj = meta.manifest as Record<string, unknown>;\n const moduleKind = manifestObj.module_kind === 'custom' ? 'custom' : 'hand_authored';\n const pkgFn = moduleKind === 'custom' ? packageJsonCustom : packageJson;\n\n writeFileSync(\n join(target, 'module.json'),\n JSON.stringify(manifestObj, null, 2) + '\\n',\n 'utf-8',\n );\n writeFileSync(\n join(target, 'package.json'),\n pkgFn({ slug: meta.module_slug, name: meta.module_name, kind: moduleKind }),\n 'utf-8',\n );\n writeFileSync(join(target, '.gitignore'), gitignore(), 'utf-8');\n writeFileSync(\n join(target, 'README.md'),\n readmeForClone(meta, moduleKind),\n 'utf-8',\n );\n\n success(`Wrote ${moduleKind} scaffold for ${code(meta.module_slug)} into ${code(target)}`);\n info(`Next steps:`);\n out('');\n out(` ${dim('1.')} ${code(`cd ${target}`)}`);\n out(` ${dim('2.')} ${code('npm install')}`);\n out(` ${dim('3.')} ${code('dashwise module generate')}`);\n out(` ${dim('4.')} Recreate your ${code('app/')} (manifest-only clone — no source code available).`);\n out('');\n if (meta.repository_url) {\n warn(\n `Module's manifest declared ${code(meta.repository_url)} as its repo; consider running ${code(`dashwise module clone ${slug}`)} without ${code('--no-git')} to get the full source.`,\n );\n } else {\n info(\n `If you have access to the original source, ` +\n `consider running ${code(`dashwise module connect-git <repo-url>`)} ` +\n `so future clones use it.`,\n );\n }\n return 0;\n}\n\nfunction readmeForClone(\n meta: SourceMetadataResponse,\n kind: 'hand_authored' | 'custom',\n): string {\n return `# ${meta.module_name}\n\nManifest-only clone of \\`${meta.module_slug}\\` (${kind}) at version \\`${meta.current_version ?? 'unpublished'}\\`.\n\nThe original source code wasn't available — this directory contains\nonly the published \\`module.json\\` + a starter scaffold. Recreate\n\\`app/\\` based on the manifest.\n\n## Get started\n\n\\`\\`\\`bash\nnpm install\ndashwise module generate\ndashwise module dev\n\\`\\`\\`\n`;\n}\n","/**\n * `dashwise module connect-git <repo-url>` — write the Git repository\n * URL into the local `module.json#repository.url`.\n *\n * v1 scope: local manifest mutation only. The backend reads\n * `repository` from the manifest on the next `module publish` and\n * captures the URL + the actual `commit` + `branch` from the local\n * git working tree at publish time (P5b for the commit-capture\n * follow-up). For now, this command just sets the URL so the\n * marketplace + `module clone` know where to look.\n *\n * The URL is light-validated: must be a real URL, https:// or git@\n * shorthand also accepted. Branch can be passed via `--branch\n * <name>` to default to a non-`main` branch (rare, but common\n * for monorepos).\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { code, fail, info, success } from '../../lib/output.js';\n\nexport interface ConnectGitOptions {\n dir?: string;\n branch?: string;\n}\n\nexport async function moduleConnectGitCommand(\n repoUrl: string,\n options: ConnectGitOptions,\n): Promise<number> {\n if (!repoUrl || typeof repoUrl !== 'string') {\n fail('Usage: `dashwise module connect-git <repo-url>`');\n return 1;\n }\n if (!isPlausibleRepoUrl(repoUrl)) {\n fail(`Repo URL ${code(repoUrl)} doesn't look like https:// or git@host:owner/repo.`);\n return 1;\n }\n\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n fail(\n `No ${code('module.json')} found in ${code(projectRoot)}. Run \\`dashwise module init\\` first.`,\n );\n return 1;\n }\n let manifest: Record<string, unknown>;\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n } catch (err) {\n fail(`Could not parse ${code(manifestPath)}: ${(err as Error).message}`);\n return 1;\n }\n\n const existing = (manifest.repository as Record<string, unknown> | undefined) ?? {};\n const next: Record<string, unknown> = {\n ...existing,\n type: 'git',\n url: repoUrl,\n };\n if (options.branch) {\n next.branch = options.branch;\n } else if (typeof existing.branch === 'string') {\n // Preserve any branch already set.\n next.branch = existing.branch;\n }\n manifest.repository = next;\n\n writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\\n', 'utf-8');\n success(`Connected to ${code(repoUrl)}`);\n if (next.branch) info(`Branch: ${code(String(next.branch))}`);\n info(`Updated ${code('module.json')}.`);\n return 0;\n}\n\n/**\n * Accept three URL shapes commonly used for Git remotes:\n * - https://github.com/org/repo\n * - https://github.com/org/repo.git\n * - git@github.com:org/repo.git\n *\n * Rejects obvious garbage; the backend (or git itself, at clone\n * time) does the real validation.\n */\nfunction isPlausibleRepoUrl(url: string): boolean {\n if (url.startsWith('https://') || url.startsWith('http://')) {\n try {\n new URL(url);\n return true;\n } catch {\n return false;\n }\n }\n // git@host:owner/repo[.git] shorthand\n return /^git@[^:]+:[^/]+\\/.+/.test(url);\n}\n","/**\n * `dashwise module convert [dir]` — turn an EXISTING standalone Next.js\n * app into a DashWise module, idempotently.\n *\n * The \"build standalone now, link to DashWise later\" on-ramp: a developer\n * builds a normal Next.js app, then runs `convert` to inject the module\n * shape (manifest + auth wiring + SDK dep + runtime config). It is\n * deliberately CONSERVATIVE — it creates missing files but never\n * overwrites an author's existing `module.json`, `layout`, or\n * `next.config`; for those it warns with the manual edit needed. Reuses\n * the same file generators as `dashwise module init` so a converted app\n * matches a scaffolded one.\n *\n * Decoupled from any backend module id — `convert` is purely local. Link\n * to DashWise afterwards with `dashwise dev` (local) or `dashwise module\n * publish` (deploy).\n */\n\nimport {\n existsSync,\n mkdirSync,\n readFileSync,\n readdirSync,\n statSync,\n writeFileSync,\n} from 'node:fs';\nimport { basename, dirname, join, resolve } from 'node:path';\nimport {\n appApiAuthCallbackTs,\n appApiAuthSessionTs,\n appApiAuthSignInTs,\n appApiAuthSignOutTs,\n appLayoutCustomTsx,\n appSignInErrorPageTsx,\n envLocalExample,\n isValidSlug,\n manifestJson,\n middlewareTs,\n type ScaffoldOptions,\n} from '../../lib/scaffold.js';\n\n/** Pinned to match the scaffold's `@dashai/sdk` dependency. */\nconst SDK_DEP_RANGE = '^2.0.0';\n\n/** Source dirs scanned for outbound `https://` hosts (allowlist seeding). */\nconst SCAN_DIRS = ['app', 'src', 'pages', 'lib', 'components'];\nconst SCAN_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '.mjs'];\nconst MAX_SCAN_FILES = 2000;\n\nexport interface ConvertResult {\n slug: string;\n name: string;\n /** Files newly written. */\n created: string[];\n /** Files already present, left untouched. */\n skipped: string[];\n /** Manual actions the author must take (we don't auto-edit these). */\n warnings: string[];\n /** Hosts discovered in source + merged into runtime.outbound_apis. */\n outboundApis: string[];\n /** True when an existing custom manifest was missing its runtime block. */\n runtimeBlockAdded: boolean;\n}\n\nfunction deriveSlug(input: string): string {\n return input\n .toLowerCase()\n .replace(/^@[^/]+\\//, '') // drop npm scope\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 63);\n}\n\n/**\n * The convert engine (pure-ish: only touches the target dir). Throws on a\n * non-Next.js dir or an unusable slug; otherwise returns a change report.\n */\nexport function convertModule(opts: {\n dir: string;\n slug?: string;\n name?: string;\n repositoryUrl?: string;\n}): ConvertResult {\n const dir = resolve(opts.dir);\n const pkgPath = join(dir, 'package.json');\n if (!existsSync(pkgPath)) {\n throw new Error(\n 'No package.json found — run `dashwise module convert` inside a Next.js project.',\n );\n }\n const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8')) as {\n name?: string;\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n const nextConfigFile = ['next.config.mjs', 'next.config.js', 'next.config.ts'].find(\n (f) => existsSync(join(dir, f)),\n );\n const looksNext =\n Boolean(pkg.dependencies?.next || pkg.devDependencies?.next) ||\n nextConfigFile !== undefined ||\n existsSync(join(dir, 'app')) ||\n existsSync(join(dir, 'src', 'app'));\n if (!looksNext) {\n throw new Error(\n 'This does not look like a Next.js app (no `next` dependency, next.config, or app/ directory).',\n );\n }\n\n const slug = opts.slug ?? deriveSlug(pkg.name ?? basename(dir));\n if (!isValidSlug(slug)) {\n throw new Error(\n `Could not derive a valid module slug (\"${slug}\"). Pass --slug (must match /^[a-z][a-z0-9_-]*$/).`,\n );\n }\n const name = opts.name ?? pkg.name ?? slug;\n const sopts: ScaffoldOptions = {\n slug,\n name,\n kind: 'custom',\n ...(opts.repositoryUrl ? { repositoryUrl: opts.repositoryUrl } : {}),\n };\n\n const created: string[] = [];\n const skipped: string[] = [];\n const warnings: string[] = [];\n\n const writeIfMissing = (rel: string, content: string): void => {\n const p = join(dir, rel);\n if (existsSync(p)) {\n skipped.push(rel);\n return;\n }\n mkdirSync(dirname(p), { recursive: true });\n writeFileSync(p, content, 'utf-8');\n created.push(rel);\n };\n\n // 1. The manifest (created if missing; normalized below either way).\n writeIfMissing('module.json', manifestJson(sopts));\n\n // 2. Edge auth middleware + the SSO route handlers + error page.\n writeIfMissing('middleware.ts', middlewareTs());\n writeIfMissing('app/api/auth/sign-in/route.ts', appApiAuthSignInTs());\n writeIfMissing('app/api/auth/callback/route.ts', appApiAuthCallbackTs());\n writeIfMissing('app/api/auth/sign-out/route.ts', appApiAuthSignOutTs());\n writeIfMissing('app/api/auth/session/route.ts', appApiAuthSessionTs());\n writeIfMissing('app/sign-in-error/page.tsx', appSignInErrorPageTsx());\n writeIfMissing('.env.local.example', envLocalExample());\n\n // 3. Layout: only create if absent; never rewrite the author's layout.\n const layoutFile = [\n 'app/layout.tsx',\n 'app/layout.jsx',\n 'src/app/layout.tsx',\n ].find((f) => existsSync(join(dir, f)));\n if (!layoutFile) {\n writeIfMissing('app/layout.tsx', appLayoutCustomTsx(sopts));\n } else if (!readFileSync(join(dir, layoutFile), 'utf-8').includes('AuthProvider')) {\n warnings.push(\n `${layoutFile}: wrap your tree in <AuthProvider sessionEndpoint=\"/api/auth/session\"> from \"@dashai/sdk/auth/client\" so client components can read the session (the same-origin session route was scaffolded for you).`,\n );\n } else {\n skipped.push(layoutFile);\n }\n\n // 4. next.config: ensure output:'standalone' (the module runtime bundle\n // harvests `.next/standalone/server.js`). Create when absent; warn\n // when present but missing it — we don't edit arbitrary configs.\n if (!nextConfigFile) {\n writeIfMissing('next.config.mjs', standaloneNextConfig());\n } else if (!readFileSync(join(dir, nextConfigFile), 'utf-8').includes('standalone')) {\n warnings.push(\n `${nextConfigFile}: add \\`output: 'standalone'\\` — required for the module runtime bundle.`,\n );\n }\n\n // 5. @dashai/sdk dependency.\n if (!pkg.dependencies?.['@dashai/sdk']) {\n pkg.dependencies = { ...(pkg.dependencies ?? {}), '@dashai/sdk': SDK_DEP_RANGE };\n writeFileSync(pkgPath, JSON.stringify(pkg, null, 2) + '\\n', 'utf-8');\n created.push('package.json (added @dashai/sdk)');\n }\n\n // 6. Scan source for outbound https hosts → merge into the manifest's\n // allowlist, and normalize the manifest (ensure custom + runtime).\n const outboundApis = scanOutboundHosts(dir);\n const runtimeBlockAdded = normalizeManifest(join(dir, 'module.json'), {\n slug,\n name,\n outboundApis,\n });\n\n return {\n slug,\n name,\n created,\n skipped,\n warnings,\n outboundApis,\n runtimeBlockAdded,\n };\n}\n\nfunction standaloneNextConfig(): string {\n return `/** @type {import(\"next\").NextConfig} */\nconst nextConfig = {\n output: 'standalone',\n typescript: { ignoreBuildErrors: true },\n eslint: { ignoreDuringBuilds: true },\n};\nexport default nextConfig;\n`;\n}\n\n/**\n * Ensure module.json is a `custom`/`machine` manifest and merge any\n * discovered outbound hosts into `runtime.outbound_apis`. Returns true if\n * a missing runtime block was added (so the caller can surface it).\n */\nfunction normalizeManifest(\n manifestPath: string,\n opts: { slug: string; name: string; outboundApis: string[] },\n): boolean {\n const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as Record<\n string,\n unknown\n >;\n let runtimeAdded = false;\n\n if (manifest.module_kind === undefined) manifest.module_kind = 'custom';\n\n let runtime = manifest.runtime as Record<string, unknown> | undefined;\n if (manifest.module_kind === 'custom' && !runtime) {\n runtime = {\n type: 'nextjs',\n kind: 'machine',\n machine_size: 'shared-cpu-1x',\n server_actions: true,\n };\n manifest.runtime = runtime;\n runtimeAdded = true;\n }\n\n if (runtime && opts.outboundApis.length > 0) {\n const existing = Array.isArray(runtime.outbound_apis)\n ? (runtime.outbound_apis as string[])\n : [];\n runtime.outbound_apis = Array.from(\n new Set([...existing, ...opts.outboundApis]),\n ).sort();\n }\n\n writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + '\\n', 'utf-8');\n return runtimeAdded;\n}\n\n/** Walk source dirs and collect distinct external `https://` hostnames. */\nexport function scanOutboundHosts(dir: string): string[] {\n const hosts = new Set<string>();\n let scanned = 0;\n const hostRe = /https:\\/\\/([a-zA-Z0-9.-]+)/g;\n\n const walk = (abs: string): void => {\n if (scanned >= MAX_SCAN_FILES) return;\n let entries: string[];\n try {\n entries = readdirSync(abs);\n } catch {\n return;\n }\n for (const entry of entries) {\n if (entry === 'node_modules' || entry.startsWith('.')) continue;\n const p = join(abs, entry);\n let st;\n try {\n st = statSync(p);\n } catch {\n continue;\n }\n if (st.isDirectory()) {\n walk(p);\n } else if (SCAN_EXTENSIONS.some((e) => entry.endsWith(e))) {\n if (scanned >= MAX_SCAN_FILES) return;\n scanned++;\n let body: string;\n try {\n body = readFileSync(p, 'utf-8');\n } catch {\n continue;\n }\n for (const m of body.matchAll(hostRe)) {\n const host = m[1].toLowerCase();\n if (host === 'localhost' || host.endsWith('.local')) continue;\n // Skip the DashWise API itself + plain ip-ish noise.\n if (host.includes('dashwise')) continue;\n if (/^\\d+\\.\\d+\\.\\d+\\.\\d+$/.test(host)) continue;\n hosts.add(host);\n }\n }\n }\n };\n\n for (const d of SCAN_DIRS) {\n const abs = join(dir, d);\n if (existsSync(abs)) walk(abs);\n }\n // Emit full `https://<host>` patterns — the manifest's\n // runtime.outbound_apis schema (RUNTIME_OUTBOUND_PATTERN_REGEX) requires\n // the scheme; a bare host is rejected at publish/generate time.\n return Array.from(hosts, (h) => `https://${h}`).sort();\n}\n\n/** CLI wrapper: run convert, print a change report, return an exit code. */\nexport async function moduleConvertCommand(opts: {\n dir?: string;\n slug?: string;\n name?: string;\n git?: string;\n}): Promise<number> {\n try {\n const result = convertModule({\n dir: opts.dir ?? process.cwd(),\n ...(opts.slug !== undefined ? { slug: opts.slug } : {}),\n ...(opts.name !== undefined ? { name: opts.name } : {}),\n ...(opts.git !== undefined ? { repositoryUrl: opts.git } : {}),\n });\n\n console.log(`Converted \"${result.name}\" (slug: ${result.slug}) to a DashWise module.\\n`);\n if (result.created.length) {\n console.log(' Created:');\n for (const f of result.created) console.log(` + ${f}`);\n }\n if (result.skipped.length) {\n console.log(' Left as-is:');\n for (const f of result.skipped) console.log(` · ${f}`);\n }\n if (result.runtimeBlockAdded) {\n console.log(' + module.json: added runtime block (nextjs/machine)');\n }\n if (result.outboundApis.length) {\n console.log(\n ` + module.json runtime.outbound_apis: ${result.outboundApis.join(', ')}`,\n );\n }\n if (result.warnings.length) {\n console.log('\\n Manual steps needed:');\n for (const w of result.warnings) console.log(` ! ${w}`);\n }\n console.log(\n '\\nNext: `npm install`, then `dashwise dev` to run it against DashWise, or `dashwise module publish` to deploy.',\n );\n return 0;\n } catch (err) {\n console.error(\n `convert failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n return 1;\n }\n}\n","/**\n * `dashwise module export [dir]` — package a local module into a portable\n * `<slug>.zip` in the exact shape the operator ZIP-import expects\n * (`POST /api/admin/modules/import/zip` / the HQ \"Import ZIP\" action):\n * `module.json` at the archive root, no wrapper directory, with deps /\n * build output / VCS / local env files excluded.\n *\n * Closes the round-trip: a developer builds + `convert`s a module, runs\n * `export`, and hands the ZIP to an operator who deploys it. Purely local\n * — no login, no backend call.\n *\n * Note: the operator import commits text files only, so binary assets\n * (images/fonts) in the ZIP are dropped on import. They're still included\n * here so the archive is a faithful copy of the module.\n */\n\nimport {\n existsSync,\n readFileSync,\n readdirSync,\n statSync,\n} from 'node:fs';\nimport { basename, join, relative, resolve, sep } from 'node:path';\nimport AdmZip from 'adm-zip';\n\n/** Directory names never packaged (deps / build output / VCS) — mirrors the\n * backend extractor's ignore set so the round-trip is predictable. */\nconst IGNORE_DIRS = new Set([\n 'node_modules',\n '.git',\n '.next',\n '.turbo',\n '.vercel',\n 'dist',\n 'build',\n 'out',\n 'coverage',\n '.cache',\n]);\n\n/** Mirror the import limits so `export` warns before producing an un-importable ZIP. */\nconst MAX_FILES = 5_000;\nconst MAX_TOTAL_BYTES = 25 * 1024 * 1024; // 25 MiB\n\nexport interface ExportResult {\n slug: string;\n name: string;\n outPath: string;\n fileCount: number;\n totalBytes: number;\n /** True when content exceeds the import's caps (the ZIP may be rejected). */\n exceedsImportLimits: boolean;\n}\n\nfunction deriveSlug(input: string): string {\n return input\n .toLowerCase()\n .replace(/^@[^/]+\\//, '')\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 63);\n}\n\n/**\n * A local env file carries secrets and must NEVER ship — EXCEPT `*.example`\n * templates, which are safe and useful to the importer.\n */\nfunction isLocalEnvSecret(name: string): boolean {\n if (name.endsWith('.example')) return false;\n return name === '.env' || name.startsWith('.env.');\n}\n\n/**\n * Package the module at `dir` into a ZIP at `out` (default `<slug>.zip` in\n * the cwd). Throws on a missing/invalid `module.json` or an empty result.\n */\nexport function exportModule(opts: { dir: string; out?: string }): ExportResult {\n const dir = resolve(opts.dir);\n const manifestPath = join(dir, 'module.json');\n if (!existsSync(manifestPath)) {\n throw new Error(\n 'No module.json found — point at a module directory (run `dashwise module convert` first if needed).',\n );\n }\n let manifest: { name?: string; slug?: string };\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8')) as {\n name?: string;\n slug?: string;\n };\n } catch (err) {\n throw new Error(`module.json is not valid JSON: ${(err as Error).message}`);\n }\n\n const slug =\n manifest.slug?.trim() || deriveSlug(manifest.name?.trim() || basename(dir));\n const name = manifest.name?.trim() || slug;\n const outPath = resolve(opts.out ?? `${slug}.zip`);\n\n const zip = new AdmZip();\n let fileCount = 0;\n let totalBytes = 0;\n\n const walk = (abs: string): void => {\n let entries: string[];\n try {\n entries = readdirSync(abs);\n } catch {\n return;\n }\n for (const entry of entries) {\n const p = join(abs, entry);\n let st;\n try {\n st = statSync(p);\n } catch {\n continue;\n }\n if (st.isDirectory()) {\n if (IGNORE_DIRS.has(entry)) continue;\n walk(p);\n continue;\n }\n if (isLocalEnvSecret(entry)) continue;\n // Never package the output ZIP into itself.\n if (resolve(p) === outPath) continue;\n // Repo-relative path, forward slashes — lands at the archive root.\n const rel = relative(dir, p).split(sep).join('/');\n const data = readFileSync(p);\n zip.addFile(rel, data);\n fileCount += 1;\n totalBytes += data.length;\n if (fileCount > MAX_FILES) {\n throw new Error(\n `Too many files (> ${MAX_FILES}); the import limit would reject this archive. Is a build-output dir not being ignored?`,\n );\n }\n }\n };\n walk(dir);\n\n if (fileCount === 0 || !zip.getEntry('module.json')) {\n throw new Error('Nothing to export (no module.json reached the archive).');\n }\n zip.writeZip(outPath);\n\n return {\n slug,\n name,\n outPath,\n fileCount,\n totalBytes,\n exceedsImportLimits: totalBytes > MAX_TOTAL_BYTES,\n };\n}\n\nfunction humanSize(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / 1024 / 1024).toFixed(1)} MB`;\n}\n\n/** CLI wrapper: run export, print a summary, return an exit code. */\nexport async function moduleExportCommand(opts: {\n dir?: string;\n out?: string;\n}): Promise<number> {\n try {\n const result = exportModule({\n dir: opts.dir ?? process.cwd(),\n ...(opts.out !== undefined ? { out: opts.out } : {}),\n });\n\n console.log(\n `Exported \"${result.name}\" → ${relative(process.cwd(), result.outPath) || result.outPath} ` +\n `(${result.fileCount} files, ${humanSize(result.totalBytes)}).`,\n );\n console.log(\n '\\nImport-ready: an operator can deploy it via the HQ admin panel (\"Import ZIP\")\\n' +\n 'or POST /api/admin/modules/import/zip. module.json is at the archive root.',\n );\n console.log(\n 'Note: binary assets (images/fonts) are dropped on import (text-only commit);\\n' +\n 'node_modules, build output, .git, and local .env files were excluded.',\n );\n if (result.exceedsImportLimits) {\n console.warn(\n `\\n⚠ Uncompressed content exceeds the import's 25 MiB cap — the ZIP may be rejected.`,\n );\n }\n return 0;\n } catch (err) {\n console.error(\n `export failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n return 1;\n }\n}\n","/**\n * `dashwise module register [dir]` — link an EXISTING local module to\n * DashWise.\n *\n * The \"link later\" half of the build-standalone-now flow: after\n * `dashwise module convert` (or hand-authoring a `module.json`), this\n * creates the backend module record + a local-dev installation and\n * caches the runtime token in `~/.config/dashwise/auth.json#modules[slug]`\n * — exactly what `dashwise init` does as its provisioning step, but\n * against the EXISTING directory (no scaffolding). After it succeeds,\n * `dashwise dev` runs the app against DashWise (auth + data) and\n * `dashwise module publish` can deploy it.\n *\n * Reuses `POST /api/installations/dev` (which creates the module via\n * `ModulesService.createDraft` + mints a scoped `dwk_` API key). P1-C\n * C2: UNLIKE `init` (which scaffolds an empty draft), `register` pushes\n * the EXISTING local `module.json` as the request's `manifest` field so\n * the backend materializes its `owns.tables` server-side — closing the\n * convert→register gap where a converted app's tables used to be\n * silently dropped until a later `dashwise table create`.\n */\n\nimport {\n isLoggedIn,\n readConfig,\n resolveApiUrl,\n upsertModuleEntry,\n} from '../../lib/config.js';\nimport { code, fail, info, success, warn } from '../../lib/output.js';\nimport { readManifest } from '../../lib/manifest-io.js';\nimport { isValidSlug, slugValidationMessage } from '../../lib/scaffold.js';\nimport { selectWorkspace } from '../../lib/workspaces.js';\nimport {\n ApiError,\n createDevInstallation,\n type DevInstallationResponse,\n} from '../../lib/api-client.js';\n\nconst MODULE_KINDS = ['ai_builder', 'hand_authored', 'custom'] as const;\ntype ModuleKind = (typeof MODULE_KINDS)[number];\n\nexport async function moduleRegisterCommand(opts: {\n dir?: string;\n workspace?: string;\n name?: string;\n}): Promise<number> {\n // 1. Read the local manifest (the thing that makes this a module).\n let manifest;\n try {\n manifest = readManifest(opts.dir);\n } catch (err) {\n fail(`Could not read module.json: ${(err as Error).message}`);\n return 1;\n }\n if (!manifest) {\n fail(\n `No module.json found${opts.dir ? ` in ${opts.dir}` : ' in the current directory'}. ` +\n `Run ${code('dashwise module convert')} (existing app) or ${code('dashwise init')} (new) first.`,\n );\n return 1;\n }\n const slug = manifest.module?.slug;\n if (!slug || typeof slug !== 'string') {\n fail('module.json is missing `module.slug`.');\n return 1;\n }\n // P1-C C5: reject non-kebab slugs before hitting the backend — a slug\n // with underscores would be refused by the manifest validator anyway,\n // and dependency-capable modules must have kebab identity from birth.\n if (!isValidSlug(slug)) {\n fail(\n `${slugValidationMessage(slug)}\\n Fix ${code('module.slug')} in module.json, then re-run ${code('dashwise module register')}.`,\n );\n return 1;\n }\n const name =\n opts.name ?? (typeof manifest.module?.name === 'string' ? manifest.module.name : slug);\n const moduleKind: ModuleKind | undefined = MODULE_KINDS.includes(\n manifest.module_kind as ModuleKind,\n )\n ? (manifest.module_kind as ModuleKind)\n : undefined;\n const description =\n typeof manifest.module?.description === 'string'\n ? manifest.module.description\n : undefined;\n\n // 2. Require login.\n if (!isLoggedIn()) {\n fail(`Not logged in. Run ${code('dashwise login')} first.`);\n return 1;\n }\n const cfg = readConfig();\n if (!cfg) {\n fail(`CLI config missing. Run ${code('dashwise login')}.`);\n return 1;\n }\n\n // 3. Resolve the target workspace (flag or interactive picker).\n let workspace: { id: number; slug: string };\n try {\n workspace = await selectWorkspace({\n apiUrl: resolveApiUrl(),\n apiToken: cfg.token,\n ...(opts.workspace !== undefined ? { flag: opts.workspace } : {}),\n interactive: true,\n });\n } catch (err) {\n fail(`Workspace selection failed: ${(err as Error).message}`);\n return 1;\n }\n\n // 4. Create the backend module + dev install + runtime token.\n info(\n `Registering \"${name}\" (slug: ${code(slug)}) in workspace ${code(workspace.slug)} (id=${workspace.id})…`,\n );\n let response: DevInstallationResponse;\n try {\n response = await createDevInstallation(\n {\n slug,\n name,\n ...(description !== undefined ? { description } : {}),\n workspaceId: workspace.id,\n ...(moduleKind !== undefined ? { moduleKind } : {}),\n // P1-C C2: push the whole local manifest so the backend\n // materializes owns.tables into the fresh draft. `init` omits\n // this (scaffolds empty); `register` sends it because the local\n // module.json is the source of truth for an already-authored app.\n manifest: manifest as Record<string, unknown>,\n },\n { baseUrl: resolveApiUrl(), auth: { token: cfg.token } },\n );\n } catch (err) {\n if (err instanceof ApiError) {\n if (err.code === 'SLUG_ALREADY_EXISTS') {\n fail(\n `A module with slug \"${slug}\" already exists. Pick a different slug in module.json, or run ${code('dashwise module destroy-dev-install')} to reclaim it.`,\n );\n } else if (err.code === 'FORBIDDEN') {\n fail(`Not a member of workspace \"${workspace.slug}\". Join it, then retry.`);\n } else if (err.code === 'MANIFEST_INVALID') {\n // The backend rejected the pushed manifest. Surface the per-path\n // issues[] so the user can fix module.json directly.\n const issues = extractManifestIssues(err);\n fail(\n `Your module.json failed validation:\\n${issues}\\n Fix the issues above (or run ${code('dashwise module validate')} for the full report) and retry.`,\n );\n } else {\n fail(`Registration failed (${err.code || err.status}): ${err.message}`);\n }\n return 1;\n }\n fail(`Registration failed: ${(err as Error).message}`);\n return 1;\n }\n\n // 5. Cache the API key so `dashwise dev` / the SDK pick it up.\n try {\n upsertModuleEntry(slug, {\n apiKey: response.api_key,\n apiKeyId: response.api_key_id,\n installationId: response.installation.id,\n expiresAt: response.api_key_expires_at,\n });\n } catch (err) {\n warn(\n `Registered (installation id=${response.installation.id}) but failed to cache the API key: ${(err as Error).message}\\n` +\n ` API key (save this manually): ${response.api_key}\\n` +\n ` Expires: ${response.api_key_expires_at}`,\n );\n return 0;\n }\n\n const tablesApplied = response.tables_applied ?? 0;\n success(\n `Registered \"${name}\" → module #${response.module.id}, dev install #${response.installation.id}. API key cached.`,\n );\n if (tablesApplied > 0) {\n info(\n `Materialized ${code(String(tablesApplied))} ${tablesApplied === 1 ? 'table' : 'tables'} from your module.json into the dev install.`,\n );\n }\n info(\n `Next: ${code('dashwise dev')} to run it against DashWise, or ${code('dashwise module publish')} to deploy.${tablesApplied === 0 ? ` Add tables with ${code('dashwise table create')}.` : ''}`,\n );\n return 0;\n}\n\n/**\n * Pull the per-path issue list out of a 422 MANIFEST_INVALID envelope.\n * The backend puts them in `context.issues` (array of strings or of\n * `{ path, message }`); render each as a bullet. Falls back to the raw\n * message when the shape is unexpected.\n */\nfunction extractManifestIssues(err: ApiError): string {\n const issues = err.context?.issues;\n if (Array.isArray(issues) && issues.length > 0) {\n return issues\n .map((issue) => {\n if (typeof issue === 'string') return ` - ${issue}`;\n if (issue && typeof issue === 'object') {\n const o = issue as { path?: unknown; message?: unknown };\n const path = typeof o.path === 'string' ? `${o.path}: ` : '';\n const message =\n typeof o.message === 'string' ? o.message : JSON.stringify(issue);\n return ` - ${path}${message}`;\n }\n return ` - ${String(issue)}`;\n })\n .join('\\n');\n }\n return ` - ${err.message}`;\n}\n","/**\n * `dashwise module generate` — regenerate the typed wrappers from the\n * local `module.json`.\n *\n * Flow:\n * 1. Read + parse `<cwd>/module.json`.\n * 2. POST it to `/api/modules/draft/generate-sdk`.\n * 3. Write each returned file to `node_modules/@dashai/generated/<path>`.\n * 4. Print summary (file count + content hash).\n *\n * Idempotent: re-running produces bit-identical output for an\n * unchanged manifest (per the generator's content-hash guarantee).\n * Returning a fresh generation counter on each call is reserved for\n * `module dev` — the one-shot CLI path uses generation=0.\n *\n * Requires the user to be logged in (uses the saved CLI token).\n */\n\nimport { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { code, dim, fail, info, success } from '../../lib/output.js';\n\nexport interface GenerateOptions {\n /** Project root containing `module.json` (defaults to `process.cwd()`). */\n dir?: string;\n /** Monotonic counter passed to the generator (default 0). */\n generation?: number;\n /** Skip writing to node_modules — print summary only. */\n dryRun?: boolean;\n}\n\ninterface GenerateResponse {\n files: Record<string, string>;\n contentHash: string;\n}\n\n/** Resolved output directory: `<project>/node_modules/@dashai/generated/`. */\nfunction outputDir(projectRoot: string): string {\n return join(projectRoot, 'node_modules', '@dashai', 'generated');\n}\n\nexport async function moduleGenerateCommand(\n options: GenerateOptions,\n): Promise<number> {\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n fail(\n `No ${code('module.json')} found in ${code(projectRoot)}. Run \\`dashwise module init <slug>\\` first.`,\n );\n return 1;\n }\n let manifest: unknown;\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n } catch (err) {\n fail(`Could not parse ${code(manifestPath)}: ${(err as Error).message}`);\n return 1;\n }\n\n let res: GenerateResponse;\n try {\n res = await apiRequest<GenerateResponse>(\n 'POST',\n '/api/modules/draft/generate-sdk',\n {\n manifest,\n generation: options.generation ?? 0,\n },\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n if (err instanceof ApiError && err.status === 400) {\n fail(`Manifest validation failed: ${err.message}`);\n if (err.context) {\n process.stderr.write(JSON.stringify(err.context, null, 2) + '\\n');\n }\n return 1;\n }\n fail(`Could not generate SDK: ${(err as Error).message}`);\n return 1;\n }\n\n if (options.dryRun) {\n info(`Dry run: ${Object.keys(res.files).length} files`);\n info(`Hash: ${code(res.contentHash)}`);\n return 0;\n }\n\n const out = outputDir(projectRoot);\n // Wipe any prior generated content so a renamed/removed table\n // doesn't leave a stale wrapper file behind. The directory itself\n // is gitignored, so a wipe-then-rewrite is safe.\n if (existsSync(out)) {\n rmSync(out, { recursive: true, force: true });\n }\n mkdirSync(out, { recursive: true });\n for (const [relPath, content] of Object.entries(res.files)) {\n const absPath = join(out, relPath);\n const parent = dirname(absPath);\n if (!existsSync(parent)) {\n mkdirSync(parent, { recursive: true });\n }\n writeFileSync(absPath, content, 'utf-8');\n }\n\n success(\n `Generated ${Object.keys(res.files).length} files into ${code('node_modules/@dashai/generated/')}`,\n );\n info(`Hash: ${dim(res.contentHash)}`);\n return 0;\n}\n","/**\n * `dashwise module dev` — watch `module.json` + auto-regenerate the\n * SDK on every change.\n *\n * Behavior:\n * 1. Read `module.json`; run an initial `module generate` so the\n * caller starts in a coherent state.\n * 2. Watch the manifest file for changes (`fs.watch`).\n * 3. On each change event, debounce 250ms (editor saves often\n * fire two events in quick succession), then regenerate.\n * 4. Bumps the `generation` counter per regen so the emitted\n * `package.json#version` shifts (`0.0.1-gen.N`), invalidating\n * any naïve caches keyed off it.\n * 5. Runs until Ctrl-C (clean exit on SIGINT/SIGTERM).\n *\n * Does NOT spawn `next dev` itself — the user runs that in another\n * terminal. Justification: `next dev`'s own output is dense + we\n * don't want to swallow/buffer it. If users want both, an\n * orchestrator like `npm-run-all` works (`npm run dev:next` and\n * `dashwise module dev` in parallel).\n */\n\nimport { existsSync, watch as fsWatch } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { moduleGenerateCommand } from './generate.js';\nimport { code, dim, fail, info, success, warn } from '../../lib/output.js';\n\nexport interface DevOptions {\n dir?: string;\n /** Debounce window in ms for filesystem change coalescing. */\n debounceMs?: number;\n}\n\nconst DEFAULT_DEBOUNCE_MS = 250;\n\nexport async function moduleDevCommand(options: DevOptions): Promise<number> {\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n fail(`No ${code('module.json')} found in ${code(projectRoot)}.`);\n info('Run `dashwise module init <slug>` to scaffold a new module.');\n return 1;\n }\n\n info(`Watching ${code(manifestPath)} — Ctrl-C to stop.`);\n\n // 1. Initial regen.\n let generation = 0;\n const initial = await moduleGenerateCommand({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n generation,\n });\n if (initial !== 0) {\n warn('Initial regen failed; watcher will retry on the next change.');\n }\n generation += 1;\n\n // 2. Watch loop with debounce. We deliberately use `fs.watch` (vs\n // chokidar) to keep deps small — chokidar weighs ~1MB packed, fs.watch\n // is built-in. Editor saves on macOS sometimes fire 2 events\n // back-to-back; the debounce coalesces them into one regen call.\n const debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;\n let timer: NodeJS.Timeout | null = null;\n let isRunning = false;\n let pendingRegen = false;\n\n async function doRegen() {\n if (isRunning) {\n // Another regen is in flight — flag for re-run when it finishes.\n pendingRegen = true;\n return;\n }\n isRunning = true;\n try {\n const start = Date.now();\n const exit = await moduleGenerateCommand({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n generation,\n });\n const elapsedMs = Date.now() - start;\n if (exit === 0) {\n success(`Regen complete (${elapsedMs}ms, gen=${generation})`);\n } else {\n warn(`Regen failed (exit ${exit}, gen=${generation}) — will retry on next change.`);\n }\n generation += 1;\n } finally {\n isRunning = false;\n if (pendingRegen) {\n pendingRegen = false;\n // Schedule a follow-up — keeps the loop responsive when\n // the user saves rapidly.\n setImmediate(doRegen);\n }\n }\n }\n\n const watcher = fsWatch(manifestPath, (eventType) => {\n if (eventType !== 'change') return;\n if (timer !== null) clearTimeout(timer);\n timer = setTimeout(() => {\n timer = null;\n void doRegen();\n }, debounceMs);\n });\n\n // Clean shutdown.\n return new Promise<number>((resolveExit) => {\n const stop = (signal: NodeJS.Signals | 'shutdown') => {\n if (timer !== null) clearTimeout(timer);\n watcher.close();\n info(`Stopping watcher${signal === 'shutdown' ? '' : ` (${signal})`}.`);\n // Use process.stdout flush hint to ensure the message lands\n // before exit.\n process.stdout.write(dim('Goodbye.\\n'));\n resolveExit(0);\n };\n process.once('SIGINT', () => stop('SIGINT'));\n process.once('SIGTERM', () => stop('SIGTERM'));\n });\n}\n","/**\n * `dashwise module diff` — preview what will change at the next\n * publish vs the currently-published version.\n *\n * Flow:\n * 1. Read local `module.json` for the slug.\n * 2. Resolve `slug → module.id` via `/api/modules/by-slug/:slug`.\n * 3. POST the local manifest to `/api/modules/:id/draft/diff`.\n * 4. Render the structured diff as a readable summary:\n * - \"unchanged\" short-circuit\n * - tables added/removed/changed\n * - dependencies added/removed\n * - top-level meta changes (version, name, module_kind, ...)\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { code, dim, fail, info, out, success } from '../../lib/output.js';\n\ninterface FieldChange {\n field: string;\n changes: Record<string, unknown>;\n}\n\ninterface TableChange {\n table: string;\n fields_added: Array<{ slug: string; type: string }>;\n fields_removed: Array<{ slug: string; type: string }>;\n fields_changed: FieldChange[];\n}\n\ninterface DiffResponse {\n current_version: string | null;\n unchanged: boolean;\n meta_changes: Array<{ field: string; before: unknown; after: unknown }>;\n tables_added: string[];\n tables_removed: string[];\n tables_changed: TableChange[];\n deps_added: Array<{ module: string; version: string }>;\n deps_removed: Array<{ module: string; version: string }>;\n}\n\nexport interface DiffOptions {\n dir?: string;\n /** Emit the structured diff as JSON instead of the human-readable summary. */\n json?: boolean;\n}\n\nexport async function moduleDiffCommand(\n options: DiffOptions,\n): Promise<number> {\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'NO_MANIFEST', message: `No module.json found in ${projectRoot}.` } }));\n } else {\n fail(\n `No ${code('module.json')} found in ${code(projectRoot)}. Run \\`dashwise module init <slug>\\` first.`,\n );\n }\n return 1;\n }\n let manifest: { module?: { slug?: string } };\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n } catch (err) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'MANIFEST_PARSE_FAILED', message: (err as Error).message } }));\n } else {\n fail(`Could not parse ${code(manifestPath)}: ${(err as Error).message}`);\n }\n return 1;\n }\n const slug = manifest.module?.slug;\n if (!slug) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'MANIFEST_MISSING_SLUG', message: 'module.json is missing module.slug.' } }));\n } else {\n fail(`${code('module.json')} is missing ${code('module.slug')}.`);\n }\n return 1;\n }\n\n // Resolve slug → moduleId.\n let mod: { id: number; current_version: string | null };\n try {\n mod = await apiRequest<{ id: number; current_version: string | null }>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(slug)}`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'MODULE_NOT_FOUND', message: `Module ${slug} not found on the backend.` } }));\n } else {\n fail(\n `Module ${code(slug)} not found on the backend. Create + publish it first; `\n + `diff has nothing to compare against until then.`,\n );\n }\n return 1;\n }\n if (err instanceof ApiError && err.status === 401) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'NOT_LOGGED_IN', message: 'Run `dashwise login` first.' } }));\n } else {\n fail('Not logged in. Run `dashwise login` first.');\n }\n return 1;\n }\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'RESOLVE_FAILED', message: (err as Error).message } }));\n } else {\n fail(`Could not resolve module: ${(err as Error).message}`);\n }\n return 1;\n }\n\n let diff: DiffResponse;\n try {\n diff = await apiRequest<DiffResponse>(\n 'POST',\n `/api/modules/${mod.id}/draft/diff`,\n { manifest },\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 400) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'VALIDATION_FAILED', message: err.message, context: err.context ?? null } }));\n } else {\n fail(`Manifest validation failed: ${err.message}`);\n if (err.context) {\n out(JSON.stringify(err.context, null, 2));\n }\n }\n return 1;\n }\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'FETCH_FAILED', message: (err as Error).message } }));\n } else {\n fail(`Could not compute diff: ${(err as Error).message}`);\n }\n return 1;\n }\n\n if (options.json) {\n out(JSON.stringify({ ok: true, ...diff }));\n return 0;\n }\n\n if (diff.unchanged) {\n success(\n `No changes vs ${code(diff.current_version ? `v${diff.current_version}` : '(unpublished)')} — manifest is in sync.`,\n );\n return 0;\n }\n\n // Header.\n out('');\n info(\n diff.current_version\n ? `Diff vs ${code(`v${diff.current_version}`)}:`\n : 'Diff vs ' + code('(unpublished — first version)') + ':',\n );\n\n if (diff.meta_changes.length > 0) {\n out('');\n out(code('Meta:'));\n for (const m of diff.meta_changes) {\n out(` ${m.field}: ${dim(JSON.stringify(m.before))} → ${JSON.stringify(m.after)}`);\n }\n }\n\n if (diff.tables_added.length > 0) {\n out('');\n out(code(`Tables added (${diff.tables_added.length}):`));\n for (const t of diff.tables_added) out(` + ${t}`);\n }\n\n if (diff.tables_removed.length > 0) {\n out('');\n out(code(`Tables removed (${diff.tables_removed.length}):`));\n for (const t of diff.tables_removed) out(` - ${t}`);\n }\n\n if (diff.tables_changed.length > 0) {\n out('');\n out(code(`Tables changed (${diff.tables_changed.length}):`));\n for (const t of diff.tables_changed) {\n out(` ${dim('•')} ${code(t.table)}`);\n for (const f of t.fields_added) {\n out(` + field ${f.slug} (${f.type})`);\n }\n for (const f of t.fields_removed) {\n out(` - field ${f.slug} (${f.type})`);\n }\n for (const f of t.fields_changed) {\n const changeSummary = Object.entries(f.changes)\n .map(([k, v]) => `${k}=${JSON.stringify(v)}`)\n .join(' ');\n out(` ~ field ${f.field}: ${dim(changeSummary)}`);\n }\n }\n }\n\n if (diff.deps_added.length > 0) {\n out('');\n out(code(`Dependencies added (${diff.deps_added.length}):`));\n for (const d of diff.deps_added) {\n out(` + ${d.module}@${d.version}`);\n }\n }\n\n if (diff.deps_removed.length > 0) {\n out('');\n out(code(`Dependencies removed (${diff.deps_removed.length}):`));\n for (const d of diff.deps_removed) {\n out(` - ${d.module}@${d.version}`);\n }\n }\n\n out('');\n info('Run `dashwise module publish --bump <patch|minor|major>` when ready.');\n return 0;\n}\n","/**\n * `dashwise` CLI entry point.\n *\n * commander-based command tree. Each command sits in `./commands/`\n * and returns a numeric exit code; the entry handler awaits the\n * result + sets `process.exitCode` accordingly. Unhandled errors\n * are caught + printed via the shared output helpers.\n */\n\nimport { Command, Option } from 'commander';\nimport { devCommand } from './commands/dev.js';\nimport { loginCommand } from './commands/login.js';\nimport { logoutCommand } from './commands/logout.js';\nimport { profileCommand } from './commands/profile.js';\nimport { workspaceListCommand, workspaceUseCommand } from './commands/workspace.js';\nimport { moduleCloneCommand } from './commands/module/clone.js';\nimport { moduleConnectGitCommand } from './commands/module/connect-git.js';\nimport { moduleConvertCommand } from './commands/module/convert.js';\nimport { moduleExportCommand } from './commands/module/export.js';\nimport { moduleRegisterCommand } from './commands/module/register.js';\nimport { moduleDevCommand } from './commands/module/dev.js';\nimport { moduleDiffCommand } from './commands/module/diff.js';\nimport { moduleGenerateCommand } from './commands/module/generate.js';\nimport { moduleInitCommand } from './commands/module/init.js';\nimport { moduleListCommand } from './commands/module/list.js';\nimport { modulePublishCommand } from './commands/module/publish.js';\nimport { modulePullDataCommand } from './commands/module/pull-data.js';\nimport { moduleValidateCommand } from './commands/module/validate.js';\nimport { depsAddCommand } from './commands/deps/add.js';\nimport { depsCheckCommand } from './commands/deps/check.js';\nimport { depsListCommand } from './commands/deps/list.js';\nimport { depsRemoveCommand } from './commands/deps/remove.js';\n// P3-C — dependency connect surface (D4 list/bind/unbind).\nimport {\n depsBindCommand,\n depsConnectListCommand,\n depsUnbindCommand,\n} from './commands/deps/connect.js';\n// P4-C — workspace-table `uses` binding surface (U4 list/bind/unbind/decline)\n// + the `uses add --from-table` reverse on-ramp.\nimport {\n bindCommand,\n bindListCommand,\n unbindCommand,\n} from './commands/uses/bind.js';\nimport { usesAddCommand } from './commands/uses/add.js';\nimport { pullCommand } from './commands/pull.js';\nimport { DEPLOY_TARGETS, type DeployTarget } from './lib/scaffold.js';\n// HH-CC-P1-C4 — `dashwise api-keys` subcommands.\nimport {\n apiKeysCreateCommand,\n apiKeysListCommand,\n apiKeysRevokeCommand,\n} from './commands/api-keys.js';\n// Phase 2 W3 — `dashwise origins` subcommands (SSO callback allowlist).\nimport {\n originsAddCommand,\n originsListCommand,\n originsRemoveCommand,\n} from './commands/origins.js';\n// HH-CC-P1-D1 — `dashwise env export`.\nimport {\n envExportCommand,\n type EnvExportFormat,\n} from './commands/env-export.js';\nimport { queryCommand } from './commands/query.js';\nimport { moduleQueryLogCommand } from './commands/module/query-log.js';\nimport { moduleActionLogCommand } from './commands/module/action-log.js';\nimport { fail } from './lib/output.js';\n\nconst program = new Command();\n\nprogram\n .name('dashwise')\n .description('DashWise CLI — log in, author modules, publish to the marketplace.')\n .version(getVersion(), '-v, --version', 'Show the CLI version + exit')\n .option(\n '--api-url <url>',\n 'Override DashWise backend URL (default: $DASHWISE_API_URL or saved config or http://localhost:3000)',\n );\n\nprogram\n .command('login')\n .description('Sign in via the device-code flow.')\n .option('--no-prompt', 'Skip the \"open browser\" prompt; just print the URL.')\n .option('--name <name>', 'Suggested name for the minted token (default: dashwise-cli).')\n .action(async (cmdOpts: { prompt?: boolean; name?: string }) => {\n const apiUrl = program.opts<{ apiUrl?: string }>().apiUrl;\n const exit = await loginCommand({\n ...(apiUrl !== undefined ? { apiUrl } : {}),\n noPrompt: cmdOpts.prompt === false,\n ...(cmdOpts.name !== undefined ? { name: cmdOpts.name } : {}),\n });\n process.exitCode = exit;\n });\n\nprogram\n .command('logout')\n .description('Clear the local credentials and revoke the server-side token.')\n .action(async () => {\n process.exitCode = await logoutCommand();\n });\n\nprogram\n .command('profile')\n .description('Show the current user, default workspace, and accessible workspaces.')\n .option('--json', 'Emit JSON to stdout instead of human-readable kv pairs.')\n .action(async (cmdOpts: { json?: boolean }) => {\n process.exitCode = await profileCommand({\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\nconst workspace = program\n .command('workspace')\n .description('Workspace context commands.');\n\nworkspace\n .command('list')\n .description('List accessible workspaces.')\n .option('--json', 'Emit JSON to stdout instead of human-readable columns.')\n .action(async (cmdOpts: { json?: boolean }) => {\n process.exitCode = await workspaceListCommand({\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\nworkspace\n .command('use <slug>')\n .description('Set the default workspace for subsequent commands.')\n .action(async (slug: string) => {\n process.exitCode = await workspaceUseCommand(slug);\n });\n\n// One-command local dev loop. Spawns `dashwise module dev` + `next dev`\n// together with auth env vars auto-injected from the saved CLI config —\n// collapses the historical \"two terminals + manually edit .env.local\"\n// workflow into a single command. Top-level (not under `module`) because\n// it's the daily-driver entry point most developers will spend the most\n// time with.\nprogram\n .command('dev')\n .description(\n 'One-command local dev loop: runs the manifest watcher + Next.js dev server ' +\n 'together. Registers a dev-mode SSO session with the backend so workspace ' +\n 'members can sign into your locally-running module via DashWise SSO (no ' +\n 'installation_id required). Auth + dev-session env auto-injected into ' +\n 'both child processes from your saved CLI config. Run `dashwise login` first.',\n )\n .option('--dir <path>', 'Project root containing `module.json` (default: current directory).')\n .option(\n '--installation-id <id>',\n 'Use prod-mode SSO with this installation id instead of registering a dev session. ' +\n 'The installation must already exist in the target workspace.',\n )\n .option(\n '--workspace <slug-or-id>',\n 'Workspace to scope the dev session to (slug or numeric id). Required if your ' +\n 'account belongs to more than one workspace; auto-picked if you have just one.',\n )\n .option(\n '--callback-origin <url>',\n 'Additional callback origin to allowlist on the dev session (repeatable). ' +\n 'The dev server URL (http://localhost:<port>) is always allowlisted; pass ' +\n 'this for custom-domain local dev (e.g. https://myapp.local).',\n collectRepeated,\n [] as string[],\n )\n .option(\n '--api-url <url>',\n 'Override the `DASHWISE_API_URL` env var passed to children (default: saved CLI config).',\n )\n .option('--port <number>', 'Port for `next dev` (default: 3000).', parseIntOption)\n .option('--sdk-only', 'Only run the manifest watcher; skip `next dev`.')\n .option('--next-only', 'Only run `next dev`; skip the manifest watcher.')\n // HH-CC-P1-E3 — backend manifest poll loop.\n .option(\n '--no-remote-poll',\n 'Disable periodic backend manifest polling. By default, `dashwise dev` polls `GET /api/installations/:id/schema` every few seconds + writes module.json when the backend has advanced (dashboard edits, AI builder mutations, teammate commands).',\n )\n .option(\n '--remote-poll-interval <seconds>',\n 'Backend manifest poll interval, in seconds. Default: 5. Minimum: 1.',\n parseIntOption,\n )\n .action(\n async (cmdOpts: {\n dir?: string;\n installationId?: string;\n workspace?: string;\n callbackOrigin?: string[];\n apiUrl?: string;\n port?: number;\n sdkOnly?: boolean;\n nextOnly?: boolean;\n remotePoll?: boolean; // Commander negates: --no-remote-poll → remotePoll=false\n remotePollInterval?: number;\n }) => {\n process.exitCode = await devCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.installationId !== undefined ? { installationId: cmdOpts.installationId } : {}),\n ...(cmdOpts.workspace !== undefined ? { workspace: cmdOpts.workspace } : {}),\n ...(cmdOpts.callbackOrigin !== undefined && cmdOpts.callbackOrigin.length > 0\n ? { callbackOrigin: cmdOpts.callbackOrigin }\n : {}),\n ...(cmdOpts.apiUrl !== undefined ? { apiUrl: cmdOpts.apiUrl } : {}),\n ...(cmdOpts.port !== undefined ? { port: cmdOpts.port } : {}),\n ...(cmdOpts.sdkOnly !== undefined ? { sdkOnly: cmdOpts.sdkOnly } : {}),\n ...(cmdOpts.nextOnly !== undefined ? { nextOnly: cmdOpts.nextOnly } : {}),\n // Commander's --no-foo flag maps to `foo: false`. devCommand's\n // option is `noRemotePoll: boolean` — invert to map cleanly.\n ...(cmdOpts.remotePoll === false ? { noRemotePoll: true } : {}),\n ...(cmdOpts.remotePollInterval !== undefined\n ? { remotePollIntervalSec: cmdOpts.remotePollInterval }\n : {}),\n });\n },\n );\n\n// FUP-3: top-level alias for `dashwise module init`. The two-command\n// bootstrap (`dashwise login` + `dashwise init`) is the headline daily-\n// driver flow per `building-modules.md` + the LDI v1 plan — making the\n// second command three words (`dashwise module init`) was a paper-cut\n// during the dogfood. This alias preserves both spellings: muscle\n// memory continues to work, the README docs are honest.\nconst initOptions = (cmd: Command): Command =>\n cmd\n .option('--dir <path>', 'Override the target directory (default: ./<slug>).')\n .option('--name <name>', 'Human-readable module name (default: derived from slug).')\n .option('--force', 'Overwrite an existing non-empty directory.')\n .option(\n '--simple',\n 'Use the legacy minimal scaffold (hand-authored, no Next.js auth wiring). Default before 2026-05-18; opt-in now.',\n )\n .option(\n '--custom',\n \"[Deprecated alias — kept for backward compatibility.] Equivalent to the default (full Next.js + auth). Will be removed in a future major version; just call `dashwise init` without flags.\",\n )\n .option('--git <url>', 'Initial Git repository URL — written to module.json#repository.url.')\n // HH-CC-LDI-6 flags.\n .option(\n '--description <text>',\n 'Module description — forwarded to the backend when provisioning the dev installation.',\n )\n .option(\n '--workspace <slug-or-id>',\n 'Target workspace for the dev installation (slug or numeric id). When omitted in a TTY, the CLI prompts; in non-interactive mode it auto-picks when you have one workspace and errors out otherwise.',\n )\n .option(\n '--no-provision',\n 'Skip the `POST /api/installations/dev` step. Local scaffold is still written; you can provision later by re-running `dashwise init --force` (or, once it ships, `dashwise module provision-dev-install`).',\n )\n // HH-CC-P1-D2: optional platform config emission.\n .addOption(\n new Option(\n '--deploy-target <platform>',\n 'Emit a platform deploy config file alongside the scaffold (railway.json | vercel.json | fly.toml). Default: none (clean repo). Pair with `dashwise env export --format <platform>` to push env vars after provisioning.',\n ).choices([...DEPLOY_TARGETS]),\n );\n\ninterface InitCmdOpts {\n dir?: string;\n name?: string;\n force?: boolean;\n simple?: boolean;\n custom?: boolean;\n git?: string;\n description?: string;\n workspace?: string;\n // Commander maps `--no-provision` → `provision: false`.\n provision?: boolean;\n // HH-CC-P1-D2 — commander returns a string narrowed by `.choices(...)`.\n deployTarget?: DeployTarget;\n}\n\nconst initAction = async (slugArg: string | undefined, cmdOpts: InitCmdOpts): Promise<void> => {\n process.exitCode = await moduleInitCommand(slugArg, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.name !== undefined ? { name: cmdOpts.name } : {}),\n ...(cmdOpts.force !== undefined ? { force: cmdOpts.force } : {}),\n ...(cmdOpts.simple !== undefined ? { simple: cmdOpts.simple } : {}),\n ...(cmdOpts.custom !== undefined ? { custom: cmdOpts.custom } : {}),\n ...(cmdOpts.git !== undefined ? { git: cmdOpts.git } : {}),\n ...(cmdOpts.description !== undefined ? { description: cmdOpts.description } : {}),\n ...(cmdOpts.workspace !== undefined ? { workspace: cmdOpts.workspace } : {}),\n ...(cmdOpts.provision !== undefined ? { provision: cmdOpts.provision } : {}),\n ...(cmdOpts.deployTarget !== undefined ? { deployTarget: cmdOpts.deployTarget } : {}),\n });\n};\n\ninitOptions(\n program\n .command('init [slug]')\n .description(\n 'Scaffold a new DashWise module — full Next.js app with auth wiring + SSO callback + protected dashboard. Pass --simple for the legacy minimal scaffold (no auth). Top-level alias for `dashwise module init`.',\n ),\n).action(initAction);\n\nconst moduleCmd = program\n .command('module')\n .description('Module authoring commands.');\n\ninitOptions(\n moduleCmd\n .command('init [slug]')\n .description(\n 'Scaffold a new DashWise module — full Next.js app with auth wiring + SSO callback + protected dashboard. Pass --simple for the legacy minimal scaffold (no auth).',\n ),\n).action(initAction);\n\nmoduleCmd\n .command('connect-git <repo-url>')\n .description('Link the local module to a Git repository (writes module.json#repository).')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--branch <name>', 'Default branch to publish from (e.g. `main`).')\n .action(\n async (repoUrl: string, cmdOpts: { dir?: string; branch?: string }) => {\n process.exitCode = await moduleConnectGitCommand(repoUrl, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.branch !== undefined ? { branch: cmdOpts.branch } : {}),\n });\n },\n );\n\nmoduleCmd\n .command('convert [dir]')\n .description(\n 'Convert an EXISTING Next.js app into a DashWise module — idempotently inject module.json, auth wiring, the SDK dep, and output:standalone. Creates missing files; warns (never overwrites) for an existing layout/next.config/module.json.',\n )\n .option('--slug <slug>', 'Module slug (default: derived from package.json name / dir).')\n .option('--name <name>', 'Human-readable module name (default: package.json name).')\n .option('--git <url>', 'Git repository URL — written to module.json#repository.url.')\n .action(\n async (\n dir: string | undefined,\n cmdOpts: { slug?: string; name?: string; git?: string },\n ) => {\n process.exitCode = await moduleConvertCommand({\n ...(dir !== undefined ? { dir } : {}),\n ...(cmdOpts.slug !== undefined ? { slug: cmdOpts.slug } : {}),\n ...(cmdOpts.name !== undefined ? { name: cmdOpts.name } : {}),\n ...(cmdOpts.git !== undefined ? { git: cmdOpts.git } : {}),\n });\n },\n );\n\nmoduleCmd\n .command('register [dir]')\n .description(\n 'Link an existing local module (a directory with module.json — e.g. after `module convert`) to DashWise: creates the backend module record + a dev install and caches the runtime token, so `dashwise dev` / `publish` work. Requires login.',\n )\n .option('--workspace <slug-or-id>', 'Target workspace (default: interactive picker).')\n .option('--name <name>', 'Override the module name (default: module.json name).')\n .action(\n async (\n dir: string | undefined,\n cmdOpts: { workspace?: string; name?: string },\n ) => {\n process.exitCode = await moduleRegisterCommand({\n ...(dir !== undefined ? { dir } : {}),\n ...(cmdOpts.workspace !== undefined ? { workspace: cmdOpts.workspace } : {}),\n ...(cmdOpts.name !== undefined ? { name: cmdOpts.name } : {}),\n });\n },\n );\n\nmoduleCmd\n .command('export [dir]')\n .description(\n 'Package a local module into a portable <slug>.zip (module.json at the root, deps/build-output/VCS/local-.env excluded) — the exact shape the operator ZIP-import (HQ \"Import ZIP\" / POST /api/admin/modules/import/zip) expects. Closes the build → export → operator-deploy round-trip.',\n )\n .option('--out <path>', 'Output ZIP path (default: <slug>.zip in the current directory).')\n .action(\n async (dir: string | undefined, cmdOpts: { out?: string }) => {\n process.exitCode = await moduleExportCommand({\n ...(dir !== undefined ? { dir } : {}),\n ...(cmdOpts.out !== undefined ? { out: cmdOpts.out } : {}),\n });\n },\n );\n\nmoduleCmd\n .command('generate')\n .description(\"Regenerate typed wrappers from the local module.json into node_modules/@dashai/generated/.\")\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--dry-run', 'Print summary without writing files.')\n .action(async (cmdOpts: { dir?: string; dryRun?: boolean }) => {\n process.exitCode = await moduleGenerateCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.dryRun !== undefined ? { dryRun: cmdOpts.dryRun } : {}),\n });\n });\n\nmoduleCmd\n .command('dev')\n .description('Watch module.json + regenerate typed wrappers on every save. Ctrl-C to stop.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--debounce-ms <n>', 'Filesystem change debounce window (default: 250ms).', parseIntOption)\n .action(async (cmdOpts: { dir?: string; debounceMs?: number }) => {\n process.exitCode = await moduleDevCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.debounceMs !== undefined ? { debounceMs: cmdOpts.debounceMs } : {}),\n });\n });\n\nmoduleCmd\n .command('validate')\n .description('Validate the local module.json against the backend manifest validator.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .action(async (cmdOpts: { dir?: string }) => {\n process.exitCode = await moduleValidateCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n });\n });\n\nmoduleCmd\n .command('list')\n .description('List modules you own (or `--all` for owned + public).')\n .option('--all', 'Include public modules you can install but do not own.')\n .option('--workspace <slug>', 'Filter by workspace slug (default: saved default workspace).')\n .option('--json', 'Emit JSON to stdout instead of column-aligned text.')\n .action(async (cmdOpts: { all?: boolean; workspace?: string; json?: boolean }) => {\n process.exitCode = await moduleListCommand({\n ...(cmdOpts.all !== undefined ? { all: cmdOpts.all } : {}),\n ...(cmdOpts.workspace !== undefined ? { workspace: cmdOpts.workspace } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\nmoduleCmd\n .command('diff')\n .description('Show what would change at the next publish vs the currently-published version.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--json', 'Emit the structured diff as JSON instead of the human-readable summary.')\n .action(async (cmdOpts: { dir?: string; json?: boolean }) => {\n process.exitCode = await moduleDiffCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\nmoduleCmd\n .command('pull-data')\n .description(\"Export the module's own-table rows to a local JSON file (for fixtures, local dev seeding).\")\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--limit <n>', 'Max rows per table (1-1000, default 100).', parseIntOption)\n .option('--out <path>', 'Output file path (default: ./dashwise-data.json).')\n .action(async (cmdOpts: { dir?: string; limit?: number; out?: string }) => {\n process.exitCode = await modulePullDataCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.limit !== undefined ? { limit: cmdOpts.limit } : {}),\n ...(cmdOpts.out !== undefined ? { out: cmdOpts.out } : {}),\n });\n });\n\nmoduleCmd\n .command('clone <slug>')\n .description('Clone a published module locally. Uses git if repository.url is set, else writes a manifest-only scaffold.')\n .option('--dir <path>', 'Target directory (default: ./<slug>).')\n .option('--force', 'Overwrite an existing non-empty directory.')\n .option('--no-git', 'Skip git clone even when repository.url is set; use the manifest-only scaffold.')\n .action(\n async (\n slug: string,\n cmdOpts: { dir?: string; force?: boolean; git?: boolean },\n ) => {\n // commander maps `--no-git` to `git: false`; convert to our internal shape.\n process.exitCode = await moduleCloneCommand(slug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.force !== undefined ? { force: cmdOpts.force } : {}),\n ...(cmdOpts.git === false ? { noGit: true } : {}),\n });\n },\n );\n\nconst depsCmd = program\n .command('deps')\n .description(\n 'Cross-module dependency commands. Bare `dashwise deps` shows the live connect status ' +\n '(resolved / unbound) of each declared dep on your installation; the subcommands manage ' +\n 'module.json#dependencies (add / remove / list / check) and the connect lifecycle (bind / unbind).',\n )\n // Bare `dashwise deps` → the D4 connect-surface list (live backend\n // status). `dashwise deps list` (below) stays the offline local-manifest\n // read; `deps check` stays the published-provider drift probe.\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--json', 'Emit the connect-status list as JSON instead of the human-readable view.')\n .action(async (cmdOpts: { dir?: string; json?: boolean }) => {\n process.exitCode = await depsConnectListCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\ndepsCmd\n .command('list')\n .description('List declared cross-module dependencies (offline local module.json read).')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--json', 'Emit JSON to stdout instead of human-readable columns.')\n .action(async (cmdOpts: { dir?: string; json?: boolean }) => {\n process.exitCode = await depsListCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\ndepsCmd\n .command('add <provider-slug>')\n .description(\n 'Declare a cross-module dependency. Interactive in TTY (picks tables + fields from the provider\\'s exposes); non-interactive requires --table, --fields, --purpose.',\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--table <slug>', 'Provider table slug to read from (non-interactive mode).')\n .option('--fields <list>', 'Comma-separated field slugs for --table (non-interactive mode).')\n .option('--purpose <text>', 'Human-readable explanation (10-500 chars, shown at install consent).')\n .option('--version <range>', 'SemVer range to pin (default: ^<provider-current-version>).')\n .option('-y, --yes', 'Skip the replace-existing confirmation prompt.')\n .action(\n async (\n providerSlug: string,\n cmdOpts: {\n dir?: string;\n table?: string;\n fields?: string;\n purpose?: string;\n version?: string;\n yes?: boolean;\n },\n ) => {\n process.exitCode = await depsAddCommand(providerSlug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.table !== undefined ? { table: cmdOpts.table } : {}),\n ...(cmdOpts.fields !== undefined ? { fields: cmdOpts.fields } : {}),\n ...(cmdOpts.purpose !== undefined ? { purpose: cmdOpts.purpose } : {}),\n ...(cmdOpts.version !== undefined ? { version: cmdOpts.version } : {}),\n ...(cmdOpts.yes !== undefined ? { yes: cmdOpts.yes } : {}),\n });\n },\n );\n\ndepsCmd\n .command('remove <provider-slug>')\n .description('Remove a declared cross-module dependency.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('-y, --yes', 'Skip the confirmation prompt.')\n .action(async (providerSlug: string, cmdOpts: { dir?: string; yes?: boolean }) => {\n process.exitCode = await depsRemoveCommand(providerSlug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.yes !== undefined ? { yes: cmdOpts.yes } : {}),\n });\n });\n\ndepsCmd\n .command('check')\n .description('Verify each declared dep still resolves to a published provider + that every field/op is still exposed. Exits 1 on drift.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--json', 'Emit a JSON drift report to stdout.')\n .action(async (cmdOpts: { dir?: string; json?: boolean }) => {\n process.exitCode = await depsCheckCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\n// P3-C — connect lifecycle (D4). Bind (re-)connects a parked dep to a\n// provider install; unbind disconnects a bound one. Workspace-admin; the\n// install id is resolved from auth.json (the user never types it).\ndepsCmd\n .command('bind <provider-slug>')\n .description(\n \"(Re-)connect a parked dependency to its provider installation. Re-runs resolution + snapshots the contract; on success runtime reads succeed. Fails (the dep stays unbound) with the park reason if the provider isn't installed / the version doesn't match / a table/action isn't exposed. Workspace-admin.\",\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option(\n '--installation <id>',\n 'Provider installation id to bind to (disambiguates when the workspace has more than one candidate install of the provider).',\n parseIntOption,\n )\n .action(\n async (providerSlug: string, cmdOpts: { dir?: string; installation?: number }) => {\n process.exitCode = await depsBindCommand(providerSlug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.installation !== undefined ? { installation: cmdOpts.installation } : {}),\n });\n },\n );\n\ndepsCmd\n .command('unbind <provider-slug>')\n .description(\n 'Disconnect a bound dependency: NULLs the provider ref + contract snapshot and parks the dep (reason MANUALLY_UNBOUND). Runtime reads then return DEP_UNBOUND until you bind it again. Workspace-admin.',\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .action(async (providerSlug: string, cmdOpts: { dir?: string }) => {\n process.exitCode = await depsUnbindCommand(providerSlug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n });\n });\n\n// P4-C — workspace-table `uses` binding surface. Top-level (sibling of\n// `deps`) because connecting your module to an existing workspace table\n// is a daily-driver step. Bare `dashwise bind` lists the binding status\n// of every declared `uses` slot; `dashwise bind <uses-slug>` connects one\n// to a workspace table. The install id is resolved from auth.json — the\n// user never types it.\nprogram\n .command('bind [uses-slug]')\n .description(\n \"Connect the module's declared workspace-table (`uses`) slots to real tables. Bare `dashwise bind` lists every slot's status (bound / unbound / declined) with reasons + missing fields. `dashwise bind <uses-slug> [--table <name-or-id>]` binds one (interactive pick when the match is ambiguous in a TTY); `--map <usesField>=<physicalFieldName>` overrides field mappings; `--create` materializes a fresh table; `--decline` declines an optional-needs slot. Bind/unbind/decline are workspace-admin.\",\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--json', 'With no slug: emit the binding-status list as JSON.')\n .option(\n '--table <name-or-id>',\n 'Workspace table (name or numeric id) to bind the slot to. Use for scripts / to skip the interactive pick.',\n )\n .option(\n '--map <usesField=physicalFieldName>',\n 'Override a field mapping (repeatable). The server auto-completes unmapped fields by name match.',\n collectRepeated,\n [] as string[],\n )\n .option('--create', 'Materialize a fresh Data Hub table from the declared fields + bind to it.')\n .option('--decline', 'Decline this slot (optional-needs only; the module runs without it).')\n .action(\n async (\n usesSlug: string | undefined,\n cmdOpts: {\n dir?: string;\n json?: boolean;\n table?: string;\n map?: string[];\n create?: boolean;\n decline?: boolean;\n },\n ) => {\n if (usesSlug === undefined) {\n // Bare `dashwise bind` → the U4 binding-status list.\n process.exitCode = await bindListCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n return;\n }\n process.exitCode = await bindCommand(usesSlug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.table !== undefined ? { table: cmdOpts.table } : {}),\n ...(cmdOpts.map !== undefined && cmdOpts.map.length > 0 ? { map: cmdOpts.map } : {}),\n ...(cmdOpts.create !== undefined ? { create: cmdOpts.create } : {}),\n ...(cmdOpts.decline !== undefined ? { decline: cmdOpts.decline } : {}),\n });\n },\n );\n\nprogram\n .command('unbind <uses-slug>')\n .description(\n 'Disconnect a bound workspace-table (`uses`) slot: NULLs the table ref + field map and parks the slot (reason MANUALLY_UNBOUND). Runtime reads/writes then return USES_UNBOUND until you bind it again. Workspace-admin.',\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .action(async (usesSlug: string, cmdOpts: { dir?: string }) => {\n process.exitCode = await unbindCommand(usesSlug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n });\n });\n\n// P4-C — `dashwise uses` command group. Today: just `add --from-table`\n// (the reverse on-ramp: introspect an existing workspace table → generate\n// the `uses` manifest entry → push → bind, in one command).\nconst usesCmd = program\n .command('uses')\n .description('Workspace-table (`uses`) contract commands.');\n\nusesCmd\n .command('add')\n .description(\n \"On-ramp an existing workspace table: introspect it, generate the `uses.tables` manifest entry (fields + abstract types, read op by default), write module.json, push (draft-apply reconciles + parks), then bind the new slot to that table. One command from \\\"I have an Employees table\\\" to typed access.\",\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .requiredOption(\n '--from-table <id>',\n \"The existing workspace table to generate a `uses` contract from — its NUMERIC id (find it in the Dashwise UI URL). Resolving by table name isn't wired yet.\",\n )\n .option(\n '--slug <slug>',\n 'Override the generated `uses` slot slug (default: slugified table name).',\n )\n .option(\n '--ops <list>',\n 'Comma-separated operations to declare (create,read,update,delete). Default: read.',\n )\n .option(\n '--purpose <text>',\n 'Optional author-facing explanation, shown to admins at bind/consent.',\n )\n .option(\n '--no-bind',\n \"Only write + push the manifest entry; don't attempt to bind it to the source table.\",\n )\n .option('-y, --yes', 'Skip the overwrite-existing-slot confirmation prompt.')\n .action(\n async (cmdOpts: {\n dir?: string;\n fromTable: string;\n slug?: string;\n ops?: string;\n purpose?: string;\n bind?: boolean; // commander: --no-bind → bind=false\n yes?: boolean;\n }) => {\n process.exitCode = await usesAddCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n fromTable: cmdOpts.fromTable,\n ...(cmdOpts.slug !== undefined ? { slug: cmdOpts.slug } : {}),\n ...(cmdOpts.ops !== undefined ? { ops: cmdOpts.ops } : {}),\n ...(cmdOpts.purpose !== undefined ? { purpose: cmdOpts.purpose } : {}),\n ...(cmdOpts.bind === false ? { noBind: true } : {}),\n ...(cmdOpts.yes !== undefined ? { yes: cmdOpts.yes } : {}),\n });\n },\n );\n\nprogram\n .command('query')\n .description(\n 'Run a typed query against the local module installation via @dashai/sdk/query. ' +\n 'Pass one of `--inline \"<expr>\"`, `--file <path>`, or `--repl`. ' +\n '`qb`, `deps`, `db` are pre-bound to the local module\\'s generated SDK.',\n )\n .option('--dir <path>', 'Project root containing `module.json` (default: current directory).')\n .option('--inline <expression>', 'Evaluate a one-liner. e.g., `qb.tasks.where({done:false}).count()`.')\n .option('--file <path>', 'Dynamic-import a .mjs/.js file. Default export = Query | AggQuery | Promise | value.')\n .option('--repl', 'Open an interactive Node REPL with the generated SDK pre-bound. Top-level await supported.')\n .option('--json', 'Emit compact JSON (default: pretty-printed).')\n .option(\n '--explain',\n 'Call .explain() instead of .execute() — returns the Postgres plan + estimatedCost without executing the query. MVP supports joined queries; bare own/dep/view paths reject with EXPLAIN_NOT_SUPPORTED_YET.',\n )\n .option(\n '--stream',\n 'Call .stream() instead of .execute() — prints rows incrementally as JSON-lines (one row per line). Lets you see progress on big queries + Ctrl-C cleanly midway. Mutually exclusive with --explain and --repl.',\n )\n .action(\n async (cmdOpts: {\n dir?: string;\n inline?: string;\n file?: string;\n repl?: boolean;\n json?: boolean;\n explain?: boolean;\n stream?: boolean;\n }) => {\n process.exitCode = await queryCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.inline !== undefined ? { inline: cmdOpts.inline } : {}),\n ...(cmdOpts.file !== undefined ? { file: cmdOpts.file } : {}),\n ...(cmdOpts.repl !== undefined ? { repl: cmdOpts.repl } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n ...(cmdOpts.explain !== undefined ? { explain: cmdOpts.explain } : {}),\n ...(cmdOpts.stream !== undefined ? { stream: cmdOpts.stream } : {}),\n });\n },\n );\n\n// HH-CC-P1-E2 — `dashwise pull`. Top-level (sibling of `dev`, `login`,\n// `query`) because pulling the manifest is part of the daily-driver\n// loop: dashboard-side schema edits, AI-builder mutations, or\n// teammate-driven changes show up via this primitive.\nprogram\n .command('pull')\n .description(\n 'Sync local module.json from the backend. Fetches the canonical manifest for the current install and writes it to disk. Inverse of `dashwise table/field` commands.',\n )\n .option('--dir <path>', 'Project root containing `module.json` (default: current directory).')\n .option('--dry-run', 'Fetch + report drift but do not write to module.json.')\n .action(async (cmdOpts: { dir?: string; dryRun?: boolean }) => {\n process.exitCode = await pullCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.dryRun !== undefined ? { dryRun: cmdOpts.dryRun } : {}),\n });\n });\n\n// HH-CC-P1-C4 — `dashwise api-keys` subcommand group.\n// Pairs with the backend P1-C1 minting endpoint + P1-C2 runtime-guard\n// recognition. Top-level (sibling of `dev`, `pull`) because API keys\n// are a daily-driver concept for module authors deploying to Railway\n// / Vercel / Fly — not buried under `module`.\nconst apiKeysCmd = program\n .command('api-keys')\n .description(\n 'Manage per-installation API keys (`dwk_*`). Pasted into a deployed module\\'s env for production data-plane auth.',\n );\n\napiKeysCmd\n .command('list')\n .description(\n 'List API keys for the current module\\'s installation. Active only by default; pass --all for revoked too.',\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--all', 'Include revoked + expired keys in the output.')\n .option('--json', 'Emit JSON instead of the human-friendly table.')\n .action(async (cmdOpts: { dir?: string; all?: boolean; json?: boolean }) => {\n process.exitCode = await apiKeysListCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.all !== undefined ? { all: cmdOpts.all } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\napiKeysCmd\n .command('create [name]')\n .description(\n 'Mint a new API key. The plaintext key is displayed ONCE — save it then.',\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--name <name>', 'Override the positional name arg (e.g. for scripted use).')\n .option(\n '--grant <spec>',\n 'Scoped grant (repeatable). `module:<tableSlug>:<ops>`, `datahub:table=<id>:<ops>`, `datahub:app=<id>:<ops>`, or `datahub:workspace:<ops>` where <ops> is a comma list of create,read,update,delete. Any grant mints a scoped (default-deny) key (workspace-admin required). Omit for a full-access key.',\n collectRepeated,\n [] as string[],\n )\n .option(\n '--expires <days>',\n 'Days until the key expires (converted to an absolute timestamp). Default: never expires.',\n parseIntOption,\n )\n .option(\n '--raw-only',\n 'Print only the plaintext key on stdout; chatter goes to stderr. Useful for shell capture: `KEY=$(dashwise api-keys create prod --raw-only)`',\n )\n .action(\n async (\n nameArg: string | undefined,\n cmdOpts: {\n dir?: string;\n name?: string;\n grant?: string[];\n expires?: number;\n rawOnly?: boolean;\n },\n ) => {\n process.exitCode = await apiKeysCreateCommand(nameArg, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.name !== undefined ? { name: cmdOpts.name } : {}),\n ...(cmdOpts.grant !== undefined && cmdOpts.grant.length > 0\n ? { grant: cmdOpts.grant }\n : {}),\n ...(cmdOpts.expires !== undefined ? { expires: cmdOpts.expires } : {}),\n ...(cmdOpts.rawOnly !== undefined ? { rawOnly: cmdOpts.rawOnly } : {}),\n });\n },\n );\n\napiKeysCmd\n .command('revoke [key-id]')\n .description(\n 'Soft-revoke an API key. Backend keeps the row for audit; further requests return 401.',\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('-y, --yes', 'Skip the per-key confirmation message (for CI / scripts).')\n .action(\n async (\n keyIdArg: string | undefined,\n cmdOpts: { dir?: string; yes?: boolean },\n ) => {\n process.exitCode = await apiKeysRevokeCommand(keyIdArg, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.yes !== undefined ? { yes: cmdOpts.yes } : {}),\n });\n },\n );\n\n// Phase 2 W3 — `dashwise origins` subcommand group. Manages the SSO\n// callback-origin allowlist for the current module's installation.\n// Top-level (sibling of `api-keys`) because adding a deploy domain is a\n// one-liner every self-hosted module author runs. The install id is\n// resolved from auth.json — the user never types it.\nconst originsCmd = program\n .command('origins')\n .description(\n \"Manage the current module install's SSO callback-origin allowlist. Local dev (localhost) is always allowed; add deployed domains here.\",\n );\n\noriginsCmd\n .command('list')\n .description('Show the SSO callback origins configured for the current module install.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--json', 'Emit a JSON array instead of the human-friendly list.')\n .action(async (cmdOpts: { dir?: string; json?: boolean }) => {\n process.exitCode = await originsListCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n });\n\noriginsCmd\n .command('add <url>')\n .description(\n 'Add an SSO callback origin (e.g. https://app.example.com). Idempotent; non-localhost origins must be https://.',\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .action(async (url: string, cmdOpts: { dir?: string }) => {\n process.exitCode = await originsAddCommand(url, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n });\n });\n\noriginsCmd\n .command('remove <url>')\n .description('Remove an SSO callback origin from the allowlist.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .action(async (url: string, cmdOpts: { dir?: string }) => {\n process.exitCode = await originsRemoveCommand(url, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n });\n });\n\n// HH-CC-P1-D1 — `dashwise env [...]` subcommand group. Today: just\n// `export`. Future home for `env get` / `env set` if we add a\n// CLI-managed config surface beyond what the deploy story needs.\nconst envCmd = program\n .command('env')\n .description('Environment-variable helpers for deploying a module.');\n\nenvCmd\n .command('export')\n .description(\n \"Emit the env vars a deployed module needs to authenticate against DashWise. By default emits .env-style KEY=value lines; --format = env | json | railway | vercel | fly to wrap in platform-native syntax. Use --new-key <name> to mint + inline an API key in one step.\",\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option(\n '--format <fmt>',\n 'Output format: env | json | railway | vercel | fly (default: env).',\n )\n .option(\n '--new-key <name>',\n 'Mint a fresh API key with this name and inline the plaintext. (Mutually exclusive with --key.)',\n )\n .option(\n '--key <dwk_value>',\n 'Use a previously-minted API key (paste plaintext). (Mutually exclusive with --new-key.)',\n )\n .action(\n async (cmdOpts: {\n dir?: string;\n format?: string;\n newKey?: string;\n key?: string;\n }) => {\n process.exitCode = await envExportCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.format !== undefined\n ? { format: cmdOpts.format as EnvExportFormat }\n : {}),\n ...(cmdOpts.newKey !== undefined ? { newKey: cmdOpts.newKey } : {}),\n ...(cmdOpts.key !== undefined ? { key: cmdOpts.key } : {}),\n });\n },\n );\n\nmoduleCmd\n .command('publish')\n .description('Pack the current directory + upload it as a new module version.')\n .option('--dir <path>', 'Project root (default: current directory).')\n .option('--bump <direction>', 'Semver bump: patch | minor | major.')\n .option('--dry-run', 'Validate + upload but do not persist the version row.')\n .option('-y, --yes', 'Skip the confirmation prompt (for CI / scripted use).')\n .option(\n '--exclude <pattern...>',\n 'Extra exclude patterns (segment-matched) appended to the defaults.',\n )\n .action(\n async (cmdOpts: {\n dir?: string;\n bump?: 'patch' | 'minor' | 'major';\n dryRun?: boolean;\n yes?: boolean;\n exclude?: string[];\n }) => {\n process.exitCode = await modulePublishCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.bump !== undefined ? { bump: cmdOpts.bump } : {}),\n ...(cmdOpts.dryRun !== undefined ? { dryRun: cmdOpts.dryRun } : {}),\n ...(cmdOpts.yes !== undefined ? { yes: cmdOpts.yes } : {}),\n ...(cmdOpts.exclude !== undefined ? { exclude: cmdOpts.exclude } : {}),\n });\n },\n );\n\n// Phase 6 slice 6.4 (2026-05-19): per-module SDK query log reader.\n// Workspace-member-scoped on the backend.\nmoduleCmd\n .command('query-log')\n .description(\n 'Read the per-module SDK query log. Default: 50 most recent entries. ' +\n '`--slow` filters to duration_ms > 500ms; `--since 1h` narrows by time; ' +\n '`--tail` streams new entries every 5s.',\n )\n .option(\n '--module <id-or-slug>',\n 'Module to inspect (default: slug from current directory\\'s module.json).',\n )\n .option('--slow', 'Filter to slow queries only (duration_ms > 500).')\n .option(\n '--since <duration>',\n 'Only entries newer than this. Accepts \"30m\", \"1h\", \"6h\", \"2d\", \"7d\", or an ISO 8601 timestamp.',\n )\n .option('--limit <n>', 'Max rows per fetch (1-500, default 50).', parseIntOption)\n .option('--tail', 'Poll every 5s for new entries. Ctrl-C to stop.')\n .option('--json', 'Emit compact JSON instead of the table. Ignored with --tail.')\n .option('--dir <path>', 'Override project directory for module.json lookup.')\n .action(\n async (cmdOpts: {\n module?: string;\n slow?: boolean;\n since?: string;\n limit?: number;\n tail?: boolean;\n json?: boolean;\n dir?: string;\n }) => {\n process.exitCode = await moduleQueryLogCommand({\n ...(cmdOpts.module !== undefined ? { module: cmdOpts.module } : {}),\n ...(cmdOpts.slow !== undefined ? { slow: cmdOpts.slow } : {}),\n ...(cmdOpts.since !== undefined ? { since: cmdOpts.since } : {}),\n ...(cmdOpts.limit !== undefined ? { limit: cmdOpts.limit } : {}),\n ...(cmdOpts.tail !== undefined ? { tail: cmdOpts.tail } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n });\n },\n );\n\n// P7 slice 7.5b (2026-05-20): per-installation server-action audit log.\n// Follow-up (2026-05-20): added `--module <slug>` resolver.\nmoduleCmd\n .command('action-log')\n .description(\n 'Read the per-installation server-action audit log. Shows both ' +\n 'cross-module and own-module dispatches. Filter by role (caller / ' +\n 'provider), slow, since, cross-module-only. `--tail` streams new ' +\n 'entries every 5s. Pass either `--installation <id>` or ' +\n '`--module <slug>` (slug resolves to your accessible installation).',\n )\n .option(\n '--installation <id>',\n 'Installation id to inspect. Mutually exclusive with `--module`.',\n parseIntOption,\n )\n .option(\n '--module <slug>',\n \"Module slug. Resolves to the caller's accessible installation of \" +\n 'that module (first match if multi-workspace). Mutually exclusive with `--installation`.',\n )\n .option(\n '--role <caller|provider>',\n \"Which side of cross-module dispatches to show. 'caller' (default) \" +\n \"shows outbound; 'provider' shows inbound calls on this installation.\",\n )\n .option('--slow', 'Filter to slow actions only (elapsed_ms > 500).')\n .option('--cross-module-only', 'Hide own-module dispatches (cross_module=false rows).')\n .option(\n '--since <duration>',\n 'Only entries newer than this. Accepts \"30m\", \"1h\", \"6h\", \"2d\", \"7d\", or an ISO 8601 timestamp.',\n )\n .option('--limit <n>', 'Max rows per fetch (1-500, default 50).', parseIntOption)\n .option('--tail', 'Poll every 5s for new entries. Ctrl-C to stop.')\n .option('--json', 'Emit compact JSON instead of the table. Ignored with --tail.')\n .action(\n async (cmdOpts: {\n installation?: number;\n module?: string;\n role?: string;\n slow?: boolean;\n crossModuleOnly?: boolean;\n since?: string;\n limit?: number;\n tail?: boolean;\n json?: boolean;\n }) => {\n if (cmdOpts.role !== undefined && cmdOpts.role !== 'caller' && cmdOpts.role !== 'provider') {\n fail(`--role must be 'caller' or 'provider' (got \"${cmdOpts.role}\").`);\n process.exitCode = 1;\n return;\n }\n process.exitCode = await moduleActionLogCommand({\n ...(cmdOpts.installation !== undefined ? { installation: cmdOpts.installation } : {}),\n ...(cmdOpts.module !== undefined ? { module: cmdOpts.module } : {}),\n ...(cmdOpts.role !== undefined ? { role: cmdOpts.role as 'caller' | 'provider' } : {}),\n ...(cmdOpts.slow !== undefined ? { slow: cmdOpts.slow } : {}),\n ...(cmdOpts.crossModuleOnly !== undefined ? { crossModuleOnly: cmdOpts.crossModuleOnly } : {}),\n ...(cmdOpts.since !== undefined ? { since: cmdOpts.since } : {}),\n ...(cmdOpts.limit !== undefined ? { limit: cmdOpts.limit } : {}),\n ...(cmdOpts.tail !== undefined ? { tail: cmdOpts.tail } : {}),\n ...(cmdOpts.json !== undefined ? { json: cmdOpts.json } : {}),\n });\n },\n );\n\n// ── HH-CC-LDI-9: dashwise module destroy-dev-install + reset-dev-install ──\n\nmoduleCmd\n .command('destroy-dev-install')\n .description(\n \"Destroy the local-dev install for the current module. Tears down the install row + dashboard tile; if the module had no other installs and was never published, drops the module too. Local module.json is preserved (only the cached runtime token + install id in auth.json get cleared).\",\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option(\n '--module <slug>',\n \"Override the module slug (default: read from local module.json). Useful when the project dir is gone but auth.json still has the entry.\",\n )\n .option('-y, --yes', 'Skip the confirmation prompt — for CI.')\n .action(\n async (cmdOpts: { dir?: string; module?: string; yes?: boolean }) => {\n const { destroyDevInstallCommand } = await import(\n './commands/module/destroy-dev-install.js'\n );\n process.exitCode = await destroyDevInstallCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.module !== undefined ? { module: cmdOpts.module } : {}),\n ...(cmdOpts.yes !== undefined ? { yes: cmdOpts.yes } : {}),\n });\n },\n );\n\nmoduleCmd\n .command('reset-dev-install')\n .description(\n 'Destroy + re-provision the local-dev install in one shot. Useful for nuking accumulated test data, refreshing a compromised runtime token, or recovering from a wedged schema state. Keeps local module.json intact.',\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option(\n '--module <slug>',\n 'Override the module slug (default: from local module.json).',\n )\n .option(\n '--workspace <slug-or-id>',\n 'Target workspace for re-provisioning (passed through to `dashwise init`).',\n )\n .option('-y, --yes', 'Skip prompts in both destroy + re-init phases.')\n .action(\n async (cmdOpts: {\n dir?: string;\n module?: string;\n workspace?: string;\n yes?: boolean;\n }) => {\n const { resetDevInstallCommand } = await import(\n './commands/module/reset-dev-install.js'\n );\n process.exitCode = await resetDevInstallCommand({\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.module !== undefined ? { module: cmdOpts.module } : {}),\n ...(cmdOpts.workspace !== undefined\n ? { workspace: cmdOpts.workspace }\n : {}),\n ...(cmdOpts.yes !== undefined ? { yes: cmdOpts.yes } : {}),\n });\n },\n );\n\n// ── HH-CC-LDI-8: dashwise table / dashwise field schema commands ──\n\nconst tableCmd = program\n .command('table')\n .description(\n 'Schema commands for the current module — create/delete tables in the dev installation. Requires a per-module dev install (run `dashwise init` first).',\n );\n\ntableCmd\n .command('create <slug>')\n .description(\n 'Create a new table. Pass --field flags to define columns. Calls POST /api/installations/:id/schema/tables and syncs the updated manifest back to local module.json.',\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option(\n '-f, --field <spec>',\n \"Field spec — `<slug>:<type>[:required]`. Repeat for multiple fields. For options/target/default, use --field-json instead. Example: `--field title:text:required --field done:boolean`.\",\n (val: string, prev: string[] = []) => [...prev, val],\n [] as string[],\n )\n .option(\n '--field-json <json>',\n \"Field as a JSON object — `{slug,type,required?,options?,target?,default?}`. Repeatable. Use for fields where the simple syntax can't express the shape.\",\n (val: string, prev: string[] = []) => [...prev, val],\n [] as string[],\n )\n .action(\n async (\n slug: string | undefined,\n cmdOpts: { dir?: string; field?: string[]; fieldJson?: string[] },\n ) => {\n const { tableCreateCommand } = await import('./commands/table/create.js');\n process.exitCode = await tableCreateCommand(slug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.field !== undefined ? { field: cmdOpts.field } : {}),\n ...(cmdOpts.fieldJson !== undefined ? { fieldJson: cmdOpts.fieldJson } : {}),\n });\n },\n );\n\ntableCmd\n .command('delete <slug>')\n .description(\n \"Drop a table. Calls DELETE /api/installations/:id/schema/tables/:slug — the physical table is soft-deleted (recoverable for 30 days via the dashboard's trash). Updates local module.json.\",\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .action(async (slug: string | undefined, cmdOpts: { dir?: string }) => {\n const { tableDeleteCommand } = await import('./commands/table/delete.js');\n process.exitCode = await tableDeleteCommand(slug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n });\n });\n\nconst fieldCmd = program\n .command('field')\n .description(\n 'Schema commands for fields within the current module — add/remove/change-type. Field rename is deferred to v1.1 per the plan.',\n );\n\nfieldCmd\n .command('add <table-slug> [field-spec]')\n .description(\n \"Add a field to a table. Pass the spec as `<slug>:<type>[:required]` OR use --field-json for fields with options/target/default. Example: `dashwise field add tasks priority --field-json '{\\\"slug\\\":\\\"priority\\\",\\\"type\\\":\\\"single_select\\\",\\\"options\\\":[\\\"low\\\",\\\"medium\\\",\\\"high\\\"]}'`.\",\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .option(\n '--field-json <json>',\n \"Field as a JSON object. Mutually exclusive with the positional field spec.\",\n )\n .action(\n async (\n tableSlug: string | undefined,\n fieldSpec: string | undefined,\n cmdOpts: { dir?: string; fieldJson?: string },\n ) => {\n const { fieldAddCommand } = await import('./commands/field/add.js');\n process.exitCode = await fieldAddCommand(tableSlug, fieldSpec, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n ...(cmdOpts.fieldJson !== undefined ? { fieldJson: cmdOpts.fieldJson } : {}),\n });\n },\n );\n\nfieldCmd\n .command('remove <table-slug> <field-slug>')\n .description(\n 'Remove a field from a table. The backend cascades index cleanup (M2-C-FIX): any index referencing the removed field is trimmed; empty indexes are dropped.',\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .action(\n async (\n tableSlug: string | undefined,\n fieldSlug: string | undefined,\n cmdOpts: { dir?: string },\n ) => {\n const { fieldRemoveCommand } = await import('./commands/field/remove.js');\n process.exitCode = await fieldRemoveCommand(tableSlug, fieldSlug, {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n });\n },\n );\n\nfieldCmd\n .command('set-type <table-slug> <field-slug> <new-type>')\n .description(\n \"Change a field's type (e.g. text → long_text). Lossy changes (text → number with non-numeric data) are rejected by the backend's manifest validator today; v1.1 will add a structured RETYPE_UNSAFE precheck.\",\n )\n .option('--dir <path>', 'Project root (default: current directory).')\n .action(\n async (\n tableSlug: string | undefined,\n fieldSlug: string | undefined,\n newType: string | undefined,\n cmdOpts: { dir?: string },\n ) => {\n const { fieldSetTypeCommand } = await import('./commands/field/set-type.js');\n process.exitCode = await fieldSetTypeCommand(\n tableSlug,\n fieldSlug,\n newType,\n {\n ...(cmdOpts.dir !== undefined ? { dir: cmdOpts.dir } : {}),\n },\n );\n },\n );\n\n// Single async entry so unhandled errors hit the same formatter.\n(async () => {\n try {\n await program.parseAsync(process.argv);\n } catch (err) {\n fail(`Unhandled error: ${(err as Error).message ?? String(err)}`);\n if (process.env.DASHWISE_DEBUG) {\n // Print full stack when debugging — opt-in to keep normal\n // output uncluttered.\n // eslint-disable-next-line no-console\n console.error(err);\n }\n process.exitCode = 1;\n }\n})();\n\n/**\n * CLI version, injected at build time by tsup's `define` from\n * `packages/cli/package.json#version`. See tsup.config.ts.\n */\ndeclare const __CLI_VERSION__: string;\n\nfunction getVersion(): string {\n return __CLI_VERSION__;\n}\n\n/** commander helper: parse a `<n>` argument as an integer. */\nfunction parseIntOption(value: string): number {\n const n = Number.parseInt(value, 10);\n if (!Number.isFinite(n)) {\n throw new Error(`Expected an integer, got '${value}'`);\n }\n return n;\n}\n\n/**\n * commander helper: collect repeated `--option <value>` flags into\n * an array. Use as the third arg to `.option()` along with `[]` as\n * the default (fourth arg).\n *\n * Example: `--callback-origin http://localhost:3000 --callback-origin https://myapp.local`\n * yields `['http://localhost:3000', 'https://myapp.local']`.\n */\nfunction collectRepeated(value: string, previous: string[]): string[] {\n return [...previous, value];\n}\n","/**\n * `dashwise module list` — list modules the current user can author.\n *\n * Hits `GET /api/modules?owned_only=true` so the listing scope is\n * \"modules I own\" by default. Add `--all` to include public modules\n * the user could install but doesn't own. Workspace filter (`--workspace\n * <slug>`) narrows further when the user has multiple workspaces.\n *\n * Output is plain text — column-aligned slug + version + name — so\n * it pipes cleanly into grep / awk.\n */\n\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { readConfig } from '../../lib/config.js';\nimport { code, dim, fail, info, out } from '../../lib/output.js';\n\nexport interface ModuleListOptions {\n /** Include public modules (default: false — owned only). */\n all?: boolean;\n /**\n * Filter by workspace slug. Falls back to the saved default if\n * omitted, no filter if neither.\n */\n workspace?: string;\n /** Emit JSON to stdout instead of column-aligned text. */\n json?: boolean;\n}\n\ninterface ModuleSummary {\n id: number;\n slug: string;\n name: string;\n owner_workspace_id: number;\n current_version: string | null;\n verified: boolean;\n public: boolean;\n}\n\nexport async function moduleListCommand(\n options: ModuleListOptions,\n): Promise<number> {\n const cfg = readConfig();\n if (!cfg) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'NOT_LOGGED_IN', message: 'Run `dashwise login` first.' } }));\n } else {\n fail('Not logged in. Run `dashwise login` first.');\n }\n return 1;\n }\n\n // Resolve workspaceId from slug if requested.\n let workspaceId: number | undefined;\n const targetSlug = options.workspace ?? cfg.workspaceSlug;\n if (targetSlug) {\n try {\n const workspaces = await apiRequest<Array<{ id: number; slug?: string }>>(\n 'GET',\n '/api/workspaces',\n );\n const match = workspaces.find((w) => w.slug === targetSlug);\n if (!match) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'WORKSPACE_NOT_FOUND', message: `Workspace ${targetSlug} not found.` } }));\n } else {\n fail(\n `Workspace ${code(targetSlug)} not found in your accessible workspaces. Run \\`dashwise workspace list\\` to see the choices.`,\n );\n }\n return 1;\n }\n workspaceId = match.id;\n } catch (err) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'FETCH_FAILED', message: (err as Error).message } }));\n } else {\n fail(`Could not load workspaces: ${(err as Error).message}`);\n }\n return 1;\n }\n }\n\n // Build query.\n const params = new URLSearchParams();\n if (!options.all) params.set('owned_only', 'true');\n if (workspaceId !== undefined) params.set('workspaceId', String(workspaceId));\n const path = `/api/modules${params.toString() ? `?${params.toString()}` : ''}`;\n\n let modules: ModuleSummary[];\n try {\n modules = await apiRequest<ModuleSummary[]>('GET', path);\n } catch (err) {\n if (err instanceof ApiError && err.status === 401) {\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'NOT_LOGGED_IN', message: 'Run `dashwise login` first.' } }));\n } else {\n fail('Not logged in. Run `dashwise login` first.');\n }\n return 1;\n }\n if (options.json) {\n out(JSON.stringify({ ok: false, error: { code: 'FETCH_FAILED', message: (err as Error).message } }));\n } else {\n fail(`Could not list modules: ${(err as Error).message}`);\n }\n return 1;\n }\n\n if (options.json) {\n out(\n JSON.stringify({\n ok: true,\n modules: Array.isArray(modules) ? modules : [],\n total: Array.isArray(modules) ? modules.length : 0,\n }),\n );\n return 0;\n }\n\n if (!Array.isArray(modules) || modules.length === 0) {\n info(\n options.all\n ? 'No modules found.'\n : 'No modules owned by you yet. Use `dashwise module init <slug>` to scaffold one.',\n );\n return 0;\n }\n\n // Column-aligned plain output. Two passes: compute widths, then format.\n const slugWidth = Math.max(...modules.map((m) => m.slug.length), 4);\n const versionWidth = Math.max(\n ...modules.map((m) => (m.current_version ?? '(draft)').length),\n 7,\n );\n out('');\n out(\n `${'SLUG'.padEnd(slugWidth)} ${'VERSION'.padEnd(versionWidth)} NAME`,\n );\n out(\n `${'-'.repeat(slugWidth)} ${'-'.repeat(versionWidth)} ${'-'.repeat(20)}`,\n );\n for (const m of modules) {\n const version = m.current_version ?? '(draft)';\n const flags = [\n m.verified ? code('✓') : '',\n m.public ? dim('public') : '',\n ]\n .filter(Boolean)\n .join(' ');\n const flagsCol = flags ? ` ${flags}` : '';\n out(`${m.slug.padEnd(slugWidth)} ${version.padEnd(versionWidth)} ${m.name}${flagsCol}`);\n }\n out('');\n info(`${modules.length} module${modules.length === 1 ? '' : 's'}.`);\n return 0;\n}\n","/**\n * `dashwise module publish` — package the local project + upload it\n * as a new module version.\n *\n * Steps:\n * 1. Read local `module.json` to get the slug + module_kind.\n * 2. Resolve `slug → module_id` via `GET /api/modules/by-slug/:slug`.\n * 3. Pack `cwd` into a gzipped tarball via `packTarball()`. The\n * tarball excludes node_modules / .next / .git / .dashwise +\n * caps per-file at 10MB and total at 100MB (matches backend).\n * 4. POST the tarball as multipart form-data to\n * `/api/modules/:id/publish/cli` with the user's bump + flags.\n * 5. Print the resulting version + bundle hash.\n *\n * Confirms before uploading (in TTY) unless `--yes` is passed —\n * publish is the one command where a typo costs a real version bump.\n *\n * Tarball bytes live in memory (≤100MB) — no temp file. We use\n * the native `FormData` + `Blob` available on Node 18+.\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { intro, isCancel, outro, select } from '@clack/prompts';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { readConfig, resolveApiUrl } from '../../lib/config.js';\nimport { code, dim, fail, info, out, success, warn } from '../../lib/output.js';\nimport { MAX_TARBALL_BYTES, packTarball } from '../../lib/tarball.js';\n\nexport interface PublishOptions {\n /** Project root containing `module.json` (defaults to `process.cwd()`). */\n dir?: string;\n /** SemVer bump direction; required. */\n bump?: 'patch' | 'minor' | 'major';\n /** Dry run: send `dry_run=true`; backend validates without persisting. */\n dryRun?: boolean;\n /** Skip the confirmation prompt (CI / scripted runs). */\n yes?: boolean;\n /** Additional exclude patterns appended to the defaults. */\n exclude?: string[];\n}\n\ninterface ModuleByslugResponse {\n id: number;\n slug: string;\n name: string;\n current_version: string | null;\n}\n\ninterface PublishResponse {\n module_version_id: number;\n module_slug: string;\n version: string;\n bundle_url: string;\n bundle_hash: string;\n bytes_uploaded: number;\n publisher_type: string;\n verified: boolean;\n warnings: string[];\n pipeline_version: string;\n}\n\nconst VALID_BUMP = new Set(['patch', 'minor', 'major']);\n\nexport async function modulePublishCommand(\n options: PublishOptions,\n): Promise<number> {\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n fail(\n `No ${code('module.json')} found in ${code(projectRoot)}. Run \\`dashwise module init <slug>\\` first.`,\n );\n return 1;\n }\n let manifest: { module?: { slug?: string; name?: string; version?: string } };\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n } catch (err) {\n fail(`Could not parse ${code(manifestPath)}: ${(err as Error).message}`);\n return 1;\n }\n const slug = manifest.module?.slug;\n if (!slug) {\n fail(`${code('module.json')} is missing ${code('module.slug')}. Cannot publish.`);\n return 1;\n }\n\n if (!readConfig()) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n\n // Resolve / prompt for bump.\n let bump = options.bump;\n if (!bump && process.stdout.isTTY) {\n intro(`Publishing module ${code(slug)}`);\n const answer = await select({\n message: 'Bump direction?',\n options: [\n { value: 'patch', label: 'patch — bug fixes only (recommended for first publish)' },\n { value: 'minor', label: 'minor — additive changes (new fields, new tables)' },\n { value: 'major', label: 'major — breaking changes' },\n ],\n initialValue: 'patch',\n });\n if (isCancel(answer)) {\n fail('Aborted.');\n return 130;\n }\n bump = answer as 'patch' | 'minor' | 'major';\n }\n if (!bump || !VALID_BUMP.has(bump)) {\n fail('Bump direction required: `--bump patch|minor|major`.');\n return 1;\n }\n\n // Resolve slug → module id.\n let mod: ModuleByslugResponse;\n try {\n mod = await apiRequest<ModuleByslugResponse>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(slug)}`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n fail(\n `Module ${code(slug)} not found on the backend. Create it via the UI / API first, then re-run publish.`,\n );\n return 1;\n }\n if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n fail(`Could not resolve module: ${(err as Error).message}`);\n return 1;\n }\n\n info(\n `Module: ${code(mod.slug)} (id ${mod.id})${\n mod.current_version ? `, current ${code(`v${mod.current_version}`)}` : dim(', no published version yet')\n }`,\n );\n\n // Pack tarball.\n let tarball;\n try {\n tarball = await packTarball({\n cwd: projectRoot,\n ...(options.exclude !== undefined ? { extraExclude: options.exclude } : {}),\n });\n } catch (err) {\n fail(`Could not pack tarball: ${(err as Error).message}`);\n return 1;\n }\n info(\n `Packed ${tarball.filesIncluded.length} file${tarball.filesIncluded.length === 1 ? '' : 's'} into ${formatBytes(tarball.bytes.byteLength)} (cap ${formatBytes(MAX_TARBALL_BYTES)}).`,\n );\n for (const w of tarball.warnings) warn(w);\n\n // Confirm.\n if (!options.yes && process.stdout.isTTY && !options.dryRun) {\n const answer = await select({\n message: `Upload + publish ${code(`bump:${bump}`)}?`,\n options: [\n { value: 'go', label: 'Yes, upload now' },\n { value: 'cancel', label: 'No, abort' },\n ],\n initialValue: 'go',\n });\n if (isCancel(answer) || answer === 'cancel') {\n fail('Aborted.');\n return 130;\n }\n }\n\n // Multipart upload.\n const cfg = readConfig();\n if (!cfg) {\n fail('Session vanished mid-publish — re-run `dashwise login`.');\n return 1;\n }\n const url = `${resolveApiUrl()}/api/modules/${mod.id}/publish/cli`;\n const form = new FormData();\n // Native `Blob` works in Node 18+; `Buffer` is array-buffer-like\n // so we wrap it before passing to FormData.\n const blob = new Blob([new Uint8Array(tarball.bytes)], { type: 'application/gzip' });\n form.set('file', blob, 'module.tar.gz');\n form.set('bump', bump);\n if (options.dryRun) form.set('dry_run', 'true');\n\n let res: Response;\n try {\n res = await fetch(url, {\n method: 'POST',\n headers: {\n Accept: 'application/json',\n Authorization: `Bearer ${cfg.token}`,\n },\n body: form,\n });\n } catch (err) {\n fail(`Network error during upload: ${(err as Error).message}`);\n return 1;\n }\n\n const body = (await res.json().catch(() => null)) as unknown;\n if (!res.ok) {\n const env = body && typeof body === 'object' ? (body as Record<string, unknown>) : null;\n fail(\n `Publish failed (${res.status}${env?.code ? ` ${env.code}` : ''}): ${env?.message ?? '(no message)'}`,\n );\n if (env?.context) {\n out(JSON.stringify(env.context, null, 2));\n }\n return 1;\n }\n\n const result = body as PublishResponse | null;\n if (!result) {\n fail('Publish succeeded but the response body was empty or malformed.');\n return 1;\n }\n if (options.dryRun) {\n success(`Dry run OK — would publish ${code(`v${result.version}`)}`);\n } else {\n success(`Published ${code(mod.slug)} ${code(`v${result.version}`)}`);\n }\n info(`Bundle: ${code(result.bundle_url)}`);\n info(`Hash: ${dim(result.bundle_hash)}`);\n info(`Size: ${formatBytes(result.bytes_uploaded)}`);\n if (result.warnings.length > 0) {\n warn(`${result.warnings.length} warning${result.warnings.length === 1 ? '' : 's'}:`);\n for (const w of result.warnings) {\n out(` ${dim('•')} ${w}`);\n }\n }\n if (process.stdout.isTTY && !options.dryRun) outro('Done.');\n return 0;\n}\n\nfunction formatBytes(n: number): string {\n if (n < 1024) return `${n}B`;\n if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)}KB`;\n return `${(n / 1024 / 1024).toFixed(1)}MB`;\n}\n","/**\n * Tarball helper for `dashwise module publish`.\n *\n * Wraps the `tar` npm package with DashWise-specific defaults:\n * - gzip compression (server expects `.tar.gz`)\n * - sensible exclusion list (node_modules, .next, .git, ...)\n * - allowlist of files that should ALWAYS be included if present\n * (module.json, manifest.yaml, package.json, app/, server/, etc.)\n * - 100MB size cap (matches backend's `BUNDLE_TOO_LARGE` gate)\n *\n * Output is a `Uint8Array` buffer so callers can pipe it straight\n * into a `fetch` multipart upload without a temp file. The trade-off\n * is memory — but 100MB max is fine for any modern CLI host.\n */\n\nimport { existsSync, readdirSync, statSync } from 'node:fs';\nimport { join, relative } from 'node:path';\nimport * as tar from 'tar';\n\n/**\n * Patterns that should NEVER be included in the published bundle.\n * Path semantics: a candidate path matches if any segment equals\n * the pattern (e.g. `node_modules` matches `foo/node_modules/bar`).\n *\n * Kept conservative: the backend's per-file policy gate is the\n * security boundary; this list is the UX layer that keeps tarballs\n * tractable and the upload step fast.\n */\nexport const DEFAULT_EXCLUDE_PATTERNS = [\n 'node_modules',\n '.next',\n '.git',\n '.turbo',\n '.dashwise',\n '.DS_Store',\n '.env',\n '.env.local',\n '.env.development.local',\n '.env.test.local',\n '.env.production.local',\n 'coverage',\n '.nyc_output',\n '.vitest-cache',\n '.idea',\n '.vscode',\n 'dist',\n 'build',\n] as const;\n\n/** Per-file size cap. Files larger than this are excluded with a warning. */\nconst PER_FILE_BYTE_LIMIT = 10 * 1024 * 1024; // 10MB\n/** Tarball total cap — matches backend BUNDLE_TOO_LARGE gate. */\nexport const MAX_TARBALL_BYTES = 100 * 1024 * 1024; // 100MB\n\nexport interface TarballResult {\n /** Gzipped tarball bytes ready to upload. */\n bytes: Uint8Array;\n /** Files included (relative paths from `cwd`). Sorted. */\n filesIncluded: string[];\n /** Files skipped + the reason. */\n warnings: string[];\n}\n\n/**\n * Pack `cwd` into a gzipped tarball.\n *\n * The pack walks `cwd` once, applies exclusion rules + per-file size\n * limits, and emits a buffer. We don't stream-to-disk because the\n * 100MB ceiling makes the in-memory path fine + lets the caller\n * `fetch(...)` without a temp file dance.\n *\n * `extraExclude` is appended to the defaults so callers can suppress\n * additional patterns (e.g. local secrets) without forking the list.\n */\nexport async function packTarball(opts: {\n cwd: string;\n extraExclude?: readonly string[];\n}): Promise<TarballResult> {\n if (!existsSync(opts.cwd)) {\n throw new Error(`packTarball: cwd not found at ${opts.cwd}`);\n }\n const excludeSet = new Set<string>([\n ...DEFAULT_EXCLUDE_PATTERNS,\n ...(opts.extraExclude ?? []),\n ]);\n const filesIncluded: string[] = [];\n const warnings: string[] = [];\n const candidates = walk(opts.cwd, excludeSet);\n for (const abs of candidates) {\n const rel = relative(opts.cwd, abs);\n const size = statSync(abs).size;\n if (size > PER_FILE_BYTE_LIMIT) {\n warnings.push(\n `${rel} skipped — ${formatBytes(size)} exceeds ${formatBytes(PER_FILE_BYTE_LIMIT)} per-file cap`,\n );\n continue;\n }\n filesIncluded.push(rel);\n }\n if (filesIncluded.length === 0) {\n throw new Error(\n `packTarball: nothing to pack in ${opts.cwd} (after applying exclude list)`,\n );\n }\n filesIncluded.sort();\n\n // The `tar.c` API streams chunks; collect them into one buffer.\n // We use the lower-level callback form so the result is a single\n // contiguous Uint8Array — the multipart upload step expects that.\n const chunks: Buffer[] = [];\n await new Promise<void>((resolveDone, rejectDone) => {\n const stream = tar.c(\n {\n gzip: true,\n cwd: opts.cwd,\n // Don't follow symlinks — bundle-local content only.\n follow: false,\n // Preserve the exact case of paths; the backend's per-file\n // policy gate keys off these.\n portable: true,\n },\n filesIncluded,\n );\n stream.on('data', (chunk: Buffer) => chunks.push(chunk));\n stream.on('error', rejectDone);\n stream.on('end', resolveDone);\n });\n const bytes = Buffer.concat(chunks);\n if (bytes.byteLength > MAX_TARBALL_BYTES) {\n throw new Error(\n `packTarball: tarball is ${formatBytes(bytes.byteLength)}, exceeds ${formatBytes(MAX_TARBALL_BYTES)} max`,\n );\n }\n return { bytes, filesIncluded, warnings };\n}\n\n// ── helpers ────────────────────────────────────────────────────────────\n\nfunction walk(root: string, excludeSet: Set<string>): string[] {\n const out: string[] = [];\n const stack: string[] = [root];\n while (stack.length > 0) {\n const dir = stack.pop();\n if (!dir) continue;\n let entries: import('node:fs').Dirent[];\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch {\n continue; // unreadable directory — silently skip\n }\n for (const entry of entries) {\n if (excludeSet.has(entry.name)) continue;\n const abs = join(dir, entry.name);\n if (entry.isDirectory()) {\n stack.push(abs);\n } else if (entry.isFile()) {\n out.push(abs);\n }\n // Skip symlinks + sockets + everything else.\n }\n }\n return out;\n}\n\nfunction formatBytes(n: number): string {\n if (n < 1024) return `${n}B`;\n if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)}KB`;\n return `${(n / 1024 / 1024).toFixed(1)}MB`;\n}\n\n// Test seam: expose internals for unit tests without making them\n// part of the public package surface.\nexport const __forTests = {\n walk,\n formatBytes,\n PER_FILE_BYTE_LIMIT,\n};\n","/**\n * `dashwise module pull-data` — export own-table data from the\n * owner-workspace installation to a local JSON file (default\n * `dashwise-data.json` in the project root).\n *\n * Useful for: seeding local dev with production-shaped data,\n * fixture generation, manual inspection. The output shape matches\n * what `db.<table>.list()` would return through the SDK — manifest\n * slugs as keys, NOT physical `field_<id>` names — so the data\n * can be reused as fixtures for unit tests or local API mocks.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { code, dim, fail, info, success, warn } from '../../lib/output.js';\n\nexport interface PullDataOptions {\n dir?: string;\n /** Max rows per table (1-1000, default 100). */\n limit?: number;\n /** Output path (default: `dashwise-data.json` in dir). */\n out?: string;\n}\n\ninterface PullDataResponse {\n module_slug: string;\n module_version: string | null;\n tables: Array<{\n slug: string;\n total_rows: number;\n rows: Array<Record<string, unknown>>;\n }>;\n}\n\nexport async function modulePullDataCommand(\n options: PullDataOptions,\n): Promise<number> {\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n fail(\n `No ${code('module.json')} found in ${code(projectRoot)}. Run \\`dashwise module init <slug>\\` first.`,\n );\n return 1;\n }\n let manifest: { module?: { slug?: string } };\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n } catch (err) {\n fail(`Could not parse ${code(manifestPath)}: ${(err as Error).message}`);\n return 1;\n }\n const slug = manifest.module?.slug;\n if (!slug) {\n fail(`${code('module.json')} is missing ${code('module.slug')}.`);\n return 1;\n }\n\n // Resolve slug → moduleId.\n let mod: { id: number };\n try {\n mod = await apiRequest<{ id: number }>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(slug)}`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n fail(`Module ${code(slug)} not found on the backend.`);\n return 1;\n }\n if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n fail(`Could not resolve module: ${(err as Error).message}`);\n return 1;\n }\n\n const limit = options.limit ?? 100;\n let res: PullDataResponse;\n try {\n res = await apiRequest<PullDataResponse>(\n 'GET',\n `/api/modules/${mod.id}/own-data?limit=${limit}`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 400) {\n fail(`Invalid request: ${err.message}`);\n return 1;\n }\n fail(`Could not pull data: ${(err as Error).message}`);\n return 1;\n }\n\n const outPath = options.out\n ? resolve(options.out)\n : join(projectRoot, 'dashwise-data.json');\n writeFileSync(outPath, JSON.stringify(res, null, 2) + '\\n', 'utf-8');\n\n let totalRows = 0;\n for (const t of res.tables) totalRows += t.rows.length;\n success(`Wrote ${totalRows} row${totalRows === 1 ? '' : 's'} across ${res.tables.length} table${res.tables.length === 1 ? '' : 's'} to ${code(outPath)}`);\n\n // Warn on truncation per table — useful when a table has many\n // more rows than the user grabbed.\n for (const t of res.tables) {\n if (t.total_rows > t.rows.length) {\n warn(\n `Table ${code(t.slug)} truncated: ${t.rows.length} of ${t.total_rows} rows (use ${code(`--limit ${Math.min(t.total_rows, 1000)}`)} to grab more).`,\n );\n }\n }\n if (res.tables.length === 0) {\n info(dim('No owned tables on this module. (Did you publish a manifest with `owns.tables`?)'));\n }\n return 0;\n}\n","/**\n * `dashwise module validate` — run the local `module.json` through\n * the backend's `POST /api/modules/manifest/validate` endpoint.\n *\n * Useful as a pre-publish sanity check: catches structural manifest\n * errors (bad field types, unknown table refs, etc.) before paying\n * the cost of a publish round-trip.\n *\n * Output is structured-by-default: bullet-listed issues on failure,\n * \"Manifest is valid\" on success. Exit code 0 / 1 mirrors the\n * underlying validation result.\n */\n\nimport { existsSync, readFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { code, dim, fail, out, success } from '../../lib/output.js';\n\nexport interface ValidateOptions {\n dir?: string;\n}\n\ninterface ValidateOkResponse {\n ok: true;\n manifest: unknown;\n}\n\ninterface ManifestIssue {\n path?: string;\n message?: string;\n}\n\nexport async function moduleValidateCommand(\n options: ValidateOptions,\n): Promise<number> {\n const projectRoot = resolve(options.dir ?? process.cwd());\n const manifestPath = join(projectRoot, 'module.json');\n if (!existsSync(manifestPath)) {\n fail(\n `No ${code('module.json')} found in ${code(projectRoot)}. Run \\`dashwise module init <slug>\\` first.`,\n );\n return 1;\n }\n let manifest: unknown;\n try {\n manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));\n } catch (err) {\n fail(`Could not parse ${code(manifestPath)}: ${(err as Error).message}`);\n return 1;\n }\n\n try {\n const res = await apiRequest<ValidateOkResponse>(\n 'POST',\n '/api/modules/manifest/validate',\n manifest,\n );\n if (res.ok) {\n success('Manifest is valid.');\n return 0;\n }\n // Defensive — the endpoint only returns `ok:true` on success;\n // anything else throws on the API side.\n fail(`Unexpected response shape: ${JSON.stringify(res)}`);\n return 1;\n } catch (err) {\n if (err instanceof ApiError && err.status === 400) {\n const issues = readIssues(err.context);\n if (issues.length > 0) {\n fail(`Manifest is invalid (${issues.length} issue${issues.length === 1 ? '' : 's'}):`);\n for (const issue of issues) {\n const path = issue.path ?? '(root)';\n const message = issue.message ?? '(no message)';\n out(` ${dim('•')} ${code(path)}: ${message}`);\n }\n } else {\n fail(`Manifest is invalid: ${err.message}`);\n }\n return 1;\n }\n if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n fail(`Could not validate manifest: ${(err as Error).message}`);\n return 1;\n }\n}\n\nfunction readIssues(context: Record<string, unknown> | undefined): ManifestIssue[] {\n if (!context) return [];\n const v = context['issues'];\n if (!Array.isArray(v)) return [];\n return v\n .map((entry) => {\n if (!entry || typeof entry !== 'object') return null;\n const e = entry as Record<string, unknown>;\n const issue: ManifestIssue = {};\n if (typeof e.path === 'string') issue.path = e.path;\n if (typeof e.message === 'string') issue.message = e.message;\n return issue;\n })\n .filter((x): x is ManifestIssue => x !== null);\n}\n","/**\n * `dashwise deps add <provider-slug>` — declare a cross-module dep in\n * `module.json#dependencies`.\n *\n * Two modes:\n * 1. Interactive (TTY default) — fetches the provider's published\n * `exposes` block from the backend, lets the user pick tables +\n * fields via `@clack/prompts.multiselect`, prompts for the\n * required `purpose` string.\n * 2. Non-interactive (`--table`, `--fields`, `--purpose` provided\n * OR not a TTY) — single-table add with no prompts. Multi-table\n * adds are done by re-running the command per table, OR by\n * hand-editing module.json (which `deps list` then displays\n * verbatim).\n *\n * Backend reachability is best-effort: if the provider can't be\n * found (network down, slug typo, provider deleted), interactive\n * mode falls back to a minimal \"manual\" path that asks the user to\n * type the table + field names verbatim.\n *\n * Spec: dashwise-devops-docs/plans/modules-sdk-query-v1.md §9.\n */\n\nimport {\n intro,\n isCancel,\n multiselect,\n outro,\n select,\n text,\n} from '@clack/prompts';\nimport {\n ApiError,\n apiRequest,\n getInstallationDependencies,\n type RequestOptions,\n} from '../../lib/api-client.js';\nimport { readConfig, readModuleEntry, resolveApiUrl } from '../../lib/config.js';\nimport {\n readManifestOrThrow,\n writeManifest,\n type ManifestDependency,\n type ManifestShape,\n} from '../../lib/manifest-io.js';\nimport { code, dim, fail, info, out, pc, success, warn } from '../../lib/output.js';\n\nexport interface DepsAddOptions {\n dir?: string;\n /** Single-table add: required in non-interactive mode. */\n table?: string;\n /** Comma-separated field slugs for `--table`. */\n fields?: string;\n /** Human-readable purpose (10-500 chars, per manifest schema). */\n purpose?: string;\n /** SemVer range (default: `^<provider-current-version>` if backend reachable, else `^0.0.1`). */\n version?: string;\n /** Skip the confirmation step when replacing an existing dep declaration. */\n yes?: boolean;\n}\n\nconst MIN_PURPOSE_LEN = 10;\nconst MAX_PURPOSE_LEN = 500;\n\n/** Backend manifest_jsonb shape, only the parts the CLI needs. */\ninterface ProviderManifestSummary {\n module?: { slug?: string; name?: string; version?: string };\n exposes?: Array<{\n table: string;\n fields: string[];\n operations?: {\n list?: { allowed?: boolean };\n get?: { allowed?: boolean };\n search?: { allowed?: boolean };\n };\n visibility?: string;\n }>;\n}\n\ninterface ModuleByslugResponse {\n id: number;\n slug: string;\n name: string;\n current_version: string | null;\n}\n\ninterface VersionResponse {\n id: number;\n module_id: number;\n version: string;\n manifest_jsonb: ProviderManifestSummary;\n}\n\nexport async function depsAddCommand(\n providerSlug: string,\n options: DepsAddOptions,\n): Promise<number> {\n if (!providerSlug || typeof providerSlug !== 'string') {\n fail('Usage: `dashwise deps add <provider-slug>`');\n return 1;\n }\n // Module slugs are kebab-case (matches backend MODULE_SLUG_REGEX).\n if (!/^[a-z][a-z0-9-]*[a-z0-9]$/.test(providerSlug)) {\n fail(\n `Provider slug ${code(providerSlug)} is invalid. Module slugs are kebab-case (e.g. ${code('crm-app')}).`,\n );\n return 1;\n }\n\n let manifest;\n try {\n manifest = readManifestOrThrow(options.dir);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n // Refuse to self-depend (would be a no-op but confusing).\n if (manifest.module?.slug === providerSlug) {\n fail('A module cannot depend on itself.');\n return 1;\n }\n\n const isInteractive = process.stdout.isTTY;\n const hasAllNonInteractive =\n options.table !== undefined &&\n options.fields !== undefined &&\n options.purpose !== undefined;\n\n if (!isInteractive && !hasAllNonInteractive) {\n fail(\n `Non-interactive mode requires ${code('--table')}, ${code('--fields')}, and ${code('--purpose')}.`,\n );\n return 1;\n }\n\n // Fetch provider summary (best-effort — non-fatal in interactive mode).\n let providerSummary: ProviderManifestSummary | null = null;\n let resolvedVersion: string | null = null;\n try {\n const mod = await apiRequest<ModuleByslugResponse>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(providerSlug)}`,\n );\n if (mod.current_version) {\n const versions = await apiRequest<VersionResponse[]>(\n 'GET',\n `/api/modules/${mod.id}/versions`,\n );\n // Versions are returned newest-first per the controller spec; the\n // first one matching `current_version` is what's actually\n // installable. Fall back to versions[0] if no exact match.\n const current =\n versions.find((v) => v.version === mod.current_version) ??\n versions[0];\n if (current) {\n providerSummary = current.manifest_jsonb;\n resolvedVersion = current.version;\n }\n }\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n if (!isInteractive) {\n fail(\n `Provider ${code(providerSlug)} not found on the backend. Publish it first or check the slug.`,\n );\n return 1;\n }\n warn(\n `Provider ${code(providerSlug)} not found on the backend (404). You can still declare the dep manually.`,\n );\n } else if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n } else {\n warn(`Could not fetch provider summary: ${(err as Error).message}`);\n }\n }\n\n // Resolve the dep entry's fields.\n let entry: ManifestDependency;\n if (isInteractive) {\n intro(`Adding dependency on ${code(providerSlug)}`);\n const built = await collectInteractive(\n providerSlug,\n providerSummary,\n resolvedVersion,\n options,\n );\n if (built === null) {\n outro('Cancelled.');\n return 130;\n }\n entry = built;\n } else {\n // Non-interactive path: all required args are present per the\n // check above; we trust them + let the backend validate semantics\n // on the next publish.\n const fieldList = (options.fields ?? '')\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean);\n if (fieldList.length === 0) {\n fail(`${code('--fields')} must list at least one field slug.`);\n return 1;\n }\n const purposeErr = validatePurpose(options.purpose!);\n if (purposeErr) {\n fail(purposeErr);\n return 1;\n }\n entry = {\n module: providerSlug,\n version: options.version ?? (resolvedVersion ? `^${resolvedVersion}` : '^0.0.1'),\n reads: [{ table: options.table!, fields: fieldList }],\n purpose: options.purpose!,\n };\n }\n\n // Merge with existing manifest.dependencies[].\n const deps: ManifestDependency[] = manifest.dependencies ?? [];\n const existingIdx = deps.findIndex((d) => d.module === providerSlug);\n if (existingIdx >= 0) {\n if (!options.yes && isInteractive) {\n const answer = await select({\n message: `Dep on ${providerSlug} already exists. Replace it?`,\n options: [\n { value: 'replace', label: 'Replace (loses prior reads/writes)' },\n { value: 'cancel', label: 'Cancel' },\n ],\n initialValue: 'replace',\n });\n if (isCancel(answer) || answer === 'cancel') {\n outro('Cancelled.');\n return 130;\n }\n }\n deps[existingIdx] = entry;\n } else {\n deps.push(entry);\n }\n manifest.dependencies = deps;\n\n try {\n writeManifest(manifest as ManifestShape, options.dir);\n } catch (err) {\n fail(`Could not write manifest: ${(err as Error).message}`);\n return 1;\n }\n\n success(\n `${existingIdx >= 0 ? 'Replaced' : 'Added'} dependency on ${code(providerSlug)}@${entry.version}.`,\n );\n info(`Reads: ${entry.reads.map((r) => `${code(r.table)} (${r.fields.join(', ')})`).join('; ')}`);\n info(`Run ${code('dashwise module generate')} to refresh typed wrappers.`);\n\n // P3-C / D6: the manifest is the input; the backend reconciles the real\n // `module_dependencies` row on the dev install (park-not-reject) the\n // next time the manifest is pushed. Best-effort surface the resulting\n // connect status via the D4 endpoint so the author sees whether the dep\n // will RESOLVE (provider installed + compatible) or PARK (unbound), and\n // why — without pre-validating locally. Purely informational: any\n // failure here never changes the exit code (the manifest edit stands).\n await reportConnectStatus(manifest.module?.slug, providerSlug);\n\n if (isInteractive) outro('Done.');\n return 0;\n}\n\n/**\n * Best-effort: after the manifest edit, show the backend's park/resolve\n * answer for the just-declared dep (D4 `GET .../dependencies`). The\n * backend resolves against the same-workspace provider — INCLUDING an\n * unpublished same-workspace provider's DRAFT manifest (D6) — so this is\n * the authoritative \"will it connect?\" signal. We surface it verbatim;\n * we don't second-guess it locally.\n *\n * Non-fatal by contract: if the module isn't provisioned, the backend is\n * unreachable, or the connect endpoint isn't available, we print a hint\n * and return — the local manifest change is already done.\n */\nasync function reportConnectStatus(\n consumerSlug: string | undefined,\n providerSlug: string,\n): Promise<void> {\n if (!consumerSlug) return;\n\n // `readConfig()` throws on a malformed/incomplete auth.json — but this\n // whole path is best-effort AFTER a successful manifest write, so a bad\n // config must never turn `deps add` into an \"Unhandled error\" exit 1.\n // Swallow to the not-provisioned hint.\n let cfg: ReturnType<typeof readConfig>;\n let entry: ReturnType<typeof readModuleEntry>;\n try {\n cfg = readConfig();\n entry = readModuleEntry(consumerSlug);\n } catch {\n cfg = null;\n entry = null;\n }\n if (!cfg || !entry) {\n // No dev install cached → nothing to reconcile against yet.\n info(\n `Once provisioned (${code('dashwise init')}) + pushed (${code('dashwise dev')}), run ${code('dashwise deps')} to see whether ${code(providerSlug)} resolves or parks.`,\n );\n return;\n }\n\n const requestOptions: RequestOptions = {\n baseUrl: resolveApiUrl(),\n auth: { token: cfg.token },\n };\n\n try {\n const deps = await getInstallationDependencies(entry.installationId, requestOptions);\n const match = deps.find((d) => d.slug === providerSlug);\n if (!match) {\n // The manifest edit hasn't been pushed to the dev install yet, so the\n // backend has no row for it. It reconciles on the next push.\n info(\n `${code(providerSlug)} isn't reconciled server-side yet. Push the manifest (${code('dashwise dev')} watches + applies it) — then ${code('dashwise deps')} shows its resolve/park status.`,\n );\n return;\n }\n if (match.status === 'resolved') {\n const providerLine =\n match.provider != null\n ? ` (${dim(`provider install #${match.provider.installation_id} @ v${match.provider.version}`)})`\n : '';\n out(` ${pc.green('● resolved')}${providerLine}`);\n } else {\n out(` ${pc.yellow('○ unbound')} ${dim('reason:')} ${match.reason ?? dim('(unspecified)')}`);\n info(\n `Declared but not connected. Install the provider in this workspace, then ${code(`dashwise deps bind ${providerSlug}`)} — reads return ${code('DEP_UNBOUND')} until it's bound.`,\n );\n }\n } catch (err) {\n // Soft-fail: the connect surface is additive. An old backend without\n // the D4 endpoint, a 401, or a network blip must not turn a successful\n // manifest edit into a failure.\n if (err instanceof ApiError && err.status === 401) {\n info(`(Skipped connect-status check — CLI token stale; run ${code('dashwise login')} to refresh.)`);\n } else {\n info(\n `(Couldn't fetch connect status right now — run ${code('dashwise deps')} later to see whether ${code(providerSlug)} resolves or parks.)`,\n );\n }\n }\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────\n\ninterface NormalizedReadEntry {\n table: string;\n fields: string[];\n}\n\nasync function collectInteractive(\n providerSlug: string,\n summary: ProviderManifestSummary | null,\n resolvedVersion: string | null,\n options: DepsAddOptions,\n): Promise<ManifestDependency | null> {\n const reads: NormalizedReadEntry[] = [];\n\n if (summary && summary.exposes && summary.exposes.length > 0) {\n // Backend-assisted: present the actual exposes set.\n info(\n `Provider exposes ${summary.exposes.length} table${summary.exposes.length === 1 ? '' : 's'}.`,\n );\n // Filter to tables the provider actually allows `list` or `get` on\n // (others are visible-but-unreadable from a SDK perspective).\n const readableTables = summary.exposes.filter((e) => {\n const ops = e.operations;\n if (!ops) return true; // back-compat: no operations block = implicit allow\n return ops.list?.allowed === true || ops.get?.allowed === true;\n });\n if (readableTables.length === 0) {\n warn(\n `Provider ${code(providerSlug)} exposes tables but none are readable (operations.list / .get all denied).`,\n );\n return null;\n }\n\n const picked = await multiselect({\n message: 'Which tables do you want to read from?',\n options: readableTables.map((e) => ({\n value: e.table,\n label: `${e.table} ${dim(`(${e.fields.length} field${e.fields.length === 1 ? '' : 's'})`)}`,\n })),\n required: true,\n });\n if (isCancel(picked)) return null;\n\n for (const tableSlug of picked as string[]) {\n const exposeEntry = readableTables.find((e) => e.table === tableSlug)!;\n const fieldsPicked = await multiselect({\n message: `Fields to read from ${code(tableSlug)}:`,\n options: exposeEntry.fields.map((f) => ({ value: f, label: f })),\n required: true,\n initialValues: exposeEntry.fields, // pre-select all; user trims down\n });\n if (isCancel(fieldsPicked)) return null;\n reads.push({ table: tableSlug, fields: fieldsPicked as string[] });\n }\n } else {\n // Manual fallback when no backend summary is available.\n info('No provider summary available — enter table + fields manually.');\n const tableSlug = await text({\n message: 'Provider table slug to read from:',\n placeholder: 'contacts',\n validate: (v) =>\n /^[a-z][a-z0-9_]*[a-z0-9]$/.test(v) ? undefined : 'Table slugs are snake_case.',\n });\n if (isCancel(tableSlug)) return null;\n const fieldsStr = await text({\n message: 'Comma-separated field slugs:',\n placeholder: 'name, email, company',\n validate: (v) =>\n v.split(',').map((s) => s.trim()).filter(Boolean).length > 0\n ? undefined\n : 'At least one field required.',\n });\n if (isCancel(fieldsStr)) return null;\n reads.push({\n table: tableSlug as string,\n fields: (fieldsStr as string)\n .split(',')\n .map((s) => s.trim())\n .filter(Boolean),\n });\n }\n\n // Purpose — manifest validator requires 10-500 chars.\n const initialPurpose = options.purpose ?? '';\n const purpose = await text({\n message: `Why does your module need this dependency? ${dim(`(${MIN_PURPOSE_LEN}-${MAX_PURPOSE_LEN} chars; shown to workspace admins at install consent)`)}`,\n placeholder: 'Look up assignee contact info when rendering tasks.',\n initialValue: initialPurpose,\n validate: (v) => validatePurpose(v) ?? undefined,\n });\n if (isCancel(purpose)) return null;\n\n // Version range — default to `^<resolved>` for stability.\n const defaultVersion =\n options.version ?? (resolvedVersion ? `^${resolvedVersion}` : '^0.0.1');\n const version = await text({\n message: `SemVer range to pin: ${dim('(npm-style; e.g. ^1.2.3, ~1.2.0, >=1.0.0)')}`,\n placeholder: defaultVersion,\n initialValue: defaultVersion,\n validate: (v) =>\n /^[\\^~]?[0-9]+\\.[0-9]+\\.[0-9]+(-[a-zA-Z0-9.-]+)?$/.test(v) ||\n /^(>=|<=|>|<|=)?[0-9]+\\.[0-9]+\\.[0-9]+(-[a-zA-Z0-9.-]+)?$/.test(v)\n ? undefined\n : 'Must be a npm-style semver range (e.g. ^1.2.3).',\n });\n if (isCancel(version)) return null;\n\n return {\n module: providerSlug,\n version: version as string,\n reads,\n purpose: purpose as string,\n };\n}\n\nfunction validatePurpose(purpose: string): string | null {\n if (typeof purpose !== 'string') return 'Purpose must be a string.';\n if (purpose.length < MIN_PURPOSE_LEN) {\n return `Purpose must be at least ${MIN_PURPOSE_LEN} characters; got ${purpose.length}.`;\n }\n if (purpose.length > MAX_PURPOSE_LEN) {\n return `Purpose must be at most ${MAX_PURPOSE_LEN} characters; got ${purpose.length}.`;\n }\n return null;\n}\n","/**\n * `dashwise deps check` — verify each declared dep still resolves\n * against a currently-published provider and that every field /\n * operation in the contract is still exposed.\n *\n * Exit code:\n * 0 — all deps healthy\n * 1 — at least one drift issue found\n *\n * Reports per-dep issues with a clear next step:\n * - PROVIDER_NOT_FOUND → the provider was deleted or renamed\n * - NO_MATCHING_VERSION → no published version satisfies the SemVer range\n * - FIELD_NOT_EXPOSED → consumer reads a field the provider no longer exposes\n * - OP_NOT_ALLOWED → consumer declares writes the provider blocks (writes opt-in)\n *\n * Backend reachability is required — `check` is an online command by\n * design. If the backend is unreachable, exit 1 with a clear message\n * (CI workflows can catch this + retry).\n *\n * Spec: dashwise-devops-docs/plans/modules-sdk-query-v1.md §9.\n */\n\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport {\n readManifestOrThrow,\n type ManifestDependency,\n} from '../../lib/manifest-io.js';\nimport { code, dim, fail, info, out, success, warn } from '../../lib/output.js';\n\nexport interface DepsCheckOptions {\n dir?: string;\n json?: boolean;\n}\n\ninterface ProviderManifestSummary {\n exposes?: Array<{\n table: string;\n fields: string[];\n operations?: Partial<\n Record<\n 'list' | 'get' | 'search' | 'create' | 'update' | 'delete',\n { allowed?: boolean }\n >\n >;\n }>;\n}\n\ninterface ModuleByslugResponse {\n id: number;\n slug: string;\n current_version: string | null;\n}\n\ninterface VersionResponse {\n id: number;\n version: string;\n manifest_jsonb: ProviderManifestSummary;\n}\n\ninterface Issue {\n /** Stable code so JSON consumers can branch. */\n code:\n | 'PROVIDER_NOT_FOUND'\n | 'NO_MATCHING_VERSION'\n | 'FIELD_NOT_EXPOSED'\n | 'TABLE_NOT_EXPOSED'\n | 'OP_NOT_ALLOWED'\n | 'BACKEND_UNREACHABLE';\n module: string;\n message: string;\n context?: Record<string, unknown>;\n}\n\nexport async function depsCheckCommand(options: DepsCheckOptions): Promise<number> {\n let manifest;\n try {\n manifest = readManifestOrThrow(options.dir);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n const deps: ManifestDependency[] = manifest.dependencies ?? [];\n if (deps.length === 0) {\n if (options.json) {\n out(JSON.stringify({ ok: true, deps: [], issues: [] }, null, 2));\n } else {\n info('No dependencies declared. Nothing to check.');\n }\n return 0;\n }\n\n const issues: Issue[] = [];\n const perDepStatus: Array<{ module: string; ok: boolean; resolved_version: string | null }> = [];\n\n for (const dep of deps) {\n let mod: ModuleByslugResponse;\n try {\n mod = await apiRequest<ModuleByslugResponse>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(dep.module)}`,\n );\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n issues.push({\n code: 'PROVIDER_NOT_FOUND',\n module: dep.module,\n message: `Provider ${dep.module} not found on the backend. It may have been deleted or renamed.`,\n });\n perDepStatus.push({ module: dep.module, ok: false, resolved_version: null });\n continue;\n }\n if (err instanceof ApiError && err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n // Network / 500 / etc. — treat as fatal; we can't reason about\n // drift without an answer from the backend.\n issues.push({\n code: 'BACKEND_UNREACHABLE',\n module: dep.module,\n message: `Could not reach the backend: ${(err as Error).message}`,\n });\n perDepStatus.push({ module: dep.module, ok: false, resolved_version: null });\n continue;\n }\n\n // Pick the highest-matching version (newest-first per the\n // listVersions controller spec).\n let versions: VersionResponse[];\n try {\n versions = await apiRequest<VersionResponse[]>(\n 'GET',\n `/api/modules/${mod.id}/versions`,\n );\n } catch (err) {\n issues.push({\n code: 'BACKEND_UNREACHABLE',\n module: dep.module,\n message: `Could not list versions: ${(err as Error).message}`,\n });\n perDepStatus.push({ module: dep.module, ok: false, resolved_version: null });\n continue;\n }\n\n const matching = pickMatching(versions, dep.version);\n if (!matching) {\n issues.push({\n code: 'NO_MATCHING_VERSION',\n module: dep.module,\n message: `No published version satisfies ${dep.version}. Available: ${versions.map((v) => v.version).join(', ') || '(none)'}.`,\n context: { range: dep.version, available: versions.map((v) => v.version) },\n });\n perDepStatus.push({ module: dep.module, ok: false, resolved_version: null });\n continue;\n }\n\n // Drift checks against the matching version's manifest.\n const exposes = matching.manifest_jsonb.exposes ?? [];\n let depHealthy = true;\n\n for (const readEntry of dep.reads) {\n const exposeEntry = exposes.find((e) => e.table === readEntry.table);\n if (!exposeEntry) {\n issues.push({\n code: 'TABLE_NOT_EXPOSED',\n module: dep.module,\n message: `Table ${code(readEntry.table)} is no longer exposed by ${dep.module}@${matching.version}.`,\n context: { table: readEntry.table, resolved_version: matching.version },\n });\n depHealthy = false;\n continue;\n }\n const exposedFields = new Set(exposeEntry.fields);\n const missing = readEntry.fields.filter((f) => !exposedFields.has(f));\n if (missing.length > 0) {\n issues.push({\n code: 'FIELD_NOT_EXPOSED',\n module: dep.module,\n message: `Fields ${missing.map((f) => code(f)).join(', ')} on ${code(readEntry.table)} are no longer exposed by ${dep.module}@${matching.version}.`,\n context: {\n table: readEntry.table,\n missing,\n resolved_version: matching.version,\n },\n });\n depHealthy = false;\n }\n // Operation gate for list/get — we don't include search here since\n // the SDK doesn't expose it and the v1 plan doesn't either.\n const listAllowed = exposeEntry.operations?.list?.allowed !== false;\n const getAllowed = exposeEntry.operations?.get?.allowed !== false;\n if (!listAllowed && !getAllowed) {\n issues.push({\n code: 'OP_NOT_ALLOWED',\n module: dep.module,\n message: `Provider ${dep.module}@${matching.version} disallows both list AND get on ${code(readEntry.table)} — no reads possible.`,\n context: { table: readEntry.table, resolved_version: matching.version },\n });\n depHealthy = false;\n }\n }\n\n // Write-side drift (only flagged when consumer declared writes).\n for (const writeEntry of dep.writes ?? []) {\n const exposeEntry = exposes.find((e) => e.table === writeEntry.table);\n if (!exposeEntry) continue; // already flagged via reads loop\n for (const op of writeEntry.operations) {\n const gate = exposeEntry.operations?.[op as 'create' | 'update' | 'delete'];\n if (!gate || gate.allowed !== true) {\n issues.push({\n code: 'OP_NOT_ALLOWED',\n module: dep.module,\n message: `Write operation ${code(op)} on ${code(writeEntry.table)} is not allowed by ${dep.module}@${matching.version}.`,\n context: {\n table: writeEntry.table,\n operation: op,\n resolved_version: matching.version,\n },\n });\n depHealthy = false;\n }\n }\n }\n\n perDepStatus.push({\n module: dep.module,\n ok: depHealthy,\n resolved_version: matching.version,\n });\n }\n\n const ok = issues.length === 0;\n\n if (options.json) {\n out(\n JSON.stringify(\n { ok, deps: perDepStatus, issues },\n null,\n 2,\n ),\n );\n return ok ? 0 : 1;\n }\n\n // Human-readable output.\n for (const dep of perDepStatus) {\n if (dep.ok) {\n success(\n `${code(dep.module)} → ${dep.resolved_version ? `v${dep.resolved_version}` : dim('(no version)')}`,\n );\n } else {\n fail(`${code(dep.module)} ${dim('(drift detected)')}`);\n }\n }\n if (issues.length > 0) {\n out('');\n warn(`${issues.length} issue${issues.length === 1 ? '' : 's'}:`);\n for (const issue of issues) {\n out(` ${dim(`[${issue.code}]`)} ${issue.message}`);\n }\n out('');\n info(\n `Fix by removing/updating the dep (${code('dashwise deps remove <slug>')} then ${code('dashwise deps add <slug>')}) or by updating the provider.`,\n );\n } else {\n out('');\n success(`All ${perDepStatus.length} dependenc${perDepStatus.length === 1 ? 'y is' : 'ies are'} healthy.`);\n }\n return ok ? 0 : 1;\n}\n\n/**\n * Pick the newest version satisfying `range`. Range parsing is\n * intentionally minimal — covers `^x.y.z`, `~x.y.z`, `>=x.y.z`,\n * `<=x.y.z`, `>x.y.z`, `<x.y.z`, `=x.y.z`, and bare `x.y.z`. Full\n * SemVer support lives in the backend; this is a fail-soft heuristic\n * so check can give useful feedback even when offline tooling is the\n * canonical resolver.\n *\n * Caller passes `versions` in newest-first order (matches the\n * backend's `GET /:id/versions` contract).\n */\nfunction pickMatching(\n versions: VersionResponse[],\n range: string,\n): VersionResponse | null {\n for (const v of versions) {\n if (rangeSatisfied(v.version, range)) return v;\n }\n return null;\n}\n\nfunction rangeSatisfied(version: string, range: string): boolean {\n const vParts = parseSemver(version);\n if (!vParts) return false;\n const trimmed = range.trim();\n const opMatch = trimmed.match(/^(>=|<=|>|<|=|\\^|~)?(.+)$/);\n if (!opMatch) return false;\n const op = opMatch[1] ?? '=';\n const target = parseSemver(opMatch[2]);\n if (!target) return false;\n const cmp = compareSemver(vParts, target);\n switch (op) {\n case '=':\n return cmp === 0;\n case '>':\n return cmp > 0;\n case '<':\n return cmp < 0;\n case '>=':\n return cmp >= 0;\n case '<=':\n return cmp <= 0;\n case '^':\n // ^1.2.3 → >=1.2.3 <2.0.0 ; ^0.2.3 → >=0.2.3 <0.3.0 ; ^0.0.3 → >=0.0.3 <0.0.4\n if (cmp < 0) return false;\n if (target[0] > 0) return vParts[0] === target[0];\n if (target[1] > 0) return vParts[0] === 0 && vParts[1] === target[1];\n return vParts[0] === 0 && vParts[1] === 0 && vParts[2] === target[2];\n case '~':\n // ~1.2.3 → >=1.2.3 <1.3.0\n if (cmp < 0) return false;\n return vParts[0] === target[0] && vParts[1] === target[1];\n default:\n return false;\n }\n}\n\nfunction parseSemver(s: string): [number, number, number] | null {\n const m = s.trim().match(/^(\\d+)\\.(\\d+)\\.(\\d+)(?:-[a-zA-Z0-9.-]+)?$/);\n if (!m) return null;\n return [Number(m[1]), Number(m[2]), Number(m[3])];\n}\n\nfunction compareSemver(a: [number, number, number], b: [number, number, number]): number {\n for (let i = 0; i < 3; i++) {\n if (a[i] !== b[i]) return a[i] - b[i];\n }\n return 0;\n}\n\n/**\n * Test seam — expose internal helpers for unit tests without making\n * them part of the CLI's public surface. Same pattern as\n * `lib/tarball.ts#__forTests`.\n */\nexport const __forTests = {\n rangeSatisfied,\n pickMatching,\n parseSemver,\n compareSemver,\n};\n","/**\n * `dashwise deps list` — show declared cross-module dependencies.\n *\n * Pure-local read from `module.json#dependencies`. No backend call;\n * runs offline. For drift detection (does each declared dep still\n * resolve against an installed provider?) use `dashwise deps check`.\n *\n * Output shapes:\n * - Default: human-readable columns + per-dep `reads:` / `writes:`\n * summaries.\n * - `--json`: stable JSON array of `{ module, version, reads,\n * writes?, purpose }` — same shape as the manifest's\n * `dependencies[]` entries. Pipes cleanly into `jq`.\n *\n * Spec: dashwise-devops-docs/plans/modules-sdk-query-v1.md §9.\n */\n\nimport { readManifestOrThrow, type ManifestDependency } from '../../lib/manifest-io.js';\nimport { code, dim, fail, info, out } from '../../lib/output.js';\n\nexport interface DepsListOptions {\n dir?: string;\n json?: boolean;\n}\n\nexport async function depsListCommand(options: DepsListOptions): Promise<number> {\n let manifest;\n try {\n manifest = readManifestOrThrow(options.dir);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n const deps: ManifestDependency[] = manifest.dependencies ?? [];\n\n if (options.json) {\n // Stable, pipe-friendly. Empty deps list → empty array (not null);\n // jq consumers don't have to handle the absent-key case.\n out(JSON.stringify(deps, null, 2));\n return 0;\n }\n\n if (deps.length === 0) {\n info('No dependencies declared in module.json.');\n info(`Run ${code('dashwise deps add <provider-slug>')} to add one.`);\n return 0;\n }\n\n out(`${deps.length} dependenc${deps.length === 1 ? 'y' : 'ies'} declared:`);\n out('');\n for (const dep of deps) {\n out(` ${code(dep.module)}@${dep.version}`);\n out(` ${dim('purpose:')} ${dep.purpose}`);\n if (dep.reads.length > 0) {\n out(` ${dim('reads:')}`);\n for (const r of dep.reads) {\n out(` ${code(r.table)} → ${r.fields.join(', ')}`);\n }\n }\n if (dep.writes && dep.writes.length > 0) {\n out(` ${dim('writes:')}`);\n for (const w of dep.writes) {\n out(\n ` ${code(w.table)} → ${w.fields.join(', ')} (${w.operations.join('/')})`,\n );\n }\n }\n out('');\n }\n return 0;\n}\n","/**\n * `dashwise deps remove <provider-slug>` — delete the dep entry from\n * `module.json#dependencies`.\n *\n * Pure-local mutation. Idempotent: removing a slug that's not declared\n * is treated as a no-op + reported (exit 0). Confirmation prompt\n * unless `--yes` is passed.\n *\n * After successful removal, prints a reminder to re-run\n * `dashwise module generate` so the typed wrappers no longer reference\n * the removed dep. (Generated `deps.<member>` access becomes a\n * compile error in consumer code — that's the right surface to catch\n * stale references.)\n */\n\nimport { isCancel, select } from '@clack/prompts';\nimport {\n readManifestOrThrow,\n writeManifest,\n type ManifestDependency,\n} from '../../lib/manifest-io.js';\nimport { code, fail, info, success } from '../../lib/output.js';\n\nexport interface DepsRemoveOptions {\n dir?: string;\n /** Skip the confirmation prompt (CI / scripts). */\n yes?: boolean;\n}\n\nexport async function depsRemoveCommand(\n providerSlug: string,\n options: DepsRemoveOptions,\n): Promise<number> {\n if (!providerSlug || typeof providerSlug !== 'string') {\n fail('Usage: `dashwise deps remove <provider-slug>`');\n return 1;\n }\n\n let manifest;\n try {\n manifest = readManifestOrThrow(options.dir);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n const deps: ManifestDependency[] = manifest.dependencies ?? [];\n const target = deps.find((d) => d.module === providerSlug);\n if (!target) {\n // Idempotent — not an error. Mirrors `apt remove` / `npm uninstall`\n // semantics for \"wasn't installed anyway.\"\n info(`No dependency on ${code(providerSlug)} declared; nothing to remove.`);\n return 0;\n }\n\n if (!options.yes && process.stdout.isTTY) {\n const answer = await select({\n message: `Remove dependency on ${providerSlug}?`,\n options: [\n { value: 'go', label: 'Yes, remove it' },\n { value: 'cancel', label: 'No, keep it' },\n ],\n initialValue: 'go',\n });\n if (isCancel(answer) || answer === 'cancel') {\n info('Aborted.');\n return 130;\n }\n }\n\n manifest.dependencies = deps.filter((d) => d.module !== providerSlug);\n // Normalize: if the array became empty, drop the key entirely so the\n // manifest matches what `dashwise module init` emits for a fresh\n // module (no `dependencies` key at all).\n if ((manifest.dependencies as ManifestDependency[]).length === 0) {\n delete manifest.dependencies;\n }\n\n try {\n writeManifest(manifest, options.dir);\n } catch (err) {\n fail(`Could not write manifest: ${(err as Error).message}`);\n return 1;\n }\n\n success(`Removed dependency on ${code(providerSlug)}.`);\n info(`Run ${code('dashwise module generate')} to refresh typed wrappers.`);\n return 0;\n}\n","/**\n * P3-C — cross-module dependency CONNECT surface commands.\n *\n * Phase 3 (modules-platform-v2) reworks cross-module deps to\n * \"park-not-reject\": a declared dependency that can't bind to a provider\n * (no provider install in the workspace, version mismatch, exposes/action\n * coverage gap, kind hygiene) is PARKED as a `module_dependencies` row\n * with `status='unbound'` rather than failing the install. These commands\n * are the author/operator surface over those rows:\n *\n * - `dashwise deps` list the live connect status (D4 GET)\n * - `dashwise deps bind <slug>` (re-)connect a parked dep (D4 bind)\n * - `dashwise deps unbind <slug>` disconnect a bound dep (D4 unbind)\n *\n * Unlike `dashwise deps list` / `dashwise deps check` (which read the\n * LOCAL manifest / probe published providers), these hit the backend's\n * per-installation dependency state — the source of truth for whether a\n * runtime dep read will succeed or 409 with `DEP_UNBOUND`.\n *\n * Auth: the user's CLI bearer (JWT). Listing needs workspace membership;\n * bind/unbind need workspace-admin. The install id is resolved from the\n * current `module.json#module.slug` + `auth.json#modules[<slug>]`, so the\n * user never types it. Same install-resolution + error-mapping shape as\n * `dashwise origins`.\n */\n\nimport {\n ApiError,\n bindDependency,\n getInstallationDependencies,\n unbindDependency,\n type InstallationDependency,\n type RequestOptions,\n} from '../../lib/api-client.js';\nimport { readConfig, readModuleEntry, resolveApiUrl } from '../../lib/config.js';\nimport { readManifestOrThrow } from '../../lib/manifest-io.js';\nimport { code, dim, fail, info, out, pc, success, warn } from '../../lib/output.js';\n\ninterface CommonOptions {\n dir?: string;\n}\n\ninterface ResolvedContext {\n installationId: number;\n slug: string;\n requestOptions: RequestOptions;\n}\n\n/**\n * Shared setup: resolve the slug + install id from the current project\n * dir + auth.json, build a JWT-authed RequestOptions. Mirrors\n * `origins.ts#loadContext`. Errors thrown as plain `Error`; callers\n * `catch` + `fail(err.message)` + return 1.\n */\nfunction loadContext(opts: CommonOptions): ResolvedContext {\n const manifest = readManifestOrThrow(opts.dir);\n const slug = manifest.module?.slug;\n if (!slug) {\n throw new Error('module.json has no module.slug — the manifest is malformed.');\n }\n const cfg = readConfig();\n if (!cfg) {\n throw new Error('Not logged in. Run `dashwise login` first.');\n }\n const entry = readModuleEntry(slug);\n if (!entry) {\n throw new Error(\n `No dev install cached for module \"${slug}\". Run \\`dashwise init ${slug} --force\\` to provision one.`,\n );\n }\n return {\n installationId: entry.installationId,\n slug,\n requestOptions: {\n baseUrl: resolveApiUrl(),\n auth: { token: cfg.token },\n },\n };\n}\n\n/**\n * Render a `resolved` / `unbound` status chip. Colored so a wall of deps\n * is scannable; the raw word is preserved for `--json` / non-TTY.\n */\nfunction statusChip(status: string): string {\n if (status === 'resolved') return pc.green('● resolved');\n if (status === 'unbound') return pc.yellow('○ unbound');\n // Forward-compat: a status the CLI doesn't know — show it verbatim.\n return pc.dim(`? ${status}`);\n}\n\n// ── `dashwise deps` (connect-surface list, D4 GET) ─────────────────────\n\nexport interface DepsConnectListOptions extends CommonOptions {\n json?: boolean;\n}\n\n/**\n * Render the D4 `GET /api/installations/:id/dependencies` response — the\n * live connect status of every declared dependency on the current\n * module's installation.\n */\nexport async function depsConnectListCommand(\n options: DepsConnectListOptions,\n): Promise<number> {\n let ctx: ResolvedContext;\n try {\n ctx = loadContext(options);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n let deps: InstallationDependency[];\n try {\n deps = await getInstallationDependencies(ctx.installationId, ctx.requestOptions);\n } catch (err) {\n return surfaceDepError(err);\n }\n\n if (options.json) {\n out(JSON.stringify(deps, null, 2));\n return 0;\n }\n\n if (deps.length === 0) {\n info(`No cross-module dependencies declared for ${code(ctx.slug)}.`);\n info(`Add one with ${code('dashwise deps add <provider-slug>')}.`);\n return 0;\n }\n\n const unbound = deps.filter((d) => d.status === 'unbound').length;\n info(\n `Cross-module dependencies for ${code(ctx.slug)} ${dim(\n `(${deps.length} declared${unbound > 0 ? `, ${unbound} unbound` : ''})`,\n )}:`,\n );\n out('');\n for (const dep of deps) {\n out(` ${statusChip(dep.status)} ${code(dep.slug)}@${dep.range ?? '*'}`);\n if (dep.status === 'resolved' && dep.provider) {\n out(\n ` ${dim('provider:')} install #${dep.provider.installation_id} @ v${dep.provider.version}`,\n );\n }\n if (dep.status === 'unbound') {\n out(` ${dim('reason:')} ${dep.reason ?? dim('(unspecified)')}`);\n }\n out('');\n }\n if (unbound > 0) {\n info(\n `Connect a parked dep with ${code('dashwise deps bind <provider-slug>')} once its provider is installed.`,\n );\n }\n return 0;\n}\n\n// ── `dashwise deps bind <slug>` (D4 bind) ──────────────────────────────\n\nexport interface DepsBindOptions extends CommonOptions {\n /** Optional provider installation id to disambiguate multiple candidates. */\n installation?: number;\n}\n\nexport async function depsBindCommand(\n providerSlug: string,\n options: DepsBindOptions,\n): Promise<number> {\n if (!providerSlug || typeof providerSlug !== 'string') {\n fail('Usage: `dashwise deps bind <provider-slug> [--installation <id>]`');\n return 1;\n }\n\n let ctx: ResolvedContext;\n try {\n ctx = loadContext(options);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n try {\n const result = await bindDependency(\n ctx.installationId,\n providerSlug,\n options.installation !== undefined\n ? { provider_installation_id: options.installation }\n : {},\n ctx.requestOptions,\n );\n const providerLine =\n result.provider != null\n ? ` → install #${result.provider.installation_id} @ v${result.provider.version}`\n : '';\n success(`Bound ${code(providerSlug)} for ${code(ctx.slug)}${providerLine}.`);\n info('Runtime reads against this dependency will now succeed.');\n return 0;\n } catch (err) {\n // Bind failure → 409 with the park reason as the error code; the row\n // stays unbound. Surface it with a clear next step.\n return surfaceBindError(err, providerSlug, ctx.slug);\n }\n}\n\n// ── `dashwise deps unbind <slug>` (D4 unbind) ──────────────────────────\n\nexport async function depsUnbindCommand(\n providerSlug: string,\n options: CommonOptions,\n): Promise<number> {\n if (!providerSlug || typeof providerSlug !== 'string') {\n fail('Usage: `dashwise deps unbind <provider-slug>`');\n return 1;\n }\n\n let ctx: ResolvedContext;\n try {\n ctx = loadContext(options);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n try {\n await unbindDependency(ctx.installationId, providerSlug, ctx.requestOptions);\n success(`Unbound ${code(providerSlug)} for ${code(ctx.slug)}.`);\n warn(\n `Runtime reads against this dependency now return ${code('DEP_UNBOUND')} until you ${code('dashwise deps bind')} it again.`,\n );\n return 0;\n } catch (err) {\n return surfaceDepError(err);\n }\n}\n\n// ── error mapping ──────────────────────────────────────────────────────\n\n/**\n * Map a bind-endpoint failure. The 409 body carries the resolver's park\n * reason as `code`; translate the common ones to an actionable hint.\n */\nfunction surfaceBindError(\n err: unknown,\n providerSlug: string,\n consumerSlug: string,\n): number {\n if (err instanceof ApiError) {\n // The resolver's park reasons come back as the error code on a 409.\n switch (err.code) {\n case 'MISSING_DEPENDENCY':\n fail(\n `No installation of ${code(providerSlug)} found in ${code(consumerSlug)}'s workspace. Install the provider module first, then re-run ${code(`dashwise deps bind ${providerSlug}`)}.`,\n );\n return 1;\n case 'DEPENDENCY_VERSION_MISMATCH':\n fail(\n `The installed ${code(providerSlug)} version is outside your declared range (${err.message}). Update the range in module.json (${code(`dashwise deps add ${providerSlug}`)}) or upgrade the provider install.`,\n );\n return 1;\n case 'PROVIDER_VERSION_RECORD_MISSING':\n fail(\n `The provider ${code(providerSlug)}'s version record is missing (${err.message}). This is a provider-side data issue — the provider may need to re-publish.`,\n );\n return 1;\n case 'EXPOSES_MISSING':\n fail(\n `${code(providerSlug)} no longer exposes a table/field your dependency reads (${err.message}). Trim your ${code('reads[]')} or ask the provider to re-expose it.`,\n );\n return 1;\n case 'EXPOSES_PRIVATE':\n fail(\n `${code(providerSlug)} exposes the requested surface as ${code('private')} — it can't be read by depending modules (${err.message}).`,\n );\n return 1;\n case 'ACTION_NOT_EXPOSED':\n fail(\n `A cross-module action your dependency declares isn't exposed by ${code(providerSlug)} (${err.message}). Remove it from your dep's ${code('actions[]')} or ask the provider to expose it.`,\n );\n return 1;\n case 'PROVIDER_NOT_PRODUCTION':\n fail(\n `A production install can only bind to a production provider install; the available ${code(providerSlug)} install isn't production (${err.message}).`,\n );\n return 1;\n case 'DEPENDENCY_NOT_DECLARED':\n fail(\n `${code(consumerSlug)}'s module.json doesn't declare a dependency on ${code(providerSlug)}. Add it with ${code(`dashwise deps add ${providerSlug}`)} + push the manifest first.`,\n );\n return 1;\n default:\n // Any other park reason / generic error — show the code + message.\n fail(\n `Could not bind ${code(providerSlug)}: ${err.code}${err.message ? ` — ${err.message}` : ''}. The dependency stays unbound.`,\n );\n return 1;\n }\n }\n fail(`Bind failed: ${(err as Error).message}`);\n return 1;\n}\n\n/**\n * Generic dependency-endpoint error mapping (list + unbind). Bind has its\n * own richer mapping in {@link surfaceBindError}.\n */\nfunction surfaceDepError(err: unknown): number {\n if (err instanceof ApiError) {\n switch (err.code) {\n case 'UNAUTHENTICATED':\n fail(\n `Auth rejected by backend. Your CLI token may be stale — run ${code('dashwise login')} then retry.`,\n );\n return 1;\n case 'NOT_WORKSPACE_MEMBER':\n fail(\n `You're not a member of this installation's workspace. Dependency management requires workspace membership.`,\n );\n return 1;\n case 'NOT_WORKSPACE_ADMIN':\n case 'FORBIDDEN':\n fail(\n `Not authorized. Binding / unbinding dependencies requires workspace-admin.`,\n );\n return 1;\n case 'INSTALLATION_NOT_FOUND':\n fail(\n `Installation not found. It may have been destroyed; re-provision via ${code('dashwise init <slug>')}.`,\n );\n return 1;\n case 'DEPENDENCY_NOT_DECLARED':\n fail(\n `No such dependency declared in this module's manifest. Run ${code('dashwise deps')} to see declared deps.`,\n );\n return 1;\n default:\n fail(`Backend rejected: ${err.code} ${err.status} — ${err.message}`);\n return 1;\n }\n }\n fail(`Dependency operation failed: ${(err as Error).message}`);\n return 1;\n}\n","/**\n * P4-C — the `dashwise bind` family: the workspace-table `uses`\n * developer loop.\n *\n * Phase 4 (modules-platform-v2) adds the `uses` plane — a module reads +\n * writes a WORKSPACE table the workspace already owns (declared in\n * `module.json#uses[].tables[]`). Each declared slot is BOUND to a\n * physical workspace table via a `field_map`. These commands are the\n * author/operator surface over those `module_table_bindings` rows:\n *\n * - `dashwise bind` list the live binding status (U4 GET)\n * - `dashwise bind <slug>` [--table N] (re-)bind a slot to a workspace table\n * - `dashwise bind <slug> --create` materialize + bind a fresh table\n * - `dashwise bind <slug> --decline` decline an optional-needs slot\n * - `dashwise unbind <slug>` disconnect a bound slot\n *\n * The `bind <slug>` path resolves candidates via the U4 candidates\n * endpoint: with `--table` it picks the named/id'd candidate (script\n * mode); interactively it prompts when the match is ambiguous. `--map\n * <usesField>=<physicalFieldName>` overrides individual field mappings;\n * the server auto-completes the rest by name match.\n *\n * Auth: the user's CLI bearer (JWT). Listing needs workspace membership;\n * bind/unbind/decline need workspace-admin. The install id is resolved\n * from `module.json#module.slug` + `auth.json#modules[<slug>]`, so the\n * user never types it — same install-resolution + error-mapping shape as\n * `dashwise deps` / `dashwise origins`.\n */\n\nimport { isCancel, select } from '@clack/prompts';\nimport {\n ApiError,\n getBindingCandidates,\n getInstallationBindings,\n introspectWorkspaceTable,\n putBinding,\n unbindBinding,\n declineBinding,\n type BindingCandidate,\n type InstallationBinding,\n type RequestOptions,\n} from '../../lib/api-client.js';\nimport { readConfig, readModuleEntry, resolveApiUrl } from '../../lib/config.js';\nimport {\n readManifestOrThrow,\n type ManifestUsesTable,\n} from '../../lib/manifest-io.js';\nimport { code, dim, fail, info, out, pc, success, warn } from '../../lib/output.js';\n\ninterface CommonOptions {\n dir?: string;\n}\n\ninterface ResolvedContext {\n installationId: number;\n slug: string;\n /** Project dir the manifest was read from (for re-reading `uses` slots). */\n dir?: string;\n requestOptions: RequestOptions;\n}\n\n/**\n * Shared setup: resolve the module slug + install id from the current\n * project dir + auth.json, build a JWT-authed RequestOptions. Mirrors\n * `deps/connect.ts#loadContext`. Errors thrown as plain `Error`; callers\n * `catch` + `fail(err.message)` + return 1.\n */\nfunction loadContext(opts: CommonOptions): ResolvedContext {\n const manifest = readManifestOrThrow(opts.dir);\n const slug = manifest.module?.slug;\n if (!slug) {\n throw new Error('module.json has no module.slug — the manifest is malformed.');\n }\n const cfg = readConfig();\n if (!cfg) {\n throw new Error('Not logged in. Run `dashwise login` first.');\n }\n const entry = readModuleEntry(slug);\n if (!entry) {\n throw new Error(\n `No dev install cached for module \"${slug}\". Run \\`dashwise init ${slug} --force\\` to provision one.`,\n );\n }\n return {\n installationId: entry.installationId,\n slug,\n ...(opts.dir !== undefined ? { dir: opts.dir } : {}),\n requestOptions: {\n baseUrl: resolveApiUrl(),\n auth: { token: cfg.token },\n },\n };\n}\n\n/**\n * Render a `bound` / `unbound` / `declined` status chip. Colored so a\n * wall of slots is scannable; the raw word is preserved for `--json` /\n * non-TTY consumers who read the JSON path.\n */\nfunction statusChip(status: string): string {\n if (status === 'bound') return pc.green('● bound');\n if (status === 'unbound') return pc.yellow('○ unbound');\n if (status === 'declined') return pc.dim('⊘ declined');\n // Forward-compat: a status the CLI doesn't know — show it verbatim.\n return pc.dim(`? ${status}`);\n}\n\n/** Human-readable ops summary, e.g. `read, update`. */\nfunction opsLine(ops: string[]): string {\n return ops.length > 0 ? ops.join(', ') : dim('(none)');\n}\n\n// ── `dashwise bind` (binding-surface list, U4 GET) ─────────────────────\n\nexport interface BindListOptions extends CommonOptions {\n json?: boolean;\n}\n\n/**\n * Render the U4 `GET /api/installations/:id/bindings` response — the live\n * binding status of every declared `uses` slot on the current module's\n * installation, with status chips + reasons + missing fields.\n */\nexport async function bindListCommand(\n options: BindListOptions,\n): Promise<number> {\n let ctx: ResolvedContext;\n try {\n ctx = loadContext(options);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n let bindings: InstallationBinding[];\n try {\n bindings = await getInstallationBindings(ctx.installationId, ctx.requestOptions);\n } catch (err) {\n return surfaceBindingError(err);\n }\n\n if (options.json) {\n out(JSON.stringify(bindings, null, 2));\n return 0;\n }\n\n if (bindings.length === 0) {\n info(`No workspace-table ${code('uses')} slots declared for ${code(ctx.slug)}.`);\n info(\n `Declare one by hand in ${code('module.json#uses.tables')}, or on-ramp an existing table with ${code('dashwise uses add --from-table <name>')}.`,\n );\n return 0;\n }\n\n const unbound = bindings.filter((b) => b.status === 'unbound').length;\n info(\n `Workspace-table bindings for ${code(ctx.slug)} ${dim(\n `(${bindings.length} declared${unbound > 0 ? `, ${unbound} unbound` : ''})`,\n )}:`,\n );\n out('');\n for (const b of bindings) {\n // Enforced ops = manifest ops ∩ consented ops. Surface both when they\n // diverge so the author sees a pending-consent gap at a glance.\n const enforced = b.ops.filter((o) => (b.consented_ops ?? []).includes(o));\n const opsSummary =\n b.status === 'bound' && enforced.length !== b.ops.length\n ? `${opsLine(enforced)} ${dim(`(declared ${opsLine(b.ops)}; re-bind to consent to the rest)`)}`\n : opsLine(b.ops);\n out(` ${statusChip(b.status)} ${code(b.uses_slug)} ${dim(`[${opsSummary}]`)}`);\n if (b.purpose) {\n out(` ${dim('purpose:')} ${b.purpose}`);\n }\n if (b.status === 'bound' && b.table) {\n out(` ${dim('table:')} ${b.table.name} ${dim(`(id ${b.table.id})`)}`);\n const mapped = b.field_map ? Object.keys(b.field_map).length : 0;\n if (mapped > 0) {\n out(` ${dim('fields:')} ${mapped} mapped`);\n }\n }\n if (b.status === 'unbound') {\n out(` ${dim('reason:')} ${b.reason ?? dim('(unspecified)')}`);\n }\n if (b.missing_fields && b.missing_fields.length > 0) {\n out(\n ` ${pc.yellow('missing:')} ${b.missing_fields.join(', ')} ${dim('(required field(s) not mapped)')}`,\n );\n }\n out('');\n }\n if (unbound > 0) {\n info(\n `Connect a parked slot with ${code('dashwise bind <uses-slug> --table <name>')} (or ${code('--create')} to materialize a fresh table).`,\n );\n }\n return 0;\n}\n\n// ── `dashwise bind <uses-slug>` (U4 candidates → PUT) ──────────────────\n\nexport interface BindOptions extends CommonOptions {\n /** Workspace table name or numeric id to bind to (script mode). */\n table?: string;\n /** Repeatable `<usesField>=<physicalFieldName>` mapping override. */\n map?: string[];\n /** Materialize a fresh Data Hub table + bind to it. */\n create?: boolean;\n /** Decline an optional-needs slot (the module runs without it). */\n decline?: boolean;\n}\n\nexport async function bindCommand(\n usesSlug: string,\n options: BindOptions,\n): Promise<number> {\n if (!usesSlug || typeof usesSlug !== 'string') {\n fail(\n 'Usage: `dashwise bind <uses-slug> [--table <name-or-id>] [--map <usesField>=<physicalFieldName>...]`, `--create`, or `--decline`.',\n );\n return 1;\n }\n\n // --create / --decline / --table are mutually-exclusive modes.\n const modes = [options.create, options.decline, options.table !== undefined].filter(\n Boolean,\n ).length;\n if (modes > 1) {\n fail(\n `Pass at most one of ${code('--table')}, ${code('--create')}, ${code('--decline')} — they select different bind modes.`,\n );\n return 1;\n }\n if (options.decline && (options.map ?? []).length > 0) {\n fail(`${code('--map')} makes no sense with ${code('--decline')} (nothing is being bound).`);\n return 1;\n }\n\n let ctx: ResolvedContext;\n try {\n ctx = loadContext(options);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n // --decline: optional-needs slots only; backend enforces DECLINE_NOT_ALLOWED.\n if (options.decline) {\n return declineSlot(ctx, usesSlug);\n }\n\n // --create: materialize a plain Data Hub table from the manifest fields\n // spec + bind with full consent. No candidate resolution needed.\n if (options.create) {\n return bindViaCreate(ctx, usesSlug);\n }\n\n // Bind to an existing workspace table. Parse any --map overrides first\n // (fail-fast, zero side effects on a typo) — but they resolve to\n // physical field IDS only after we pick a candidate (the candidate's\n // auto_field_map + the introspected physical fields carry the ids).\n let mapOverrides: Record<string, string>;\n try {\n mapOverrides = parseMapOverrides(options.map);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n // Resolve the target table via the U4 candidates endpoint.\n let candidates: BindingCandidate[];\n try {\n candidates = await getBindingCandidates(\n ctx.installationId,\n usesSlug,\n ctx.requestOptions,\n );\n } catch (err) {\n return surfaceBindingError(err);\n }\n\n const chosen = await chooseCandidate(candidates, usesSlug, options.table);\n if (chosen === 'cancelled') {\n info('Cancelled.');\n return 130;\n }\n if (chosen === null) {\n // No candidate resolved — chooseCandidate already printed the reason.\n return 1;\n }\n\n // Build the `field_map` (declared-field-slug → physical-field-id) to\n // send. Starts from the candidate's `auto_field_map`; each `--map\n // <usesField>=<physicalName>` override replaces one entry. Overrides\n // are given by physical NAME/slug, so resolve them to ids by\n // introspecting the chosen table (only when overrides are present — no\n // extra round-trip on the common auto-bind path). An override naming a\n // field that doesn't exist on the table is a hard, local error.\n let fieldMap: Record<string, number> | undefined;\n try {\n fieldMap = await buildFieldMap(ctx, chosen, mapOverrides);\n } catch (err) {\n if (err instanceof ApiError) return surfaceBindingError(err);\n fail((err as Error).message);\n return 1;\n }\n\n let result: InstallationBinding;\n try {\n result = await putBinding(\n ctx.installationId,\n usesSlug,\n fieldMap !== undefined\n ? { table_id: chosen.table_id, field_map: fieldMap }\n : { table_id: chosen.table_id },\n ctx.requestOptions,\n );\n } catch (err) {\n return surfacePutBindingError(err, usesSlug, ctx.slug);\n }\n\n reportBoundOk(result, ctx.slug);\n return 0;\n}\n\n/**\n * Choose the candidate to bind. Three paths:\n * - `--table <name-or-id>` → match a candidate by numeric id or name\n * (script-friendly; errors clearly on miss/ambiguity).\n * - no flag + TTY + >1 candidate → interactive @clack pick list.\n * - no flag + exactly one candidate → auto-pick it.\n * - no flag + non-TTY + >1 candidate → error asking for --table.\n * - zero candidates → error with the on-ramp / --create hint.\n *\n * Returns the chosen candidate, `null` (unresolvable — message printed),\n * or `'cancelled'` (user aborted the interactive pick).\n */\nasync function chooseCandidate(\n candidates: BindingCandidate[],\n usesSlug: string,\n tableFlag: string | undefined,\n): Promise<BindingCandidate | null | 'cancelled'> {\n if (candidates.length === 0) {\n fail(\n `No workspace table can satisfy ${code(usesSlug)} yet. Create a matching table (or ${code(`dashwise bind ${usesSlug} --create`)} to materialize one from the declared fields).`,\n );\n return null;\n }\n\n if (tableFlag !== undefined) {\n const match = matchCandidate(candidates, tableFlag);\n if (!match) {\n const list = candidates\n .map((c) => ` - ${c.name} ${dim(`(id ${c.table_id}, score ${c.match_score})`)}`)\n .join('\\n');\n fail(\n `No candidate table matching ${code(tableFlag)} for ${code(usesSlug)}. Candidates:\\n${list}`,\n );\n return null;\n }\n return match;\n }\n\n if (candidates.length === 1) {\n return candidates[0]!;\n }\n\n // Multiple candidates, no --table.\n if (process.stdout.isTTY) {\n const choice = await select({\n message: `Which workspace table should ${usesSlug} bind to?`,\n options: candidates.map((c) => ({\n value: String(c.table_id),\n label: c.name,\n hint:\n c.missing_required.length > 0\n ? `id=${c.table_id}, score=${c.match_score}, missing: ${c.missing_required.join(', ')}`\n : `id=${c.table_id}, score=${c.match_score}, full coverage`,\n })),\n });\n if (isCancel(choice)) return 'cancelled';\n return candidates.find((c) => String(c.table_id) === choice) ?? null;\n }\n\n // Non-interactive + ambiguous → require --table.\n const list = candidates\n .map((c) => ` - ${c.name} ${dim(`(id ${c.table_id}, score ${c.match_score})`)}`)\n .join('\\n');\n fail(\n `${candidates.length} candidate tables for ${code(usesSlug)}. Re-run with ${code('--table <name-or-id>')} to pick one:\\n${list}`,\n );\n return null;\n}\n\n/** Match a candidate by numeric id (exact) or name (exact, case-sensitive). */\nfunction matchCandidate(\n candidates: BindingCandidate[],\n flag: string,\n): BindingCandidate | undefined {\n const asNumber = Number.parseInt(flag, 10);\n const isNumeric = !Number.isNaN(asNumber) && String(asNumber) === flag;\n if (isNumeric) {\n return candidates.find((c) => c.table_id === asNumber);\n }\n return candidates.find((c) => c.name === flag);\n}\n\n/**\n * Build the `field_map` (declared-field-slug → physical-field-id) to send\n * in the PUT body.\n *\n * - No `--map` overrides: forward the candidate's `auto_field_map` if it\n * has entries, else `undefined` (let the server compute the whole map by\n * name-match).\n * - With overrides: introspect the chosen table (one call) to resolve each\n * `<usesField>=<physicalName>` to the physical field's id, then apply\n * those on top of the auto map. An override that names a physical field\n * the table doesn't have is a hard local error (fail before the PUT).\n */\nasync function buildFieldMap(\n ctx: ResolvedContext,\n candidate: BindingCandidate,\n overrides: Record<string, string>,\n): Promise<Record<string, number> | undefined> {\n const overrideKeys = Object.keys(overrides);\n if (overrideKeys.length === 0) {\n return Object.keys(candidate.auto_field_map).length > 0\n ? { ...candidate.auto_field_map }\n : undefined;\n }\n\n // Resolve override physical NAMES/slugs → ids against the actual table.\n const table = await introspectWorkspaceTable(\n ctx.installationId,\n String(candidate.table_id),\n ctx.requestOptions,\n );\n const byName = new Map<string, number>();\n for (const f of table.fields) {\n byName.set(f.slug, f.id);\n if (f.name) byName.set(f.name, f.id);\n }\n\n const merged: Record<string, number> = { ...candidate.auto_field_map };\n for (const [usesField, physicalName] of Object.entries(overrides)) {\n const id = byName.get(physicalName);\n if (id === undefined) {\n const available = table.fields\n .map((f) => (f.name && f.name !== f.slug ? `${f.slug} (${f.name})` : f.slug))\n .join(', ');\n throw new Error(\n `--map ${usesField}=${physicalName}: table \"${table.name}\" has no field named \"${physicalName}\". Available: ${available}.`,\n );\n }\n merged[usesField] = id;\n }\n return merged;\n}\n\n/** Parse repeatable `--map <usesField>=<physicalFieldName>` into a record. */\nfunction parseMapOverrides(specs: string[] | undefined): Record<string, string> {\n const out: Record<string, string> = {};\n for (const spec of specs ?? []) {\n const eq = spec.indexOf('=');\n if (eq <= 0 || eq === spec.length - 1) {\n throw new Error(\n `Invalid --map \"${spec}\". Expected \\`<usesField>=<physicalFieldName>\\` (e.g. \\`--map name=full_name\\`).`,\n );\n }\n const usesField = spec.slice(0, eq).trim();\n const physicalName = spec.slice(eq + 1).trim();\n if (!usesField || !physicalName) {\n throw new Error(`Invalid --map \"${spec}\": both sides must be non-empty.`);\n }\n if (out[usesField] !== undefined) {\n throw new Error(`Duplicate --map for uses field \"${usesField}\".`);\n }\n out[usesField] = physicalName;\n }\n return out;\n}\n\n/** `--create` path: materialize a fresh Data Hub table + bind to it. */\nasync function bindViaCreate(ctx: ResolvedContext, usesSlug: string): Promise<number> {\n // Sanity: the slot must be `if_missing: 'create'` in the manifest for the\n // server to allow materialization. Pre-check locally for a clearer error\n // than the round-trip; the server re-validates authoritatively.\n const slot = findUsesSlot(ctx, usesSlug);\n if (slot && slot.if_missing !== undefined && slot.if_missing !== 'create') {\n warn(\n `${code(usesSlug)} declares ${code(`if_missing: \"${slot.if_missing}\"`)}, not ${code('\"create\"')} — the backend may reject ${code('--create')}. Set it to ${code('create')} in module.json if you want a table materialized.`,\n );\n }\n\n let result: InstallationBinding;\n try {\n result = await putBinding(\n ctx.installationId,\n usesSlug,\n { create: true },\n ctx.requestOptions,\n );\n } catch (err) {\n return surfacePutBindingError(err, usesSlug, ctx.slug);\n }\n if (result.table) {\n success(\n `Materialized ${code(result.table.name)} ${dim(`(id ${result.table.id})`)} and bound ${code(usesSlug)} for ${code(ctx.slug)}.`,\n );\n info(\n `The new table is a plain user-owned Data Hub table — it stays in the workspace when the module is uninstalled.`,\n );\n } else {\n success(`Bound ${code(usesSlug)} for ${code(ctx.slug)} to a freshly-created table.`);\n }\n return 0;\n}\n\n/** `--decline` path: mark an optional-needs slot declined. */\nasync function declineSlot(ctx: ResolvedContext, usesSlug: string): Promise<number> {\n try {\n await declineBinding(ctx.installationId, usesSlug, ctx.requestOptions);\n success(`Declined ${code(usesSlug)} for ${code(ctx.slug)} — the module runs without it.`);\n return 0;\n } catch (err) {\n return surfacePutBindingError(err, usesSlug, ctx.slug);\n }\n}\n\n/** Look up the local manifest's `uses` slot by slug (best-effort). */\nfunction findUsesSlot(\n ctx: ResolvedContext,\n usesSlug: string,\n): ManifestUsesTable | undefined {\n try {\n const manifest = readManifestOrThrow(ctx.dir);\n return manifest.uses?.tables?.find((t) => t.slug === usesSlug);\n } catch {\n return undefined;\n }\n}\n\nfunction reportBoundOk(result: InstallationBinding, moduleSlug: string): void {\n const tableLine = result.table\n ? ` → ${result.table.name} ${dim(`(id ${result.table.id})`)}`\n : '';\n success(`Bound ${code(result.uses_slug)} for ${code(moduleSlug)}${tableLine}.`);\n const consented = result.consented_ops ?? [];\n info(\n `Consented ops: ${opsLine(consented)}. Runtime reads/writes against this slot now succeed.`,\n );\n if (result.missing_fields && result.missing_fields.length > 0) {\n warn(\n `Still unmapped required field(s): ${result.missing_fields.join(', ')}. Re-run with ${code('--map <usesField>=<physicalFieldName>')} to map them.`,\n );\n }\n}\n\n// ── `dashwise unbind <uses-slug>` (U4 unbind) ──────────────────────────\n\nexport async function unbindCommand(\n usesSlug: string,\n options: CommonOptions,\n): Promise<number> {\n if (!usesSlug || typeof usesSlug !== 'string') {\n fail('Usage: `dashwise unbind <uses-slug>`');\n return 1;\n }\n\n let ctx: ResolvedContext;\n try {\n ctx = loadContext(options);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n try {\n await unbindBinding(ctx.installationId, usesSlug, ctx.requestOptions);\n success(`Unbound ${code(usesSlug)} for ${code(ctx.slug)}.`);\n warn(\n `Runtime reads/writes against this slot now return ${code('USES_UNBOUND')} until you ${code('dashwise bind')} it again.`,\n );\n return 0;\n } catch (err) {\n return surfaceBindingError(err);\n }\n}\n\n// ── error mapping ──────────────────────────────────────────────────────\n\n/**\n * Map a PUT-binding / decline failure. The backend returns a typed\n * error `code` on the envelope; translate the common ones to an\n * actionable hint. The binding row is unchanged on failure.\n */\nfunction surfacePutBindingError(\n err: unknown,\n usesSlug: string,\n moduleSlug: string,\n): number {\n if (err instanceof ApiError) {\n switch (err.code) {\n case 'TABLE_NOT_IN_WORKSPACE':\n fail(\n `The chosen table isn't in ${code(moduleSlug)}'s workspace (${err.message}). A ${code('uses')} binding can only target a table the install's workspace owns.`,\n );\n return 1;\n case 'TABLE_IS_MODULE_MANAGED':\n fail(\n `That table is module-managed — ${code('uses')} bindings target plain WORKSPACE tables only. Reach a module's own tables via ${code('dashwise deps')} instead.`,\n );\n return 1;\n case 'MISSING_REQUIRED_FIELDS':\n fail(\n `The table is missing required field(s) the ${code(usesSlug)} contract needs (${err.message}). Map them explicitly with ${code('--map <usesField>=<physicalFieldName>')}, or pick a table that has them.`,\n );\n return 1;\n case 'FIELD_TYPE_INCOMPATIBLE':\n fail(\n `A mapped physical field's type is incompatible with the declared abstract type (${err.message}). Map to a compatible field with ${code('--map')}.`,\n );\n return 1;\n case 'FIELD_NOT_FOUND':\n fail(\n `A ${code('--map')} referenced a physical field that doesn't exist on the table (${err.message}). Check the field name.`,\n );\n return 1;\n case 'DECLINE_NOT_ALLOWED':\n fail(\n `${code(usesSlug)} is a required need — it can't be declined. Bind it to a table (${code(`dashwise bind ${usesSlug} --table <name>`)}) or set ${code('if_missing: \"optional\"')} in module.json.`,\n );\n return 1;\n case 'USES_SLOT_NOT_DECLARED':\n case 'BINDING_NOT_FOUND':\n fail(\n `${code(moduleSlug)}'s module.json doesn't declare a ${code('uses')} slot named ${code(usesSlug)}. Add it (or ${code('dashwise uses add --from-table <name>')}) + push the manifest first.`,\n );\n return 1;\n case 'NOT_WORKSPACE_ADMIN':\n case 'FORBIDDEN':\n fail(`Not authorized. Binding / unbinding / declining requires workspace-admin.`);\n return 1;\n default:\n fail(\n `Could not bind ${code(usesSlug)}: ${err.code}${err.message ? ` — ${err.message}` : ''}. The binding is unchanged.`,\n );\n return 1;\n }\n }\n fail(`Bind failed: ${(err as Error).message}`);\n return 1;\n}\n\n/**\n * Generic binding-endpoint error mapping (list + candidates + unbind).\n * The PUT/decline paths use the richer {@link surfacePutBindingError}.\n */\nfunction surfaceBindingError(err: unknown): number {\n if (err instanceof ApiError) {\n switch (err.code) {\n case 'UNAUTHENTICATED':\n fail(\n `Auth rejected by backend. Your CLI token may be stale — run ${code('dashwise login')} then retry.`,\n );\n return 1;\n case 'NOT_WORKSPACE_MEMBER':\n fail(\n `You're not a member of this installation's workspace. Binding management requires workspace membership.`,\n );\n return 1;\n case 'NOT_WORKSPACE_ADMIN':\n case 'FORBIDDEN':\n fail(`Not authorized. Binding / unbinding requires workspace-admin.`);\n return 1;\n case 'INSTALLATION_NOT_FOUND':\n fail(\n `Installation not found. It may have been destroyed; re-provision via ${code('dashwise init <slug>')}.`,\n );\n return 1;\n case 'USES_SLOT_NOT_DECLARED':\n case 'BINDING_NOT_FOUND':\n fail(\n `No such ${code('uses')} slot declared in this module's manifest. Run ${code('dashwise bind')} to see declared slots.`,\n );\n return 1;\n default:\n fail(`Backend rejected: ${err.code} ${err.status} — ${err.message}`);\n return 1;\n }\n }\n fail(`Binding operation failed: ${(err as Error).message}`);\n return 1;\n}\n","/**\n * P4-C — `dashwise uses add --from-table <name>`: the reverse on-ramp.\n *\n * The forward path (`dashwise bind`) connects a slot you already declared\n * in `module.json#uses`. This is the inverse: you point at an EXISTING\n * workspace table and the CLI does everything from there —\n *\n * 1. Introspect the table's physical fields + types by its numeric id\n * (via GET /api/tables/:id + GET /api/fields/table/:id).\n * 2. GENERATE a `uses.tables[]` manifest entry from it — folding each\n * physical field type into its abstract `uses` type (link_row /\n * formula / ai fields are skipped; they're not v1 `uses` fields).\n * 3. Write the entry into local `module.json`.\n * 4. PUSH the manifest to the dev install (draft-apply reconciles the\n * new slot — it parks NOT_BOUND_YET until bound).\n * 5. BIND the freshly-declared slot to that same table (skipped with\n * `--no-bind`).\n *\n * One command from \"I have an Employees table\" to typed `db.uses.employees`\n * access. Requires login + a provisioned dev install (`dashwise init`).\n */\n\nimport {\n ApiError,\n applyDraftManifest,\n getModuleBySlug,\n introspectWorkspaceTable,\n type RequestOptions,\n type WorkspaceTableField,\n type WorkspaceTableIntrospection,\n} from '../../lib/api-client.js';\nimport { readConfig, readModuleEntry, resolveApiUrl } from '../../lib/config.js';\nimport {\n readManifestOrThrow,\n writeManifest,\n type ManifestShape,\n type ManifestUsesField,\n type ManifestUsesTable,\n} from '../../lib/manifest-io.js';\nimport {\n abstractTypeForPhysical,\n USES_OPERATIONS,\n type UsesOperation,\n} from '../../lib/uses-types.js';\nimport { code, dim, fail, info, out, success, warn } from '../../lib/output.js';\nimport { bindCommand } from './bind.js';\n\nexport interface UsesAddOptions {\n dir?: string;\n /** The workspace table to on-ramp (name or numeric id). Required. */\n fromTable: string;\n /** Override the generated slot slug (default: slugified table name). */\n slug?: string;\n /** Comma-separated ops to declare (default: `read`). */\n ops?: string;\n /** Optional author-facing purpose string. */\n purpose?: string;\n /** Skip the auto-bind step (only write + push the manifest entry). */\n noBind?: boolean;\n /** Skip the overwrite-existing-slot confirmation. */\n yes?: boolean;\n}\n\ninterface ResolvedContext {\n installationId: number;\n moduleSlug: string;\n dir?: string;\n manifest: ManifestShape;\n requestOptions: RequestOptions;\n}\n\nexport async function usesAddCommand(options: UsesAddOptions): Promise<number> {\n if (!options.fromTable) {\n fail('Usage: `dashwise uses add --from-table <name-or-id>`');\n return 1;\n }\n\n // Parse --ops early (fail-fast, no side effects on a typo).\n let ops: UsesOperation[];\n try {\n ops = parseOps(options.ops);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n let ctx: ResolvedContext;\n try {\n ctx = loadContext(options);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n // ── 1. Introspect the workspace table ──────────────────────────────\n let table: WorkspaceTableIntrospection;\n try {\n table = await introspectWorkspaceTable(\n ctx.installationId,\n options.fromTable,\n ctx.requestOptions,\n );\n } catch (err) {\n return surfaceIntrospectError(err, options.fromTable);\n }\n\n // ── 2. Generate the uses.tables[] entry ────────────────────────────\n const slotSlug = options.slug ?? slugify(table.name);\n if (!isKebab(slotSlug)) {\n fail(\n `Generated slot slug ${code(slotSlug)} isn't kebab-case. Pass ${code('--slug <kebab-slug>')} explicitly.`,\n );\n return 1;\n }\n\n const { fields, skipped } = generateFields(table.fields);\n if (fields.length === 0) {\n fail(\n `Table ${code(table.name)} has no fields representable as a v1 ${code('uses')} contract (all are link_row / formula / ai / file). Nothing to declare.`,\n );\n return 1;\n }\n\n const slot: ManifestUsesTable = {\n slug: slotSlug,\n ops,\n fields,\n if_missing: 'require',\n };\n if (options.purpose) slot.purpose = options.purpose;\n\n // Report what we generated before mutating anything.\n info(\n `Generated a ${code('uses')} contract ${code(slotSlug)} from table ${code(table.name)} ${dim(`(id ${table.table_id})`)}:`,\n );\n out(` ${dim('ops:')} ${ops.join(', ')}`);\n for (const f of fields) {\n const req = f.required ? dim(' (required)') : '';\n out(` ${dim('field:')} ${code(f.slug)} → ${f.types.join(' | ')}${req}`);\n }\n if (skipped.length > 0) {\n warn(\n `Skipped ${skipped.length} field(s) not representable in a v1 uses contract: ${skipped.join(', ')}.`,\n );\n }\n\n // ── 3. Merge into module.json + write ──────────────────────────────\n const uses = ctx.manifest.uses ?? { tables: [] };\n const tables = uses.tables ?? [];\n const existingIdx = tables.findIndex((t) => t.slug === slotSlug);\n if (existingIdx >= 0 && !options.yes) {\n fail(\n `A ${code('uses')} slot ${code(slotSlug)} already exists in module.json. Re-run with ${code('--yes')} to replace it, or pass a different ${code('--slug')}.`,\n );\n return 1;\n }\n if (existingIdx >= 0) {\n tables[existingIdx] = slot;\n } else {\n tables.push(slot);\n }\n uses.tables = tables;\n ctx.manifest.uses = uses;\n\n try {\n writeManifest(ctx.manifest, ctx.dir);\n } catch (err) {\n fail(`Could not write manifest: ${(err as Error).message}`);\n return 1;\n }\n success(\n `${existingIdx >= 0 ? 'Replaced' : 'Added'} ${code(`uses.tables[${slotSlug}]`)} in module.json.`,\n );\n\n // ── 4. Push the manifest (draft-apply reconciles the new slot) ─────\n const pushed = await pushManifest(ctx);\n if (!pushed) {\n // pushManifest already surfaced the reason. The local edit stands;\n // don't attempt to bind against an un-pushed slot.\n info(\n `The manifest edit is saved locally. Push it (${code('dashwise dev')} watches + applies, or re-run once the backend is reachable), then ${code(`dashwise bind ${slotSlug} --table ${table.table_id}`)}.`,\n );\n return 1;\n }\n\n // ── 5. Bind the new slot to the source table ───────────────────────\n if (options.noBind) {\n info(\n `Skipped auto-bind (${code('--no-bind')}). Connect it when ready: ${code(`dashwise bind ${slotSlug} --table ${table.table_id}`)}.`,\n );\n return 0;\n }\n\n info(`Binding ${code(slotSlug)} to ${code(table.name)}…`);\n // Delegate to the same bind path a user would run by hand — it resolves\n // the candidate (the source table will be an exact match), validates\n // coverage + type compat, and sets consented_ops = the declared ops.\n const bindExit = await bindCommand(slotSlug, {\n ...(ctx.dir !== undefined ? { dir: ctx.dir } : {}),\n table: String(table.table_id),\n });\n if (bindExit !== 0) {\n warn(\n `The ${code('uses')} slot was declared + pushed, but the auto-bind didn't complete. Retry with ${code(`dashwise bind ${slotSlug} --table ${table.table_id}`)}.`,\n );\n return bindExit;\n }\n return 0;\n}\n\n// ── context ────────────────────────────────────────────────────────────\n\nfunction loadContext(opts: UsesAddOptions): ResolvedContext {\n const manifest = readManifestOrThrow<ManifestShape>(opts.dir);\n const moduleSlug = manifest.module?.slug;\n if (!moduleSlug) {\n throw new Error('module.json has no module.slug — the manifest is malformed.');\n }\n const cfg = readConfig();\n if (!cfg) {\n throw new Error('Not logged in. Run `dashwise login` first.');\n }\n const entry = readModuleEntry(moduleSlug);\n if (!entry) {\n throw new Error(\n `No dev install cached for module \"${moduleSlug}\". Run \\`dashwise init ${moduleSlug} --force\\` to provision one.`,\n );\n }\n return {\n installationId: entry.installationId,\n moduleSlug,\n ...(opts.dir !== undefined ? { dir: opts.dir } : {}),\n manifest,\n requestOptions: {\n baseUrl: resolveApiUrl(),\n auth: { token: cfg.token },\n },\n };\n}\n\n// ── manifest push ───────────────────────────────────────────────────────\n\n/**\n * Apply the (freshly-written) manifest to the dev install via\n * `PUT /api/modules/:id/draft/manifest`, so the backend reconciles the\n * new `uses` slot (parks it NOT_BOUND_YET, ready to bind). Resolves the\n * module id from the slug first. Returns true on success; on failure\n * prints a clear reason + returns false (the caller keeps the local edit\n * and skips the bind).\n */\nasync function pushManifest(ctx: ResolvedContext): Promise<boolean> {\n let moduleId: number;\n try {\n const mod = await getModuleBySlug(ctx.moduleSlug, ctx.requestOptions);\n moduleId = mod.id;\n } catch (err) {\n if (err instanceof ApiError && err.status === 404) {\n warn(\n `Module ${code(ctx.moduleSlug)} isn't registered on the backend yet. Run ${code('dashwise module register')} (or ${code('dashwise init')}) before on-ramping a table.`,\n );\n return false;\n }\n warn(`Couldn't resolve the module id to push the manifest: ${(err as Error).message}`);\n return false;\n }\n\n try {\n await applyDraftManifest(\n moduleId,\n ctx.manifest as Record<string, unknown>,\n ctx.requestOptions,\n );\n success('Pushed the manifest — the backend parked the new slot, ready to bind.');\n return true;\n } catch (err) {\n if (err instanceof ApiError) {\n // A validation failure means the generated entry (or the rest of the\n // manifest) didn't pass — surface the structured issues if present.\n if (err.code === 'MANIFEST_INVALID' || err.status === 400) {\n fail(`Manifest rejected by the backend validator: ${err.message}`);\n const issues = extractIssues(err.context);\n for (const issue of issues) out(` ${dim('-')} ${issue}`);\n } else {\n fail(`Manifest push failed: ${err.code} ${err.status} — ${err.message}`);\n }\n } else {\n fail(`Manifest push failed: ${(err as Error).message}`);\n }\n return false;\n }\n}\n\n/** Pull human-readable issue strings out of a MANIFEST_INVALID context. */\nfunction extractIssues(context: Record<string, unknown> | undefined): string[] {\n if (!context) return [];\n const raw = (context as { issues?: unknown }).issues;\n if (!Array.isArray(raw)) return [];\n return raw.map((i) => {\n if (typeof i === 'string') return i;\n if (i && typeof i === 'object') {\n const o = i as { path?: unknown; message?: unknown };\n const path = typeof o.path === 'string' ? o.path : '';\n const message = typeof o.message === 'string' ? o.message : JSON.stringify(i);\n return path ? `${path}: ${message}` : message;\n }\n return String(i);\n });\n}\n\n// ── field generation ────────────────────────────────────────────────────\n\n/**\n * Fold each physical field into a `uses` field with its abstract type.\n * Physical types not representable in a v1 `uses` contract (link_row /\n * formula / ai / file / multi_file / phone) are collected in `skipped`\n * and surfaced to the user. `required` carries through from the physical\n * field so the generated contract demands the same coverage.\n */\nfunction generateFields(physical: WorkspaceTableField[]): {\n fields: ManifestUsesField[];\n skipped: string[];\n} {\n const fields: ManifestUsesField[] = [];\n const skipped: string[] = [];\n for (const f of physical) {\n const abstract = abstractTypeForPhysical(f.type);\n if (abstract === null) {\n skipped.push(`${f.slug} (${f.type})`);\n continue;\n }\n const entry: ManifestUsesField = { slug: f.slug, types: [abstract] };\n if (f.required) entry.required = true;\n fields.push(entry);\n }\n return { fields, skipped };\n}\n\n// ── parsing / helpers ───────────────────────────────────────────────────\n\nfunction parseOps(opsCsv: string | undefined): UsesOperation[] {\n if (opsCsv === undefined) return ['read'];\n const parsed = opsCsv\n .split(',')\n .map((o) => o.trim())\n .filter(Boolean);\n if (parsed.length === 0) {\n throw new Error(`--ops must list at least one of ${USES_OPERATIONS.join(', ')}.`);\n }\n const seen = new Set<UsesOperation>();\n for (const op of parsed) {\n if (!(USES_OPERATIONS as readonly string[]).includes(op)) {\n throw new Error(\n `Invalid --ops value \"${op}\". Allowed: ${USES_OPERATIONS.join(', ')}.`,\n );\n }\n seen.add(op as UsesOperation);\n }\n // Canonical order regardless of input order.\n return USES_OPERATIONS.filter((o) => seen.has(o));\n}\n\n/** Slugify a table name into a kebab-case slot slug. */\nfunction slugify(name: string): string {\n return name\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '');\n}\n\nconst KEBAB_REGEX = /^[a-z][a-z0-9-]*[a-z0-9]$/;\nfunction isKebab(slug: string): boolean {\n return KEBAB_REGEX.test(slug);\n}\n\n// ── error mapping ────────────────────────────────────────────────────────\n\nfunction surfaceIntrospectError(err: unknown, tableRef: string): number {\n if (err instanceof ApiError) {\n switch (err.code) {\n case 'NON_NUMERIC_TABLE_REF':\n // The retarget resolves by numeric id only (name→id resolution is\n // not yet wired — task_2f6a4cc2). Echo the actionable message.\n fail(err.message);\n return 1;\n case 'NOT_FOUND':\n fail(\n `No workspace table with id ${code(tableRef)} is visible to you. Check the id (find it in the Dashwise UI URL, or via ${code('GET /api/tables/application/:applicationId')}).`,\n );\n return 1;\n case 'TABLE_IS_MODULE_MANAGED':\n fail(\n `Table ${code(tableRef)} is module-managed — ${code('uses')} is for plain WORKSPACE tables. Reach a module's own tables via ${code('dashwise deps')} instead.`,\n );\n return 1;\n case 'UNAUTHENTICATED':\n fail(\n `Auth rejected by backend. Your CLI token may be stale — run ${code('dashwise login')} then retry.`,\n );\n return 1;\n case 'NOT_WORKSPACE_MEMBER':\n case 'FORBIDDEN':\n fail(`You're not a member of the workspace that owns table ${code(tableRef)}.`);\n return 1;\n default:\n fail(`Backend rejected: ${err.code} ${err.status} — ${err.message}`);\n return 1;\n }\n }\n fail(`Table introspection failed: ${(err as Error).message}`);\n return 1;\n}\n","/**\n * P4-C — the `uses`-plane abstract type system, mirrored CLI-side.\n *\n * Phase 4 (modules-platform-v2) `uses` contracts declare ABSTRACT field\n * types (`text`, `email`, `number`, …). At bind time the physical field\n * must be *compatible* with the declared abstract type per a single\n * static map defined next to the backend's manifest schema (U1). The CLI\n * mirrors that map here for two reasons:\n *\n * 1. `dashwise uses add --from-table` introspects a physical table's\n * field types and must GENERATE the abstract `types[]` for each\n * declared field — the inverse of the compat check (given a physical\n * type, which abstract types accept it?).\n * 2. Fail-fast local validation of a hand-authored `--map` before the\n * round-trip (the backend re-validates authoritatively).\n *\n * The backend's manifest validator remains the source of truth at\n * apply/bind time; this mirror must stay in lockstep with it (covered by\n * the shared spec + the CLI's own unit test asserting the pairs).\n */\n\n/**\n * Abstract types a `uses` field may declare. Excludes `link_row` /\n * `formula` / `ai` (no cross-plane links in v1) — those physical types\n * are simply not accepted by any abstract type, so a field of that\n * physical type is skipped by `--from-table` generation.\n */\nexport const USES_ABSTRACT_TYPES = [\n 'text',\n 'long_text',\n 'number',\n 'boolean',\n 'date',\n 'email',\n 'url',\n 'single_select',\n // Backend registry key is `multi_select` (FIELD_TYPE_MULTI_SELECT); the\n // manifest schema's `USES_FIELD_TYPES` enum only admits that exact token.\n // Emitting `multiple_select` here would fail the round-trip PUT with\n // MANIFEST_INVALID, so this MUST stay `multi_select` to match the backend.\n 'multi_select',\n] as const;\nexport type UsesAbstractType = (typeof USES_ABSTRACT_TYPES)[number];\n\n/**\n * The ONE static compatibility map (U1): abstract type → the physical\n * field types that satisfy it. The `uses` side declares the abstract type\n * it needs; the physical field must be one of these.\n *\n * Mirror of the backend's map — keep in lockstep. `datetime` is folded\n * into `date`'s acceptance set (the physical registry has both `date` and\n * `datetime`; a `date` abstract need accepts either temporal column).\n */\nexport const USES_TYPE_COMPAT: Record<UsesAbstractType, readonly string[]> = {\n text: ['text', 'long_text', 'email', 'url'],\n long_text: ['long_text'],\n number: ['number', 'rating'],\n boolean: ['boolean'],\n date: ['date'],\n email: ['email'],\n url: ['url', 'text'],\n single_select: ['single_select'],\n multi_select: ['multi_select'],\n};\n\n/**\n * Physical field types that map cleanly to a single \"best\" abstract type\n * when GENERATING a `uses` contract from an existing table\n * (`dashwise uses add --from-table`). The chosen abstract type is the\n * most-specific one that accepts the physical type — e.g. an `email`\n * column becomes abstract `email` (not `text`), so re-binding in another\n * workspace still demands an email-shaped column.\n *\n * Physical types with no entry here (link_row / formula / ai / file /\n * multi_file / phone) are NOT representable as a v1 `uses` field and are\n * skipped by the generator (surfaced to the user as \"skipped: <slug>\").\n */\nexport const PHYSICAL_TO_ABSTRACT: Record<string, UsesAbstractType> = {\n text: 'text',\n long_text: 'long_text',\n number: 'number',\n rating: 'number',\n boolean: 'boolean',\n // A date-with-time column has physical registry type `date` (with\n // `config.includeTime`), NOT a distinct `datetime` type — the backend\n // registry has no `datetime` key. So introspection only ever reports\n // `date` here; there is no `datetime` physical entry to fold.\n date: 'date',\n email: 'email',\n url: 'url',\n single_select: 'single_select',\n multi_select: 'multi_select',\n};\n\n/**\n * Given a physical field type, return the abstract `uses` type to declare\n * for it — or `null` when the physical type isn't representable as a v1\n * `uses` field (caller skips it).\n */\nexport function abstractTypeForPhysical(\n physicalType: string,\n): UsesAbstractType | null {\n return PHYSICAL_TO_ABSTRACT[physicalType] ?? null;\n}\n\n/**\n * True when a physical field type satisfies a declared abstract type\n * (i.e. it appears in that abstract type's compat set). Used for\n * fail-fast local `--map` validation; the backend re-checks.\n */\nexport function physicalSatisfiesAbstract(\n abstractType: string,\n physicalType: string,\n): boolean {\n const accepted = USES_TYPE_COMPAT[abstractType as UsesAbstractType];\n return accepted !== undefined && accepted.includes(physicalType);\n}\n\n/** The closed set of `uses` operations, in canonical order. */\nexport const USES_OPERATIONS = ['create', 'read', 'update', 'delete'] as const;\nexport type UsesOperation = (typeof USES_OPERATIONS)[number];\n","/**\n * `dashwise pull`\n *\n * P1-E2 (BaaS Phase 1, Bucket E sprint 2) — pull the canonical manifest\n * from the backend and write it to local `module.json`. Inverse of the\n * write-back-from-GET pattern used by schema-mutation commands; lets\n * users sync after dashboard-side schema edits OR after another tool\n * (DashAI, a teammate) mutated the backend.\n *\n * Per the manifest spec (`dashwise-devops-docs/plans/dashwise-manifest-spec.md`):\n * the manifest is a derived export of backend state; `pull` is the\n * primitive that materializes that derivation locally.\n *\n * Reuses the existing `GET /api/installations/:id/schema` endpoint —\n * `BaaS Phase 1 / E6` is a no-op for `dashwise pull`'s purposes; the\n * exporter primitive already exists with the right auth model\n * (local-flavor runtime token).\n *\n * Flags:\n * --dir <path> project root (default: cwd)\n * --dry-run fetch + diff; don't write\n *\n * Exit codes: 0 on success (synced or already in sync), 1 on any\n * failure (not logged in, no install cached, backend rejected, etc.).\n *\n * Future polish (not in P1-E2):\n * - --force / git-dirty check (defer until pull becomes routine\n * enough that workflow conflicts are realistic; for now git is\n * the safety net — local file is in a repo)\n * - rich diff rendering (terraform-plan style)\n */\n\nimport { ApiError, getInstallationSchema } from '../lib/api-client.js';\nimport { manifestPath, writeManifest, type ManifestShape } from '../lib/manifest-io.js';\nimport { loadSchemaCommandContext } from '../lib/schema-command-context.js';\nimport { code, dim, fail, info, success } from '../lib/output.js';\n\nexport interface PullOptions {\n dir?: string;\n dryRun?: boolean;\n}\n\nexport async function pullCommand(options: PullOptions): Promise<number> {\n let ctx: ReturnType<typeof loadSchemaCommandContext>;\n try {\n ctx = loadSchemaCommandContext({\n ...(options.dir !== undefined ? { dir: options.dir } : {}),\n });\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n info(`Pulling manifest for installation ${ctx.entry.installationId}…`);\n\n let remoteManifest: Record<string, unknown>;\n try {\n const response = await getInstallationSchema(ctx.requestOptions);\n remoteManifest = response.manifest;\n } catch (err) {\n return surfacePullFailure(err);\n }\n\n // Compare local vs remote using the canonical JSON form the CLI\n // writes elsewhere (writeManifest's format). Object-equality via\n // JSON.stringify is fine here — the manifest is small + the\n // backend returns keys in a stable order (object spread in\n // schema-propose.service.ts:getManifest).\n const localJson = JSON.stringify(ctx.manifest, null, 2) + '\\n';\n const remoteJson = JSON.stringify(remoteManifest, null, 2) + '\\n';\n\n if (localJson === remoteJson) {\n success('Already in sync — local module.json matches backend.');\n return 0;\n }\n\n const localBytes = Buffer.byteLength(localJson, 'utf8');\n const remoteBytes = Buffer.byteLength(remoteJson, 'utf8');\n const delta = remoteBytes - localBytes;\n const deltaStr = delta === 0 ? '0 bytes' : `${delta > 0 ? '+' : ''}${delta} bytes`;\n\n if (options.dryRun) {\n info(\n `Drift detected (${deltaStr}). ${code('--dry-run')} — not writing.`,\n );\n info(`Run ${code('dashwise pull')} without ${code('--dry-run')} to apply.`);\n return 0;\n }\n\n try {\n writeManifest(remoteManifest as ManifestShape, ctx.projectRoot);\n } catch (err) {\n fail(`Failed to write ${manifestPath(ctx.projectRoot)}: ${(err as Error).message}`);\n return 1;\n }\n\n success(\n `Synced module.json from backend (${deltaStr}). ${dim(`Run \\`dashwise module generate\\` to refresh typed SDK if your watcher isn't running.`)}`,\n );\n return 0;\n}\n\n/**\n * Map a pull-time ApiError into a user-friendly message. Different\n * code set from the schema-mutation commands (no TABLE_SLUG_EXISTS etc.)\n * because pull is read-only — the failure modes are auth + connectivity.\n */\nfunction surfacePullFailure(err: unknown): number {\n if (err instanceof ApiError) {\n switch (err.code) {\n case 'UNAUTHENTICATED':\n fail(\n `Runtime token rejected. The cached token for this module may be expired — re-run \\`dashwise init <slug> --force\\` to mint a fresh one.`,\n );\n break;\n case 'SANDBOX_TOKEN_NOT_ACCEPTED':\n fail(\n `Schema-read endpoint requires a local-dev runtime token (kind=local). The cached token is the wrong kind — re-run \\`dashwise init <slug> --force\\`.`,\n );\n break;\n case 'INSTALL_MISMATCH':\n fail(\n `Runtime token is bound to a different installation than expected. The cached install id may be stale — re-run \\`dashwise init <slug> --force\\`.`,\n );\n break;\n case 'INSTALLATION_NOT_FOUND':\n fail(\n `The backend has no record of this installation. It may have been destroyed (GC, manual cleanup). Re-run \\`dashwise init <slug>\\` to provision a fresh one.`,\n );\n break;\n default:\n fail(`Backend rejected: ${err.code} ${err.status} — ${err.message}`);\n }\n return 1;\n }\n fail(`Pull failed: ${(err as Error).message}`);\n return 1;\n}\n","/**\n * `dashwise api-keys` — per-installation API key management.\n *\n * HH-CC-P1-C4 (BaaS Phase 1 Bucket C sprint 4). Pairs with the\n * backend (C1: minting endpoint, C2: runtime-guard recognition).\n *\n * Subcommands:\n * - `list` List API keys for the current module's install\n * - `create <name>` Mint a new key; prints the plaintext ONCE\n * - `revoke <key-id>` Soft-revoke a key (irreversible from the CLI)\n *\n * Auth: CLI bearer (JWT) — these are workspace-admin operations, NOT\n * runtime-data-plane operations. The runtime token cached in\n * `auth.json#modules[slug]` doesn't grant this permission; the user's\n * own login bearer does.\n *\n * Install resolution: from the current `module.json#module.slug` +\n * `auth.json#modules[<slug>].installationId`. Operates only on the\n * install currently bound to this project dir.\n */\n\nimport {\n ApiError,\n apiRequest as _apiRequest, // re-exported here only to keep imports tidy in tests\n createApiKey,\n listApiKeys,\n revokeApiKey,\n type ApiKeyGrantInput,\n type ApiKeyGrantRow,\n type ApiKeyPublic,\n type RequestOptions,\n} from '../lib/api-client.js';\nimport {\n readConfig,\n readModuleEntry,\n resolveApiUrl,\n} from '../lib/config.js';\nimport { readManifestOrThrow } from '../lib/manifest-io.js';\nimport { code, dim, fail, info, success, warn } from '../lib/output.js';\n\n// Silence unused-import lint — kept for symmetry with sibling commands\n// (some of which DO directly call apiRequest from this file).\nvoid _apiRequest;\n\ninterface CommonOptions {\n dir?: string;\n}\n\ninterface ResolvedContext {\n installationId: number;\n slug: string;\n requestOptions: RequestOptions;\n}\n\n/**\n * Shared setup: resolve the slug + install id from the current\n * project dir + auth.json, build a JWT-authed RequestOptions.\n *\n * Errors are thrown as plain `Error` instances; callers `catch` +\n * `fail(err.message)` + return 1.\n */\nfunction loadContext(opts: CommonOptions): ResolvedContext {\n const manifest = readManifestOrThrow(opts.dir);\n const slug = manifest.module?.slug;\n if (!slug) {\n throw new Error(\n `module.json has no module.slug — the manifest is malformed.`,\n );\n }\n const cfg = readConfig();\n if (!cfg) {\n throw new Error('Not logged in. Run `dashwise login` first.');\n }\n const entry = readModuleEntry(slug);\n if (!entry) {\n throw new Error(\n `No dev install cached for module \"${slug}\". Run \\`dashwise init ${slug} --force\\` to provision one.`,\n );\n }\n return {\n installationId: entry.installationId,\n slug,\n requestOptions: {\n baseUrl: resolveApiUrl(),\n auth: { token: cfg.token },\n },\n };\n}\n\n// ── list ─────────────────────────────────────────────────────────────\n\nexport interface ApiKeysListOptions extends CommonOptions {\n /** Include revoked keys in the output. Default: false (active only). */\n all?: boolean;\n json?: boolean;\n}\n\nexport async function apiKeysListCommand(\n options: ApiKeysListOptions,\n): Promise<number> {\n let ctx: ResolvedContext;\n try {\n ctx = loadContext(options);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n let keys: ApiKeyPublic[];\n try {\n const resp = await listApiKeys(ctx.installationId, ctx.requestOptions);\n keys = resp.api_keys;\n } catch (err) {\n return surfaceApiKeysError(err);\n }\n\n const filtered = options.all ? keys : keys.filter((k) => k.revoked_at === null);\n\n if (options.json) {\n process.stdout.write(`${JSON.stringify(filtered, null, 2)}\\n`);\n return 0;\n }\n\n if (filtered.length === 0) {\n info(\n options.all\n ? `No API keys (active or revoked) for ${code(ctx.slug)}.`\n : `No active API keys for ${code(ctx.slug)}. Run ${code('dashwise api-keys create <name>')} to mint one, or ${code('dashwise api-keys list --all')} to include revoked.`,\n );\n return 0;\n }\n\n info(`API keys for ${code(ctx.slug)} (install id=${ctx.installationId}):`);\n for (const k of filtered) {\n const status = formatKeyStatus(k);\n const lastUsed = k.last_used_at\n ? `last used ${formatRelative(new Date(k.last_used_at))}`\n : 'never used';\n process.stdout.write(\n ` ${code(`#${k.id}`)} ${k.name} ${dim(`dwk_${k.key_prefix}…`)} ${status} ${dim(`(${lastUsed})`)}\\n`,\n );\n // P1-C: the backend now returns each key's scoped grants. Render a\n // compact summary line beneath the key so `list` shows what each key\n // can actually do. A key with no grants is full-access.\n const grantLines = formatGrants(k.grants);\n if (grantLines.length > 0) {\n for (const line of grantLines) {\n process.stdout.write(` ${dim(line)}\\n`);\n }\n } else if (k.grants !== undefined) {\n // Backend returned grants=[] explicitly → full access.\n process.stdout.write(` ${dim('full install access (no grants)')}\\n`);\n }\n }\n return 0;\n}\n\n// ── create ───────────────────────────────────────────────────────────\n\nexport interface ApiKeysCreateOptions extends CommonOptions {\n name?: string;\n /**\n * Repeatable scoped-grant spec. Two shapes (P1-C):\n * - `module:<tableSlug>:<ops>` — grant on a module-owned table\n * - `datahub:table=<id>:<ops>` — grant on one Data Hub table\n * - `datahub:app=<id>:<ops>` — grant on a whole Data Hub database\n * - `datahub:workspace:<ops>` — workspace-wide Data Hub grant\n * where `<ops>` is a comma list of `create,read,update,delete`.\n * When any grant is present, the backend mints the key in scoped\n * (default-deny) mode. Omit for a full-access key (workspace-member\n * mintable on local installs; admin required otherwise).\n */\n grant?: string[];\n /** Days until expiry. Converted to an absolute ISO-8601 `expires_at`. */\n expires?: number;\n /** Print only the raw key on stdout (everything else to stderr).\n * Lets shell substitution work: KEY=$(dashwise api-keys create ... --raw-only) */\n rawOnly?: boolean;\n}\n\nexport async function apiKeysCreateCommand(\n nameArg: string | undefined,\n options: ApiKeysCreateOptions,\n): Promise<number> {\n const name = nameArg ?? options.name;\n if (!name) {\n fail('Usage: `dashwise api-keys create <name>` (e.g. `dashwise api-keys create production`)');\n return 1;\n }\n\n // Parse --grant specs BEFORE resolving context / hitting the network,\n // so a typo fails fast with a clear message + zero side effects.\n let grants: ApiKeyGrantInput[] | undefined;\n try {\n grants = parseGrants(options.grant);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n let expiresAt: string | undefined;\n try {\n expiresAt = resolveExpiresAt(options.expires);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n let ctx: ResolvedContext;\n try {\n ctx = loadContext(options);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n const body: {\n name: string;\n grants?: ApiKeyGrantInput[];\n expires_at?: string;\n } = { name };\n if (grants !== undefined) body.grants = grants;\n if (expiresAt !== undefined) body.expires_at = expiresAt;\n\n let resp;\n try {\n resp = await createApiKey(ctx.installationId, body, ctx.requestOptions);\n } catch (err) {\n return surfaceApiKeysError(err);\n }\n\n if (options.rawOnly) {\n // Stderr for chatter, stdout for the key. Lets shell capture\n // work cleanly: KEY=$(dashwise api-keys create prod --raw-only)\n process.stderr.write(\n `Created API key #${resp.api_key.id} (${resp.api_key.name}) for install ${ctx.installationId}.\\n`,\n );\n process.stdout.write(`${resp.raw_key}\\n`);\n return 0;\n }\n\n success(\n `Created API key ${code(`#${resp.api_key.id}`)} (${resp.api_key.name}) for ${code(ctx.slug)}.`,\n );\n // Echo the scope the key was minted with so the user can confirm they\n // got what they asked for (grant validation happens server-side).\n const grantLines = formatGrants(resp.api_key.grants);\n if (grantLines.length > 0) {\n info(` ${dim('scope:')} scoped to`);\n for (const line of grantLines) info(` ${line}`);\n } else {\n info(` ${dim('scope:')} full install access (no grants)`);\n }\n info('');\n warn(\n 'This is the ONLY time the full key is displayed. Save it now — the backend stores a hash, not the plaintext.',\n );\n info('');\n process.stdout.write(` ${code(resp.raw_key)}\\n`);\n info('');\n info(`Use in a deployed module's env (the two-var contract):`);\n info(` ${code(`DASHWISE_API_URL=${resolveApiUrl()}`)}`);\n info(` ${code(`DASHWISE_API_KEY=${resp.raw_key.slice(0, 12)}…`)}`);\n return 0;\n}\n\n// ── revoke ───────────────────────────────────────────────────────────\n\nexport interface ApiKeysRevokeOptions extends CommonOptions {\n yes?: boolean;\n}\n\nexport async function apiKeysRevokeCommand(\n keyIdArg: string | undefined,\n options: ApiKeysRevokeOptions,\n): Promise<number> {\n if (!keyIdArg) {\n fail('Usage: `dashwise api-keys revoke <key-id>` — id from `dashwise api-keys list`');\n return 1;\n }\n const keyId = Number.parseInt(keyIdArg, 10);\n if (!Number.isFinite(keyId) || keyId <= 0) {\n fail(`Invalid key id \"${keyIdArg}\" — expected a positive integer.`);\n return 1;\n }\n\n let ctx: ResolvedContext;\n try {\n ctx = loadContext(options);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n // For v1 we accept --yes only (no interactive prompt). Future\n // could prompt; for now the CLI is non-interactive-friendly by\n // default. A misclick on a single key id is recoverable (re-mint\n // takes seconds), so the friction-free path is right.\n if (!options.yes) {\n info(\n `Revoking API key #${keyId} for ${code(ctx.slug)} (install ${ctx.installationId}). Pass ${code('--yes')} to skip this confirmation in scripts.`,\n );\n }\n\n let resp;\n try {\n resp = await revokeApiKey(ctx.installationId, keyId, ctx.requestOptions);\n } catch (err) {\n return surfaceApiKeysError(err);\n }\n\n success(\n `Revoked API key #${resp.api_key.id} (${resp.api_key.name}). Future requests with this key will return 401.`,\n );\n return 0;\n}\n\n// ── error mapping ────────────────────────────────────────────────────\n\nfunction surfaceApiKeysError(err: unknown): number {\n if (err instanceof ApiError) {\n switch (err.code) {\n case 'UNAUTHENTICATED':\n fail(\n `Auth rejected by backend. Your CLI token may be stale — run ${code('dashwise login')} then retry.`,\n );\n return 1;\n case 'NOT_WORKSPACE_MEMBER':\n fail(\n `You're not a member of this installation's workspace. API-key management requires workspace membership.`,\n );\n return 1;\n case 'NOT_WORKSPACE_ADMIN':\n case 'FORBIDDEN':\n // P1-C authz: minting a scoped key (with grants) or any key on a\n // non-local install requires workspace ADMIN; members can only\n // mint on local installs. The backend sends NOT_WORKSPACE_ADMIN for\n // the admin-required case; FORBIDDEN is kept as a defensive alias.\n fail(\n `Not authorized. Minting scoped keys (with --grant) or keys on non-local installs requires workspace-admin; members can mint full-access keys on local dev installs only.`,\n );\n return 1;\n case 'INVALID_GRANT':\n fail(\n `A --grant referenced a table/app the backend rejected (${err.message}). Data Hub grants need a table or app that exists in this workspace; module grants need a table your manifest owns.`,\n );\n return 1;\n case 'INSTALLATION_NOT_FOUND':\n fail(\n `Installation not found. It may have been destroyed; re-provision via ${code('dashwise init <slug>')}.`,\n );\n return 1;\n case 'API_KEY_NOT_FOUND':\n fail(\n `API key not found for this installation. Use ${code('dashwise api-keys list')} to see valid ids.`,\n );\n return 1;\n default:\n fail(`Backend rejected: ${err.code} ${err.status} — ${err.message}`);\n return 1;\n }\n }\n fail(`API-key operation failed: ${(err as Error).message}`);\n return 1;\n}\n\n// ── grant parsing (P1-C `--grant`) ───────────────────────────────────\n\nconst GRANT_OPERATIONS = ['create', 'read', 'update', 'delete'] as const;\ntype GrantOperation = (typeof GRANT_OPERATIONS)[number];\n\n/**\n * Parse repeatable `--grant` specs into the backend's `ApiKeyGrantDto[]`.\n * Returns `undefined` when no `--grant` was passed (so the key is minted\n * full-access). Throws a `GrantSpecError`-flavored `Error` with a clear\n * message on any malformed spec.\n *\n * Accepted shapes:\n * module:<tableSlug>:<ops>\n * datahub:table=<id>:<ops>\n * datahub:app=<id>:<ops>\n * datahub:workspace:<ops>\n * where <ops> = comma list drawn from create,read,update,delete.\n */\nfunction parseGrants(specs: string[] | undefined): ApiKeyGrantInput[] | undefined {\n if (!specs || specs.length === 0) return undefined;\n return specs.map((spec) => parseGrantSpec(spec));\n}\n\nfunction parseGrantSpec(spec: string): ApiKeyGrantInput {\n const raw = spec.trim();\n const parts = raw.split(':');\n const source = parts[0];\n\n if (source === 'module') {\n // module:<tableSlug>:<ops>\n if (parts.length !== 3) {\n throw new Error(\n `Invalid --grant \"${spec}\". Module grants are \\`module:<tableSlug>:<ops>\\` (e.g. \\`module:tasks:read,create\\`).`,\n );\n }\n const tableSlug = parts[1];\n if (!tableSlug) {\n throw new Error(`Invalid --grant \"${spec}\": missing table slug.`);\n }\n return {\n source: 'module',\n tableSlug,\n operations: parseOps(parts[2], spec),\n };\n }\n\n if (source === 'datahub') {\n // datahub:table=<id>:<ops> | datahub:app=<id>:<ops> | datahub:workspace:<ops>\n const scope = parts[1];\n if (!scope) {\n throw new Error(\n `Invalid --grant \"${spec}\". Data Hub grants are \\`datahub:table=<id>:<ops>\\`, \\`datahub:app=<id>:<ops>\\`, or \\`datahub:workspace:<ops>\\`.`,\n );\n }\n if (scope === 'workspace') {\n if (parts.length !== 3) {\n throw new Error(\n `Invalid --grant \"${spec}\". Workspace-wide Data Hub grants are \\`datahub:workspace:<ops>\\`.`,\n );\n }\n // No tableId / applicationId — a workspace-wide Data Hub grant.\n return { source: 'datahub', operations: parseOps(parts[2], spec) };\n }\n const eq = scope.indexOf('=');\n const scopeKind = eq === -1 ? scope : scope.slice(0, eq);\n const scopeVal = eq === -1 ? '' : scope.slice(eq + 1);\n if ((scopeKind !== 'table' && scopeKind !== 'app') || scopeVal === '') {\n throw new Error(\n `Invalid --grant \"${spec}\". Data Hub scope must be \\`table=<id>\\`, \\`app=<id>\\`, or \\`workspace\\`.`,\n );\n }\n if (parts.length !== 3) {\n throw new Error(\n `Invalid --grant \"${spec}\". Data Hub grants are \\`datahub:${scopeKind}=<id>:<ops>\\`.`,\n );\n }\n const id = Number.parseInt(scopeVal, 10);\n if (!Number.isInteger(id) || id <= 0 || String(id) !== scopeVal) {\n throw new Error(\n `Invalid --grant \"${spec}\": ${scopeKind} id must be a positive integer (got \"${scopeVal}\").`,\n );\n }\n const operations = parseOps(parts[2], spec);\n return scopeKind === 'table'\n ? { source: 'datahub', tableId: id, operations }\n : { source: 'datahub', applicationId: id, operations };\n }\n\n throw new Error(\n `Invalid --grant \"${spec}\": unknown source \"${source}\". Use \\`module:…\\` or \\`datahub:…\\`.`,\n );\n}\n\nfunction parseOps(opsCsv: string, spec: string): GrantOperation[] {\n const ops = opsCsv\n .split(',')\n .map((o) => o.trim())\n .filter(Boolean);\n if (ops.length === 0) {\n throw new Error(\n `Invalid --grant \"${spec}\": at least one operation is required (${GRANT_OPERATIONS.join(', ')}).`,\n );\n }\n const seen = new Set<GrantOperation>();\n for (const op of ops) {\n if (!(GRANT_OPERATIONS as readonly string[]).includes(op)) {\n throw new Error(\n `Invalid --grant \"${spec}\": unknown operation \"${op}\". Allowed: ${GRANT_OPERATIONS.join(', ')}.`,\n );\n }\n seen.add(op as GrantOperation);\n }\n // Emit in canonical order (create, read, update, delete) regardless of\n // input order, so the request body is deterministic.\n return GRANT_OPERATIONS.filter((op) => seen.has(op));\n}\n\n/**\n * Convert a `--expires <days>` value to an absolute ISO-8601 timestamp\n * the backend accepts as `expires_at`. Returns `undefined` when no\n * `--expires` was passed (never expires). Throws on a non-positive /\n * non-finite day count.\n */\nfunction resolveExpiresAt(days: number | undefined): string | undefined {\n if (days === undefined) return undefined;\n if (!Number.isFinite(days) || days <= 0) {\n throw new Error(`--expires must be a positive number of days (got ${days}).`);\n }\n return new Date(Date.now() + days * 24 * 60 * 60 * 1000).toISOString();\n}\n\n/**\n * Render grant rows into compact human lines, one per (source, scope):\n * operations are collapsed across rows that share a scope. e.g.\n * `module tasks: read, create`\n * `datahub table#12: read`\n * `datahub app#4: read, update`\n * `datahub workspace: read`\n */\nfunction formatGrants(grants: ApiKeyGrantRow[] | undefined): string[] {\n if (!grants || grants.length === 0) return [];\n const byScope = new Map<string, { label: string; ops: Set<string> }>();\n for (const g of grants) {\n const label = grantScopeLabel(g);\n const existing = byScope.get(label);\n if (existing) existing.ops.add(g.operation);\n else byScope.set(label, { label, ops: new Set([g.operation]) });\n }\n return [...byScope.values()].map((s) => {\n const ops = GRANT_OPERATIONS.filter((o) => s.ops.has(o));\n return `${s.label}: ${ops.join(', ')}`;\n });\n}\n\nfunction grantScopeLabel(g: ApiKeyGrantRow): string {\n if (g.source === 'module') return `module ${g.table_slug ?? '?'}`;\n if (g.table_id != null) return `datahub table#${g.table_id}`;\n if (g.application_id != null) return `datahub app#${g.application_id}`;\n return 'datahub workspace';\n}\n\n// ── presentation helpers ─────────────────────────────────────────────\n\nfunction formatKeyStatus(k: ApiKeyPublic): string {\n if (k.revoked_at) return dim('[revoked]');\n if (k.expires_at && new Date(k.expires_at).getTime() <= Date.now()) {\n return dim('[expired]');\n }\n return dim('[active]');\n}\n\nfunction formatRelative(d: Date): string {\n const deltaMs = Date.now() - d.getTime();\n const sec = Math.floor(deltaMs / 1000);\n if (sec < 60) return `${sec}s ago`;\n const min = Math.floor(sec / 60);\n if (min < 60) return `${min}m ago`;\n const hr = Math.floor(min / 60);\n if (hr < 24) return `${hr}h ago`;\n const day = Math.floor(hr / 24);\n return `${day}d ago`;\n}\n","/**\n * `dashwise origins` — manage the current module install's SSO\n * callback-origin allowlist (Phase 2 W3).\n *\n * The scaffold's sign-in route sends its own public origin to the\n * backend as the SSO `callback_url`; the backend only accepts an origin\n * that is allowlisted for the install. `kind='local'` installs allow\n * `http://localhost:<any-port>` (and `127.0.0.1`) implicitly, so local\n * dev needs no config. A DEPLOYED custom domain must be added here.\n *\n * Subcommands:\n * - `list` Show the current allowlist\n * - `add <url>` Add an origin (idempotent; full-replace under the hood)\n * - `remove <url>` Remove an origin\n *\n * Auth: CLI bearer (JWT) — origins management is a workspace-admin\n * operation, NOT a runtime-data-plane operation. The `dwk_` key cached\n * in `auth.json#modules[slug]` doesn't grant this; the user's login\n * bearer does.\n *\n * Install resolution: from the current `module.json#module.slug` +\n * `auth.json#modules[<slug>].installationId`. The user never types an\n * install id — it's internal bookkeeping.\n *\n * Wire model: the backend exposes GET (read) + PUT (full-replace). There\n * is no add/remove endpoint, so `add` / `remove` here do a client-side\n * read-modify-write against the current list.\n */\n\nimport {\n ApiError,\n getOrigins,\n setOrigins,\n type RequestOptions,\n} from '../lib/api-client.js';\nimport { readConfig, readModuleEntry, resolveApiUrl } from '../lib/config.js';\nimport { readManifestOrThrow } from '../lib/manifest-io.js';\nimport { code, dim, fail, info, success } from '../lib/output.js';\n\ninterface CommonOptions {\n dir?: string;\n}\n\ninterface ResolvedContext {\n installationId: number;\n slug: string;\n requestOptions: RequestOptions;\n}\n\n/**\n * Shared setup: resolve the slug + install id from the current project\n * dir + auth.json, build a JWT-authed RequestOptions. Errors thrown as\n * plain `Error`; callers `catch` + `fail(err.message)` + return 1.\n */\nfunction loadContext(opts: CommonOptions): ResolvedContext {\n const manifest = readManifestOrThrow(opts.dir);\n const slug = manifest.module?.slug;\n if (!slug) {\n throw new Error(\n `module.json has no module.slug — the manifest is malformed.`,\n );\n }\n const cfg = readConfig();\n if (!cfg) {\n throw new Error('Not logged in. Run `dashwise login` first.');\n }\n const entry = readModuleEntry(slug);\n if (!entry) {\n throw new Error(\n `No dev install cached for module \"${slug}\". Run \\`dashwise init ${slug} --force\\` to provision one.`,\n );\n }\n return {\n installationId: entry.installationId,\n slug,\n requestOptions: {\n baseUrl: resolveApiUrl(),\n auth: { token: cfg.token },\n },\n };\n}\n\n/**\n * Client-side origin normalization used for de-dup + membership checks.\n * We compare by the URL's origin (scheme + host + explicit port) so\n * `https://x.com` and `https://x.com/` collapse to the same entry. On a\n * non-URL input we fall back to the trimmed raw string (the backend does\n * the authoritative validation on write).\n */\nfunction normalizeOrigin(raw: string): string {\n const trimmed = raw.trim();\n try {\n return new URL(trimmed).origin;\n } catch {\n return trimmed;\n }\n}\n\n// ── list ─────────────────────────────────────────────────────────────\n\nexport interface OriginsListOptions extends CommonOptions {\n json?: boolean;\n}\n\nexport async function originsListCommand(\n options: OriginsListOptions,\n): Promise<number> {\n let ctx: ResolvedContext;\n try {\n ctx = loadContext(options);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n let origins: string[];\n try {\n const resp = await getOrigins(ctx.installationId, ctx.requestOptions);\n origins = resp.allowed_origins;\n } catch (err) {\n return surfaceOriginsError(err);\n }\n\n if (options.json) {\n process.stdout.write(`${JSON.stringify(origins, null, 2)}\\n`);\n return 0;\n }\n\n info(\n `SSO callback origins for ${code(ctx.slug)} ${dim(\n '(localhost is always allowed for local dev installs)',\n )}:`,\n );\n if (origins.length === 0) {\n info(` ${dim('(none configured — only implicit localhost applies)')}`);\n info('');\n info(\n `Add a deployed domain with ${code('dashwise origins add https://your-domain')}.`,\n );\n return 0;\n }\n for (const o of origins) {\n process.stdout.write(` ${o}\\n`);\n }\n return 0;\n}\n\n// ── add ──────────────────────────────────────────────────────────────\n\nexport async function originsAddCommand(\n urlArg: string | undefined,\n options: CommonOptions,\n): Promise<number> {\n if (!urlArg) {\n fail('Usage: `dashwise origins add <url>` (e.g. `dashwise origins add https://app.example.com`)');\n return 1;\n }\n const origin = normalizeOrigin(urlArg);\n\n let ctx: ResolvedContext;\n try {\n ctx = loadContext(options);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n // Read-modify-write: fetch the current list, add if absent, PUT back.\n let current: string[];\n try {\n current = (await getOrigins(ctx.installationId, ctx.requestOptions))\n .allowed_origins;\n } catch (err) {\n return surfaceOriginsError(err);\n }\n\n if (current.some((o) => normalizeOrigin(o) === origin)) {\n info(`${code(origin)} is already allowlisted for ${code(ctx.slug)}. Nothing to do.`);\n return 0;\n }\n\n const next = [...current, origin];\n try {\n const resp = await setOrigins(ctx.installationId, next, ctx.requestOptions);\n success(`Added ${code(origin)} to the SSO callback allowlist for ${code(ctx.slug)}.`);\n info(` ${dim(`${resp.allowed_origins.length} origin(s) now configured.`)}`);\n } catch (err) {\n return surfaceOriginsError(err);\n }\n return 0;\n}\n\n// ── remove ───────────────────────────────────────────────────────────\n\nexport async function originsRemoveCommand(\n urlArg: string | undefined,\n options: CommonOptions,\n): Promise<number> {\n if (!urlArg) {\n fail('Usage: `dashwise origins remove <url>`');\n return 1;\n }\n const origin = normalizeOrigin(urlArg);\n\n let ctx: ResolvedContext;\n try {\n ctx = loadContext(options);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n let current: string[];\n try {\n current = (await getOrigins(ctx.installationId, ctx.requestOptions))\n .allowed_origins;\n } catch (err) {\n return surfaceOriginsError(err);\n }\n\n const next = current.filter((o) => normalizeOrigin(o) !== origin);\n if (next.length === current.length) {\n fail(\n `${code(origin)} is not in the allowlist for ${code(ctx.slug)}. Run ${code('dashwise origins list')} to see current entries.`,\n );\n return 1;\n }\n\n try {\n await setOrigins(ctx.installationId, next, ctx.requestOptions);\n success(`Removed ${code(origin)} from the SSO callback allowlist for ${code(ctx.slug)}.`);\n } catch (err) {\n return surfaceOriginsError(err);\n }\n return 0;\n}\n\n// ── error mapping ────────────────────────────────────────────────────\n\nfunction surfaceOriginsError(err: unknown): number {\n if (err instanceof ApiError) {\n switch (err.code) {\n case 'UNAUTHENTICATED':\n fail(\n `Auth rejected by backend. Your CLI token may be stale — run ${code('dashwise login')} then retry.`,\n );\n return 1;\n case 'NOT_WORKSPACE_MEMBER':\n fail(\n `You're not a member of this installation's workspace. Origins management requires workspace membership.`,\n );\n return 1;\n case 'NOT_WORKSPACE_ADMIN':\n case 'FORBIDDEN':\n fail(\n `Not authorized. Managing SSO callback origins requires workspace-admin.`,\n );\n return 1;\n case 'INVALID_ORIGIN':\n fail(\n `The backend rejected an origin (${err.message}). Non-localhost origins must be absolute https:// URLs.`,\n );\n return 1;\n case 'INSTALLATION_NOT_FOUND':\n fail(\n `Installation not found. It may have been destroyed; re-provision via ${code('dashwise init <slug>')}.`,\n );\n return 1;\n default:\n fail(`Backend rejected: ${err.code} ${err.status} — ${err.message}`);\n return 1;\n }\n }\n fail(`Origins operation failed: ${(err as Error).message}`);\n return 1;\n}\n","/**\n * `dashwise env export` — emit the env vars a deployed module needs\n * to authenticate against the DashWise data plane.\n *\n * HH-CC-P1-D1 (BaaS Phase 1 Bucket D sprint 1). Pairs with:\n * - P1-C1/C4: the API-key infrastructure that supplies\n * `DASHWISE_API_KEY` for production deploys.\n *\n * Default output (--format env): plain `KEY=value` lines suitable\n * for `.env`, Railway dashboard's \"raw env\" paste box, Vercel's\n * import-env, or any Docker-style env file.\n *\n * Other formats wrap the SAME values in platform-native syntax so\n * the user can pipe-copy without rewriting:\n *\n * --format json {\"KEY\": \"value\", ...}\n * --format railway `railway variables set KEY=value …` (single line)\n * --format vercel `vercel env add KEY production` (one per var)\n * --format fly `fly secrets set KEY=value …` (single line)\n *\n * Phase 2 wire protocol: the output is exactly the two-var contract —\n * `DASHWISE_API_URL` + `DASHWISE_API_KEY`. There is no\n * `DASHWISE_INSTALLATION_ID` (the key binds the install server-side) and\n * no `NEXT_PUBLIC_DASHWISE_API_URL` (the scaffold's `next.config` derives\n * it from `DASHWISE_API_URL` at build time).\n *\n * For the `DASHWISE_API_KEY` slot the user has three options:\n *\n * - Default: emit a placeholder + a one-line hint to run\n * `dashwise api-keys create <name>` separately. Multi-export\n * re-uses the same key without polluting the key list.\n * - `--new-key <name>`: mint a fresh key + inline the plaintext\n * in the output. Convenient for first deploys.\n * - `--key dwk_...`: caller supplies a previously-minted key\n * (e.g. from a password manager). No backend round-trip.\n */\n\nimport { createApiKey, ApiError } from '../lib/api-client.js';\nimport { readConfig, readModuleEntry, resolveApiUrl } from '../lib/config.js';\nimport { readManifestOrThrow } from '../lib/manifest-io.js';\nimport { code, dim, fail, info, warn } from '../lib/output.js';\n\nexport type EnvExportFormat = 'env' | 'json' | 'railway' | 'vercel' | 'fly';\n\nexport interface EnvExportOptions {\n dir?: string;\n format?: EnvExportFormat;\n /** Mint a NEW API key with this name + inline it in the output. */\n newKey?: string;\n /** Use a previously-minted API key (paste plaintext). */\n key?: string;\n}\n\nconst PLACEHOLDER =\n '<run-`dashwise-api-keys-create-<name>`-and-paste-here>';\n\nexport async function envExportCommand(\n options: EnvExportOptions,\n): Promise<number> {\n const format: EnvExportFormat = options.format ?? 'env';\n if (!['env', 'json', 'railway', 'vercel', 'fly'].includes(format)) {\n fail(\n `Unknown --format \"${format}\". Allowed: env | json | railway | vercel | fly.`,\n );\n return 1;\n }\n if (options.newKey && options.key) {\n fail(\n `Pass either --new-key (mint fresh) or --key (paste existing). Not both.`,\n );\n return 1;\n }\n\n let manifest;\n try {\n manifest = readManifestOrThrow(options.dir);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n const slug = manifest.module?.slug;\n if (!slug) {\n fail('module.json has no module.slug — the manifest is malformed.');\n return 1;\n }\n const cfg = readConfig();\n if (!cfg) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n const entry = readModuleEntry(slug);\n if (!entry) {\n fail(\n `No dev install cached for module \"${slug}\". Run \\`dashwise init ${slug} --force\\` to provision one.`,\n );\n return 1;\n }\n\n const apiUrl = resolveApiUrl();\n // Internal-only: needed to address the mint endpoint when `--new-key`\n // is passed. It is NOT emitted as an env var (Phase 2 two-var contract).\n const installationId = entry.installationId;\n\n // Resolve the API key slot.\n let apiKey: string;\n let apiKeyComment: string | null = null;\n if (options.key !== undefined) {\n if (!options.key.startsWith('dwk_')) {\n fail(`--key value must start with \\`dwk_\\` (got \"${options.key.slice(0, 8)}…\").`);\n return 1;\n }\n apiKey = options.key;\n apiKeyComment = '# DASHWISE_API_KEY supplied via --key';\n } else if (options.newKey !== undefined) {\n try {\n const resp = await createApiKey(\n installationId,\n { name: options.newKey },\n {\n baseUrl: apiUrl,\n auth: { token: cfg.token },\n },\n );\n apiKey = resp.raw_key;\n apiKeyComment = `# DASHWISE_API_KEY minted by --new-key (id=${resp.api_key.id}, name=\"${resp.api_key.name}\")`;\n // Emit a warning to stderr so even when stdout is captured to\n // a file, the user knows a key was just minted (visible in\n // their terminal).\n process.stderr.write(\n `${dim('[env export]')} Minted API key #${resp.api_key.id} (${resp.api_key.name}). The plaintext below is the ONLY time it's shown — save the file or paste it now.\\n`,\n );\n } catch (err) {\n if (err instanceof ApiError) {\n fail(`Failed to mint API key: ${err.code} ${err.status} — ${err.message}`);\n } else {\n fail(`Failed to mint API key: ${(err as Error).message}`);\n }\n return 1;\n }\n } else {\n apiKey = PLACEHOLDER;\n apiKeyComment =\n '# DASHWISE_API_KEY — run `dashwise api-keys create <name>` to mint one + paste here.';\n }\n\n // Single source of truth for the env shape — the Phase 2 two-var\n // contract. Other formats below render this same set in their\n // platform-native syntax. NOTE: `DASHWISE_INSTALLATION_ID` and\n // `NEXT_PUBLIC_DASHWISE_API_URL` are intentionally NOT emitted — the\n // API key resolves the install server-side, and the scaffold's\n // `next.config` derives the public URL from `DASHWISE_API_URL`.\n const entries: Array<{ key: string; value: string; comment?: string }> = [\n {\n key: 'DASHWISE_API_URL',\n value: apiUrl,\n comment: '# DashWise backend URL — same value the CLI is logged into.',\n },\n {\n key: 'DASHWISE_API_KEY',\n value: apiKey,\n ...(apiKeyComment !== null ? { comment: apiKeyComment } : {}),\n },\n ];\n\n process.stdout.write(render(entries, format));\n // Trailing newline for `env` / shell formats so subsequent prompt\n // appears on a fresh line.\n if (format !== 'json') process.stdout.write('\\n');\n\n // Friendly footer to stderr (so it doesn't pollute redirected\n // stdout). Suggests the next step.\n if (apiKey === PLACEHOLDER) {\n info('');\n info(\n `Next: ${code(`dashwise api-keys create <name>`)} → paste the plaintext into ${code('DASHWISE_API_KEY')}.`,\n );\n } else if (options.newKey !== undefined) {\n info('');\n warn(\n 'API key plaintext is shown ONLY once. Save the output of this command now.',\n );\n }\n return 0;\n}\n\nfunction render(\n entries: Array<{ key: string; value: string; comment?: string }>,\n format: EnvExportFormat,\n): string {\n switch (format) {\n case 'env': {\n const lines: string[] = [];\n for (const e of entries) {\n if (e.comment) lines.push(e.comment);\n lines.push(`${e.key}=${e.value}`);\n lines.push('');\n }\n return lines.join('\\n').trimEnd();\n }\n case 'json': {\n const obj: Record<string, string> = {};\n for (const e of entries) obj[e.key] = e.value;\n return JSON.stringify(obj, null, 2);\n }\n case 'railway': {\n // Railway CLI: `railway variables set KEY=value KEY2=value2`.\n // Single line so the user can pipe-copy.\n const parts = entries.map((e) => `${e.key}='${e.value.replace(/'/g, \"'\\\\''\")}'`);\n return `railway variables set ${parts.join(' ')}`;\n }\n case 'vercel': {\n // Vercel doesn't have a one-shot bulk set in `vercel env`.\n // Emit one line per var. Production scope by default; user\n // can edit if they want preview/development.\n const lines = entries.map(\n (e) =>\n `echo ${shellQuote(e.value)} | vercel env add ${e.key} production`,\n );\n return lines.join('\\n');\n }\n case 'fly': {\n // `fly secrets set KEY=value KEY2=value2`. Single command per\n // Fly's recommendation (sets are atomic — multi-var avoids\n // multiple machine restarts).\n const parts = entries.map((e) => `${e.key}=${shellQuote(e.value)}`);\n return `fly secrets set ${parts.join(' ')}`;\n }\n }\n}\n\n/**\n * Minimal POSIX-shell single-quote escape. Wraps the value in single\n * quotes + escapes embedded single quotes via `'\\''`. Safe for\n * direct interpolation into a shell command.\n */\nfunction shellQuote(value: string): string {\n return `'${value.replace(/'/g, \"'\\\\''\")}'`;\n}\n","/**\n * `dashwise query` — run typed queries against the local module's\n * installation via the @dashai/sdk query plane.\n *\n * Three modes:\n * --inline \"<expr>\" Evaluate a one-liner. `qb`, `deps`, `db` are\n * pre-bound to the local module's generated SDK.\n * Example:\n * dashwise query --inline \"qb.tasks.where({done:false}).count()\"\n * --file <path> Dynamic-import a .mjs/.js file. The file should\n * export a default that's either a Query, an\n * AggQuery, or a Promise.\n * Example file:\n * import { qb } from '@dashai/generated';\n * export default qb.tasks.where({done:false}).limit(20);\n * --repl Open a Node REPL with the generated SDK pre-bound.\n * Top-level await supported. Ctrl-D to exit.\n *\n * All three modes:\n * - Run in the current directory (must contain `module.json` +\n * `node_modules/@dashai/generated`).\n * - Load env from `.env.local` if present (matches the scaffold's\n * dev-loop convention); DASHWISE_API_URL / _INSTALLATION_ID /\n * _API_TOKEN must be set before the SDK can hit the backend.\n * - Print the result as pretty-printed JSON. `--json` flag emits\n * compact JSON for piping.\n *\n * v1 limits:\n * - --file accepts .mjs / .js only. .ts requires `tsx` which we\n * don't bundle yet. Workaround: `npx tsx <path>` directly.\n * - --inline expression must be valid JS (or `await`-friendly\n * pattern). TS syntax not supported in --inline either.\n *\n * Spec: dashwise-devops-docs/plans/modules-sdk-query-v1.md §6.3, §9.\n */\n\nimport { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join, resolve as pathResolve } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { manifestPath, readManifestOrThrow } from '../lib/manifest-io.js';\nimport { code, dim, fail, info, out } from '../lib/output.js';\n\nexport interface QueryCommandOptions {\n dir?: string;\n inline?: string;\n file?: string;\n repl?: boolean;\n json?: boolean;\n /**\n * Phase 5 `.explain()` flag (2026-05-19). When true, the runner\n * calls `.explain()` on the resulting Query/JoinedQuery/AggQuery\n * (returning the Postgres plan envelope) instead of `.execute()`.\n * No-op for `--repl` mode — REPL users call `.explain()` themselves.\n *\n * Backend MVP supports joined queries only; bare own/dep/view paths\n * reject server-side with EXPLAIN_NOT_SUPPORTED_YET. The CLI passes\n * the call through unchanged and surfaces the typed error to the\n * caller.\n */\n explain?: boolean;\n /**\n * Phase 6 streaming flag (2026-05-20). When true, the runner calls\n * `.stream()` instead of `.execute()` and prints rows incrementally\n * as JSON-lines (one row per line, terminated by `\\n`). Lets users\n * see progress on big queries + Ctrl-C cleanly midway. Mutually\n * exclusive with `--explain` (different ops) and `--repl` (REPL\n * users call `.stream()` themselves and use `for await`).\n *\n * `--json` is implied — streaming always emits JSON-lines, never\n * the pretty-printed result wrapper. Bare-array `--json` output is\n * what most users want anyway when piping into `jq`.\n */\n stream?: boolean;\n}\n\nexport async function queryCommand(options: QueryCommandOptions): Promise<number> {\n const projectRoot = pathResolve(options.dir ?? process.cwd());\n\n // Sanity: must be inside a module project.\n try {\n readManifestOrThrow(projectRoot);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n // Must have run `dashwise module generate` so @dashai/generated\n // exists. Surface the missing-package case with the right next step.\n const generatedPath = join(\n projectRoot,\n 'node_modules',\n '@dashai',\n 'generated',\n );\n if (!existsSync(generatedPath)) {\n fail(\n `No ${code('@dashai/generated')} in ${code('node_modules')}. Run ${code('dashwise module generate')} first.`,\n );\n return 1;\n }\n\n // Best-effort env loading from .env.local — matches what the\n // scaffold ships + what `dashwise module dev` would inject. The\n // generated SDK reads these via `process.env.DASHWISE_*` so we\n // hydrate `process.env` directly (vs. a richer dotenv parser —\n // the format is k=v lines, no quoting needed for the dev env).\n hydrateEnvFromDotenvLocal(projectRoot);\n\n // Exactly one mode flag must be set.\n const modes = [\n options.inline !== undefined ? 'inline' : null,\n options.file !== undefined ? 'file' : null,\n options.repl === true ? 'repl' : null,\n ].filter(Boolean);\n if (modes.length === 0) {\n fail('Pass one of: `--inline \"expr\"`, `--file <path>`, or `--repl`.');\n return 1;\n }\n if (modes.length > 1) {\n fail(`--inline / --file / --repl are mutually exclusive (got: ${modes.join(', ')}).`);\n return 1;\n }\n\n // Phase 5 (2026-05-19): --explain is meaningless with --repl (REPL\n // users call .explain() themselves). Reject the combo with a clear\n // message rather than silently ignoring.\n if (options.explain === true && options.repl === true) {\n fail('--explain has no effect with --repl. In the REPL, call `.explain()` directly on your builder.');\n return 1;\n }\n // Phase 6 streaming (2026-05-20): same logic for --stream + --repl.\n if (options.stream === true && options.repl === true) {\n fail('--stream has no effect with --repl. In the REPL, call `.stream()` directly + use `for await`.');\n return 1;\n }\n // --explain and --stream are different operations (return plan vs.\n // stream rows). Mutual exclusion prevents accidental misuse like\n // \"stream the explain plan\" which has no defined semantic.\n if (options.explain === true && options.stream === true) {\n fail('--explain and --stream are mutually exclusive — `.explain()` returns a single plan envelope; `.stream()` yields rows.');\n return 1;\n }\n const explain = options.explain === true;\n const stream = options.stream === true;\n\n if (options.repl) return runRepl(generatedPath);\n if (options.file !== undefined)\n return runFile(options.file, projectRoot, options.json === true, explain, stream);\n if (options.inline !== undefined)\n return runInline(\n options.inline,\n projectRoot,\n generatedPath,\n options.json === true,\n explain,\n stream,\n );\n // Unreachable per the modes check above.\n return 1;\n}\n\n// ── Mode: --inline ──────────────────────────────────────────────────────\n\n/**\n * Evaluate a one-liner expression with `qb`, `deps`, `db` in scope.\n *\n * Strategy: write a temp `.mjs` file that imports the generated SDK\n * + evaluates the expression as a default export, then dynamic-import\n * it. The temp file lives in tmpdir; cleaned up on the way out (or\n * left on disk if the process is killed — best-effort cleanup).\n *\n * Reason for temp-file vs. `new Function(...)`: dynamic import gives\n * us proper ESM semantics + module-resolution against `node_modules/@dashai/generated`,\n * which `new Function` doesn't. Cost is one syscall per invocation.\n */\nasync function runInline(\n expression: string,\n projectRoot: string,\n _generatedPath: string,\n jsonCompact: boolean,\n explain: boolean,\n stream: boolean,\n): Promise<number> {\n const tmpDir = mkdtempSync(join(tmpdir(), 'dashwise-query-'));\n const tmpFile = join(tmpDir, 'inline.mjs');\n // Strip a trailing semicolon if present so the embedded expression\n // is a valid value position.\n const cleanedExpr = expression.trim().replace(/;\\s*$/, '');\n const source = [\n \"import { qb, deps, db } from '@dashai/generated';\",\n `export default (async () => (${cleanedExpr}))();`,\n '',\n ].join('\\n');\n writeFileSync(tmpFile, source, 'utf-8');\n try {\n return await importAndPrint(tmpFile, projectRoot, jsonCompact, explain, stream);\n } finally {\n try {\n rmSync(tmpDir, { recursive: true, force: true });\n } catch {\n // Best-effort cleanup. tmp dirs get reaped by the OS.\n }\n }\n}\n\n// ── Mode: --file ────────────────────────────────────────────────────────\n\n/**\n * Run a `.mjs` / `.js` file via dynamic import. The file should\n * export a default that's a Query / AggQuery / Promise / value.\n *\n * `.ts` files are NOT supported in v1 — would require bundling `tsx`\n * or running through `node --import tsx`. Users can shell out via\n * `npx tsx <file>` directly for TS today.\n */\nasync function runFile(\n file: string,\n projectRoot: string,\n jsonCompact: boolean,\n explain: boolean,\n stream: boolean,\n): Promise<number> {\n const abs = pathResolve(projectRoot, file);\n if (!existsSync(abs)) {\n fail(`File not found: ${code(abs)}`);\n return 1;\n }\n if (!/\\.(mjs|js)$/.test(abs)) {\n fail(\n `Only .mjs / .js files are supported in v1. For .ts files, run ${code('npx tsx <file>')} directly. (Tracked: bundle tsx for native .ts support.)`,\n );\n return 1;\n }\n return importAndPrint(abs, projectRoot, jsonCompact, explain, stream);\n}\n\n// ── Mode: --repl ────────────────────────────────────────────────────────\n\n/**\n * Open an interactive Node REPL with the generated SDK pre-bound.\n *\n * Implementation: Node's built-in `repl` module. The generated SDK is\n * imported once at startup + its exports (`qb`, `deps`, `db`) are\n * added to the REPL's context object. Top-level await works because\n * Node's REPL has supported it since v12.\n *\n * Exit with `.exit` or Ctrl-D. Stack traces from query errors stay\n * in the REPL so users can keep iterating.\n */\nasync function runRepl(generatedPath: string): Promise<number> {\n let generated: Record<string, unknown>;\n try {\n generated = await dynamicImportFromPath(generatedPath);\n } catch (err) {\n fail(\n `Could not import ${code('@dashai/generated')}: ${(err as Error).message}`,\n );\n info(\n `Try running ${code('dashwise module generate')} to refresh the typed wrappers.`,\n );\n return 1;\n }\n\n info(`${code('dashwise query --repl')} — Node REPL with qb / deps / db pre-bound.`);\n info(`Try: ${code('await qb.<table>.execute()')} Ctrl-D to exit.`);\n out('');\n\n // Dynamic require for Node's repl module — keep it lazy so the\n // command's startup cost stays low for the inline/file modes.\n const repl = await import('node:repl');\n const server = repl.start({\n prompt: `${code('dashwise')}${dim('>')} `,\n useColors: true,\n useGlobal: false,\n });\n // Inject the generated SDK's exports into the REPL context so\n // users type `qb.tasks.execute()` without imports.\n for (const [key, value] of Object.entries(generated)) {\n Object.defineProperty(server.context, key, {\n configurable: false,\n enumerable: true,\n writable: false,\n value,\n });\n }\n\n return new Promise<number>((resolveExit) => {\n server.on('exit', () => {\n out(dim('Goodbye.'));\n resolveExit(0);\n });\n });\n}\n\n// ── Helpers ────────────────────────────────────────────────────────────\n\n/**\n * Dynamic-import `file` (resolving from `projectRoot`'s\n * `node_modules`), await the default export if it's a Promise / Query\n * / AggQuery, and pretty-print the result.\n */\nasync function importAndPrint(\n file: string,\n projectRoot: string,\n jsonCompact: boolean,\n explain: boolean,\n stream: boolean,\n): Promise<number> {\n // Switch cwd so bare imports inside the file resolve against the\n // project's `node_modules` instead of the CLI's own. Saved + restored\n // around the import — defensive in case the consumer's code touches\n // process.cwd elsewhere.\n const originalCwd = process.cwd();\n try {\n process.chdir(projectRoot);\n const url = pathToFileURL(file).toString();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const mod: any = await import(url);\n let result = mod.default;\n // Default-export shapes we handle:\n // - Promise<T> → await it\n // - Query / AggQuery → .execute() (or .explain() if --explain,\n // or .stream() if --stream)\n // - Anything else → print as-is\n if (result && typeof result.then === 'function') {\n result = await result;\n }\n if (result && typeof result.toAst === 'function') {\n // Phase 6 streaming (2026-05-20): --stream takes precedence over\n // --execute (they're mutually exclusive at the option-parse level,\n // but ordering matters at dispatch time). Iterate the async\n // iterable + print one JSON-line per row so consumers can pipe\n // into jq / line-oriented tools.\n if (stream && typeof result.stream === 'function') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const iterable = result.stream() as AsyncIterable<unknown>;\n let rowCount = 0;\n for await (const row of iterable) {\n out(JSON.stringify(row));\n rowCount++;\n }\n // Emit a final summary on stderr so it doesn't pollute the\n // JSON-lines stdout stream. Consumers piping into jq see ONLY\n // the data; humans see \"streamed N rows\" at the bottom.\n if (!jsonCompact) {\n info(`Streamed ${rowCount} row${rowCount === 1 ? '' : 's'}.`);\n }\n return 0;\n }\n // Phase 5 `.explain()` (2026-05-19): if --explain was passed,\n // call .explain() instead of .execute(). All three builder\n // shapes (Query, JoinedQuery, AggQuery) expose .explain() since\n // the SDK slice landed alongside this CLI flag.\n if (explain && typeof result.explain === 'function') {\n result = await result.explain();\n } else if (typeof result.execute === 'function') {\n result = await result.execute();\n }\n }\n if (jsonCompact) {\n out(JSON.stringify(result));\n } else {\n out(JSON.stringify(result, null, 2));\n }\n return 0;\n } catch (err) {\n fail(`Query failed: ${(err as Error).message}`);\n if (process.env.DASHWISE_DEBUG) {\n // eslint-disable-next-line no-console\n console.error(err);\n }\n return 1;\n } finally {\n process.chdir(originalCwd);\n }\n}\n\n/**\n * Resolve `@dashai/generated` from the project's node_modules and\n * dynamic-import its entry. Returns the module's exports object.\n */\nasync function dynamicImportFromPath(\n generatedDir: string,\n): Promise<Record<string, unknown>> {\n // Project-local @dashai/generated has `index.js` per the codegen\n // emitter; resolve directly rather than going through Node's package\n // resolution to keep the path deterministic.\n const entry = join(generatedDir, 'index.js');\n if (!existsSync(entry)) {\n throw new Error(`Expected ${entry} to exist. Did 'dashwise module generate' run?`);\n }\n const url = pathToFileURL(entry).toString();\n return (await import(url)) as Record<string, unknown>;\n}\n\n/**\n * Read `.env.local` from `projectRoot` and merge into `process.env`\n * without overwriting existing values. Supports `KEY=value` lines\n * + `#`-prefixed comments + blank lines — same dialect the scaffold's\n * `.env.local.example` uses. Robust enough for the dev-loop env.\n */\nfunction hydrateEnvFromDotenvLocal(projectRoot: string): void {\n const envFile = join(projectRoot, '.env.local');\n if (!existsSync(envFile)) return;\n const raw = readFileSync(envFile, 'utf-8');\n for (const line of raw.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (trimmed.length === 0 || trimmed.startsWith('#')) continue;\n const eq = trimmed.indexOf('=');\n if (eq <= 0) continue;\n const key = trimmed.slice(0, eq).trim();\n let value = trimmed.slice(eq + 1).trim();\n // Strip a single surrounding quote pair if present.\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n if (process.env[key] === undefined) {\n process.env[key] = value;\n }\n }\n}\n\n// Use manifestPath() from manifest-io so the import isn't tree-shaken\n// for unused-import lint without an actual call.\nvoid manifestPath;\n","/**\n * `dashwise module query-log` — read the per-module SDK query log.\n *\n * Hits `GET /api/modules/:moduleId/query-log?since=...&slow=...&limit=...`\n * (added in dashwise-backend Phase 6 slice 6.4). Workspace-member-\n * scoped on the server side — non-members get 403 NOT_A_WORKSPACE_MEMBER.\n *\n * Module resolution order:\n * 1. `--module <id-or-slug>` if provided\n * 2. `module.json#module.slug` in the current directory if present\n * 3. Otherwise fail with a \"which module?\" message\n *\n * Output: column-aligned table by default; pass `--json` for compact\n * JSON suitable for piping into `jq`.\n *\n * `--tail` polls every 5s for new entries (the last-seen `created_at`\n * becomes the next poll's `since` filter). Stops on Ctrl-C. Server\n * still enforces the 500-row response cap per poll, so very busy\n * modules may see \"(more entries above)\" between polls if log\n * volume exceeds 500/5s.\n */\n\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { readManifestOrThrow } from '../../lib/manifest-io.js';\nimport { code, dim, fail, info, out } from '../../lib/output.js';\n\nexport interface ModuleQueryLogOptions {\n /**\n * Module to read the log for. Accepts a numeric id (`123`) or a\n * slug (`my-module`). If omitted, falls back to the slug in the\n * current directory's `module.json`.\n */\n module?: string;\n /**\n * Filter to slow queries only (duration_ms > 500 — matches the\n * SDK/backend slow-query threshold).\n */\n slow?: boolean;\n /**\n * Filter rows where `created_at >= NOW() - <since>`. Duration\n * shorthand (`30m`, `1h`, `2d`, `7d`) or ISO 8601 timestamp.\n * Passed through to the backend's validator.\n */\n since?: string;\n /**\n * Max rows to fetch per call. Default 50; backend caps at 500.\n */\n limit?: number;\n /**\n * Poll for new entries every 5s. Stops on Ctrl-C. Mutually\n * exclusive with `--json` (tail mode prints the table format\n * incrementally).\n */\n tail?: boolean;\n /**\n * Emit compact JSON instead of the table. Useful for piping into\n * `jq` / scripting. Ignored when `--tail` is set.\n */\n json?: boolean;\n /**\n * Override project directory (for `module.json` slug lookup).\n * Defaults to `process.cwd()`. Only consulted when `--module` is\n * absent.\n */\n dir?: string;\n}\n\ninterface QueryLogRow {\n id: string;\n request_id: string;\n installation_id: number;\n module_id: number;\n endpoint: 'query' | 'explain';\n ast_hash: string | null;\n duration_ms: number;\n row_count: number | null;\n error_code: string | null;\n error_message: string | null;\n created_at: string;\n}\n\ninterface QueryLogResponse {\n entries: QueryLogRow[];\n count: number;\n}\n\ninterface ModuleByIdResponse {\n id: number;\n slug: string;\n}\n\nconst POLL_INTERVAL_MS = 5_000;\n\nexport async function moduleQueryLogCommand(\n options: ModuleQueryLogOptions,\n): Promise<number> {\n // Resolve the moduleId. The user can pass `--module <id-or-slug>`\n // or we infer from the current directory's manifest.\n let moduleId: number;\n try {\n moduleId = await resolveModuleId(options.module, options.dir);\n } catch (err) {\n fail((err as Error).message);\n return 1;\n }\n\n if (options.tail) {\n return runTail(moduleId, options);\n }\n return runOnce(moduleId, options);\n}\n\n// ── One-shot mode (default) ──────────────────────────────────────\n\nasync function runOnce(\n moduleId: number,\n options: ModuleQueryLogOptions,\n): Promise<number> {\n const params: Record<string, string> = {};\n if (options.slow) params.slow = 'true';\n if (options.since) params.since = options.since;\n if (typeof options.limit === 'number') params.limit = String(options.limit);\n const qs = new URLSearchParams(params).toString();\n const path = `/api/modules/${moduleId}/query-log${qs ? `?${qs}` : ''}`;\n\n let body: QueryLogResponse;\n try {\n body = await apiRequest<QueryLogResponse>('GET', path);\n } catch (err) {\n return handleApiError(err);\n }\n\n if (options.json) {\n out(JSON.stringify(body));\n return 0;\n }\n\n if (body.entries.length === 0) {\n info(\n options.slow\n ? 'No slow queries in the requested window.'\n : 'No query log entries in the requested window.',\n );\n return 0;\n }\n\n renderTable(body.entries);\n out('');\n info(`${body.count} ${body.count === 1 ? 'entry' : 'entries'}.`);\n return 0;\n}\n\n// ── --tail mode ──────────────────────────────────────────────────\n\nasync function runTail(\n moduleId: number,\n options: ModuleQueryLogOptions,\n): Promise<number> {\n // Initial fetch — use whatever filters the user passed plus a\n // reasonable starting window if `--since` wasn't set.\n const initialParams: Record<string, string> = {};\n if (options.slow) initialParams.slow = 'true';\n initialParams.since = options.since ?? '5m';\n if (typeof options.limit === 'number') initialParams.limit = String(options.limit);\n const initialQs = new URLSearchParams(initialParams).toString();\n\n info(`Tailing query log for module ${moduleId}. Ctrl-C to stop.`);\n out('');\n\n // Track the most-recent created_at across polls so we can fetch\n // strictly-new rows. The backend's `since` param does a NOW()-based\n // window, so we use a small overlap (2s) to ensure we don't miss\n // entries whose created_at lands between poll cycles. De-dup by\n // request_id locally to suppress overlap repeats.\n const seenIds = new Set<string>();\n let firstPoll = true;\n\n // Print headers once up front; subsequent polls append rows without\n // re-printing.\n printTableHeader();\n\n // Initial poll uses the user-specified since; subsequent polls use\n // a fixed 7s window (5s poll interval + 2s overlap).\n while (true) {\n try {\n const path = `/api/modules/${moduleId}/query-log?${firstPoll ? initialQs : buildTailParams(options)}`;\n const body = await apiRequest<QueryLogResponse>('GET', path);\n\n // Print rows in chronological order (response is DESC, reverse\n // for the tail's natural \"latest at bottom\" reading order).\n const newRows: QueryLogRow[] = [];\n for (const row of [...body.entries].reverse()) {\n if (seenIds.has(row.request_id)) continue;\n seenIds.add(row.request_id);\n newRows.push(row);\n }\n for (const row of newRows) {\n out(formatRow(row));\n }\n firstPoll = false;\n } catch (err) {\n // Don't crash the tail on transient errors — log + continue.\n info(dim(`(tail poll error: ${(err as Error).message})`));\n }\n await sleep(POLL_INTERVAL_MS);\n }\n}\n\nfunction buildTailParams(options: ModuleQueryLogOptions): string {\n const params: Record<string, string> = { since: '7s' };\n if (options.slow) params.slow = 'true';\n if (typeof options.limit === 'number') params.limit = String(options.limit);\n return new URLSearchParams(params).toString();\n}\n\n// ── Module-id resolution ─────────────────────────────────────────\n\nasync function resolveModuleId(\n moduleArg: string | undefined,\n dir: string | undefined,\n): Promise<number> {\n // 1. Explicit --module: numeric → use as-is; slug → lookup.\n if (moduleArg && moduleArg.length > 0) {\n const asInt = Number.parseInt(moduleArg, 10);\n if (Number.isFinite(asInt) && String(asInt) === moduleArg) {\n return asInt;\n }\n return lookupModuleIdBySlug(moduleArg);\n }\n // 2. Fall back to module.json in the project directory.\n const projectRoot = dir ?? process.cwd();\n try {\n const manifest = readManifestOrThrow(projectRoot);\n if (manifest?.module?.slug) {\n return lookupModuleIdBySlug(manifest.module.slug);\n }\n } catch {\n // Manifest absent or malformed — fall through to the error below.\n }\n throw new Error(\n `No module specified. Pass --module <id-or-slug> or run inside a module project directory containing module.json.`,\n );\n}\n\nasync function lookupModuleIdBySlug(slug: string): Promise<number> {\n const found = await apiRequest<ModuleByIdResponse>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(slug)}`,\n );\n if (!found || typeof found.id !== 'number') {\n throw new Error(`Module ${code(slug)} not found.`);\n }\n return found.id;\n}\n\n// ── Error handling ───────────────────────────────────────────────\n\nfunction handleApiError(err: unknown): number {\n if (err instanceof ApiError) {\n if (err.status === 401) {\n fail('Not logged in. Run `dashwise login` first.');\n return 1;\n }\n if (err.status === 403) {\n fail(\n `Forbidden — you are not a member of this module's owner workspace. ` +\n `Use \\`dashwise workspace list\\` to see what you have access to.`,\n );\n return 1;\n }\n if (err.status === 404) {\n fail(`Module not found.`);\n return 1;\n }\n }\n fail(`Could not load query log: ${(err as Error).message}`);\n return 1;\n}\n\n// ── Table rendering ──────────────────────────────────────────────\n\n/**\n * Column widths chosen to fit a typical 80-col terminal plus a\n * little slack. ID is the bigint serialized as string (up to ~19\n * digits); we show only the last 8 for compactness — the request_id\n * is the real trace anchor anyway.\n */\nconst COL_WIDTHS = {\n time: 19, // \"YYYY-MM-DD HH:MM:SS\"\n endpoint: 7, // \"query\" | \"explain\"\n ms: 6, // \"12345\" with margin\n rows: 5,\n code: 18,\n request: 12, // first 12 chars of request_id (most are UUIDs)\n};\n\nfunction renderTable(entries: QueryLogRow[]): void {\n out('');\n printTableHeader();\n // Server returns DESC (newest first) — preserve that for one-shot\n // mode so the most-recent activity is at the top of the screen.\n for (const row of entries) {\n out(formatRow(row));\n }\n}\n\nfunction printTableHeader(): void {\n out(\n [\n 'TIME'.padEnd(COL_WIDTHS.time),\n 'ENDPT'.padEnd(COL_WIDTHS.endpoint),\n 'MS'.padStart(COL_WIDTHS.ms),\n 'ROWS'.padStart(COL_WIDTHS.rows),\n 'CODE'.padEnd(COL_WIDTHS.code),\n 'REQ',\n ].join(' '),\n );\n out(\n [\n '-'.repeat(COL_WIDTHS.time),\n '-'.repeat(COL_WIDTHS.endpoint),\n '-'.repeat(COL_WIDTHS.ms),\n '-'.repeat(COL_WIDTHS.rows),\n '-'.repeat(COL_WIDTHS.code),\n '-'.repeat(COL_WIDTHS.request),\n ].join(' '),\n );\n}\n\nfunction formatRow(row: QueryLogRow): string {\n const time = formatTimestamp(row.created_at);\n const endpoint = row.endpoint.padEnd(COL_WIDTHS.endpoint);\n const ms = String(row.duration_ms).padStart(COL_WIDTHS.ms);\n const rows =\n row.row_count === null ? '—'.padStart(COL_WIDTHS.rows) : String(row.row_count).padStart(COL_WIDTHS.rows);\n const errCode = row.error_code ?? '';\n const codeCol = errCode\n ? code(errCode).padEnd(COL_WIDTHS.code + (code(errCode).length - errCode.length))\n : 'OK'.padEnd(COL_WIDTHS.code);\n const req = row.request_id.slice(0, COL_WIDTHS.request);\n return [time, endpoint, ms, rows, codeCol, dim(req)].join(' ');\n}\n\nfunction formatTimestamp(iso: string): string {\n // YYYY-MM-DD HH:MM:SS for compact display; preserves UTC if the\n // input is Z-suffixed. We deliberately don't convert to local TZ\n // here so log entries are reproducible across consumers in\n // different timezones.\n return iso.slice(0, 19).replace('T', ' ');\n}\n\n// ── Misc ─────────────────────────────────────────────────────────\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n","/**\n * `dashwise module action-log` — read the per-installation server-action\n * audit log (cross-module + own-module dispatches).\n *\n * Hits `GET /api/modules/runtime/installations/:installationId/action-log`\n * (added in dashwise-backend Phase 7 slice 7.5a). Workspace-member-scoped\n * server-side — non-members get 403 NOT_A_WORKSPACE_MEMBER.\n *\n * **Why per-installation, not per-module**: cross-module dispatches are\n * events between TWO installations. The audit row keys by\n * installation id (not module id). The CLI surfaces either side\n * (`--role caller` for outbound; `--role provider` for inbound) so\n * authors can debug both directions from the same command.\n *\n * The user provides `--installation <id>` directly. A `--module <slug>`\n * convenience that resolves to the user's default-workspace\n * installation is a planned follow-up; it needs a new backend\n * \"list-installations-by-module-in-workspace\" endpoint.\n *\n * Output: column-aligned table by default; pass `--json` for compact\n * JSON suitable for piping into `jq`.\n *\n * `--tail` polls every 5s for new entries (last-seen `created_at`\n * becomes the next poll's `since` filter). Stops on Ctrl-C. Server\n * still enforces the 500-row response cap per poll.\n */\n\nimport { ApiError, apiRequest } from '../../lib/api-client.js';\nimport { code, dim, fail, info, out } from '../../lib/output.js';\n\nexport interface ModuleActionLogOptions {\n /**\n * Installation to read the log for (numeric id). Mutually exclusive\n * with `module` — exactly one must be set. (Validated by the CLI\n * binder; the action handler treats both as optional + checks.)\n */\n installation?: number;\n /**\n * Module slug — resolves to the caller's accessible installation\n * via `GET /api/modules/by-slug/:slug/my-installation`. Convenience\n * for the common case where the user has one workspace's\n * installation; multi-workspace authors should use `--installation`\n * with an explicit id (or `dashwise workspace use <slug>` to fix\n * the default).\n */\n module?: string;\n /**\n * Which side of cross-module dispatches to query.\n * - `caller` (default) → outbound actions THIS installation invoked\n * - `provider` → inbound actions OTHER modules invoked on THIS installation\n */\n role?: 'caller' | 'provider';\n /**\n * Filter to slow actions only (elapsed_ms > 500 — matches the\n * SDK/backend slow threshold). Uses the partial slow-action index.\n */\n slow?: boolean;\n /**\n * Filter rows where `created_at >= NOW() - <since>`. Duration\n * shorthand (`30m`, `1h`, `2d`, `7d`) or ISO 8601 timestamp.\n */\n since?: string;\n /** Filter to cross-module dispatches only (cross_module=true rows). */\n crossModuleOnly?: boolean;\n /** Max rows per call. Default 50; backend caps at 500. */\n limit?: number;\n /**\n * Poll every 5s for new entries. Stops on Ctrl-C. Mutually exclusive\n * with `--json` (tail mode prints incrementally as rows arrive).\n */\n tail?: boolean;\n /** Compact JSON instead of the table. Ignored when `--tail` is set. */\n json?: boolean;\n}\n\ninterface ActionLogRow {\n id: string;\n request_id: string;\n caller_installation_id: number;\n caller_module_slug: string;\n caller_user_id: number | null;\n provider_installation_id: number;\n provider_module_slug: string;\n action_name: string;\n input_hash: string;\n output_hash: string | null;\n ok: boolean;\n error_code: string | null;\n elapsed_ms: number;\n cross_module: boolean;\n created_at: string;\n}\n\ninterface ActionLogResponse {\n entries: ActionLogRow[];\n count: number;\n}\n\nconst POLL_INTERVAL_MS = 5_000;\n\nexport async function moduleActionLogCommand(\n options: ModuleActionLogOptions,\n): Promise<number> {\n // Validate mutually-exclusive scope flags.\n if (options.installation === undefined && options.module === undefined) {\n fail('Must pass either `--installation <id>` or `--module <slug>`.');\n return 1;\n }\n if (options.installation !== undefined && options.module !== undefined) {\n fail('`--installation` and `--module` are mutually exclusive — pass one or the other.');\n return 1;\n }\n\n // If --module was passed, resolve to an installation id.\n let installationId = options.installation;\n if (installationId === undefined && options.module !== undefined) {\n try {\n const resolved = await apiRequest<{ installation_id: number; module_slug: string }>(\n 'GET',\n `/api/modules/by-slug/${encodeURIComponent(options.module)}/my-installation`,\n );\n installationId = resolved.installation_id;\n } catch (err) {\n return mapAndPrintError(err, options.json);\n }\n }\n if (options.tail) {\n return runTail(installationId as number, options);\n }\n return runOnce(installationId as number, options);\n}\n\n// ── One-shot mode ────────────────────────────────────────────────\n\nasync function runOnce(installationId: number, options: ModuleActionLogOptions): Promise<number> {\n const params: Record<string, string> = {};\n if (options.role !== undefined) params.role = options.role;\n if (options.slow) params.slow = 'true';\n if (options.crossModuleOnly) params.cross_module_only = 'true';\n if (options.since !== undefined) params.since = options.since;\n if (options.limit !== undefined) params.limit = String(options.limit);\n\n let response: ActionLogResponse;\n try {\n response = await apiRequest<ActionLogResponse>(\n 'GET',\n `/api/modules/runtime/installations/${installationId}/action-log?${new URLSearchParams(params).toString()}`,\n );\n } catch (err) {\n return mapAndPrintError(err, options.json);\n }\n\n if (options.json) {\n out(JSON.stringify(response));\n return 0;\n }\n\n printTable(response.entries);\n if (response.entries.length === 0) {\n info('No entries.');\n }\n return 0;\n}\n\n// ── Tail mode ────────────────────────────────────────────────────\n\nasync function runTail(installationId: number, options: ModuleActionLogOptions): Promise<number> {\n if (options.json) {\n fail('`--tail` and `--json` are mutually exclusive.');\n return 1;\n }\n info(`Tailing action log for installation ${code(String(installationId))} every 5s. Ctrl-C to stop.`);\n\n let lastSeen: string | undefined;\n const printed = new Set<string>();\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const params: Record<string, string> = {};\n if (options.role !== undefined) params.role = options.role;\n if (options.slow) params.slow = 'true';\n if (options.crossModuleOnly) params.cross_module_only = 'true';\n if (lastSeen !== undefined) params.since = lastSeen;\n else if (options.since !== undefined) params.since = options.since;\n params.limit = String(options.limit ?? 100);\n\n try {\n const response = await apiRequest<ActionLogResponse>(\n 'GET',\n `/api/modules/runtime/installations/${installationId}/action-log?${new URLSearchParams(params).toString()}`,\n );\n // Backend returns rows newest-first; we want oldest-first when\n // tailing so the user reads down the page. Reverse + dedup by id.\n const fresh = response.entries.filter((e) => !printed.has(e.id)).reverse();\n if (fresh.length > 0) {\n for (const entry of fresh) {\n printed.add(entry.id);\n printRow(entry);\n }\n // Update since-anchor to the newest row we just printed.\n lastSeen = fresh[fresh.length - 1].created_at;\n }\n } catch (err) {\n // Tail mode swallows transient errors + keeps polling. Fatal\n // (401/403) drops out so the user knows to re-login.\n if (err instanceof ApiError && (err.status === 401 || err.status === 403)) {\n return mapAndPrintError(err, false);\n }\n dim(`(tail: transient error — ${(err as Error).message})`);\n }\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n}\n\n// ── Output ───────────────────────────────────────────────────────\n\nfunction printTable(rows: ActionLogRow[]): void {\n if (rows.length === 0) {\n out('');\n out(' (no entries)');\n out('');\n return;\n }\n const widths = {\n time: 19,\n elapsed: 5,\n cross: 5,\n caller: 18,\n action: 22,\n code: 18,\n };\n out('');\n out(\n `${'TIME'.padEnd(widths.time)} ${'MS'.padStart(widths.elapsed)} ${'CROSS'.padEnd(widths.cross)} ${'CALLER'.padEnd(widths.caller)} ${'ACTION'.padEnd(widths.action)} ${'CODE'.padEnd(widths.code)}`,\n );\n out(\n `${'-'.repeat(widths.time)} ${'-'.repeat(widths.elapsed)} ${'-'.repeat(widths.cross)} ${'-'.repeat(widths.caller)} ${'-'.repeat(widths.action)} ${'-'.repeat(widths.code)}`,\n );\n for (const r of rows) {\n printRow(r);\n }\n out('');\n info(`${rows.length} entr${rows.length === 1 ? 'y' : 'ies'}.`);\n}\n\nfunction printRow(r: ActionLogRow): void {\n const time = r.created_at.slice(0, 19).replace('T', ' ');\n const cross = r.cross_module ? code('yes') : dim(' no');\n const codeCol = r.ok ? dim('-') : code(r.error_code ?? 'ERROR');\n out(\n `${time.padEnd(19)} ${String(r.elapsed_ms).padStart(5)} ${cross.padEnd(5)} ${r.caller_module_slug.padEnd(18)} ${r.action_name.padEnd(22)} ${codeCol}`,\n );\n}\n\nfunction mapAndPrintError(err: unknown, json: boolean | undefined): number {\n if (err instanceof ApiError) {\n if (err.status === 401) {\n const msg = 'Not logged in. Run `dashwise login` first.';\n if (json) out(JSON.stringify({ ok: false, error: { code: 'NOT_LOGGED_IN', message: msg } }));\n else fail(msg);\n return 1;\n }\n if (err.status === 403) {\n const msg = 'Workspace-member access required for this installation.';\n if (json) out(JSON.stringify({ ok: false, error: { code: 'FORBIDDEN', message: msg } }));\n else fail(msg);\n return 1;\n }\n if (err.status === 404) {\n const msg = 'Installation not found.';\n if (json) out(JSON.stringify({ ok: false, error: { code: 'INSTALLATION_NOT_FOUND', message: msg } }));\n else fail(msg);\n return 1;\n }\n }\n const msg = `Could not fetch action log: ${(err as Error).message}`;\n if (json) out(JSON.stringify({ ok: false, error: { code: 'FETCH_FAILED', message: (err as Error).message } }));\n else fail(msg);\n return 1;\n}\n"]}
|