@databricks/appkit-ui 0.91.3 → 0.93.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/CLAUDE.md +2 -0
- package/NOTICE.md +3 -3
- package/dist/cli/commands/doctor/checks-existence.js +15 -0
- package/dist/cli/commands/doctor/checks-existence.js.map +1 -1
- package/dist/cli/commands/plugin/add/add.js +398 -0
- package/dist/cli/commands/plugin/add/add.js.map +1 -0
- package/dist/cli/commands/plugin/add/plan.js +216 -0
- package/dist/cli/commands/plugin/add/plan.js.map +1 -0
- package/dist/cli/commands/plugin/add/resolve.js +45 -0
- package/dist/cli/commands/plugin/add/resolve.js.map +1 -0
- package/dist/cli/commands/plugin/create/resource-defaults.js +4 -0
- package/dist/cli/commands/plugin/create/resource-defaults.js.map +1 -1
- package/dist/cli/commands/plugin/index.js +4 -1
- package/dist/cli/commands/plugin/index.js.map +1 -1
- package/dist/cli/commands/plugin/schema-resources.js +2 -1
- package/dist/cli/commands/plugin/schema-resources.js.map +1 -1
- package/dist/cli/commands/registry/add.js +3 -2
- package/dist/cli/commands/registry/add.js.map +1 -1
- package/dist/cli/commands/registry/config-plan.js +1 -1
- package/dist/cli/commands/registry/config-plan.js.map +1 -1
- package/dist/cli/commands/registry/config-writer.js +77 -9
- package/dist/cli/commands/registry/config-writer.js.map +1 -1
- package/dist/cli/commands/registry/env-writer.js +15 -2
- package/dist/cli/commands/registry/env-writer.js.map +1 -1
- package/dist/cli/commands/registry/server-register.js +62 -26
- package/dist/cli/commands/registry/server-register.js.map +1 -1
- package/dist/cli/commands/registry/workspace-picker.js +47 -2
- package/dist/cli/commands/registry/workspace-picker.js.map +1 -1
- package/dist/cli/deploy-config.js.map +1 -1
- package/dist/cli/index.js +1 -1
- package/dist/react/beta.d.ts +3 -1
- package/dist/react/beta.js +3 -1
- package/dist/react/charts/base.d.ts +1 -1
- package/dist/react/charts/base.d.ts.map +1 -1
- package/dist/react/charts/base.js +5 -3
- package/dist/react/charts/base.js.map +1 -1
- package/dist/react/charts/constants.js +13 -1
- package/dist/react/charts/constants.js.map +1 -1
- package/dist/react/charts/create-chart.js +1 -1
- package/dist/react/charts/create-chart.js.map +1 -1
- package/dist/react/charts/index.d.ts +1 -1
- package/dist/react/charts/types.d.ts +7 -3
- package/dist/react/charts/types.d.ts.map +1 -1
- package/dist/react/charts/types.js.map +1 -1
- package/dist/react/charts/wrapper.d.ts +1 -1
- package/dist/react/charts/wrapper.d.ts.map +1 -1
- package/dist/react/charts/wrapper.js +12 -5
- package/dist/react/charts/wrapper.js.map +1 -1
- package/dist/react/design-page.d.ts +33 -0
- package/dist/react/design-page.d.ts.map +1 -0
- package/dist/react/design-page.js +173 -0
- package/dist/react/design-page.js.map +1 -0
- package/dist/react/hooks/use-design-ready.d.ts +19 -0
- package/dist/react/hooks/use-design-ready.d.ts.map +1 -0
- package/dist/react/hooks/use-design-ready.js +33 -0
- package/dist/react/hooks/use-design-ready.js.map +1 -0
- package/dist/react/index.d.ts +2 -2
- package/dist/schemas/manifest.d.ts +79 -0
- package/dist/schemas/manifest.d.ts.map +1 -1
- package/dist/schemas/manifest.js +10 -1
- package/dist/schemas/manifest.js.map +1 -1
- package/dist/shared/src/plugin.d.ts.map +1 -1
- package/docs/api/appkit/Enumeration.ResourceType.md +9 -0
- package/docs/api/appkit/TypeAlias.ResourcePermission.md +1 -0
- package/docs/api/appkit/Variable.design.md +6 -0
- package/docs/api/appkit-ui/data/AreaChart.md +2 -2
- package/docs/api/appkit-ui/data/BarChart.md +2 -2
- package/docs/api/appkit-ui/data/DonutChart.md +2 -2
- package/docs/api/appkit-ui/data/HeatmapChart.md +2 -2
- package/docs/api/appkit-ui/data/LineChart.md +2 -2
- package/docs/api/appkit-ui/data/PieChart.md +2 -2
- package/docs/api/appkit-ui/data/RadarChart.md +2 -2
- package/docs/api/appkit-ui/data/ScatterChart.md +2 -2
- package/docs/api/appkit.md +1 -0
- package/docs/plugins/agents.md +3 -3
- package/docs/plugins/analytics.md +8 -0
- package/docs/plugins/design.md +233 -0
- package/docs/plugins/manifest.md +1 -0
- package/llms.txt +2 -0
- package/package.json +1 -1
- package/sbom.cdx.json +1 -1
package/CLAUDE.md
CHANGED
|
@@ -49,6 +49,7 @@ npx @databricks/appkit docs <query>
|
|
|
49
49
|
- [Caching](./docs/plugins/caching.md): AppKit provides both global and plugin-level caching capabilities.
|
|
50
50
|
- [Creating custom plugins](./docs/plugins/custom-plugins.md): If you need custom API routes or background logic, implement an AppKit plugin. The fastest way is to use the CLI:
|
|
51
51
|
- [Database plugin](./docs/plugins/database.md): This plugin is currently beta. APIs may change between minor releases. Import from @databricks/appkit/beta. See Plugin Stability Tiers.
|
|
52
|
+
- [Design plugin](./docs/plugins/design.md): This plugin is currently beta. APIs may change between minor releases. Import from @databricks/appkit/beta. See Plugin Stability Tiers.
|
|
52
53
|
- [Execution context](./docs/plugins/execution-context.md): AppKit uses the service principal by default. Open a caller scope when an
|
|
53
54
|
- [Files plugin](./docs/plugins/files.md): File operations against Databricks Unity Catalog Volumes. Supports listing, reading, downloading, uploading, deleting, and previewing files with built-in caching, retry, and timeout handling via the execution interceptor pipeline.
|
|
54
55
|
- [Genie plugin](./docs/plugins/genie.md): Integrates Databricks AI/BI Genie spaces into your AppKit application, enabling natural language data queries via a conversational interface.
|
|
@@ -317,6 +318,7 @@ npx @databricks/appkit docs <query>
|
|
|
317
318
|
- [Type Alias: WorkspaceClientLike](./docs/api/appkit/TypeAlias.WorkspaceClientLike.md): Structural shape of a Databricks SDK client used by fromSupervisorApi.
|
|
318
319
|
- [Variable: agents](./docs/api/appkit/Variable.agents.md): Plugin factory for the agents plugin. Discovers agents from
|
|
319
320
|
- [Variable: aiSearch](./docs/api/appkit/Variable.aiSearch.md)
|
|
321
|
+
- [Variable: design](./docs/api/appkit/Variable.design.md)
|
|
320
322
|
- [Variable: READ_ACTIONS](./docs/api/appkit/Variable.READ_ACTIONS.md): Actions that only read data.
|
|
321
323
|
- [Variable: sql](./docs/api/appkit/Variable.sql.md): SQL helper namespace
|
|
322
324
|
- [Variable: SUPERVISOR_EXTENSION_KEY](./docs/api/appkit/Variable.SUPERVISOR_EXTENSION_KEY.md): Namespace key under which the adapter reads its hosted-tool payload
|
package/NOTICE.md
CHANGED
|
@@ -60,10 +60,10 @@ This Software contains code from the following open source projects:
|
|
|
60
60
|
| [dompurify](https://www.npmjs.com/package/dompurify) | 3.4.17 | (MPL-2.0 OR Apache-2.0) | https://github.com/cure53/DOMPurify |
|
|
61
61
|
| [dotenv](https://www.npmjs.com/package/dotenv) | 16.6.1 | BSD-2-Clause | https://github.com/motdotla/dotenv#readme |
|
|
62
62
|
| [drizzle-orm](https://www.npmjs.com/package/drizzle-orm) | 0.45.2 | Apache-2.0 | https://orm.drizzle.team |
|
|
63
|
-
| [echarts](https://www.npmjs.com/package/echarts) | 6.
|
|
63
|
+
| [echarts](https://www.npmjs.com/package/echarts) | 6.1.0 | Apache-2.0 | https://echarts.apache.org |
|
|
64
64
|
| [echarts-for-react](https://www.npmjs.com/package/echarts-for-react) | 3.0.5 | MIT | https://github.com/hustcc/echarts-for-react |
|
|
65
65
|
| [embla-carousel-react](https://www.npmjs.com/package/embla-carousel-react) | 8.6.0 | MIT | https://www.embla-carousel.com |
|
|
66
|
-
| [express](https://www.npmjs.com/package/express) | 4.22.
|
|
66
|
+
| [express](https://www.npmjs.com/package/express) | 4.22.3 | MIT | http://expressjs.com/ |
|
|
67
67
|
| [get-port](https://www.npmjs.com/package/get-port) | 7.2.0 | MIT | https://github.com/sindresorhus/get-port#readme |
|
|
68
68
|
| [input-otp](https://www.npmjs.com/package/input-otp) | 1.4.2 | MIT | https://input-otp.rodz.dev/ |
|
|
69
69
|
| [jiti](https://www.npmjs.com/package/jiti) | 1.21.7, 2.6.1 | MIT | https://github.com/unjs/jiti#readme |
|
|
@@ -83,6 +83,6 @@ This Software contains code from the following open source projects:
|
|
|
83
83
|
| [tailwind-merge](https://www.npmjs.com/package/tailwind-merge) | 3.4.0 | MIT | https://github.com/dcastil/tailwind-merge |
|
|
84
84
|
| [vaul](https://www.npmjs.com/package/vaul) | 1.1.2 | MIT | https://vaul.emilkowal.ski/ |
|
|
85
85
|
| [ws](https://www.npmjs.com/package/ws) | 7.5.10, 8.21.0 | MIT | https://github.com/websockets/ws |
|
|
86
|
-
| [yaml](https://www.npmjs.com/package/yaml) | 2.
|
|
86
|
+
| [yaml](https://www.npmjs.com/package/yaml) | 2.9.1 | ISC | https://eemeli.org/yaml/ |
|
|
87
87
|
| [zod](https://www.npmjs.com/package/zod) | 4.6.7 | MIT | https://zod.dev |
|
|
88
88
|
|
|
@@ -179,6 +179,20 @@ const probeFunction = async (client, target) => {
|
|
|
179
179
|
return classifyError(err, target);
|
|
180
180
|
}
|
|
181
181
|
};
|
|
182
|
+
const probeModelService = async (client, target) => {
|
|
183
|
+
const name = field(target, "name");
|
|
184
|
+
if (!name) return missingField("name");
|
|
185
|
+
try {
|
|
186
|
+
const res = await client.request({
|
|
187
|
+
method: "GET",
|
|
188
|
+
path: `/api/2.1/unity-catalog/model-services/${encodeURIComponent(name)}`
|
|
189
|
+
});
|
|
190
|
+
if (res.ok) return EXISTENCE_OK;
|
|
191
|
+
throw Object.assign(new Error(await res.text()), { statusCode: res.status });
|
|
192
|
+
} catch (err) {
|
|
193
|
+
return classifyError(err, target);
|
|
194
|
+
}
|
|
195
|
+
};
|
|
182
196
|
function lakebaseAuthHint(message) {
|
|
183
197
|
if (/password authentication failed/i.test(message)) return "Lakebase uses an OAuth token as the password, so this usually means the PGUSER/role doesn't match your identity. Check PGUSER is your exact login.";
|
|
184
198
|
}
|
|
@@ -229,6 +243,7 @@ const PROBES = {
|
|
|
229
243
|
volume: probeVolume,
|
|
230
244
|
vector_search_index: probeVectorIndex,
|
|
231
245
|
uc_function: probeFunction,
|
|
246
|
+
model_service: probeModelService,
|
|
232
247
|
postgres: probePostgres
|
|
233
248
|
};
|
|
234
249
|
async function runExistenceProbe(client, target) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checks-existence.js","names":[],"sources":["../../../../src/cli/commands/doctor/checks-existence.ts"],"sourcesContent":["/**\n * Layer: existence — per-resource-type probes that prove a declared resource\n * exists and is reachable via the cheapest read the SDK offers.\n *\n * The client is typed structurally against the facade's modular clients.\n */\n\nimport {\n AppkitNotInstalledError,\n getLakebasePool,\n type LakebasePoolHandle,\n} from \"./databricks-client\";\nimport type { LayerResult, ResourceTarget } from \"./types\";\nimport { errorMessage } from \"./utils\";\n\n/** A passing existence check. Shared, never mutated by callers. */\nconst EXISTENCE_OK: LayerResult = { layer: \"existence\", status: \"ok\" };\n\ninterface DoctorWorkspaceClient {\n warehouses: {\n getWarehouse: (r: { id: string }) => Promise<{ state?: string }>;\n };\n genie: {\n genieGetSpace: (r: { spaceId: string }) => Promise<unknown>;\n };\n jobs: {\n getJob: (r: { jobId: bigint }) => Promise<unknown>;\n };\n vectorSearch: {\n getVectorIndex: (r: { name: string }) => Promise<unknown>;\n };\n modelServing: {\n getInferenceEndpoint: (r: { name: string }) => Promise<unknown>;\n };\n volumes: {\n getVolume: (r: { fullNameArg: string }) => Promise<unknown>;\n };\n functions: {\n getFunction: (r: { fullNameArg: string }) => Promise<unknown>;\n };\n}\n\ntype ExistenceProbe = (\n client: DoctorWorkspaceClient,\n target: ResourceTarget,\n) => Promise<LayerResult>;\n\n// Read the HTTP status / Databricks error code off an ApiError structurally.\n// Two shapes can reach here: the wrapper's `ApiError` (`statusCode` /\n// `errorCode`) and the modular SDK's (`httpStatusCode` / `code`).\nfunction statusCodeOf(err: unknown): number | undefined {\n if (!err || typeof err !== \"object\") return undefined;\n const e = err as { statusCode?: unknown; httpStatusCode?: unknown };\n const code = e.statusCode ?? e.httpStatusCode;\n return typeof code === \"number\" && code >= 0 ? code : undefined;\n}\n\nfunction errorCodeOf(err: unknown): string | undefined {\n if (!err || typeof err !== \"object\") return undefined;\n const e = err as { errorCode?: unknown; code?: unknown };\n const code = e.errorCode ?? e.code;\n return typeof code === \"string\" && code.length > 0 ? code : undefined;\n}\n\n// The SDK message often embeds a JSON blob; pull the inner `message` out so\n// doctor prints one clean line, not a dump.\nfunction cleanMessage(err: unknown): string {\n const raw = errorMessage(err);\n const m = raw.match(/\"message\"\\s*:\\s*\"([^\"]+)\"/);\n return m ? m[1] : raw;\n}\n\n/** The resource's configured identifier (id / name / path / host), for short\n * messages. */\nfunction displayId(target: ResourceTarget): string | null {\n return field(target, \"id\", \"name\", \"path\", \"index_name\", \"indexName\", \"host\");\n}\n\nfunction classifyError(err: unknown, target: ResourceTarget): LayerResult {\n const status = statusCodeOf(err);\n const errorCode = errorCodeOf(err);\n const message = cleanMessage(err);\n const id = displayId(target);\n const quoted = id ? `\"${id}\"` : null;\n\n if (status === 404 || errorCode === \"RESOURCE_DOES_NOT_EXIST\") {\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"NOT_FOUND\",\n detail: quoted ? `${quoted} not found` : \"not found\",\n };\n }\n // A malformed id/name often comes back as 400 rather than 404.\n if (status === 400 || errorCode === \"INVALID_PARAMETER_VALUE\") {\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"INVALID_VALUE\",\n detail: quoted\n ? `${quoted} is not a valid id/name`\n : `invalid id/name: ${message}`,\n };\n }\n // A 403 is genuinely ambiguous: several APIs (jobs, warehouses) return it for a\n // resource that doesn't exist as well as for one you can't read, so claiming\n // \"no permission\" outright would misdiagnose a wrong id. Say both.\n if (status === 403 || errorCode === \"PERMISSION_DENIED\") {\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"ACCESS_DENIED\",\n detail: quoted\n ? `${quoted} not found, or you don't have access to it`\n : \"not found, or you don't have access to it\",\n };\n }\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"PROBE_FAILED\",\n detail: quoted\n ? `read failed for ${quoted}: ${message}`\n : `read failed: ${message}`,\n };\n}\n\n/** Normalizes a field key so camelCase (`indexName`) and snake_case\n * (`index_name`) spellings match. */\nfunction normalizeKey(key: string): string {\n return key.toLowerCase().replace(/[_-]/g, \"\");\n}\n\n/** Looks up a resolved field value by any of the accepted key spellings. */\nfunction field(target: ResourceTarget, ...names: string[]): string | null {\n const wanted = new Set(names.map(normalizeKey));\n for (const [key, value] of Object.entries(target.fieldValues)) {\n if (wanted.has(normalizeKey(key)) && value.length > 0) return value;\n }\n return null;\n}\n\nfunction missingField(fieldName: string): LayerResult {\n return {\n layer: \"existence\",\n status: \"skipped\",\n code: \"MISSING_FIELD\",\n detail: `no ${fieldName} configured — can't probe`,\n };\n}\n\nconst probeWarehouse: ExistenceProbe = async (client, target) => {\n const id = field(target, \"id\");\n if (!id) return missingField(\"id\");\n try {\n const wh = await client.warehouses.getWarehouse({ id });\n const state = wh.state;\n if (state && state !== \"RUNNING\") {\n return {\n layer: \"existence\",\n status: \"warn\",\n code: \"WAREHOUSE_NOT_RUNNING\",\n detail: `warehouse exists but is ${state} (will cold-start on first query)`,\n };\n }\n return EXISTENCE_OK;\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\nconst probeServing: ExistenceProbe = async (client, target) => {\n const name = field(target, \"name\");\n // The API only accepts a name; if configured by id, probe with it anyway and\n // flag the likely cause on failure.\n const idOnly = name === null ? field(target, \"id\") : null;\n const value = name ?? idOnly;\n if (!value) return missingField(\"name\");\n try {\n await client.modelServing.getInferenceEndpoint({ name: value });\n return EXISTENCE_OK;\n } catch (err) {\n const result = classifyError(err, target);\n if (idOnly && result.status === \"error\") {\n result.hint =\n \"Serving endpoints are looked up by name, but this resource is configured by id. Set DATABRICKS_SERVING_ENDPOINT_NAME to the endpoint's name.\";\n }\n return result;\n }\n};\n\nconst probeGenie: ExistenceProbe = async (client, target) => {\n const spaceId = field(target, \"id\");\n if (!spaceId) return missingField(\"id\");\n try {\n await client.genie.genieGetSpace({ spaceId });\n return EXISTENCE_OK;\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\nconst probeJob: ExistenceProbe = async (client, target) => {\n const raw = field(target, \"id\");\n if (!raw) return missingField(\"id\");\n const id = raw.trim();\n // Validate the digits directly rather than via Number(): job ids are int64, so\n // past 2^53 Number() silently rounds (and Number.isInteger still passes),\n // which would probe a *different* job and report a false not-found. A string\n // check also rejects \"1e3\" and \"0x10\", both of which Number() would accept.\n if (!/^\\d+$/.test(id)) {\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"INVALID_ID\",\n detail: `\"${raw}\" is not a valid job id (expected an integer)`,\n };\n }\n try {\n // BigInt keeps int64 precision (the digits were validated above).\n await client.jobs.getJob({ jobId: BigInt(id) });\n return EXISTENCE_OK;\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\nconst probeVolume: ExistenceProbe = async (client, target) => {\n // The read API wants the 3-level name (catalog.schema.volume), but the env\n // value is usually a /Volumes/... path.\n const raw = field(target, \"path\", \"name\");\n if (!raw) return missingField(\"path\");\n const name = toThreeLevelVolumeName(raw);\n if (!name) {\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"INVALID_NAME\",\n detail: `\"${raw}\" is not a valid volume path (expected /Volumes/catalog/schema/volume or catalog.schema.volume)`,\n };\n }\n try {\n await client.volumes.getVolume({ fullNameArg: name });\n return EXISTENCE_OK;\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\nconst probeVectorIndex: ExistenceProbe = async (client, target) => {\n const name = field(target, \"indexName\", \"index_name\", \"name\");\n if (!name) return missingField(\"indexName\");\n try {\n await client.vectorSearch.getVectorIndex({ name });\n return EXISTENCE_OK;\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\nconst probeFunction: ExistenceProbe = async (client, target) => {\n const name = field(target, \"name\");\n if (!name) return missingField(\"name\");\n try {\n await client.functions.getFunction({ fullNameArg: name });\n return EXISTENCE_OK;\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\nfunction lakebaseAuthHint(message: string): string | undefined {\n if (/password authentication failed/i.test(message)) {\n return (\n \"Lakebase uses an OAuth token as the password, so this usually means the\" +\n \" PGUSER/role doesn't match your identity. Check PGUSER is your exact\" +\n \" login.\"\n );\n }\n return undefined;\n}\n\n// Lakebase has no cheap control-plane `.get()`, so existence is proven by a\n// real connection + `SELECT 1`.\nconst probePostgres: ExistenceProbe = async (client, target) => {\n if (!field(target, \"endpointPath\") && !field(target, \"host\")) {\n return missingField(\"host/endpoint\");\n }\n\n let pool: LakebasePoolHandle | null = null;\n try {\n pool = await getLakebasePool(client);\n await pool.query(\"SELECT 1\");\n return EXISTENCE_OK;\n } catch (err) {\n if (err instanceof AppkitNotInstalledError) {\n return {\n layer: \"existence\",\n status: \"skipped\",\n code: \"APPKIT_NOT_INSTALLED\",\n detail: err.message,\n };\n }\n const message = cleanMessage(err);\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"CONNECTION_FAILED\",\n detail: `could not connect to Lakebase Postgres: ${message}`,\n hint: lakebaseAuthHint(message),\n };\n } finally {\n if (pool) {\n try {\n await pool.end();\n } catch {\n // best-effort close\n }\n }\n }\n};\n\n/**\n * Normalizes a volume reference to the SDK's 3-level `catalog.schema.volume`\n * name, accepting either an already-dotted name or a `/Volumes/c/s/v/...` path.\n */\nexport function toThreeLevelVolumeName(raw: string): string | null {\n const trimmed = raw.trim();\n if (/^[^./\\s]+\\.[^./\\s]+\\.[^./\\s]+$/.test(trimmed)) return trimmed;\n\n const m = trimmed.match(/^\\/Volumes\\/([^/]+)\\/([^/]+)\\/([^/]+)/);\n if (m) return `${m[1]}.${m[2]}.${m[3]}`;\n\n return null;\n}\n\n// Unlisted types fall through to NOT_IMPLEMENTED in runExistenceProbe.\nconst PROBES: Record<string, ExistenceProbe> = {\n sql_warehouse: probeWarehouse,\n serving_endpoint: probeServing,\n genie_space: probeGenie,\n job: probeJob,\n volume: probeVolume,\n vector_search_index: probeVectorIndex,\n uc_function: probeFunction,\n postgres: probePostgres,\n};\n\nexport async function runExistenceProbe(\n client: unknown,\n target: ResourceTarget,\n): Promise<LayerResult> {\n const probe = PROBES[target.type];\n if (!probe) {\n return {\n layer: \"existence\",\n status: \"skipped\",\n code: \"NOT_IMPLEMENTED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IT,MAAM,SAAyC;CAC7C,eAAe;CACf,kBAAkB;CAClB,aAAa;CACb,KAAK;CACL,QAAQ;CACR,qBAAqB;CACrB,aAAa;CACb,UAAU;CACX;AAED,eAAsB,kBACpB,QACA,QACsB;CACtB,MAAM,QAAQ,OAAO,OAAO;AAC5B,KAAI,CAAC,MACH,QAAO;EACL,OAAO;EACP,QAAQ;EACR,MAAM;EACN,QAAQ,uCAAuC,OAAO;EACvD;AAEH,QAAO,MAAM,QAAiC,OAAO"}
|
|
1
|
+
{"version":3,"file":"checks-existence.js","names":[],"sources":["../../../../src/cli/commands/doctor/checks-existence.ts"],"sourcesContent":["/**\n * Layer: existence — per-resource-type probes that prove a declared resource\n * exists and is reachable via the cheapest read the SDK offers.\n *\n * The client is typed structurally against the facade's modular clients.\n */\n\nimport {\n AppkitNotInstalledError,\n getLakebasePool,\n type LakebasePoolHandle,\n} from \"./databricks-client\";\nimport type { LayerResult, ResourceTarget } from \"./types\";\nimport { errorMessage } from \"./utils\";\n\n/** A passing existence check. Shared, never mutated by callers. */\nconst EXISTENCE_OK: LayerResult = { layer: \"existence\", status: \"ok\" };\n\ninterface DoctorWorkspaceClient {\n warehouses: {\n getWarehouse: (r: { id: string }) => Promise<{ state?: string }>;\n };\n genie: {\n genieGetSpace: (r: { spaceId: string }) => Promise<unknown>;\n };\n jobs: {\n getJob: (r: { jobId: bigint }) => Promise<unknown>;\n };\n vectorSearch: {\n getVectorIndex: (r: { name: string }) => Promise<unknown>;\n };\n modelServing: {\n getInferenceEndpoint: (r: { name: string }) => Promise<unknown>;\n };\n volumes: {\n getVolume: (r: { fullNameArg: string }) => Promise<unknown>;\n };\n functions: {\n getFunction: (r: { fullNameArg: string }) => Promise<unknown>;\n };\n request: (r: { method: string; path: string }) => Promise<Response>;\n}\n\ntype ExistenceProbe = (\n client: DoctorWorkspaceClient,\n target: ResourceTarget,\n) => Promise<LayerResult>;\n\n// Read the HTTP status / Databricks error code off an ApiError structurally.\n// Two shapes can reach here: the wrapper's `ApiError` (`statusCode` /\n// `errorCode`) and the modular SDK's (`httpStatusCode` / `code`).\nfunction statusCodeOf(err: unknown): number | undefined {\n if (!err || typeof err !== \"object\") return undefined;\n const e = err as { statusCode?: unknown; httpStatusCode?: unknown };\n const code = e.statusCode ?? e.httpStatusCode;\n return typeof code === \"number\" && code >= 0 ? code : undefined;\n}\n\nfunction errorCodeOf(err: unknown): string | undefined {\n if (!err || typeof err !== \"object\") return undefined;\n const e = err as { errorCode?: unknown; code?: unknown };\n const code = e.errorCode ?? e.code;\n return typeof code === \"string\" && code.length > 0 ? code : undefined;\n}\n\n// The SDK message often embeds a JSON blob; pull the inner `message` out so\n// doctor prints one clean line, not a dump.\nfunction cleanMessage(err: unknown): string {\n const raw = errorMessage(err);\n const m = raw.match(/\"message\"\\s*:\\s*\"([^\"]+)\"/);\n return m ? m[1] : raw;\n}\n\n/** The resource's configured identifier (id / name / path / host), for short\n * messages. */\nfunction displayId(target: ResourceTarget): string | null {\n return field(target, \"id\", \"name\", \"path\", \"index_name\", \"indexName\", \"host\");\n}\n\nfunction classifyError(err: unknown, target: ResourceTarget): LayerResult {\n const status = statusCodeOf(err);\n const errorCode = errorCodeOf(err);\n const message = cleanMessage(err);\n const id = displayId(target);\n const quoted = id ? `\"${id}\"` : null;\n\n if (status === 404 || errorCode === \"RESOURCE_DOES_NOT_EXIST\") {\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"NOT_FOUND\",\n detail: quoted ? `${quoted} not found` : \"not found\",\n };\n }\n // A malformed id/name often comes back as 400 rather than 404.\n if (status === 400 || errorCode === \"INVALID_PARAMETER_VALUE\") {\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"INVALID_VALUE\",\n detail: quoted\n ? `${quoted} is not a valid id/name`\n : `invalid id/name: ${message}`,\n };\n }\n // A 403 is genuinely ambiguous: several APIs (jobs, warehouses) return it for a\n // resource that doesn't exist as well as for one you can't read, so claiming\n // \"no permission\" outright would misdiagnose a wrong id. Say both.\n if (status === 403 || errorCode === \"PERMISSION_DENIED\") {\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"ACCESS_DENIED\",\n detail: quoted\n ? `${quoted} not found, or you don't have access to it`\n : \"not found, or you don't have access to it\",\n };\n }\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"PROBE_FAILED\",\n detail: quoted\n ? `read failed for ${quoted}: ${message}`\n : `read failed: ${message}`,\n };\n}\n\n/** Normalizes a field key so camelCase (`indexName`) and snake_case\n * (`index_name`) spellings match. */\nfunction normalizeKey(key: string): string {\n return key.toLowerCase().replace(/[_-]/g, \"\");\n}\n\n/** Looks up a resolved field value by any of the accepted key spellings. */\nfunction field(target: ResourceTarget, ...names: string[]): string | null {\n const wanted = new Set(names.map(normalizeKey));\n for (const [key, value] of Object.entries(target.fieldValues)) {\n if (wanted.has(normalizeKey(key)) && value.length > 0) return value;\n }\n return null;\n}\n\nfunction missingField(fieldName: string): LayerResult {\n return {\n layer: \"existence\",\n status: \"skipped\",\n code: \"MISSING_FIELD\",\n detail: `no ${fieldName} configured — can't probe`,\n };\n}\n\nconst probeWarehouse: ExistenceProbe = async (client, target) => {\n const id = field(target, \"id\");\n if (!id) return missingField(\"id\");\n try {\n const wh = await client.warehouses.getWarehouse({ id });\n const state = wh.state;\n if (state && state !== \"RUNNING\") {\n return {\n layer: \"existence\",\n status: \"warn\",\n code: \"WAREHOUSE_NOT_RUNNING\",\n detail: `warehouse exists but is ${state} (will cold-start on first query)`,\n };\n }\n return EXISTENCE_OK;\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\nconst probeServing: ExistenceProbe = async (client, target) => {\n const name = field(target, \"name\");\n // The API only accepts a name; if configured by id, probe with it anyway and\n // flag the likely cause on failure.\n const idOnly = name === null ? field(target, \"id\") : null;\n const value = name ?? idOnly;\n if (!value) return missingField(\"name\");\n try {\n await client.modelServing.getInferenceEndpoint({ name: value });\n return EXISTENCE_OK;\n } catch (err) {\n const result = classifyError(err, target);\n if (idOnly && result.status === \"error\") {\n result.hint =\n \"Serving endpoints are looked up by name, but this resource is configured by id. Set DATABRICKS_SERVING_ENDPOINT_NAME to the endpoint's name.\";\n }\n return result;\n }\n};\n\nconst probeGenie: ExistenceProbe = async (client, target) => {\n const spaceId = field(target, \"id\");\n if (!spaceId) return missingField(\"id\");\n try {\n await client.genie.genieGetSpace({ spaceId });\n return EXISTENCE_OK;\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\nconst probeJob: ExistenceProbe = async (client, target) => {\n const raw = field(target, \"id\");\n if (!raw) return missingField(\"id\");\n const id = raw.trim();\n // Validate the digits directly rather than via Number(): job ids are int64, so\n // past 2^53 Number() silently rounds (and Number.isInteger still passes),\n // which would probe a *different* job and report a false not-found. A string\n // check also rejects \"1e3\" and \"0x10\", both of which Number() would accept.\n if (!/^\\d+$/.test(id)) {\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"INVALID_ID\",\n detail: `\"${raw}\" is not a valid job id (expected an integer)`,\n };\n }\n try {\n // BigInt keeps int64 precision (the digits were validated above).\n await client.jobs.getJob({ jobId: BigInt(id) });\n return EXISTENCE_OK;\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\nconst probeVolume: ExistenceProbe = async (client, target) => {\n // The read API wants the 3-level name (catalog.schema.volume), but the env\n // value is usually a /Volumes/... path.\n const raw = field(target, \"path\", \"name\");\n if (!raw) return missingField(\"path\");\n const name = toThreeLevelVolumeName(raw);\n if (!name) {\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"INVALID_NAME\",\n detail: `\"${raw}\" is not a valid volume path (expected /Volumes/catalog/schema/volume or catalog.schema.volume)`,\n };\n }\n try {\n await client.volumes.getVolume({ fullNameArg: name });\n return EXISTENCE_OK;\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\nconst probeVectorIndex: ExistenceProbe = async (client, target) => {\n const name = field(target, \"indexName\", \"index_name\", \"name\");\n if (!name) return missingField(\"indexName\");\n try {\n await client.vectorSearch.getVectorIndex({ name });\n return EXISTENCE_OK;\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\nconst probeFunction: ExistenceProbe = async (client, target) => {\n const name = field(target, \"name\");\n if (!name) return missingField(\"name\");\n try {\n await client.functions.getFunction({ fullNameArg: name });\n return EXISTENCE_OK;\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\n// request() resolves on any status; throw non-OK so classifyError reads it.\nconst probeModelService: ExistenceProbe = async (client, target) => {\n const name = field(target, \"name\");\n if (!name) return missingField(\"name\");\n try {\n const res = await client.request({\n method: \"GET\",\n path: `/api/2.1/unity-catalog/model-services/${encodeURIComponent(name)}`,\n });\n if (res.ok) return EXISTENCE_OK;\n throw Object.assign(new Error(await res.text()), {\n statusCode: res.status,\n });\n } catch (err) {\n return classifyError(err, target);\n }\n};\n\nfunction lakebaseAuthHint(message: string): string | undefined {\n if (/password authentication failed/i.test(message)) {\n return (\n \"Lakebase uses an OAuth token as the password, so this usually means the\" +\n \" PGUSER/role doesn't match your identity. Check PGUSER is your exact\" +\n \" login.\"\n );\n }\n return undefined;\n}\n\n// Lakebase has no cheap control-plane `.get()`, so existence is proven by a\n// real connection + `SELECT 1`.\nconst probePostgres: ExistenceProbe = async (client, target) => {\n if (!field(target, \"endpointPath\") && !field(target, \"host\")) {\n return missingField(\"host/endpoint\");\n }\n\n let pool: LakebasePoolHandle | null = null;\n try {\n pool = await getLakebasePool(client);\n await pool.query(\"SELECT 1\");\n return EXISTENCE_OK;\n } catch (err) {\n if (err instanceof AppkitNotInstalledError) {\n return {\n layer: \"existence\",\n status: \"skipped\",\n code: \"APPKIT_NOT_INSTALLED\",\n detail: err.message,\n };\n }\n const message = cleanMessage(err);\n return {\n layer: \"existence\",\n status: \"error\",\n code: \"CONNECTION_FAILED\",\n detail: `could not connect to Lakebase Postgres: ${message}`,\n hint: lakebaseAuthHint(message),\n };\n } finally {\n if (pool) {\n try {\n await pool.end();\n } catch {\n // best-effort close\n }\n }\n }\n};\n\n/**\n * Normalizes a volume reference to the SDK's 3-level `catalog.schema.volume`\n * name, accepting either an already-dotted name or a `/Volumes/c/s/v/...` path.\n */\nexport function toThreeLevelVolumeName(raw: string): string | null {\n const trimmed = raw.trim();\n if (/^[^./\\s]+\\.[^./\\s]+\\.[^./\\s]+$/.test(trimmed)) return trimmed;\n\n const m = trimmed.match(/^\\/Volumes\\/([^/]+)\\/([^/]+)\\/([^/]+)/);\n if (m) return `${m[1]}.${m[2]}.${m[3]}`;\n\n return null;\n}\n\n// Unlisted types fall through to NOT_IMPLEMENTED in runExistenceProbe.\nconst PROBES: Record<string, ExistenceProbe> = {\n sql_warehouse: probeWarehouse,\n serving_endpoint: probeServing,\n genie_space: probeGenie,\n job: probeJob,\n volume: probeVolume,\n vector_search_index: probeVectorIndex,\n uc_function: probeFunction,\n model_service: probeModelService,\n postgres: probePostgres,\n};\n\nexport async function runExistenceProbe(\n client: unknown,\n target: ResourceTarget,\n): Promise<LayerResult> {\n const probe = PROBES[target.type];\n if (!probe) {\n return {\n layer: \"existence\",\n status: \"skipped\",\n code: \"NOT_IMPLEMENTED\",\n detail: `existence check not implemented for ${target.type}`,\n };\n }\n return probe(client as DoctorWorkspaceClient, target);\n}\n"],"mappings":";;;;;;;;;;;AAgBA,MAAM,eAA4B;CAAE,OAAO;CAAa,QAAQ;CAAM;AAmCtE,SAAS,aAAa,KAAkC;AACtD,KAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;CAC5C,MAAM,IAAI;CACV,MAAM,OAAO,EAAE,cAAc,EAAE;AAC/B,QAAO,OAAO,SAAS,YAAY,QAAQ,IAAI,OAAO;;AAGxD,SAAS,YAAY,KAAkC;AACrD,KAAI,CAAC,OAAO,OAAO,QAAQ,SAAU,QAAO;CAC5C,MAAM,IAAI;CACV,MAAM,OAAO,EAAE,aAAa,EAAE;AAC9B,QAAO,OAAO,SAAS,YAAY,KAAK,SAAS,IAAI,OAAO;;AAK9D,SAAS,aAAa,KAAsB;CAC1C,MAAM,MAAM,aAAa,IAAI;CAC7B,MAAM,IAAI,IAAI,MAA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AI,CAAC,MACH,QAAO;EACL,OAAO;EACP,QAAQ;EACR,MAAM;EACN,QAAQ,uCAAuC,OAAO;EACvD;AAEH,QAAO,MAAM,QAAiC,OAAO"}
|
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
import { APP_YAML_FILE } from "../../../deploy-config.js";
|
|
2
|
+
import { planHasContent } from "../../registry/config-plan.js";
|
|
3
|
+
import { bundleConflicts, preflightConfig, reportConfigWrite, validateBundle, writeConfig } from "../../registry/config-writer.js";
|
|
4
|
+
import { parseEnv, serializeEnvAppend } from "../../registry/env-reconcile.js";
|
|
5
|
+
import { findServerRoot, profileFromEnv } from "../../registry/add.js";
|
|
6
|
+
import { AUTH_MODE_BOTH, AUTH_MODE_FIELD, AUTH_MODE_OBO, AUTH_MODE_SP, authKey, buildAddPlan, findMissingValues, oboCapable, parseSetAuthModes, parseSetValues, resolveAuthModes, resourceConfigured, selectResources } from "./plan.js";
|
|
7
|
+
import { discoverIndexColumns, resolveDerivedValues } from "./resolve.js";
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
import fs from "node:fs";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
import { Command } from "commander";
|
|
12
|
+
import process from "node:process";
|
|
13
|
+
import pc from "picocolors";
|
|
14
|
+
import { parseDocument } from "yaml";
|
|
15
|
+
|
|
16
|
+
//#region src/cli/commands/plugin/add/add.ts
|
|
17
|
+
const MANIFEST_FILE = "appkit.plugins.json";
|
|
18
|
+
function loadPlugin(cwd, name) {
|
|
19
|
+
const file = path.join(cwd, MANIFEST_FILE);
|
|
20
|
+
if (!fs.existsSync(file)) throw new Error(`${MANIFEST_FILE} not found in ${cwd}; run \`appkit plugin sync --write\` first`);
|
|
21
|
+
const plugins = JSON.parse(fs.readFileSync(file, "utf-8")).plugins ?? {};
|
|
22
|
+
const plugin = plugins[name];
|
|
23
|
+
if (!plugin) throw new Error(`unknown plugin "${name}"; available: ${Object.keys(plugins).sort().join(", ")}`);
|
|
24
|
+
return {
|
|
25
|
+
...plugin,
|
|
26
|
+
name,
|
|
27
|
+
resources: {
|
|
28
|
+
required: plugin.resources?.required ?? [],
|
|
29
|
+
optional: plugin.resources?.optional ?? []
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
function authModeLabel(mode) {
|
|
34
|
+
if (mode === AUTH_MODE_OBO) return "on behalf of user";
|
|
35
|
+
if (mode === AUTH_MODE_BOTH) return "service principal and on behalf of user";
|
|
36
|
+
return "service principal";
|
|
37
|
+
}
|
|
38
|
+
/** Bails out of the command on Ctrl+C in a prompt. */
|
|
39
|
+
async function answered(value) {
|
|
40
|
+
const { cancel, isCancel } = await import("@clack/prompts");
|
|
41
|
+
if (isCancel(value)) {
|
|
42
|
+
cancel("Cancelled.");
|
|
43
|
+
process.exit(1);
|
|
44
|
+
}
|
|
45
|
+
return value;
|
|
46
|
+
}
|
|
47
|
+
/** Asks which optional resources to configure (they're only added with values). */
|
|
48
|
+
async function promptOptional(plugin, values) {
|
|
49
|
+
const { confirm } = await import("@clack/prompts");
|
|
50
|
+
const picked = [];
|
|
51
|
+
for (const r of plugin.resources.optional) {
|
|
52
|
+
if (resourceConfigured(r, values)) continue;
|
|
53
|
+
if (await answered(await confirm({
|
|
54
|
+
message: `Configure ${r.alias}? ${pc.dim(`${r.description ?? ""} (optional)`)}`,
|
|
55
|
+
initialValue: false
|
|
56
|
+
}))) picked.push(r);
|
|
57
|
+
}
|
|
58
|
+
return picked;
|
|
59
|
+
}
|
|
60
|
+
/** As `apps init`: one question, then one per resource for "Mixed". */
|
|
61
|
+
async function promptAuthModes(resources) {
|
|
62
|
+
const capable = resources.filter(oboCapable);
|
|
63
|
+
if (capable.length === 0) return {};
|
|
64
|
+
const { log, select } = await import("@clack/prompts");
|
|
65
|
+
const appMode = await answered(await select({
|
|
66
|
+
message: "How should the app access resources?",
|
|
67
|
+
options: [
|
|
68
|
+
{
|
|
69
|
+
value: AUTH_MODE_SP,
|
|
70
|
+
label: "Service principal"
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
value: AUTH_MODE_OBO,
|
|
74
|
+
label: "On behalf of user"
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
value: "mixed",
|
|
78
|
+
label: "Mixed (choose per resource)"
|
|
79
|
+
}
|
|
80
|
+
]
|
|
81
|
+
}));
|
|
82
|
+
const modes = {};
|
|
83
|
+
for (const r of capable) {
|
|
84
|
+
modes[authKey(r)] = appMode === "mixed" ? await answered(await select({
|
|
85
|
+
message: `How should the app access ${r.alias}?`,
|
|
86
|
+
options: [
|
|
87
|
+
{
|
|
88
|
+
value: AUTH_MODE_OBO,
|
|
89
|
+
label: "On behalf of user"
|
|
90
|
+
},
|
|
91
|
+
{
|
|
92
|
+
value: AUTH_MODE_SP,
|
|
93
|
+
label: "Service principal"
|
|
94
|
+
},
|
|
95
|
+
{
|
|
96
|
+
value: AUTH_MODE_BOTH,
|
|
97
|
+
label: "Both"
|
|
98
|
+
}
|
|
99
|
+
]
|
|
100
|
+
})) : appMode;
|
|
101
|
+
log.info(`${r.alias}: ${authModeLabel(modes[authKey(r)])}`);
|
|
102
|
+
}
|
|
103
|
+
for (const r of resources) if (!oboCapable(r)) log.info(`${r.alias}: ${authModeLabel(AUTH_MODE_SP)} (only option)`);
|
|
104
|
+
return modes;
|
|
105
|
+
}
|
|
106
|
+
/** Prompts for each missing value, or fails on the first one when not interactive. */
|
|
107
|
+
async function fillMissing(missing, values, interactive) {
|
|
108
|
+
if (missing.length > 0 && !interactive) {
|
|
109
|
+
const m = missing[0];
|
|
110
|
+
throw new Error(`missing value for ${m.setKey}; use --set ${m.setKey}=value`);
|
|
111
|
+
}
|
|
112
|
+
if (missing.length === 0) return;
|
|
113
|
+
const { text } = await import("@clack/prompts");
|
|
114
|
+
for (const m of missing) {
|
|
115
|
+
const field = m.resource.fields?.[m.field];
|
|
116
|
+
const value = await answered(await text({
|
|
117
|
+
message: `${m.resource.alias}: ${m.field}`,
|
|
118
|
+
placeholder: field?.description,
|
|
119
|
+
validate: (v) => !v?.trim() || /[\r\n]/.test(v) ? "Enter a value" : void 0
|
|
120
|
+
}));
|
|
121
|
+
values[`${m.resource.resourceKey}.${m.field}`] = value.trim();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/** aiSearch's default index columns (production won't start without them): discovered, else prompted. */
|
|
125
|
+
async function aiSearchColumns(values, profile, interactive) {
|
|
126
|
+
const indexName = values["vector-search-index.id"];
|
|
127
|
+
try {
|
|
128
|
+
const columns = await discoverIndexColumns(indexName, profile);
|
|
129
|
+
if (columns.length > 0) {
|
|
130
|
+
console.log(pc.dim(`Index columns: ${columns.join(", ")}`));
|
|
131
|
+
return columns;
|
|
132
|
+
}
|
|
133
|
+
} catch (err) {
|
|
134
|
+
console.warn(pc.yellow(`Could not discover the columns of ${indexName}: ${err.message}`));
|
|
135
|
+
}
|
|
136
|
+
if (!interactive) throw new Error(`aiSearch needs the columns of ${indexName} to start in production; run with workspace access (--profile) or interactively to enter them`);
|
|
137
|
+
const { text } = await import("@clack/prompts");
|
|
138
|
+
return (await answered(await text({
|
|
139
|
+
message: `Columns to return from ${indexName} (comma-separated)`,
|
|
140
|
+
validate: (v) => v?.split(",").some((c) => c.trim()) ? void 0 : "Enter at least one column"
|
|
141
|
+
}))).split(",").map((c) => c.trim()).filter(Boolean);
|
|
142
|
+
}
|
|
143
|
+
/** What an app.yaml env entry points at, for comparing two entries. */
|
|
144
|
+
function entryKey(e) {
|
|
145
|
+
return JSON.stringify([e.valueFrom, e.value]);
|
|
146
|
+
}
|
|
147
|
+
/** The first item per key, in order. */
|
|
148
|
+
function firstBy(xs, key) {
|
|
149
|
+
return xs.filter((x, i) => xs.findIndex((y) => key(y) === key(x)) === i);
|
|
150
|
+
}
|
|
151
|
+
/** Env names the plan would set differently from .env, app.yaml or earlier plugins. */
|
|
152
|
+
function envConflicts(cwd, plan, pending = []) {
|
|
153
|
+
const dotEnv = fs.existsSync(path.join(cwd, ".env")) ? parseEnv(fs.readFileSync(path.join(cwd, ".env"), "utf-8")) : {};
|
|
154
|
+
const appYamlFile = path.join(cwd, APP_YAML_FILE);
|
|
155
|
+
const appEnv = /* @__PURE__ */ new Map();
|
|
156
|
+
if (fs.existsSync(appYamlFile)) {
|
|
157
|
+
const env = parseDocument(fs.readFileSync(appYamlFile, "utf-8")).toJSON()?.env;
|
|
158
|
+
for (const e of env ?? []) if (e?.name) appEnv.set(e.name, entryKey(e));
|
|
159
|
+
}
|
|
160
|
+
for (const p of pending) {
|
|
161
|
+
for (const e of p.dotEnv) if (!dotEnv[e.env]) dotEnv[e.env] = e.value;
|
|
162
|
+
for (const e of p.appYamlEnv) if (!appEnv.has(e.name)) appEnv.set(e.name, entryKey(e));
|
|
163
|
+
}
|
|
164
|
+
const out = /* @__PURE__ */ new Set();
|
|
165
|
+
for (const e of plan.dotEnv) if (dotEnv[e.env] && e.value && dotEnv[e.env] !== e.value) out.add(e.env);
|
|
166
|
+
for (const e of plan.appYamlEnv) {
|
|
167
|
+
const have = appEnv.get(e.name);
|
|
168
|
+
if (have !== void 0 && have !== entryKey(e)) out.add(e.name);
|
|
169
|
+
}
|
|
170
|
+
return [...out];
|
|
171
|
+
}
|
|
172
|
+
/** Plans one plugin without writing: prompts, derived values, file plan, registration config. */
|
|
173
|
+
async function preparePlugin(cwd, req, opts, pending) {
|
|
174
|
+
if (req.authMode !== void 0 && req.authMode !== AUTH_MODE_SP && req.authMode !== AUTH_MODE_OBO) throw new Error(`invalid --auth-mode value: "${req.authMode}" (must be obo or sp; use --set <plugin>.<resourceKey>.${AUTH_MODE_FIELD}=both for a single resource)`);
|
|
175
|
+
const plugin = loadPlugin(cwd, req.name);
|
|
176
|
+
const values = parseSetValues(req.set, plugin);
|
|
177
|
+
const setModes = parseSetAuthModes(req.set, plugin);
|
|
178
|
+
const interactive = !opts.yes && Boolean(process.stdin.isTTY);
|
|
179
|
+
let resources = selectResources(plugin, values);
|
|
180
|
+
if (interactive) resources.push(...await promptOptional(plugin, values));
|
|
181
|
+
const promptedModes = interactive && req.authMode === void 0 ? await promptAuthModes(resources.filter((r) => !(authKey(r) in setModes))) : {};
|
|
182
|
+
const { modes, keptSP } = resolveAuthModes(resources, setModes, promptedModes, req.authMode);
|
|
183
|
+
if (keptSP.length > 0) console.log(`Note: these resources cannot be accessed on behalf of the user and use the service principal: ${keptSP.join(", ")}`);
|
|
184
|
+
const missingNow = () => findMissingValues(plugin.name, resources, values, modes);
|
|
185
|
+
await fillMissing(missingNow().filter((m) => !m.resource.fields?.[m.field]?.resolve), values, interactive);
|
|
186
|
+
const profile = opts.profile ?? profileFromEnv(cwd);
|
|
187
|
+
for (const r of resources) try {
|
|
188
|
+
for (const [k, v] of Object.entries(await resolveDerivedValues(r, values, profile))) values[k] ||= v;
|
|
189
|
+
} catch (err) {
|
|
190
|
+
console.warn(pc.yellow(`Could not resolve derived values for ${r.alias}: ${err.message}`));
|
|
191
|
+
}
|
|
192
|
+
await fillMissing(missingNow(), values, interactive);
|
|
193
|
+
resources = selectResources(plugin, values);
|
|
194
|
+
const config = pluginConfig(plugin, resources, modes, plugin.name === "aiSearch" && opts.register !== false ? await aiSearchColumns(values, profile, interactive) : void 0);
|
|
195
|
+
const plan = buildAddPlan(plugin, resources, values, modes);
|
|
196
|
+
const conflicts = [...envConflicts(cwd, plan, pending), ...bundleConflicts(cwd, plan, pending)];
|
|
197
|
+
if (conflicts.length > 0) throw new Error(`${conflicts.join(", ")} already set to a different resource or value in .env, app.yaml or databricks.yml; nothing was written. Edit those entries by hand, then rerun.`);
|
|
198
|
+
return {
|
|
199
|
+
plugin,
|
|
200
|
+
plan,
|
|
201
|
+
config
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
/** Requests from `plugin add a b --set ...`: each plugin gets its own --set pairs. */
|
|
205
|
+
function requestsFromArgs(names, set, authMode) {
|
|
206
|
+
for (const sv of set) {
|
|
207
|
+
const prefix = sv.split(".")[0];
|
|
208
|
+
if (!names.includes(prefix)) throw new Error(`--set "${sv}" is for "${prefix}", which this run doesn't add (${names.join(", ")})`);
|
|
209
|
+
}
|
|
210
|
+
return names.map((name) => ({
|
|
211
|
+
name,
|
|
212
|
+
set: set.filter((sv) => sv.split(".")[0] === name),
|
|
213
|
+
authMode
|
|
214
|
+
}));
|
|
215
|
+
}
|
|
216
|
+
const dataPlanSchema = z.object({
|
|
217
|
+
version: z.literal(1),
|
|
218
|
+
plugins: z.array(z.object({
|
|
219
|
+
name: z.string().min(1),
|
|
220
|
+
authMode: z.enum([AUTH_MODE_OBO, AUTH_MODE_SP]).optional(),
|
|
221
|
+
set: z.record(z.string(), z.string()).optional()
|
|
222
|
+
})).min(1)
|
|
223
|
+
});
|
|
224
|
+
/** Requests from a data plan file (`.appkit/data-plan.json`, version 1). */
|
|
225
|
+
function requestsFromPlan(file) {
|
|
226
|
+
const parsed = dataPlanSchema.safeParse(JSON.parse(fs.readFileSync(file, "utf-8")));
|
|
227
|
+
if (!parsed.success) throw new Error(`invalid data plan ${file}: ${parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ")}`);
|
|
228
|
+
return parsed.data.plugins.map((p) => ({
|
|
229
|
+
name: p.name,
|
|
230
|
+
authMode: p.authMode,
|
|
231
|
+
set: Object.entries(p.set ?? {}).map(([k, v]) => {
|
|
232
|
+
const parts = k.split(".");
|
|
233
|
+
return `${parts.length >= 3 && parts[0] === p.name ? k : `${p.name}.${k}`}=${v}`;
|
|
234
|
+
})
|
|
235
|
+
}));
|
|
236
|
+
}
|
|
237
|
+
/** Plans every plugin, then writes each file once (one dev-server restart). */
|
|
238
|
+
async function runPluginAdd(names, opts) {
|
|
239
|
+
const cwd = opts.cwd ? path.resolve(opts.cwd) : process.cwd();
|
|
240
|
+
if (opts.fromPlan && (names.length > 0 || opts.set.length > 0 || opts.authMode)) throw new Error("--from-plan can't be combined with plugin names, --set or --auth-mode");
|
|
241
|
+
if (!opts.fromPlan && names.length === 0) throw new Error("name at least one plugin, or pass --from-plan <file>");
|
|
242
|
+
const requests = opts.fromPlan ? requestsFromPlan(path.resolve(cwd, opts.fromPlan)) : requestsFromArgs(names, opts.set, opts.authMode);
|
|
243
|
+
const seen = /* @__PURE__ */ new Set();
|
|
244
|
+
for (const r of requests) {
|
|
245
|
+
if (seen.has(r.name)) throw new Error(`plugin "${r.name}" is listed twice`);
|
|
246
|
+
seen.add(r.name);
|
|
247
|
+
}
|
|
248
|
+
preflightConfig(cwd);
|
|
249
|
+
const prepared = [];
|
|
250
|
+
for (const req of requests) prepared.push(await preparePlugin(cwd, req, opts, prepared.map((p) => p.plan)));
|
|
251
|
+
if (opts.register === false) for (const { plugin, config } of prepared) {
|
|
252
|
+
if (!config) continue;
|
|
253
|
+
console.log(`${pc.bold("Register it with this config in your createApp call:")}\n` + pc.dim(` ${plugin.name}(${toSource(config)})`));
|
|
254
|
+
}
|
|
255
|
+
else await registerInServer(cwd, prepared);
|
|
256
|
+
const plans = prepared.map((p) => p.plan);
|
|
257
|
+
await writeDotEnv(cwd, plans.flatMap((p) => p.dotEnv));
|
|
258
|
+
const merged = {
|
|
259
|
+
appYamlEnv: firstBy(plans.flatMap((p) => p.appYamlEnv), (x) => x.name),
|
|
260
|
+
bundleVariables: firstBy(plans.flatMap((p) => p.bundleVariables), (x) => x.name),
|
|
261
|
+
resourceBindings: firstBy(plans.flatMap((p) => p.resourceBindings), (x) => x.name),
|
|
262
|
+
userApiScopes: [...new Set(plans.flatMap((p) => p.userApiScopes ?? []))],
|
|
263
|
+
unverifiedTypes: [...new Set(plans.flatMap((p) => p.unverifiedTypes))]
|
|
264
|
+
};
|
|
265
|
+
if (planHasContent(merged)) {
|
|
266
|
+
const result = writeConfig(cwd, merged);
|
|
267
|
+
reportConfigWrite(result);
|
|
268
|
+
if (result.databricksYmlChanged) validateBundle(cwd, opts.profile ?? profileFromEnv(cwd));
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
/** One .env write: fills empty `KEY=` placeholders, appends new names, keeps set values. */
|
|
272
|
+
async function writeDotEnv(cwd, entries) {
|
|
273
|
+
const { readEnvFile } = await import("../../registry/env-writer.js");
|
|
274
|
+
const envPath = path.join(cwd, ".env");
|
|
275
|
+
const existing = readEnvFile(envPath);
|
|
276
|
+
const dotEnv = firstBy(entries, (e) => e.env);
|
|
277
|
+
const filled = dotEnv.filter((e) => existing[e.env] === "" && e.value);
|
|
278
|
+
const newEnv = dotEnv.filter((e) => !(e.env in existing));
|
|
279
|
+
if (filled.length === 0 && newEnv.length === 0) return;
|
|
280
|
+
let content = fs.existsSync(envPath) ? fs.readFileSync(envPath, "utf-8") : "";
|
|
281
|
+
for (const e of filled) content = content.replace(new RegExp(`^(\\s*(?:export\\s+)?${e.env}\\s*=).*$`, "m"), (_, key) => key + e.value);
|
|
282
|
+
const append = serializeEnvAppend(newEnv);
|
|
283
|
+
if (append) {
|
|
284
|
+
if (content.length > 0 && !content.endsWith("\n")) content += "\n";
|
|
285
|
+
content += append;
|
|
286
|
+
}
|
|
287
|
+
fs.writeFileSync(envPath, content);
|
|
288
|
+
console.log(`${pc.green("Updated .env:")} ${[...filled, ...newEnv].map((e) => e.env).join(", ")}`);
|
|
289
|
+
}
|
|
290
|
+
/** Plugins that default to the service principal unless told otherwise. */
|
|
291
|
+
const AUTH_OPTION_PLUGINS = new Set([
|
|
292
|
+
"files",
|
|
293
|
+
"aiSearch",
|
|
294
|
+
"agents"
|
|
295
|
+
]);
|
|
296
|
+
const OBO = "on-behalf-of-user";
|
|
297
|
+
/** The `createApp` config an OBO plan needs (the SP is unbound), plus aiSearch columns. */
|
|
298
|
+
function pluginConfig(plugin, resources, modes, columns) {
|
|
299
|
+
let obo = false;
|
|
300
|
+
if (AUTH_OPTION_PLUGINS.has(plugin.name)) {
|
|
301
|
+
const governed = resources.filter((r) => oboCapable(r) && (plugin.name !== "agents" || r.type === "model_service"));
|
|
302
|
+
const oboRes = governed.filter((r) => modes[authKey(r)] === AUTH_MODE_OBO);
|
|
303
|
+
obo = oboRes.length > 0 && oboRes.length === governed.length;
|
|
304
|
+
if (plugin.name === "agents") {
|
|
305
|
+
for (const r of resources) if (r.type === "volume" && modes[authKey(r)] === AUTH_MODE_OBO) console.warn(pc.yellow(`agents loads skills from ${r.resourceKey} as the service principal at boot, which gets no access in obo mode; use --set agents.${r.resourceKey}.authMode=sp (or both).`));
|
|
306
|
+
}
|
|
307
|
+
if (plugin.name === "files" && oboRes.length > 0 && !obo) {
|
|
308
|
+
const keys = oboRes.map((r) => filesVolumeKey(r));
|
|
309
|
+
if (keys.every(Boolean)) return { volumes: Object.fromEntries(keys.map((k) => [k, { auth: OBO }])) };
|
|
310
|
+
}
|
|
311
|
+
if (oboRes.length > 0 && !obo) console.warn(pc.yellow(`${plugin.name} is registered with one auth setting for all its resources; set auth per volume or index in its config to mix on-behalf-of-user (${oboRes.map((r) => r.resourceKey).join(", ")}) with service principal access.`));
|
|
312
|
+
}
|
|
313
|
+
if (plugin.name === "aiSearch") {
|
|
314
|
+
const index = {
|
|
315
|
+
...columns && { columns },
|
|
316
|
+
...obo && { auth: OBO }
|
|
317
|
+
};
|
|
318
|
+
return Object.keys(index).length > 0 ? { indexes: { default: index } } : void 0;
|
|
319
|
+
}
|
|
320
|
+
return obo ? { auth: OBO } : void 0;
|
|
321
|
+
}
|
|
322
|
+
/** Volume key as FilesPlugin.discoverVolumes derives it from DATABRICKS_VOLUME_<KEY>. */
|
|
323
|
+
function filesVolumeKey(r) {
|
|
324
|
+
const prefix = "DATABRICKS_VOLUME_";
|
|
325
|
+
return Object.values(r.fields ?? {}).map((f) => f.env).find((e) => e?.startsWith(prefix) && e.length > 18)?.slice(18).toLowerCase();
|
|
326
|
+
}
|
|
327
|
+
/** Source text for a config literal: `{ auth: "x", columns: ["a"] }`. */
|
|
328
|
+
function toSource(v) {
|
|
329
|
+
if (Array.isArray(v)) return `[${v.map(toSource).join(", ")}]`;
|
|
330
|
+
if (v && typeof v === "object") return `{ ${Object.entries(v).map(([k, x]) => `${/^[A-Za-z_$][\w$]*$/.test(k) ? k : JSON.stringify(k)}: ${toSource(x)}`).join(", ")} }`;
|
|
331
|
+
return JSON.stringify(v);
|
|
332
|
+
}
|
|
333
|
+
async function registerInServer(cwd, prepared) {
|
|
334
|
+
const serverRoot = findServerRoot(cwd);
|
|
335
|
+
const { findServerFile, registerPluginsInServer } = await import("../../registry/server-register.js");
|
|
336
|
+
const serverFile = findServerFile(serverRoot);
|
|
337
|
+
const entries = prepared.map(({ plugin, config }) => {
|
|
338
|
+
let importPath = plugin.stability === "beta" && plugin.package === "@databricks/appkit" ? `${plugin.package}/beta` : plugin.package;
|
|
339
|
+
if (plugin.package.startsWith(".")) {
|
|
340
|
+
const from = path.dirname(serverFile ?? serverRoot);
|
|
341
|
+
const rel = path.relative(from, path.resolve(cwd, plugin.package)).split(path.sep).join("/");
|
|
342
|
+
importPath = rel.startsWith(".") ? rel : `./${rel}`;
|
|
343
|
+
}
|
|
344
|
+
return {
|
|
345
|
+
importPath,
|
|
346
|
+
exportName: plugin.name,
|
|
347
|
+
callArgs: config ? toSource(config) : ""
|
|
348
|
+
};
|
|
349
|
+
});
|
|
350
|
+
registerPluginsInServer(serverRoot, entries).forEach((result, i) => {
|
|
351
|
+
const { importPath, exportName, callArgs } = entries[i];
|
|
352
|
+
const call = `${exportName}(${callArgs})`;
|
|
353
|
+
const shown = result.file && path.relative(cwd, path.join(serverRoot, result.file));
|
|
354
|
+
if (result.status === "wired") console.log(`${pc.green("Registered")} ${call} in ${shown}`);
|
|
355
|
+
else if (result.status === "already") {
|
|
356
|
+
console.log(pc.dim(`${exportName} is already registered in ${shown}`));
|
|
357
|
+
if (callArgs) console.warn(pc.yellow(` Make sure it is configured as ${call} for the chosen auth mode.`));
|
|
358
|
+
} else console.log(pc.yellow(`Couldn't auto-register ${exportName}: ${result.reason}.`) + "\nAdd it to your server's createApp call:\n" + pc.dim(` import { ${exportName} } from "${importPath}";\n createApp({ plugins: [${call}, /* ... */] });`));
|
|
359
|
+
});
|
|
360
|
+
}
|
|
361
|
+
/** A fresh `plugin add` command (commander keeps parsed values per instance). */
|
|
362
|
+
const createPluginAddCommand = () => new Command("add").description("Add plugins from appkit.plugins.json to the app: server registration, .env, app.yaml and databricks.yml, each written once").argument("[plugins...]", "Plugin names, as in appkit.plugins.json").option("--from-plan <file>", "Add the plugins listed in a data plan file (e.g. .appkit/data-plan.json, version 1)").option("--set <plugin.resourceKey.field=value>", "Set resource values (format: plugin.resourceKey.field=value, can specify multiple)", (v, acc) => [...acc, v], []).option("--auth-mode <mode>", "Default resource auth mode: obo (on behalf of the user) or sp (service principal). With obo, resources that cannot be accessed on behalf of the user use sp. Prompts if not provided in interactive mode, otherwise sp.").option("-C, --cwd <dir>", "Run as if started in <dir>").option("-y, --yes", "Don't prompt; fail on missing required values").option("--no-register", "Don't edit the server entry to register the plugin").option("-p, --profile <name>", "Databricks profile for bundle validate (defaults to the app's DATABRICKS_CONFIG_PROFILE)").addHelpText("after", `
|
|
363
|
+
Resource configuration (--set), as in \`databricks apps init\`:
|
|
364
|
+
Set resource values using --set plugin.resourceKey.field=value
|
|
365
|
+
Keys are defined in the app's appkit.plugins.json manifest.
|
|
366
|
+
Multi-field resources (e.g., database, secret) require all fields to be set together.
|
|
367
|
+
Use --set plugin.resourceKey.authMode=obo|sp|both to choose how the app accesses a resource:
|
|
368
|
+
on behalf of the user (obo), as the app's service principal (sp), or both.
|
|
369
|
+
obo/both add the resource's user_api_scopes; sp/both bind it with its permission.
|
|
370
|
+
|
|
371
|
+
Several plugins can be added in one run; each file is written once, so a dev
|
|
372
|
+
server watching them restarts once. Rerunning with the same input changes nothing.
|
|
373
|
+
Existing entries in .env, app.yaml and databricks.yml are never overwritten.
|
|
374
|
+
|
|
375
|
+
Data plan file (--from-plan), version 1:
|
|
376
|
+
{ "version": 1,
|
|
377
|
+
"plugins": [
|
|
378
|
+
{ "name": "analytics", "authMode": "obo",
|
|
379
|
+
"set": { "sql-warehouse.id": "abc123" } },
|
|
380
|
+
{ "name": "genie", "set": { "genie-space.id": "s1", "genie-space.name": "Sales" } } ] }
|
|
381
|
+
"set" keys are the --set keys, with or without the plugin prefix ("authMode" works per
|
|
382
|
+
resource, e.g. "sql-warehouse.authMode": "both"); "authMode" is the plugin's default.
|
|
383
|
+
|
|
384
|
+
Examples:
|
|
385
|
+
$ appkit plugin add analytics --set analytics.sql-warehouse.id=abc123
|
|
386
|
+
$ appkit plugin add analytics --auth-mode obo --set analytics.sql-warehouse.id=abc123
|
|
387
|
+
$ appkit plugin add jobs --auth-mode obo --set jobs.job.authMode=sp --set jobs.job.id=42
|
|
388
|
+
$ appkit plugin add analytics genie --set analytics.sql-warehouse.id=abc123 \\
|
|
389
|
+
--set genie.genie-space.id=s1 --set genie.genie-space.name=Sales
|
|
390
|
+
$ appkit plugin add --from-plan .appkit/data-plan.json --yes`).action((names, opts) => runPluginAdd(names, opts).catch((err) => {
|
|
391
|
+
console.error(pc.red(err.message));
|
|
392
|
+
process.exit(1);
|
|
393
|
+
}));
|
|
394
|
+
const pluginAddCommand = createPluginAddCommand();
|
|
395
|
+
|
|
396
|
+
//#endregion
|
|
397
|
+
export { pluginAddCommand };
|
|
398
|
+
//# sourceMappingURL=add.js.map
|