@dashai/sdk 0.8.0 → 0.10.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/dist/deps/index.d.cts +2 -2
- package/dist/deps/index.d.ts +2 -2
- package/dist/index.cjs +146 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +146 -3
- package/dist/index.js.map +1 -1
- package/dist/query/index.d.cts +1 -1
- package/dist/query/index.d.ts +1 -1
- package/dist/react/index.d.cts +1 -1
- package/dist/react/index.d.ts +1 -1
- package/dist/{types-BLNQ1S1C.d.cts → types-BwlzFHbq.d.cts} +109 -1
- package/dist/{types-BLNQ1S1C.d.ts → types-BwlzFHbq.d.ts} +109 -1
- package/package.json +2 -3
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/data/deps.ts","../src/data/errors.ts","../src/data/http.ts","../src/data/client.ts","../src/data/dev-client.ts","../src/index.ts"],"names":["durationMs","assertValidTableSlug","MODULE_SLUG_REGEX","TABLE_SLUG_REGEX"],"mappings":";;;;;;;;AA2CA,IAAM,iBAAA,GAAoB,2BAAA;AAO1B,IAAM,gBAAA,GAAmB,2BAAA;AAEzB,SAAS,wBAAwB,IAAA,EAAoB;AACnD,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,IAAY,CAAC,iBAAA,CAAkB,IAAA,CAAK,IAAI,CAAA,EAAG;AAC7D,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,uCAAuC,IAAI,CAAA,wHAAA;AAAA,KAC7C;AAAA,EACF;AACF;AAEA,SAAS,qBAAqB,IAAA,EAAoB;AAChD,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,IAAY,CAAC,gBAAA,CAAiB,IAAA,CAAK,IAAI,CAAA,EAAG;AAC5D,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,oCAAoC,IAAI,CAAA,mEAAA;AA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AK,EAAA,CAAG,OAAA,EAAQ,EAAG,WAAW,UAAU,CAAA;AACtD;AAEA,SAAS,qBAAqB,CAAA,EAAqC;AACjE,EAAA,IAAI,CAAC,CAAA,IAAK,OAAO,CAAA,KAAM,UAAU,OAAO,KAAA;AACxC,EAAA,MAAM,CAAA,GAAI,CAAA;AAWV,EAAA,MAAM,WAAW,CAAA,CAAE,MAAA,KAAW,MAAA,IAAa,OAAO,EAAE,MAAA,KAAW,QAAA;AAC/D,EAAA,MAAM,UAAU,CAAA,CAAE,KAAA,KAAU,MAAA,IAAa,OAAO,EAAE,KAAA,KAAU,QAAA;AAC5D,EAAA,MAAM,SAAA,GACJ,EAAE,OAAA,KAAY,MAAA,IACb,OAAO,CAAA,CAAE,OAAA,KAAY,QAAA,IAAY,CAAA,CAAE,OAAA,KAAY,IAAA;AAClD,EAAA,OAAO,YAAY,OAAA,IAAW,SAAA;AAChC;;;ACpSO,IAAM,OAAA,GAC2B,OAAA","file":"index.js","sourcesContent":["/**\n * Borrowed-table accessor: `client.deps(providerSlug).db<Row>(tableSlug)`.\n *\n * Phase 1 of the SDK query plane — see\n * `dashwise-devops-docs/plans/modules-sdk-query-v1.md` §6.2.\n *\n * The factory is intentionally a thin wrapper around the existing\n * {@link HttpTransport}: cross-module reads target a parallel URL\n * shape (`/deps/<provider>/db/<table>/list` instead of\n * `/db/<table>/list`) but otherwise behave identically — same JSON\n * body, same {@link Page} envelope, same {@link DashwiseError} model.\n * No new transport, no new auth flow, no new caching.\n *\n * Cross-module **writes** are deliberately omitted: the returned\n * {@link ReadOnlyTableClient} has no `create` / `update` / `delete`.\n * See plan §4.3 — writes flow through provider-published actions in\n * a later phase, never as direct mutations across the trust boundary.\n *\n * Slug validation runs client-side as a fail-fast check so a typo\n * doesn't reach the backend as a 404 from a malformed URL. The\n * authoritative check is server-side: the backend re-validates\n * provider existence + contract coverage on every call.\n */\n\nimport type { HttpTransport } from './http.js';\nimport type {\n BaseRow,\n Deps,\n ListOpts,\n Page,\n ReadOnlyTableClient,\n} from './types.js';\n\n/**\n * Module-slug character set matches the backend manifest validator's\n * `MODULE_SLUG_REGEX` exactly: kebab-case, 2-63 chars, starts with a\n * letter, ends with letter/digit, no leading/trailing dash.\n *\n * Mirrored here (not imported from the backend) because the SDK is\n * published independently — pulling backend code in would couple\n * release cycles. If the backend's regex changes, the SDK's mirror\n * must update in lockstep; covered by an integration test.\n */\nconst MODULE_SLUG_REGEX = /^[a-z][a-z0-9-]*[a-z0-9]$/;\n\n/**\n * Table-slug character set matches the backend's `SLUG_REGEX`: snake_case,\n * 2-63 chars, starts with a letter, ends with letter/digit. Same\n * mirror-vs-import tradeoff as {@link MODULE_SLUG_REGEX}.\n */\nconst TABLE_SLUG_REGEX = /^[a-z][a-z0-9_]*[a-z0-9]$/;\n\nfunction assertValidProviderSlug(slug: string): void {\n if (typeof slug !== 'string' || !MODULE_SLUG_REGEX.test(slug)) {\n throw new Error(\n `@dashai/sdk: invalid provider slug \"${slug}\". Provider slugs are the dependency module's slug (kebab-case, e.g. \"crm-app\"); must match /^[a-z][a-z0-9-]*[a-z0-9]$/.`,\n );\n }\n}\n\nfunction assertValidTableSlug(slug: string): void {\n if (typeof slug !== 'string' || !TABLE_SLUG_REGEX.test(slug)) {\n throw new Error(\n `@dashai/sdk: invalid table slug \"${slug}\". Table slugs must match /^[a-z][a-z0-9_]*[a-z0-9]$/ (snake_case).`,\n );\n }\n}\n\n/**\n * Build a {@link Deps} accessor for `providerSlug`. Validates the\n * slug shape eagerly; defers everything else to the backend.\n *\n * Exported for use by `createClient()` in `./client.ts`. Not part\n * of the public API directly — consumers reach it via `client.deps(...)`.\n */\nexport function makeDeps(transport: HttpTransport, providerSlug: string): Deps {\n assertValidProviderSlug(providerSlug);\n\n return {\n db<Row extends BaseRow>(tableSlug: string): ReadOnlyTableClient<Row> {\n assertValidTableSlug(tableSlug);\n return makeBorrowedTableClient<Row>(transport, providerSlug, tableSlug);\n },\n };\n}\n\n/**\n * Internal: produce a {@link ReadOnlyTableClient} for one specific\n * `(providerSlug, tableSlug)` pair. Closure captures the transport +\n * the URL root so the public methods are tiny.\n */\nfunction makeBorrowedTableClient<Row extends BaseRow>(\n transport: HttpTransport,\n providerSlug: string,\n tableSlug: string,\n): ReadOnlyTableClient<Row> {\n // URL shape mirrors the owned-table CRUD pipeline but interpolates\n // the provider's slug between the installation root + the table\n // segment: `/deps/<provider>/db/<table>/...`. The full URL after\n // the transport's base prefix is therefore\n // `<baseUrl>/api/modules/<installationId>/deps/<provider>/db/<table>/<op>`.\n const root = `/deps/${providerSlug}/db/${tableSlug}`;\n\n return {\n async list(opts?: ListOpts<Row>): Promise<Page<Row>> {\n const body = opts ?? {};\n const result = await transport.request<Page<Row>>('POST', `${root}/list`, body);\n // Same defense-in-depth shape coercion as the owned-table client:\n // if the backend ever responds with a bare array (older endpoint\n // version, proxy stripping the envelope, etc.), wrap it so the\n // consumer always sees `{ rows, ... }`.\n if (Array.isArray(result)) {\n return {\n rows: result as Row[],\n total: result.length,\n limit: body.limit ?? result.length,\n offset: body.offset ?? 0,\n };\n }\n return result;\n },\n\n async get(id: number): Promise<Row> {\n return transport.request<Row>('GET', `${root}/${id}`);\n },\n };\n}\n","/**\n * Error model for @dashai/sdk.\n *\n * The backend speaks a structured error envelope:\n *\n * {\n * \"code\": \"ROW_NOT_FOUND\",\n * \"message\": \"Row 123 not found in tasks\",\n * \"retriable\": false,\n * \"context\": { ... }\n * }\n *\n * This module wraps that envelope in a typed `DashwiseError` plus a small\n * set of subclasses for the codes consumers most commonly want to branch\n * on (network errors, auth failures, row-not-found, contract violations).\n *\n * Anything not matched by a specific subclass becomes a plain\n * `DashwiseError` carrying the raw `code`. Branch on `.code` for codes\n * we don't have a class for; use `instanceof` for the common cases.\n */\n\n/**\n * Known error codes. Not exhaustive — the backend emits many codes\n * specific to individual modules / endpoints. Use these constants when\n * you want compile-time safety; otherwise treat `err.code` as a string.\n *\n * The list is curated to the codes a module author is most likely to\n * branch on. Adding a new code here is a non-breaking change.\n */\nexport const DashwiseErrorCode = {\n // Auth / authz\n UNAUTHENTICATED: 'UNAUTHENTICATED',\n FORBIDDEN: 'FORBIDDEN',\n TOKEN_EXPIRED: 'TOKEN_EXPIRED',\n INSTALLATION_NOT_FOUND: 'INSTALLATION_NOT_FOUND',\n INSTALLATION_MODE_UNSUPPORTED: 'INSTALLATION_MODE_UNSUPPORTED',\n // Contract enforcement\n CONTRACT_VIOLATION: 'CONTRACT_VIOLATION',\n FIELD_NOT_READABLE: 'FIELD_NOT_READABLE',\n FILTER_OP_UNKNOWN: 'FILTER_OP_UNKNOWN',\n OPERATION_NOT_ALLOWED: 'OPERATION_NOT_ALLOWED',\n // Cross-module dependencies (Phase 1 of the SDK query plane —\n // see dashwise-devops-docs/plans/modules-sdk-query-v1.md).\n // Surfaced when reading borrowed tables via `client.deps(slug)`.\n DEPENDENCY_NOT_DECLARED: 'DEPENDENCY_NOT_DECLARED',\n TABLE_NOT_IN_CONTRACT: 'TABLE_NOT_IN_CONTRACT',\n PROVIDER_TABLE_MISSING: 'PROVIDER_TABLE_MISSING',\n OPERATION_NOT_ALLOWED_BY_PROVIDER: 'OPERATION_NOT_ALLOWED_BY_PROVIDER',\n // Query-plane joins (Phase 3 — see\n // dashwise-devops-docs/plans/modules-sdk-query-v1-p3-execution.md).\n // Surfaced when `.join('<slug>')` / `.leftJoin('<slug>')` can't\n // resolve the target. Pre-declared in slice 3.1 so slice 3.2's\n // backend translator can emit them through fromBackendEnvelope\n // without an SDK roundtrip.\n LINK_FIELD_NOT_FOUND: 'LINK_FIELD_NOT_FOUND',\n NOT_A_LINK_FIELD: 'NOT_A_LINK_FIELD',\n JOIN_NOT_LINKED: 'JOIN_NOT_LINKED',\n // Cross-module actions (Phase 7 slice 7.3a — see\n // dashwise-devops-docs/plans/modules-sdk-query-v1-p7-cross-module-writes.md).\n // Surfaced when `qb.deps.<dep>.actions.<name>(input)` (generated\n // factory) dispatches against the new backend endpoint\n // `POST :installationId/deps/:providerSlug/actions/:actionName`.\n // Slice 7.2b ships the backend emitter; slice 7.3a (this slice)\n // reserves the codes + maps them to DepActionError in the SDK.\n ACTION_NOT_EXPOSED: 'ACTION_NOT_EXPOSED',\n ACTION_NOT_DECLARED: 'ACTION_NOT_DECLARED',\n ACTION_INPUT_INVALID: 'ACTION_INPUT_INVALID',\n ACTION_OUTPUT_INVALID: 'ACTION_OUTPUT_INVALID',\n ACTION_RATE_LIMITED: 'ACTION_RATE_LIMITED',\n ACTION_EXECUTION_FAILED: 'ACTION_EXECUTION_FAILED',\n // Data plane\n ROW_NOT_FOUND: 'ROW_NOT_FOUND',\n TABLE_NOT_FOUND: 'TABLE_NOT_FOUND',\n VALIDATION_FAILED: 'VALIDATION_FAILED',\n ROW_LIMIT_EXCEEDED: 'ROW_LIMIT_EXCEEDED',\n STORAGE_LIMIT_EXCEEDED: 'STORAGE_LIMIT_EXCEEDED',\n // Outbound / runtime\n OUTBOUND_NOT_ALLOWED: 'OUTBOUND_NOT_ALLOWED',\n OUTBOUND_CONCURRENCY_LIMITED: 'OUTBOUND_CONCURRENCY_LIMITED',\n // Transport\n NETWORK_ERROR: 'NETWORK_ERROR',\n TIMEOUT: 'TIMEOUT',\n // Server\n INTERNAL_ERROR: 'INTERNAL_ERROR',\n} as const;\n\nexport type DashwiseErrorCode = (typeof DashwiseErrorCode)[keyof typeof DashwiseErrorCode];\n\n/**\n * Base class for every error thrown by @dashai/sdk. Carries the\n * structured envelope from the backend (or a synthetic one for\n * client-side failures like network errors / timeouts).\n *\n * Always thrown — never returned as a value. The async client methods\n * `.list()` / `.get()` etc. reject with one of these on failure.\n */\nexport class DashwiseError extends Error {\n readonly code: string;\n readonly status: number;\n readonly retriable: boolean;\n readonly context: Record<string, unknown> | undefined;\n /**\n * Backend-issued trace anchor (Phase 6 slice 6.2, 2026-05-19).\n * Mirrors the `x-request-id` response header. Populated whenever\n * the backend's `RuntimeQueryController` (or any future endpoint\n * that echoes the header) is the origin of this error. `null` when\n * the failure is client-side (NetworkError / TimeoutError — the\n * request never reached the server, so there's no server-issued\n * ID to surface).\n *\n * Use this as a debugging trace anchor when filing a bug against a\n * specific failed query — the matching row in `module_query_log`\n * carries the full backend context (ast_hash, error_code,\n * duration_ms, etc.).\n */\n readonly requestId: string | null;\n\n constructor(\n code: string,\n message: string,\n options: {\n status?: number;\n retriable?: boolean;\n context?: Record<string, unknown>;\n cause?: unknown;\n /**\n * Phase 6 slice 6.2: backend `x-request-id` response header,\n * captured by the transport before throwing. Pass `undefined`\n * (or omit) for client-side errors that never hit the server.\n */\n requestId?: string | null;\n } = {},\n ) {\n super(message);\n this.name = this.constructor.name;\n this.code = code;\n this.status = options.status ?? 0;\n this.retriable = options.retriable ?? false;\n this.context = options.context;\n this.requestId = options.requestId ?? null;\n if (options.cause !== undefined) {\n // Node 18+ and modern browsers support Error.cause natively.\n // Use a property assignment because `super({ cause })` is awkward\n // when the base class only takes a string.\n (this as { cause?: unknown }).cause = options.cause;\n }\n }\n}\n\n/** Network-level failure (DNS, connection refused, TLS, fetch threw). */\nexport class NetworkError extends DashwiseError {\n constructor(message: string, cause?: unknown) {\n super(DashwiseErrorCode.NETWORK_ERROR, message, { retriable: true, cause });\n }\n}\n\n/** Request exceeded the configured timeout (`timeoutMs`). */\nexport class TimeoutError extends DashwiseError {\n constructor(message: string, timeoutMs: number) {\n super(DashwiseErrorCode.TIMEOUT, message, {\n retriable: true,\n context: { timeout_ms: timeoutMs },\n });\n }\n}\n\n/** 401 — token missing/invalid. */\nexport class UnauthenticatedError extends DashwiseError {\n constructor(message = 'Authentication required', requestId: string | null = null) {\n super(DashwiseErrorCode.UNAUTHENTICATED, message, { status: 401, requestId });\n }\n}\n\n/** 403 — caller lacks the role/scope for this operation. */\nexport class ForbiddenError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.FORBIDDEN, message, { status: 403, context, requestId });\n }\n}\n\n/** 404 — `GET /db/<table>/<id>` for a missing or soft-deleted row. */\nexport class RowNotFoundError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.ROW_NOT_FOUND, message, { status: 404, context, requestId });\n }\n}\n\n/**\n * Schema-level rejection: dep contract violated, table not exposed, field\n * not readable, filter op not allowed. Covers the family of \"you asked for\n * something the manifest doesn't permit\" errors.\n */\nexport class ContractViolationError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.CONTRACT_VIOLATION, message, {\n status: 403,\n context,\n requestId,\n });\n }\n}\n\n/** 422-ish — request body failed validation. Inspect `context` for field-level errors. */\nexport class ValidationError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.VALIDATION_FAILED, message, {\n status: 400,\n context,\n requestId,\n });\n }\n}\n\n// ── Cross-module dependency errors ─────────────────────────────────────\n//\n// Surfaced when calling `client.deps(slug).db<Row>(table).<op>(...)`.\n// Each subclass preserves the original backend `code` (unlike the older\n// `ContractViolationError` which collapses several codes onto a single\n// `CONTRACT_VIOLATION` string — that's a known wart we don't replicate\n// in new subclasses). Branch on `instanceof` for the common cases;\n// inspect `err.code` if you need to distinguish the two contract-error\n// codes (`DEPENDENCY_NOT_DECLARED` vs `TABLE_NOT_IN_CONTRACT`).\n\n/**\n * 404 — the caller's `module.json#dependencies` doesn't declare a\n * dependency on the requested provider module, OR the declared dep\n * exists but its `reads[]` block doesn't include the requested table.\n *\n * Either way the fix is on the **caller's** side: update the manifest\n * to declare the dep / add the table to `reads[]`, then re-publish.\n *\n * Covers both `DEPENDENCY_NOT_DECLARED` and `TABLE_NOT_IN_CONTRACT` —\n * inspect `err.code` to distinguish if you need different UX per case.\n */\nexport class DependencyContractError extends DashwiseError {\n constructor(\n code: string,\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(code, message, { status: 404, context, requestId });\n }\n}\n\n/**\n * 404 — the provider's physical table no longer exists. This means the\n * provider published a version that dropped the table while the\n * consumer's installation still pinned the old contract. Recovery is\n * on the **provider's** side (republish with the table) or the\n * workspace admin's (downgrade the provider, or upgrade the consumer\n * to a version whose `dependencies[]` no longer references it).\n */\nexport class ProviderTableMissingError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.PROVIDER_TABLE_MISSING, message, {\n status: 404,\n context,\n requestId,\n });\n }\n}\n\n/**\n * 403 — the provider's `exposes.operations.<verb>.allowed` is explicitly\n * `false` for the requested verb. Distinct from `OPERATION_NOT_ALLOWED`\n * (which is the **owner's** own-table policy) — `OPERATION_NOT_ALLOWED_BY_PROVIDER`\n * is the provider opting out of letting depending modules use a verb.\n *\n * No caller-side fix; either the provider needs to flip the gate, or\n * the consumer needs to find a different way to satisfy the use case.\n */\nexport class OperationNotAllowedByProviderError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.OPERATION_NOT_ALLOWED_BY_PROVIDER, message, {\n status: 403,\n context,\n requestId,\n });\n }\n}\n\n// ── Join errors (Phase 3) ──────────────────────────────────────────────\n//\n// Surfaced when `.join('<slug>')` / `.leftJoin('<slug>')` on the\n// generated `qb` builder can't resolve the target against the\n// manifest. Pre-declared in slice 3.1; raised by the backend\n// translator in slice 3.2. Same one-subclass-with-preserved-code\n// pattern as DependencyContractError so authors can switch on\n// `err.code` for the three sub-cases:\n//\n// LINK_FIELD_NOT_FOUND `.join('xyz')` where `xyz` isn't a field\n// on the source table. Fix: pass an\n// explicit `on` argument, or correct the slug.\n//\n// NOT_A_LINK_FIELD `.join('title')` where `title` exists on\n// the source table but its type isn't\n// `link_row`. Fix: use a real link field,\n// or pass explicit `on`.\n//\n// JOIN_NOT_LINKED `.join('sibling_table')` where the target\n// is a sibling table but no link field\n// bridges them. Fix: pass explicit `on`.\n\n/**\n * 400 — `.join()` / `.leftJoin()` referenced a target the manifest\n * can't resolve. Covers the three sub-cases above; inspect\n * `err.code` to distinguish.\n *\n * Author-side fix in every case: either correct the slug, or pass\n * an explicit `on` argument to bypass link-field inference.\n */\nexport class JoinError extends DashwiseError {\n constructor(\n code: string,\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(code, message, { status: 400, context, requestId });\n }\n}\n\n// ── Cross-module action errors (Phase 7 slice 7.3a, 2026-05-20) ──────\n//\n// Surfaced by the codegen-emitted `qb.deps.<dep>.actions.<name>(input)`\n// factory when the backend's cross-module dispatch\n// (`CrossModuleActionService.dispatch()`) rejects. Six sub-cases all\n// covered by `DepActionError`; inspect `err.code` to discriminate.\n//\n// ACTION_NOT_EXPOSED 403 — provider's manifest doesn't expose\n// the action, OR visibility='private'.\n// Recovery: provider author needs to\n// publish a version that exposes it.\n// ACTION_NOT_DECLARED 403 — consumer's manifest doesn't list\n// the action in dependencies[].actions[].\n// Recovery: add it + republish.\n// ACTION_INPUT_INVALID 400 — input fails Ajv against the\n// provider's declared input schema.\n// Recovery: fix the call site (typical\n// with stale codegen + drift).\n// ACTION_OUTPUT_INVALID 500 — provider returned a value that fails\n// the declared output schema. This is a\n// PROVIDER-author bug; consumer can\n// only file an issue.\n// ACTION_RATE_LIMITED 429 — per-actor or per-caller-installation\n// rate limit exceeded. Retry with\n// backoff after Retry-After (slice 7.4).\n// ACTION_EXECUTION_FAILED 200-envelope — action body threw, timed out,\n// or OOM-ed. Provider-author bug;\n// trace surfaced in err.context.trace.\n\n/**\n * Single subclass for every cross-module action failure. The code\n * (and HTTP status) varies per sub-case; the wrapping class lets\n * consumers `catch (e) { if (e instanceof DepActionError) {...} }`\n * regardless of which sub-case fired.\n */\nexport class DepActionError extends DashwiseError {\n constructor(\n code: string,\n message: string,\n status: number,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(code, message, {\n status,\n retriable: code === DashwiseErrorCode.ACTION_RATE_LIMITED,\n context,\n requestId,\n });\n }\n}\n\n// ── Factory: backend envelope → typed error ────────────────────────────\n\ninterface BackendErrorEnvelope {\n code?: string;\n message?: string;\n retriable?: boolean;\n context?: Record<string, unknown>;\n}\n\n/**\n * Build a typed `DashwiseError` from the backend's response envelope.\n *\n * The mapping picks the most specific subclass for codes we have a class\n * for; everything else becomes a plain `DashwiseError` carrying the raw\n * code. This keeps the type set small while still letting consumers\n * branch on string codes when they want to.\n *\n * Phase 6 slice 6.2 (2026-05-19): accepts an optional `requestId` —\n * the backend's `x-request-id` response header — and threads it onto\n * every produced error so consumers can use it as a debugging trace\n * anchor. Default `null` for backward compat; the transport always\n * passes it through.\n */\nexport function fromBackendEnvelope(\n status: number,\n envelope: BackendErrorEnvelope | null,\n requestId: string | null = null,\n): DashwiseError {\n const code = envelope?.code ?? codeFromStatus(status);\n const message = envelope?.message ?? `HTTP ${status}`;\n const context = envelope?.context;\n\n switch (code) {\n case DashwiseErrorCode.UNAUTHENTICATED:\n case DashwiseErrorCode.TOKEN_EXPIRED:\n return new UnauthenticatedError(message, requestId);\n case DashwiseErrorCode.FORBIDDEN:\n return new ForbiddenError(message, context, requestId);\n case DashwiseErrorCode.ROW_NOT_FOUND:\n return new RowNotFoundError(message, context, requestId);\n case DashwiseErrorCode.CONTRACT_VIOLATION:\n case DashwiseErrorCode.FIELD_NOT_READABLE:\n case DashwiseErrorCode.FILTER_OP_UNKNOWN:\n case DashwiseErrorCode.OPERATION_NOT_ALLOWED:\n return new ContractViolationError(message, context, requestId);\n case DashwiseErrorCode.VALIDATION_FAILED:\n return new ValidationError(message, context, requestId);\n case DashwiseErrorCode.DEPENDENCY_NOT_DECLARED:\n case DashwiseErrorCode.TABLE_NOT_IN_CONTRACT:\n return new DependencyContractError(code, message, context, requestId);\n case DashwiseErrorCode.PROVIDER_TABLE_MISSING:\n return new ProviderTableMissingError(message, context, requestId);\n case DashwiseErrorCode.OPERATION_NOT_ALLOWED_BY_PROVIDER:\n return new OperationNotAllowedByProviderError(message, context, requestId);\n case DashwiseErrorCode.LINK_FIELD_NOT_FOUND:\n case DashwiseErrorCode.NOT_A_LINK_FIELD:\n case DashwiseErrorCode.JOIN_NOT_LINKED:\n return new JoinError(code, message, context, requestId);\n case DashwiseErrorCode.ACTION_NOT_EXPOSED:\n case DashwiseErrorCode.ACTION_NOT_DECLARED:\n return new DepActionError(code, message, 403, context, requestId);\n case DashwiseErrorCode.ACTION_INPUT_INVALID:\n return new DepActionError(code, message, 400, context, requestId);\n case DashwiseErrorCode.ACTION_OUTPUT_INVALID:\n return new DepActionError(code, message, 500, context, requestId);\n case DashwiseErrorCode.ACTION_RATE_LIMITED:\n return new DepActionError(code, message, 429, context, requestId);\n case DashwiseErrorCode.ACTION_EXECUTION_FAILED:\n // ACTION_EXECUTION_FAILED arrives as a 200 envelope from the\n // backend (the host succeeded; the action body crashed). The\n // _callAction helper unwraps the envelope and synthesizes this\n // via the factory call — status 200 reflects \"the transport was\n // fine; the failure is in the application layer\".\n return new DepActionError(code, message, 200, context, requestId);\n default:\n return new DashwiseError(code, message, {\n status,\n retriable: envelope?.retriable ?? false,\n context,\n requestId,\n });\n }\n}\n\nfunction codeFromStatus(status: number): string {\n if (status === 401) return DashwiseErrorCode.UNAUTHENTICATED;\n if (status === 403) return DashwiseErrorCode.FORBIDDEN;\n if (status === 404) return DashwiseErrorCode.ROW_NOT_FOUND;\n if (status >= 500) return DashwiseErrorCode.INTERNAL_ERROR;\n return 'HTTP_ERROR';\n}\n","/**\n * HTTP transport for @dashai/sdk.\n *\n * Wraps `globalThis.fetch` with:\n * - configurable base URL + installation scoping\n * - token attachment via the caller-supplied resolver\n * - timeout enforcement via `AbortController`\n * - response envelope parsing → typed `DashwiseError`\n * - 204 No Content handling\n *\n * No retries here — retries are policy and belong one layer up. The\n * `retriable` flag on `DashwiseError` is hinting to the caller, not\n * something the transport acts on automatically. (We'd rather a module\n * author opt into retry per-call than have the SDK silently double-fire\n * an idempotent-looking POST that wasn't actually idempotent.)\n */\n\nimport {\n DashwiseError,\n NetworkError,\n TimeoutError,\n fromBackendEnvelope,\n} from './errors.js';\nimport type { ClientConfig, FetchImpl, SlowQueryInfo } from './types.js';\n\nexport interface HttpTransport {\n /**\n * Make a request to the DashWise API.\n *\n * @param method HTTP verb.\n * @param path Path appended to the installation-scoped base URL,\n * starting with `/`. Example: `/db/tasks/list`.\n * @param body JSON-serializable body. Omit/pass `undefined` to skip\n * the body entirely.\n * @returns Parsed JSON response, or `undefined` for 204 No Content.\n * @throws `DashwiseError` (or a subclass) on any non-2xx response,\n * `NetworkError` on transport failure, `TimeoutError` on\n * aborted requests.\n */\n request<T = unknown>(method: string, path: string, body?: unknown): Promise<T>;\n\n /**\n * Phase 6 streaming (2026-05-19): low-level transport entry that\n * returns the unparsed `Response` so the caller can stream the body\n * chunk-by-chunk. Used by `qb.from(...).stream()` to consume the\n * backend's SSE endpoint.\n *\n * Differs from `request()`:\n * - No body parsing — caller owns the `Response.body` ReadableStream.\n * - Caller MUST handle non-2xx (read the error envelope from the\n * response body + throw the typed `DashwiseError`); this method\n * returns the Response regardless of status so error JSON can\n * be read off the stream.\n * - Optional `signal` parameter for caller-side cancellation\n * (combined with the transport's own timeout). Abort propagates\n * to fetch, which cancels the underlying network read.\n * - Timeout handling: still applies via the transport's\n * `timeoutMs` config, but ONLY to the headers-arrival phase.\n * Streaming bodies can take arbitrarily long; the stream\n * reader's own backpressure handles the long tail.\n */\n streamRaw(\n method: string,\n path: string,\n body?: unknown,\n signal?: AbortSignal,\n ): Promise<Response>;\n}\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst DEFAULT_SLOW_QUERY_THRESHOLD_MS = 500;\nconst TRAILING_SLASH = /\\/+$/;\nconst LEADING_SLASH = /^\\/+/;\n\n/**\n * Build the installation-scoped base URL. The runtime data API lives at\n * `/api/modules/<installation-id>` — every request from the SDK is\n * relative to that prefix.\n */\nfunction buildBaseUrl(baseUrl: string, installationId: number | string): string {\n if (!baseUrl) {\n throw new Error('@dashai/sdk: `baseUrl` is required');\n }\n const trimmed = baseUrl.replace(TRAILING_SLASH, '');\n return `${trimmed}/api/modules/${installationId}`;\n}\n\nfunction resolveFetch(custom: FetchImpl | undefined): FetchImpl {\n if (custom) return custom;\n if (typeof globalThis.fetch !== 'function') {\n throw new Error(\n '@dashai/sdk: no `fetch` available. On Node < 18, pass an explicit `fetch` in `createClient({...})`.',\n );\n }\n return globalThis.fetch.bind(globalThis);\n}\n\n/**\n * Parse a `Response` body, tolerating empty / non-JSON responses. Returns\n * `null` if there's no body or if the body fails to parse.\n *\n * We never throw from here — the caller decides what to do based on the\n * presence of an envelope.\n */\nasync function readBody(res: Response): Promise<unknown> {\n if (res.status === 204) return undefined;\n const contentType = res.headers.get('content-type') ?? '';\n if (!contentType.includes('application/json')) {\n // Non-JSON 200s shouldn't happen from DashWise, but handle them anyway.\n try {\n return await res.text();\n } catch {\n return null;\n }\n }\n try {\n return await res.json();\n } catch {\n return null;\n }\n}\n\n/**\n * Create an HTTP transport from the public client config.\n *\n * The returned `request` function captures the config + closes over it,\n * so the client can be shared across concurrent calls without rebuilding\n * the transport per call.\n */\nexport function createHttp(config: ClientConfig): HttpTransport {\n const base = buildBaseUrl(config.baseUrl, config.installationId);\n const doFetch = resolveFetch(config.fetch);\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const staticHeaders: Record<string, string> = {\n Accept: 'application/json',\n ...(config.headers ?? {}),\n };\n // Phase 6 slice 6.3 (2026-05-19): slow-query callback wiring.\n // Read once at transport construction — config is immutable after\n // createClient. If `onSlowQuery` is unset, the per-request hot path\n // skips the duration comparison entirely (zero overhead).\n const onSlowQuery = config.onSlowQuery;\n const slowQueryThresholdMs =\n config.slowQueryThresholdMs ?? DEFAULT_SLOW_QUERY_THRESHOLD_MS;\n\n /**\n * Fire the slow-query callback if (a) it's configured and (b) the\n * round-trip exceeded the threshold. Always-safe: any exception the\n * caller's callback throws is caught and silently dropped — a buggy\n * observability hook MUST NOT crash the query path. Same failure-\n * isolation contract the backend's `ModuleQueryLogService.record()`\n * uses.\n */\n function maybeFireSlowQuery(info: SlowQueryInfo): void {\n if (!onSlowQuery) return;\n if (info.durationMs <= slowQueryThresholdMs) return;\n try {\n onSlowQuery(info);\n } catch {\n // Swallow — observability is best-effort.\n }\n }\n\n async function request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const normalizedPath = `/${path.replace(LEADING_SLASH, '')}`;\n // Paths starting with `/api/` are treated as absolute (rooted at\n // baseUrl) instead of installation-scoped. Used by Phase 7's\n // `_callAction()` which hits `/api/modules/runtime/installations/...`\n // — a sibling namespace to the installation-scoped CRUD endpoints.\n // All existing call sites use installation-relative paths\n // (e.g. `/db/tasks/list`), so this is backward-compatible.\n const url = normalizedPath.startsWith('/api/')\n ? `${config.baseUrl.replace(/\\/+$/, '')}${normalizedPath}`\n : `${base}${normalizedPath}`;\n\n // Resolve token AFTER building URL so a failing resolver still gives\n // the consumer a useful error path-context. The resolver may be async\n // (e.g. session lookup); the same instance is allowed to mutate\n // between calls (token refresh).\n const token = config.getToken ? await config.getToken() : null;\n\n const headers: Record<string, string> = { ...staticHeaders };\n if (body !== undefined) {\n headers['Content-Type'] = 'application/json';\n }\n if (token) {\n headers['Authorization'] = `Bearer ${token}`;\n }\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n\n // Phase 6 slice 6.3: capture the round-trip start AFTER token\n // resolution (which can be slow if the resolver hits a network)\n // but BEFORE the fetch — measures what the consumer cares about:\n // the actual HTTP request's perceived latency.\n const start = Date.now();\n\n let res: Response;\n try {\n res = await doFetch(url, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n signal: controller.signal,\n });\n } catch (err) {\n clearTimeout(timer);\n const durationMs = Date.now() - start;\n if (isAbortError(err)) {\n maybeFireSlowQuery({\n method,\n path: normalizedPath,\n durationMs,\n status: 0,\n success: false,\n requestId: null,\n });\n throw new TimeoutError(`Request to ${method} ${normalizedPath} timed out`, timeoutMs);\n }\n maybeFireSlowQuery({\n method,\n path: normalizedPath,\n durationMs,\n status: 0,\n success: false,\n requestId: null,\n });\n throw new NetworkError(\n `Network failure on ${method} ${normalizedPath}: ${describeError(err)}`,\n err,\n );\n }\n clearTimeout(timer);\n\n const parsed = await readBody(res);\n const durationMs = Date.now() - start;\n\n // Phase 6 slice 6.2 (2026-05-19): capture the backend's\n // `x-request-id` response header so we can attach it to any\n // thrown `DashwiseError` as a debugging trace anchor. The\n // backend echoes this header on every query/explain response\n // (and will on more endpoints as Phase 6 rolls out); for\n // endpoints that don't echo it yet, we get `null` and the\n // error carries `requestId: null` — same semantic as a\n // client-side NetworkError / TimeoutError.\n const requestId = res.headers.get('x-request-id');\n\n if (!res.ok) {\n maybeFireSlowQuery({\n method,\n path: normalizedPath,\n durationMs,\n status: res.status,\n success: false,\n requestId,\n });\n const envelope = isEnvelope(parsed) ? parsed : null;\n throw fromBackendEnvelope(res.status, envelope, requestId);\n }\n\n maybeFireSlowQuery({\n method,\n path: normalizedPath,\n durationMs,\n status: res.status,\n success: true,\n requestId,\n });\n\n // 204 / empty body → caller gets `undefined` typed as `T`. The data\n // plane's `delete` is the only operation that legitimately produces\n // a void result; everything else returns a body.\n return parsed as T;\n }\n\n /**\n * Phase 6 streaming (2026-05-19): low-level streaming entry — see\n * `HttpTransport.streamRaw` JSDoc for the contract.\n *\n * Implementation mirrors `request()`'s setup (URL + token + static\n * headers + AbortController) but skips body parsing entirely. The\n * caller's `signal`, if provided, is combined with the transport's\n * own timeout controller so EITHER trigger cancels the fetch.\n */\n async function streamRaw(\n method: string,\n path: string,\n body?: unknown,\n signal?: AbortSignal,\n ): Promise<Response> {\n const normalizedPath = `/${path.replace(LEADING_SLASH, '')}`;\n const url = `${base}${normalizedPath}`;\n const token = config.getToken ? await config.getToken() : null;\n\n const headers: Record<string, string> = { ...staticHeaders };\n if (body !== undefined) {\n headers['Content-Type'] = 'application/json';\n }\n if (token) {\n headers['Authorization'] = `Bearer ${token}`;\n }\n\n // Combine the caller's signal with our timeout controller.\n // Either trigger cancels the fetch.\n const timeoutController = new AbortController();\n const timer = setTimeout(() => timeoutController.abort(), timeoutMs);\n const combinedController = new AbortController();\n if (signal) {\n if (signal.aborted) combinedController.abort();\n else signal.addEventListener('abort', () => combinedController.abort(), { once: true });\n }\n timeoutController.signal.addEventListener(\n 'abort',\n () => combinedController.abort(),\n { once: true },\n );\n\n // onSlowQuery wiring: measure round-trip from fetch start to\n // headers-arrival. Streaming responses linger after headers; we\n // fire `onSlowQuery` once when headers come back, NOT once per\n // chunk. The `success` flag reflects HTTP status at that point;\n // in-band SSE error events are observable by the caller separately.\n const start = Date.now();\n let res: Response;\n try {\n res = await doFetch(url, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n signal: combinedController.signal,\n });\n } catch (err) {\n clearTimeout(timer);\n const durationMs = Date.now() - start;\n if (isAbortError(err)) {\n maybeFireSlowQuery({\n method,\n path: normalizedPath,\n durationMs,\n status: 0,\n success: false,\n requestId: null,\n });\n // If the caller-supplied signal aborted, surface that as a\n // standard AbortError (consumer can branch on `e.name`).\n // Otherwise it's our timeout firing.\n if (signal?.aborted) {\n const e = new Error('Aborted by caller');\n e.name = 'AbortError';\n throw e;\n }\n throw new TimeoutError(\n `Streaming request to ${method} ${normalizedPath} timed out before headers arrived`,\n timeoutMs,\n );\n }\n maybeFireSlowQuery({\n method,\n path: normalizedPath,\n durationMs,\n status: 0,\n success: false,\n requestId: null,\n });\n throw new NetworkError(\n `Network failure on ${method} ${normalizedPath}: ${describeError(err)}`,\n err,\n );\n }\n clearTimeout(timer);\n\n const requestId = res.headers.get('x-request-id');\n maybeFireSlowQuery({\n method,\n path: normalizedPath,\n durationMs: Date.now() - start,\n status: res.status,\n success: res.ok,\n requestId,\n });\n\n // Hand the Response back regardless of status — caller reads the\n // error envelope from the body (the standard JSON error path) OR\n // streams the body when ok.\n return res;\n }\n\n return { request, streamRaw };\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────────\n\nfunction isAbortError(err: unknown): boolean {\n if (!err || typeof err !== 'object') return false;\n const e = err as { name?: string; code?: string };\n return e.name === 'AbortError' || e.code === 'ABORT_ERR';\n}\n\nfunction describeError(err: unknown): string {\n if (err instanceof Error) return err.message;\n if (typeof err === 'string') return err;\n try {\n return JSON.stringify(err);\n } catch {\n return '<unknown error>';\n }\n}\n\nfunction isEnvelope(value: unknown): value is {\n code?: string;\n message?: string;\n retriable?: boolean;\n context?: Record<string, unknown>;\n} {\n if (!value || typeof value !== 'object') return false;\n const v = value as Record<string, unknown>;\n // We accept the envelope if it has at least `code` OR `message` —\n // matches what `DomainError` filters emit from the backend.\n return typeof v.code === 'string' || typeof v.message === 'string';\n}\n\n// Re-export DashwiseError so consumers of the http module alone get the\n// full error model without a second import.\nexport { DashwiseError };\n","/**\n * `createClient()` — the public factory for talking to the DashWise\n * runtime data API.\n *\n * Returns a `Client` whose `db<Row>(slug)` method binds a table slug +\n * row type and produces a chainable `{ list, get, create, update, delete }`\n * surface.\n *\n * Two-layer use:\n * 1. Generated per-module typed wrappers call this and re-export a\n * typed `db.tasks` / `db.notes` / etc. — the user-facing API for\n * modules that ran `dashwise module generate`.\n * 2. Direct use for hand-authored scripts, integration tooling, custom\n * modules that don't run codegen — operate on\n * `Record<string, unknown>` rows with the generic `db<Row>(slug)`\n * shape.\n *\n * The HTTP path layout mirrors the existing runtime data plane in\n * `dashwise-backend/src/modules/modules/runtime/data/runtime-table.controller.ts`:\n *\n * POST /api/modules/<installation>/db/<table>/list\n * GET /api/modules/<installation>/db/<table>/<id>\n * POST /api/modules/<installation>/db/<table>\n * PATCH /api/modules/<installation>/db/<table>/<id>\n * DELETE /api/modules/<installation>/db/<table>/<id>\n */\n\nimport { makeDeps } from './deps.js';\nimport { fromBackendEnvelope } from './errors.js';\nimport { createHttp, type HttpTransport } from './http.js';\nimport type {\n BaseInsert,\n BaseRow,\n BaseUpdate,\n Client,\n ClientConfig,\n Deps,\n ListOpts,\n Page,\n TableClient,\n} from './types.js';\n\n/**\n * Create a DashWise SDK client. The returned client is thread-safe and\n * can be cached for the lifetime of the process (or the Next.js request).\n *\n * @example\n * const client = createClient({\n * baseUrl: 'https://api.dashwise.io',\n * installationId: 'sandbox',\n * getToken: () => process.env.DASHWISE_TOKEN ?? null,\n * });\n *\n * const page = await client.db<TasksRow>('tasks').list({\n * filter: { done: false },\n * limit: 50,\n * });\n */\nexport function createClient(config: ClientConfig): Client {\n const transport = createHttp(config);\n return {\n db<\n Row extends BaseRow,\n Insert extends BaseInsert = BaseInsert,\n Update extends BaseUpdate = BaseUpdate,\n >(tableSlug: string): TableClient<Row, Insert, Update> {\n assertValidTableSlug(tableSlug);\n return makeTableClient<Row, Insert, Update>(transport, tableSlug);\n },\n\n deps(providerSlug: string): Deps {\n // Validation lives inside `makeDeps` so the same checks apply\n // whether deps is reached via `createClient` or via a test\n // harness that constructs the transport directly.\n return makeDeps(transport, providerSlug);\n },\n\n request<T = unknown>(method: string, path: string, body?: unknown): Promise<T> {\n return transport.request<T>(method, path, body);\n },\n\n streamRaw(\n method: string,\n path: string,\n body?: unknown,\n signal?: AbortSignal,\n ): Promise<Response> {\n return transport.streamRaw(method, path, body, signal);\n },\n\n async _callAction<TOutput = unknown>(\n providerSlug: string,\n actionName: string,\n input: unknown,\n opts?: { timeoutMs?: number; idempotencyKey?: string },\n ): Promise<TOutput> {\n assertValidModuleSlug(providerSlug);\n assertValidActionName(actionName);\n // The backend endpoint is rooted at\n // `<baseUrl>/api/modules/runtime/installations/<consumerId>/deps/<slug>/actions/<name>`\n // — a sibling namespace to the installation-scoped CRUD\n // endpoints. The transport's `request()` treats paths starting\n // with `/api/` as absolute (rooted at baseUrl) instead of\n // installation-scoped.\n const path =\n `/api/modules/runtime/installations/${config.installationId}/deps/${encodeURIComponent(\n providerSlug,\n )}/actions/${encodeURIComponent(actionName)}`;\n const body: Record<string, unknown> = { input };\n if (opts?.idempotencyKey !== undefined) {\n body.idempotency_key = opts.idempotencyKey;\n }\n if (opts?.timeoutMs !== undefined) {\n body.timeout_ms = opts.timeoutMs;\n }\n const envelope = await transport.request<CrossModuleActionEnvelope<TOutput>>(\n 'POST',\n path,\n body,\n );\n // The transport throws on HTTP 4xx/5xx with the envelope mapped\n // to typed errors via fromBackendEnvelope. A successful HTTP\n // status with `ok: false` is the action-body-failure path — we\n // synthesize a DepActionError so consumers have one place to\n // catch.\n if (envelope.ok === false) {\n const requestId = envelope.cross_module?.request_id ?? null;\n throw fromBackendEnvelope(\n 200,\n {\n code: envelope.error.code,\n message: envelope.error.message,\n context: envelope.error.trace\n ? { trace: envelope.error.trace }\n : undefined,\n },\n requestId,\n );\n }\n return envelope.result;\n },\n };\n}\n\ninterface CrossModuleActionEnvelopeOk<T> {\n ok: true;\n result: T;\n elapsed_ms: number;\n executor: string;\n cross_module: {\n caller_installation_id: number;\n provider_installation_id: number;\n provider_module_slug: string;\n provider_module_version: string;\n request_id: string;\n };\n}\n\ninterface CrossModuleActionEnvelopeErr {\n ok: false;\n error: { code: string; message: string; trace?: string };\n elapsed_ms: number;\n executor: string;\n cross_module: CrossModuleActionEnvelopeOk<unknown>['cross_module'];\n}\n\ntype CrossModuleActionEnvelope<T> =\n | CrossModuleActionEnvelopeOk<T>\n | CrossModuleActionEnvelopeErr;\n\nconst ACTION_NAME_REGEX = /^[a-zA-Z_$][a-zA-Z0-9_$]{0,63}$/;\nconst MODULE_SLUG_REGEX = /^[a-z][a-z0-9-]*[a-z0-9]$/;\n\nfunction assertValidModuleSlug(slug: string): void {\n if (!MODULE_SLUG_REGEX.test(slug)) {\n throw new Error(\n `Invalid provider module slug \"${slug}\" — must be kebab-case (^[a-z][a-z0-9-]*[a-z0-9]$).`,\n );\n }\n}\n\nfunction assertValidActionName(name: string): void {\n if (!ACTION_NAME_REGEX.test(name)) {\n throw new Error(\n `Invalid action name \"${name}\" — must be a JS identifier (letters/digits/underscore/$, starts non-digit, ≤64 chars).`,\n );\n }\n}\n\n/**\n * Module-slug character set matches the manifest validator's table-slug\n * rule (`^[a-z][a-z0-9_]*$`). Slugs are baked into URL paths, so\n * unsafe characters would route to the wrong resource (or 400).\n */\nconst TABLE_SLUG_REGEX = /^[a-z][a-z0-9_]*$/;\n\nfunction assertValidTableSlug(slug: string): void {\n if (typeof slug !== 'string' || !TABLE_SLUG_REGEX.test(slug)) {\n throw new Error(\n `@dashai/sdk: invalid table slug \"${slug}\". Slugs must match /^[a-z][a-z0-9_]*$/.`,\n );\n }\n}\n\nfunction makeTableClient<\n Row extends BaseRow,\n Insert extends BaseInsert,\n Update extends BaseUpdate,\n>(transport: HttpTransport, tableSlug: string): TableClient<Row, Insert, Update> {\n const root = `/db/${tableSlug}`;\n\n return {\n async list(opts?: ListOpts<Row>): Promise<Page<Row>> {\n // SDK Query Plane v1 Phase 2 slice 6 (2026-05-19): `.list()` now\n // compiles to a Query AST and posts to the unified `/query`\n // endpoint instead of `/db/<slug>/list`. The on-wire input\n // shape is `{ ast: QueryAst }`; the output `Page<Row>` envelope\n // is identical to what the legacy endpoint returned. Consumers\n // see no behavior change — same fields accepted, same response.\n //\n // Why route through /query: single read path going forward.\n // Future query-plane improvements (sub-query caching, observability,\n // slow-query warnings) light up `.list()` automatically without\n // touching this file again. The legacy `/db/<slug>/list` endpoint\n // stays in place for non-SDK consumers (sandbox iframes, AI\n // builder tooling that hits it directly).\n //\n // The other CRUD methods below (`.get` / `.create` / `.update` /\n // `.delete`) keep using `/db/<slug>/...` — the query plane is\n // read-only by design, and per-row reads + writes have no AST\n // representation in v1.\n const ast: Record<string, unknown> = {\n v: 1,\n from: { kind: 'owned', slug: tableSlug },\n };\n if (opts?.filter !== undefined) ast.where = opts.filter;\n if (opts?.sort !== undefined && opts.sort.length > 0) {\n ast.orderBy = opts.sort;\n }\n if (typeof opts?.limit === 'number') ast.limit = opts.limit;\n if (typeof opts?.offset === 'number') ast.offset = opts.offset;\n\n const result = await transport.request<Page<Row>>('POST', '/query', { ast });\n // Defence in depth: same Page-envelope coercion as before. The\n // query plane always returns a proper envelope today; this\n // fallback covers misconfigured proxies + future endpoint shape\n // drift.\n if (Array.isArray(result)) {\n return {\n rows: result as Row[],\n total: result.length,\n limit: opts?.limit ?? result.length,\n offset: opts?.offset ?? 0,\n };\n }\n return result;\n },\n\n async get(id: number): Promise<Row> {\n return transport.request<Row>('GET', `${root}/${id}`);\n },\n\n async create(body: Insert): Promise<Row> {\n return transport.request<Row>('POST', root, body);\n },\n\n async update(id: number, patch: Update): Promise<Row> {\n return transport.request<Row>('PATCH', `${root}/${id}`, patch);\n },\n\n async delete(id: number): Promise<void> {\n await transport.request<void>('DELETE', `${root}/${id}`);\n },\n };\n}\n","/**\n * `createDevClient()` — `createClient()`'s zero-config sibling for local dev.\n *\n * Resolves `baseUrl`, `installationId`, and `getToken` from a layered\n * config chain so a developer who has run `dashwise login` (and, for the\n * full local-dev experience, `dashwise init`) can do:\n *\n * ```ts\n * import { createDevClient } from '@dashai/sdk';\n * const client = createDevClient({ moduleSlug: 'my-tasks' });\n * ```\n *\n * …without copying tokens or installation ids around. The flow this\n * enables is the end-to-end \"two-command bootstrap\" the CLI's\n * `dashwise login` + `dashwise init` pair targets.\n *\n * ## Resolution chain\n *\n * For each field, the first non-empty source wins:\n *\n * 1. Explicit `overrides` argument (per-call escape hatch).\n * 2. Environment variables — `DASHWISE_API_URL` / `DASHWISE_API_TOKEN`\n * / `DASHWISE_INSTALLATION_ID` / `DASHWISE_RUNTIME_TOKEN` (HH-CC-LDI-5).\n * Standard for CI, Docker, prod-like setups; also the path\n * `dashwise dev` uses to inject per-module credentials into the\n * Next.js child process.\n * 3. The CLI's saved config at `$XDG_CONFIG_HOME/dashwise/auth.json`\n * (or platform default) — written by `dashwise login` (top-level\n * `apiUrl` + `token`) and `dashwise init` (per-module entry under\n * `modules[slug]`).\n *\n * ## Per-module local-dev tokens (HH-CC-LDI-5)\n *\n * When `overrides.moduleSlug` is set, the SDK looks up the per-module\n * entry in `auth.json`:\n *\n * ```jsonc\n * {\n * \"apiUrl\": \"http://localhost:3000\",\n * \"token\": \"dwc_...\", // CLI bearer (login)\n * \"modules\": {\n * \"my-tasks\": {\n * \"runtimeToken\": \"<JWT>\", // long-lived runtime token (LDI-2)\n * \"installationId\": 4242, // numeric install id (LDI-2)\n * \"expiresAt\": \"2026-08-22T...\" // informational only\n * }\n * }\n * }\n * ```\n *\n * Per-module entries are written by `dashwise init` (HH-CC-LDI-6) when\n * a developer provisions a local-dev install. The SDK prefers the\n * `runtimeToken` over the legacy CLI bearer (`token`) when both\n * exist, and sets `installationId` to the literal `'sandbox'` — the\n * URL placeholder the backend's `RuntimeTokenGuard` accepts (the\n * token resolves to the actual install on the server side).\n *\n * If `moduleSlug` is unset, OR the named module isn't in the\n * `modules` map, OR the entry lacks a `runtimeToken`, the resolver\n * falls back to the legacy chain (`token` field + `'local'` install\n * id, which the backend will reject — surfacing as a typed\n * `UnauthenticatedError` on the first request).\n *\n * ## Safety rails\n *\n * - **Production refusal.** When `NODE_ENV === 'production'`, the file\n * fallback is skipped. Prod deploys MUST set env vars explicitly;\n * accidentally shipping with `~/.config/dashwise/auth.json` baked into\n * a Docker image would be a credential leak.\n * - **Edge / browser refusal.** `fs` / `os` / `path` imports happen\n * lazily inside a try/catch with a Node-detection guard. In edge or\n * browser runtimes the file fallback is silently skipped — env vars\n * are still honored.\n * - **No throw on missing creds at construction time.** Same contract\n * as `createClient()` — the throw happens at the first request when\n * the resolver returns null AND the backend rejects the call. This\n * lets bundlers tree-shake the function into builds where it's only\n * called conditionally.\n *\n * ## When to use which\n *\n * - `createClient(config)` — production, edge runtime, anywhere you\n * want explicit control over auth resolution\n * - `createDevClient()` — local development, REPL exploration, ad-hoc\n * scripts where typing the env-var dance every time is friction\n *\n * Both return the same `Client` shape — switching is a one-line change.\n */\n\nimport { createClient } from './client.js';\nimport type { Client, ClientConfig, TokenResolver } from './types.js';\n\n/**\n * Subset of `ClientConfig` the caller can override on top of the\n * auto-resolved defaults. Anything omitted uses the resolution chain.\n *\n * `fetch`, `timeoutMs`, `headers`, `onSlowQuery`, `slowQueryThresholdMs`\n * are passed through unchanged when provided.\n */\nexport interface CreateDevClientOptions\n extends Partial<Omit<ClientConfig, 'getToken'>> {\n /**\n * Per-request token resolver. If set, overrides the auto-resolved\n * token entirely. Pass `() => null` to explicitly disable token\n * attachment (rare — only useful for hitting public endpoints).\n */\n getToken?: TokenResolver;\n\n /**\n * HH-CC-LDI-5 — module slug for per-module runtime-token lookup.\n *\n * When set, `createDevClient` reads\n * `~/.config/dashwise/auth.json#modules[<moduleSlug>]` looking for\n * a `runtimeToken`. If found, that token is used as the bearer\n * (overriding `DASHWISE_API_TOKEN` / file-level `token`) and the\n * SDK sends `installationId='sandbox'` — the URL placeholder\n * accepted by the backend's `RuntimeTokenGuard`. The runtime\n * token itself binds to a specific install on the server side.\n *\n * If `moduleSlug` is unset or the entry is missing, the legacy\n * resolution chain applies (CLI bearer + `'local'` installation\n * id, which the backend will 401 — surfacing as a typed\n * `UnauthenticatedError` on the first request).\n *\n * Typical usage: scaffolded modules read `module.json#module.slug`\n * and pass it here. The CLI's `dashwise dev` command also exports\n * it as the `DASHWISE_RUNTIME_TOKEN` env var so child processes\n * (e.g. `next dev`) can authenticate without re-reading the file.\n */\n moduleSlug?: string;\n}\n\n/**\n * Resolve config from env + saved CLI file + overrides, then hand off\n * to `createClient`. Synchronous — all sources are sync-readable.\n *\n * Throws only on truly unrecoverable problems (no `baseUrl` anywhere).\n * Missing token is fine at construction — the resolver returns null and\n * the backend's 401 surfaces a clear `UnauthenticatedError`.\n */\nexport function createDevClient(overrides: CreateDevClientOptions = {}): Client {\n const fileConfig = readCliConfigFile();\n\n const baseUrl =\n overrides.baseUrl ??\n readEnv('DASHWISE_API_URL') ??\n fileConfig?.apiUrl ??\n null;\n if (!baseUrl) {\n throw new Error(\n '@dashai/sdk: createDevClient() could not resolve a baseUrl. ' +\n 'Pass `{ baseUrl }` explicitly, set `DASHWISE_API_URL`, or run `dashwise login` ' +\n 'to create the CLI config file.',\n );\n }\n\n // HH-CC-LDI-5: resolve the per-module runtime token if either an\n // explicit `DASHWISE_RUNTIME_TOKEN` env (set by `dashwise dev`) or a\n // file-level `modules[slug].runtimeToken` entry (set by\n // `dashwise init`) is available. The env var wins, mirroring the\n // env > file precedence of every other field.\n //\n // When this resolves to non-null, it's preferred over the legacy\n // CLI bearer token (`token` field + `DASHWISE_API_TOKEN`). The two\n // tokens have different lifecycles + scopes — the bearer is the\n // user's long-lived CLI credential, the runtime token is a JWT\n // bound to a specific local-dev install.\n const moduleEntry = overrides.moduleSlug\n ? fileConfig?.modules?.[overrides.moduleSlug]\n : undefined;\n const runtimeToken =\n readEnv('DASHWISE_RUNTIME_TOKEN') ?? moduleEntry?.runtimeToken ?? null;\n\n // installationId: explicit override > env var > 'sandbox' if we\n // have a runtime token (URL placeholder for runtime-token auth) >\n // legacy 'local' fallback. The 'local' fallback exists for\n // backward compat with pre-LDI flows; the backend will 401 it,\n // surfacing a clear UnauthenticatedError the developer can act on.\n const installationId =\n overrides.installationId ??\n readEnv('DASHWISE_INSTALLATION_ID') ??\n (runtimeToken !== null ? 'sandbox' : 'local');\n\n // Token resolution: runtime token > legacy bearer token. Snapshot\n // at construction (same rationale as the original implementation —\n // a developer would need to re-login + restart their dev server\n // for the token to change).\n const snapshotToken =\n runtimeToken ??\n readEnv('DASHWISE_API_TOKEN') ??\n fileConfig?.token ??\n null;\n const resolvedGetToken: TokenResolver =\n overrides.getToken ?? (() => snapshotToken);\n\n return createClient({\n ...overrides,\n baseUrl,\n installationId,\n getToken: resolvedGetToken,\n });\n}\n\n// ── Internals ───────────────────────────────────────────────────────────\n\n/** Minimal view of the CLI's `auth.json` — only the fields we use. */\ninterface CliConfigFileShape {\n apiUrl?: string;\n token?: string;\n /**\n * HH-CC-LDI-5 — per-module local-dev install metadata, keyed by\n * the module's slug (matches `module.json#module.slug`).\n *\n * Written by `dashwise init` (LDI-6); read here for the\n * per-module runtime-token lookup. The SDK only consumes\n * `runtimeToken`; `installationId` + `expiresAt` are\n * informational (the CLI uses them for `dashwise module\n * status` / token-rotation flows).\n */\n modules?: Record<string, CliConfigModuleEntry>;\n}\n\n/** Per-module entry within `auth.json#modules`. */\ninterface CliConfigModuleEntry {\n /** JWT runtime token minted by `POST /api/installations/dev`. */\n runtimeToken?: string;\n /** Numeric installation id the runtime token resolves to. */\n installationId?: number;\n /** ISO timestamp; informational only (not enforced client-side). */\n expiresAt?: string;\n}\n\n/**\n * Read an env var with empty-string treated as unset. Safe on edge /\n * browser builds where `process` may be a polyfill shim with no `env`.\n */\nfunction readEnv(key: string): string | undefined {\n if (typeof process === 'undefined' || !process.env) return undefined;\n const v = process.env[key];\n return typeof v === 'string' && v.length > 0 ? v : undefined;\n}\n\n/**\n * Detect whether we're in a Node-like runtime that can actually `import\n * 'node:fs'`. Edge runtime, Cloudflare Workers, Deno without compat,\n * and browsers all fail this check.\n */\nfunction isNodeRuntime(): boolean {\n if (typeof process === 'undefined') return false;\n if (!process.versions || typeof process.versions.node !== 'string') {\n return false;\n }\n return true;\n}\n\n/**\n * Load + parse `auth.json` from the CLI's config directory. Returns\n * `null` if:\n * - We're not in Node (edge / browser)\n * - `NODE_ENV === 'production'` (prod must use env vars; refusing the\n * file fallback is the safety rail against accidental credential\n * leaks into Docker images)\n * - The file doesn't exist (user hasn't run `dashwise login`)\n * - The file exists but is unreadable / unparseable (corrupt — caller\n * should re-login; we don't surface a noisy warning because the\n * env-var path is still valid)\n *\n * Mirrors the path resolution in `@dashai/cli`'s\n * `packages/cli/src/lib/config.ts#configPath()` — kept in sync by\n * convention since the SDK can't depend on the CLI.\n */\nfunction readCliConfigFile(): CliConfigFileShape | null {\n if (!isNodeRuntime()) return null;\n if (readEnv('NODE_ENV') === 'production') return null;\n try {\n // Lazy require so bundlers that don't tree-shake the function call\n // (e.g. esbuild without `--platform=node`) still drop the imports\n // when this branch is unreachable at build time.\n //\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const fs = require('node:fs') as typeof import('node:fs');\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const path = require('node:path') as typeof import('node:path');\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const os = require('node:os') as typeof import('node:os');\n\n const dir = resolveConfigDir(path, os);\n const file = path.join(dir, 'auth.json');\n if (!fs.existsSync(file)) return null;\n\n const raw = fs.readFileSync(file, 'utf-8');\n const parsed = JSON.parse(raw) as unknown;\n if (!isPlausibleFileShape(parsed)) return null;\n return parsed;\n } catch {\n // Any failure → fall through to env-var-only mode. We deliberately\n // don't log here: a missing / corrupt file is \"no fallback\n // available,\" not \"something is broken.\" If env vars are also\n // missing, the createClient-level error message will guide the\n // developer to run `dashwise login`.\n return null;\n }\n}\n\n/**\n * Resolve the CLI's config directory. Same priority as the CLI:\n * 1. `$XDG_CONFIG_HOME/dashwise/`\n * 2. `%APPDATA%\\dashwise\\` on Windows\n * 3. `~/.config/dashwise/` everywhere else\n */\nfunction resolveConfigDir(\n path: typeof import('node:path'),\n os: typeof import('node:os'),\n): string {\n const xdg = readEnv('XDG_CONFIG_HOME');\n if (xdg) return path.join(xdg, 'dashwise');\n if (os.platform() === 'win32') {\n const appdata = readEnv('APPDATA');\n if (appdata) return path.join(appdata, 'dashwise');\n }\n return path.join(os.homedir(), '.config', 'dashwise');\n}\n\nfunction isPlausibleFileShape(v: unknown): v is CliConfigFileShape {\n if (!v || typeof v !== 'object') return false;\n const o = v as Record<string, unknown>;\n // We accept anything that LOOKS like an auth.json. If `apiUrl` /\n // `token` are missing or wrong-typed, our resolution chain falls\n // through to the next source — same as if the file didn't exist.\n //\n // HH-CC-LDI-5: `modules` is a record-shaped optional. We don't\n // deep-validate per-entry shapes — if a `modules[slug]` is\n // garbage, the runtime-token resolver just returns null and the\n // legacy chain takes over. Forgiveness over strictness keeps the\n // SDK resilient to a partially-written `auth.json` (e.g. the CLI\n // crashed mid-write during `init`).\n const apiUrlOk = o.apiUrl === undefined || typeof o.apiUrl === 'string';\n const tokenOk = o.token === undefined || typeof o.token === 'string';\n const modulesOk =\n o.modules === undefined ||\n (typeof o.modules === 'object' && o.modules !== null);\n return apiUrlOk && tokenOk && modulesOk;\n}\n","/**\n * @dashai/sdk — public entry point.\n *\n * Two planes:\n * - **data**: typed table client (`createClient`, `db<Row>(slug)`,\n * `Where<Row>`, `Page<T>`, `DashwiseError` + subclasses).\n * Re-exported from the default barrel.\n * - **auth**: server / middleware / client helpers for session\n * management. Imported via subpaths so consumers don't pull in\n * React / `next/headers` if they only need data.\n *\n * Auth surface (all subpath-imported):\n * - `@dashai/sdk/auth/server` — `getServerSession`, `exchangeCode`, `signOut`\n * - `@dashai/sdk/auth/middleware` — `withAuth()` Next.js edge middleware factory\n * - `@dashai/sdk/auth/client` — `useSession`, `<AuthProvider>`, `<SignOutButton>`\n * - `@dashai/sdk/auth/types` — `Session`, `AuthOptions`, `AuthErrorCode`\n *\n * SemVer policy: every named export here AND every named export from\n * the `auth/*` subpaths is part of the stable API. Breaking changes\n * require a major bump; new optional fields, new types, and additional\n * named exports are minors.\n *\n * Distribution model (per the v1 plan in\n * `dashwise-devops-docs/plans/modules-p8-p10-execution-plan.md`):\n * - **AI builder sandbox**: SDK is baked into the E2B template image.\n * - **CLI / local dev**: workspace-local resolution via pnpm\n * `workspace:*` protocol OR tarball-into-`.dashwise/sdk-tarball.tgz`.\n * - **Published modules**: SDK is pre-bundled into the Lambda image\n * by `next build`; no runtime fetch required.\n *\n * npm publication is intentionally deferred — the SDK is consumed by\n * trusted, in-workspace paths, not by external developers (yet).\n *\n * @packageDocumentation\n */\n\nexport * from './data/index.js';\n\n/**\n * SDK package version. Replaced at build time by `tsup`'s `define`\n * substitution (see `tsup.config.ts`) with the value of `version`\n * from `packages/sdk/package.json`. Consumers can read this to\n * version-skew-detect against the manifest's required SDK range.\n *\n * In non-tsup contexts (Vitest, raw `tsc`), the bare `__SDK_VERSION__`\n * identifier resolves to a static `'dev'` fallback declared below.\n * Production builds always go through tsup so the build-time value\n * is what ships.\n */\ndeclare const __SDK_VERSION__: string;\nexport const VERSION: string =\n typeof __SDK_VERSION__ === 'string' ? __SDK_VERSION__ : 'dev';\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/data/deps.ts","../src/data/errors.ts","../src/data/http.ts","../src/data/client.ts","../src/data/dev-client.ts","../src/index.ts"],"names":["durationMs","assertValidTableSlug","MODULE_SLUG_REGEX","TABLE_SLUG_REGEX"],"mappings":";;;;;;;;AA2CA,IAAM,iBAAA,GAAoB,2BAAA;AAO1B,IAAM,gBAAA,GAAmB,2BAAA;AAEzB,SAAS,wBAAwB,IAAA,EAAoB;AACnD,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,IAAY,CAAC,iBAAA,CAAkB,IAAA,CAAK,IAAI,CAAA,EAAG;AAC7D,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,uCAAuC,IAAI,CAAA,wHAAA;AAAA,KAC7C;AAAA,EACF;AACF;AAEA,SAAS,qBAAqB,IAAA,EAAoB;AAChD,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,IAAY,CAAC,gBAAA,CAAiB,IAAA,CAAK,IAAI,CAAA,EAAG;AAC5D,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,oCAAoC,IAAI,CAAA,mEAAA;AAAA,KAC1C;AAAA,EACF;AACF;AASO,SAAS,QAAA,CAAS,WAA0B,YAAA,EAA4B;AAC7E,EAAA,uBAAA,CAAwB,YAAY,CAAA;AAEpC,EAAA,OAAO;AAAA,IACL,GAAwB,SAAA,EAA6C;AACnE,MAAA,oBAAA,CAAqB,SAAS,CAAA;AAC9B,MAAA,OAAO,uBAAA,CAA6B,SAAA,EAAW,YAAA,EAAc,SAAS,CAAA;AAAA,IACxE;AAAA,GACF;AACF;AAOA,SAAS,uBAAA,CACP,SAAA,EACA,YAAA,EACA,SAAA,EAC0B;AAM1B,EAAA,MAAM,IAAA,GAAO,CAAA,MAAA,EAAS,YAAY,CAAA,IAAA,EAAO,SAAS,CAAA,CAAA;AAElD,EAA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AE,KAAA,KAAU,QAAA;AAC5D,EAAA,MAAM,SAAA,GACJ,EAAE,OAAA,KAAY,MAAA,IACb,OAAO,CAAA,CAAE,OAAA,KAAY,QAAA,IAAY,CAAA,CAAE,OAAA,KAAY,IAAA;AAClD,EAAA,OAAO,YAAY,OAAA,IAAW,SAAA;AAChC;;;AC1SO,IAAM,OAAA,GAC2B,QAAA","file":"index.js","sourcesContent":["/**\n * Borrowed-table accessor: `client.deps(providerSlug).db<Row>(tableSlug)`.\n *\n * Phase 1 of the SDK query plane — see\n * `dashwise-devops-docs/plans/modules-sdk-query-v1.md` §6.2.\n *\n * The factory is intentionally a thin wrapper around the existing\n * {@link HttpTransport}: cross-module reads target a parallel URL\n * shape (`/deps/<provider>/db/<table>/list` instead of\n * `/db/<table>/list`) but otherwise behave identically — same JSON\n * body, same {@link Page} envelope, same {@link DashwiseError} model.\n * No new transport, no new auth flow, no new caching.\n *\n * Cross-module **writes** are deliberately omitted: the returned\n * {@link ReadOnlyTableClient} has no `create` / `update` / `delete`.\n * See plan §4.3 — writes flow through provider-published actions in\n * a later phase, never as direct mutations across the trust boundary.\n *\n * Slug validation runs client-side as a fail-fast check so a typo\n * doesn't reach the backend as a 404 from a malformed URL. The\n * authoritative check is server-side: the backend re-validates\n * provider existence + contract coverage on every call.\n */\n\nimport type { HttpTransport } from './http.js';\nimport type {\n BaseRow,\n Deps,\n ListOpts,\n Page,\n ReadOnlyTableClient,\n} from './types.js';\n\n/**\n * Module-slug character set matches the backend manifest validator's\n * `MODULE_SLUG_REGEX` exactly: kebab-case, 2-63 chars, starts with a\n * letter, ends with letter/digit, no leading/trailing dash.\n *\n * Mirrored here (not imported from the backend) because the SDK is\n * published independently — pulling backend code in would couple\n * release cycles. If the backend's regex changes, the SDK's mirror\n * must update in lockstep; covered by an integration test.\n */\nconst MODULE_SLUG_REGEX = /^[a-z][a-z0-9-]*[a-z0-9]$/;\n\n/**\n * Table-slug character set matches the backend's `SLUG_REGEX`: snake_case,\n * 2-63 chars, starts with a letter, ends with letter/digit. Same\n * mirror-vs-import tradeoff as {@link MODULE_SLUG_REGEX}.\n */\nconst TABLE_SLUG_REGEX = /^[a-z][a-z0-9_]*[a-z0-9]$/;\n\nfunction assertValidProviderSlug(slug: string): void {\n if (typeof slug !== 'string' || !MODULE_SLUG_REGEX.test(slug)) {\n throw new Error(\n `@dashai/sdk: invalid provider slug \"${slug}\". Provider slugs are the dependency module's slug (kebab-case, e.g. \"crm-app\"); must match /^[a-z][a-z0-9-]*[a-z0-9]$/.`,\n );\n }\n}\n\nfunction assertValidTableSlug(slug: string): void {\n if (typeof slug !== 'string' || !TABLE_SLUG_REGEX.test(slug)) {\n throw new Error(\n `@dashai/sdk: invalid table slug \"${slug}\". Table slugs must match /^[a-z][a-z0-9_]*[a-z0-9]$/ (snake_case).`,\n );\n }\n}\n\n/**\n * Build a {@link Deps} accessor for `providerSlug`. Validates the\n * slug shape eagerly; defers everything else to the backend.\n *\n * Exported for use by `createClient()` in `./client.ts`. Not part\n * of the public API directly — consumers reach it via `client.deps(...)`.\n */\nexport function makeDeps(transport: HttpTransport, providerSlug: string): Deps {\n assertValidProviderSlug(providerSlug);\n\n return {\n db<Row extends BaseRow>(tableSlug: string): ReadOnlyTableClient<Row> {\n assertValidTableSlug(tableSlug);\n return makeBorrowedTableClient<Row>(transport, providerSlug, tableSlug);\n },\n };\n}\n\n/**\n * Internal: produce a {@link ReadOnlyTableClient} for one specific\n * `(providerSlug, tableSlug)` pair. Closure captures the transport +\n * the URL root so the public methods are tiny.\n */\nfunction makeBorrowedTableClient<Row extends BaseRow>(\n transport: HttpTransport,\n providerSlug: string,\n tableSlug: string,\n): ReadOnlyTableClient<Row> {\n // URL shape mirrors the owned-table CRUD pipeline but interpolates\n // the provider's slug between the installation root + the table\n // segment: `/deps/<provider>/db/<table>/...`. The full URL after\n // the transport's base prefix is therefore\n // `<baseUrl>/api/modules/<installationId>/deps/<provider>/db/<table>/<op>`.\n const root = `/deps/${providerSlug}/db/${tableSlug}`;\n\n return {\n async list(opts?: ListOpts<Row>): Promise<Page<Row>> {\n const body = opts ?? {};\n const result = await transport.request<Page<Row>>('POST', `${root}/list`, body);\n // Same defense-in-depth shape coercion as the owned-table client:\n // if the backend ever responds with a bare array (older endpoint\n // version, proxy stripping the envelope, etc.), wrap it so the\n // consumer always sees `{ rows, ... }`.\n if (Array.isArray(result)) {\n return {\n rows: result as Row[],\n total: result.length,\n limit: body.limit ?? result.length,\n offset: body.offset ?? 0,\n };\n }\n return result;\n },\n\n async get(id: number): Promise<Row> {\n return transport.request<Row>('GET', `${root}/${id}`);\n },\n };\n}\n","/**\n * Error model for @dashai/sdk.\n *\n * The backend speaks a structured error envelope:\n *\n * {\n * \"code\": \"ROW_NOT_FOUND\",\n * \"message\": \"Row 123 not found in tasks\",\n * \"retriable\": false,\n * \"context\": { ... }\n * }\n *\n * This module wraps that envelope in a typed `DashwiseError` plus a small\n * set of subclasses for the codes consumers most commonly want to branch\n * on (network errors, auth failures, row-not-found, contract violations).\n *\n * Anything not matched by a specific subclass becomes a plain\n * `DashwiseError` carrying the raw `code`. Branch on `.code` for codes\n * we don't have a class for; use `instanceof` for the common cases.\n */\n\n/**\n * Known error codes. Not exhaustive — the backend emits many codes\n * specific to individual modules / endpoints. Use these constants when\n * you want compile-time safety; otherwise treat `err.code` as a string.\n *\n * The list is curated to the codes a module author is most likely to\n * branch on. Adding a new code here is a non-breaking change.\n */\nexport const DashwiseErrorCode = {\n // Auth / authz\n UNAUTHENTICATED: 'UNAUTHENTICATED',\n FORBIDDEN: 'FORBIDDEN',\n TOKEN_EXPIRED: 'TOKEN_EXPIRED',\n INSTALLATION_NOT_FOUND: 'INSTALLATION_NOT_FOUND',\n INSTALLATION_MODE_UNSUPPORTED: 'INSTALLATION_MODE_UNSUPPORTED',\n // Contract enforcement\n CONTRACT_VIOLATION: 'CONTRACT_VIOLATION',\n FIELD_NOT_READABLE: 'FIELD_NOT_READABLE',\n FILTER_OP_UNKNOWN: 'FILTER_OP_UNKNOWN',\n OPERATION_NOT_ALLOWED: 'OPERATION_NOT_ALLOWED',\n // Cross-module dependencies (Phase 1 of the SDK query plane —\n // see dashwise-devops-docs/plans/modules-sdk-query-v1.md).\n // Surfaced when reading borrowed tables via `client.deps(slug)`.\n DEPENDENCY_NOT_DECLARED: 'DEPENDENCY_NOT_DECLARED',\n TABLE_NOT_IN_CONTRACT: 'TABLE_NOT_IN_CONTRACT',\n PROVIDER_TABLE_MISSING: 'PROVIDER_TABLE_MISSING',\n OPERATION_NOT_ALLOWED_BY_PROVIDER: 'OPERATION_NOT_ALLOWED_BY_PROVIDER',\n // Query-plane joins (Phase 3 — see\n // dashwise-devops-docs/plans/modules-sdk-query-v1-p3-execution.md).\n // Surfaced when `.join('<slug>')` / `.leftJoin('<slug>')` can't\n // resolve the target. Pre-declared in slice 3.1 so slice 3.2's\n // backend translator can emit them through fromBackendEnvelope\n // without an SDK roundtrip.\n LINK_FIELD_NOT_FOUND: 'LINK_FIELD_NOT_FOUND',\n NOT_A_LINK_FIELD: 'NOT_A_LINK_FIELD',\n JOIN_NOT_LINKED: 'JOIN_NOT_LINKED',\n // Cross-module actions (Phase 7 slice 7.3a — see\n // dashwise-devops-docs/plans/modules-sdk-query-v1-p7-cross-module-writes.md).\n // Surfaced when `qb.deps.<dep>.actions.<name>(input)` (generated\n // factory) dispatches against the new backend endpoint\n // `POST :installationId/deps/:providerSlug/actions/:actionName`.\n // Slice 7.2b ships the backend emitter; slice 7.3a (this slice)\n // reserves the codes + maps them to DepActionError in the SDK.\n ACTION_NOT_EXPOSED: 'ACTION_NOT_EXPOSED',\n ACTION_NOT_DECLARED: 'ACTION_NOT_DECLARED',\n ACTION_INPUT_INVALID: 'ACTION_INPUT_INVALID',\n ACTION_OUTPUT_INVALID: 'ACTION_OUTPUT_INVALID',\n ACTION_RATE_LIMITED: 'ACTION_RATE_LIMITED',\n ACTION_EXECUTION_FAILED: 'ACTION_EXECUTION_FAILED',\n // Data plane\n ROW_NOT_FOUND: 'ROW_NOT_FOUND',\n TABLE_NOT_FOUND: 'TABLE_NOT_FOUND',\n VALIDATION_FAILED: 'VALIDATION_FAILED',\n ROW_LIMIT_EXCEEDED: 'ROW_LIMIT_EXCEEDED',\n STORAGE_LIMIT_EXCEEDED: 'STORAGE_LIMIT_EXCEEDED',\n // Outbound / runtime\n OUTBOUND_NOT_ALLOWED: 'OUTBOUND_NOT_ALLOWED',\n OUTBOUND_CONCURRENCY_LIMITED: 'OUTBOUND_CONCURRENCY_LIMITED',\n // Transport\n NETWORK_ERROR: 'NETWORK_ERROR',\n TIMEOUT: 'TIMEOUT',\n // Server\n INTERNAL_ERROR: 'INTERNAL_ERROR',\n} as const;\n\nexport type DashwiseErrorCode = (typeof DashwiseErrorCode)[keyof typeof DashwiseErrorCode];\n\n/**\n * Base class for every error thrown by @dashai/sdk. Carries the\n * structured envelope from the backend (or a synthetic one for\n * client-side failures like network errors / timeouts).\n *\n * Always thrown — never returned as a value. The async client methods\n * `.list()` / `.get()` etc. reject with one of these on failure.\n */\nexport class DashwiseError extends Error {\n readonly code: string;\n readonly status: number;\n readonly retriable: boolean;\n readonly context: Record<string, unknown> | undefined;\n /**\n * Backend-issued trace anchor (Phase 6 slice 6.2, 2026-05-19).\n * Mirrors the `x-request-id` response header. Populated whenever\n * the backend's `RuntimeQueryController` (or any future endpoint\n * that echoes the header) is the origin of this error. `null` when\n * the failure is client-side (NetworkError / TimeoutError — the\n * request never reached the server, so there's no server-issued\n * ID to surface).\n *\n * Use this as a debugging trace anchor when filing a bug against a\n * specific failed query — the matching row in `module_query_log`\n * carries the full backend context (ast_hash, error_code,\n * duration_ms, etc.).\n */\n readonly requestId: string | null;\n\n constructor(\n code: string,\n message: string,\n options: {\n status?: number;\n retriable?: boolean;\n context?: Record<string, unknown>;\n cause?: unknown;\n /**\n * Phase 6 slice 6.2: backend `x-request-id` response header,\n * captured by the transport before throwing. Pass `undefined`\n * (or omit) for client-side errors that never hit the server.\n */\n requestId?: string | null;\n } = {},\n ) {\n super(message);\n this.name = this.constructor.name;\n this.code = code;\n this.status = options.status ?? 0;\n this.retriable = options.retriable ?? false;\n this.context = options.context;\n this.requestId = options.requestId ?? null;\n if (options.cause !== undefined) {\n // Node 18+ and modern browsers support Error.cause natively.\n // Use a property assignment because `super({ cause })` is awkward\n // when the base class only takes a string.\n (this as { cause?: unknown }).cause = options.cause;\n }\n }\n}\n\n/** Network-level failure (DNS, connection refused, TLS, fetch threw). */\nexport class NetworkError extends DashwiseError {\n constructor(message: string, cause?: unknown) {\n super(DashwiseErrorCode.NETWORK_ERROR, message, { retriable: true, cause });\n }\n}\n\n/** Request exceeded the configured timeout (`timeoutMs`). */\nexport class TimeoutError extends DashwiseError {\n constructor(message: string, timeoutMs: number) {\n super(DashwiseErrorCode.TIMEOUT, message, {\n retriable: true,\n context: { timeout_ms: timeoutMs },\n });\n }\n}\n\n/** 401 — token missing/invalid. */\nexport class UnauthenticatedError extends DashwiseError {\n constructor(message = 'Authentication required', requestId: string | null = null) {\n super(DashwiseErrorCode.UNAUTHENTICATED, message, { status: 401, requestId });\n }\n}\n\n/** 403 — caller lacks the role/scope for this operation. */\nexport class ForbiddenError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.FORBIDDEN, message, { status: 403, context, requestId });\n }\n}\n\n/** 404 — `GET /db/<table>/<id>` for a missing or soft-deleted row. */\nexport class RowNotFoundError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.ROW_NOT_FOUND, message, { status: 404, context, requestId });\n }\n}\n\n/**\n * Schema-level rejection: dep contract violated, table not exposed, field\n * not readable, filter op not allowed. Covers the family of \"you asked for\n * something the manifest doesn't permit\" errors.\n */\nexport class ContractViolationError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.CONTRACT_VIOLATION, message, {\n status: 403,\n context,\n requestId,\n });\n }\n}\n\n/** 422-ish — request body failed validation. Inspect `context` for field-level errors. */\nexport class ValidationError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.VALIDATION_FAILED, message, {\n status: 400,\n context,\n requestId,\n });\n }\n}\n\n// ── Cross-module dependency errors ─────────────────────────────────────\n//\n// Surfaced when calling `client.deps(slug).db<Row>(table).<op>(...)`.\n// Each subclass preserves the original backend `code` (unlike the older\n// `ContractViolationError` which collapses several codes onto a single\n// `CONTRACT_VIOLATION` string — that's a known wart we don't replicate\n// in new subclasses). Branch on `instanceof` for the common cases;\n// inspect `err.code` if you need to distinguish the two contract-error\n// codes (`DEPENDENCY_NOT_DECLARED` vs `TABLE_NOT_IN_CONTRACT`).\n\n/**\n * 404 — the caller's `module.json#dependencies` doesn't declare a\n * dependency on the requested provider module, OR the declared dep\n * exists but its `reads[]` block doesn't include the requested table.\n *\n * Either way the fix is on the **caller's** side: update the manifest\n * to declare the dep / add the table to `reads[]`, then re-publish.\n *\n * Covers both `DEPENDENCY_NOT_DECLARED` and `TABLE_NOT_IN_CONTRACT` —\n * inspect `err.code` to distinguish if you need different UX per case.\n */\nexport class DependencyContractError extends DashwiseError {\n constructor(\n code: string,\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(code, message, { status: 404, context, requestId });\n }\n}\n\n/**\n * 404 — the provider's physical table no longer exists. This means the\n * provider published a version that dropped the table while the\n * consumer's installation still pinned the old contract. Recovery is\n * on the **provider's** side (republish with the table) or the\n * workspace admin's (downgrade the provider, or upgrade the consumer\n * to a version whose `dependencies[]` no longer references it).\n */\nexport class ProviderTableMissingError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.PROVIDER_TABLE_MISSING, message, {\n status: 404,\n context,\n requestId,\n });\n }\n}\n\n/**\n * 403 — the provider's `exposes.operations.<verb>.allowed` is explicitly\n * `false` for the requested verb. Distinct from `OPERATION_NOT_ALLOWED`\n * (which is the **owner's** own-table policy) — `OPERATION_NOT_ALLOWED_BY_PROVIDER`\n * is the provider opting out of letting depending modules use a verb.\n *\n * No caller-side fix; either the provider needs to flip the gate, or\n * the consumer needs to find a different way to satisfy the use case.\n */\nexport class OperationNotAllowedByProviderError extends DashwiseError {\n constructor(\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(DashwiseErrorCode.OPERATION_NOT_ALLOWED_BY_PROVIDER, message, {\n status: 403,\n context,\n requestId,\n });\n }\n}\n\n// ── Join errors (Phase 3) ──────────────────────────────────────────────\n//\n// Surfaced when `.join('<slug>')` / `.leftJoin('<slug>')` on the\n// generated `qb` builder can't resolve the target against the\n// manifest. Pre-declared in slice 3.1; raised by the backend\n// translator in slice 3.2. Same one-subclass-with-preserved-code\n// pattern as DependencyContractError so authors can switch on\n// `err.code` for the three sub-cases:\n//\n// LINK_FIELD_NOT_FOUND `.join('xyz')` where `xyz` isn't a field\n// on the source table. Fix: pass an\n// explicit `on` argument, or correct the slug.\n//\n// NOT_A_LINK_FIELD `.join('title')` where `title` exists on\n// the source table but its type isn't\n// `link_row`. Fix: use a real link field,\n// or pass explicit `on`.\n//\n// JOIN_NOT_LINKED `.join('sibling_table')` where the target\n// is a sibling table but no link field\n// bridges them. Fix: pass explicit `on`.\n\n/**\n * 400 — `.join()` / `.leftJoin()` referenced a target the manifest\n * can't resolve. Covers the three sub-cases above; inspect\n * `err.code` to distinguish.\n *\n * Author-side fix in every case: either correct the slug, or pass\n * an explicit `on` argument to bypass link-field inference.\n */\nexport class JoinError extends DashwiseError {\n constructor(\n code: string,\n message: string,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(code, message, { status: 400, context, requestId });\n }\n}\n\n// ── Cross-module action errors (Phase 7 slice 7.3a, 2026-05-20) ──────\n//\n// Surfaced by the codegen-emitted `qb.deps.<dep>.actions.<name>(input)`\n// factory when the backend's cross-module dispatch\n// (`CrossModuleActionService.dispatch()`) rejects. Six sub-cases all\n// covered by `DepActionError`; inspect `err.code` to discriminate.\n//\n// ACTION_NOT_EXPOSED 403 — provider's manifest doesn't expose\n// the action, OR visibility='private'.\n// Recovery: provider author needs to\n// publish a version that exposes it.\n// ACTION_NOT_DECLARED 403 — consumer's manifest doesn't list\n// the action in dependencies[].actions[].\n// Recovery: add it + republish.\n// ACTION_INPUT_INVALID 400 — input fails Ajv against the\n// provider's declared input schema.\n// Recovery: fix the call site (typical\n// with stale codegen + drift).\n// ACTION_OUTPUT_INVALID 500 — provider returned a value that fails\n// the declared output schema. This is a\n// PROVIDER-author bug; consumer can\n// only file an issue.\n// ACTION_RATE_LIMITED 429 — per-actor or per-caller-installation\n// rate limit exceeded. Retry with\n// backoff after Retry-After (slice 7.4).\n// ACTION_EXECUTION_FAILED 200-envelope — action body threw, timed out,\n// or OOM-ed. Provider-author bug;\n// trace surfaced in err.context.trace.\n\n/**\n * Single subclass for every cross-module action failure. The code\n * (and HTTP status) varies per sub-case; the wrapping class lets\n * consumers `catch (e) { if (e instanceof DepActionError) {...} }`\n * regardless of which sub-case fired.\n */\nexport class DepActionError extends DashwiseError {\n constructor(\n code: string,\n message: string,\n status: number,\n context?: Record<string, unknown>,\n requestId: string | null = null,\n ) {\n super(code, message, {\n status,\n retriable: code === DashwiseErrorCode.ACTION_RATE_LIMITED,\n context,\n requestId,\n });\n }\n}\n\n// ── Factory: backend envelope → typed error ────────────────────────────\n\ninterface BackendErrorEnvelope {\n code?: string;\n message?: string;\n retriable?: boolean;\n context?: Record<string, unknown>;\n}\n\n/**\n * Build a typed `DashwiseError` from the backend's response envelope.\n *\n * The mapping picks the most specific subclass for codes we have a class\n * for; everything else becomes a plain `DashwiseError` carrying the raw\n * code. This keeps the type set small while still letting consumers\n * branch on string codes when they want to.\n *\n * Phase 6 slice 6.2 (2026-05-19): accepts an optional `requestId` —\n * the backend's `x-request-id` response header — and threads it onto\n * every produced error so consumers can use it as a debugging trace\n * anchor. Default `null` for backward compat; the transport always\n * passes it through.\n */\nexport function fromBackendEnvelope(\n status: number,\n envelope: BackendErrorEnvelope | null,\n requestId: string | null = null,\n): DashwiseError {\n const code = envelope?.code ?? codeFromStatus(status);\n const message = envelope?.message ?? `HTTP ${status}`;\n const context = envelope?.context;\n\n switch (code) {\n case DashwiseErrorCode.UNAUTHENTICATED:\n case DashwiseErrorCode.TOKEN_EXPIRED:\n return new UnauthenticatedError(message, requestId);\n case DashwiseErrorCode.FORBIDDEN:\n return new ForbiddenError(message, context, requestId);\n case DashwiseErrorCode.ROW_NOT_FOUND:\n return new RowNotFoundError(message, context, requestId);\n case DashwiseErrorCode.CONTRACT_VIOLATION:\n case DashwiseErrorCode.FIELD_NOT_READABLE:\n case DashwiseErrorCode.FILTER_OP_UNKNOWN:\n case DashwiseErrorCode.OPERATION_NOT_ALLOWED:\n return new ContractViolationError(message, context, requestId);\n case DashwiseErrorCode.VALIDATION_FAILED:\n return new ValidationError(message, context, requestId);\n case DashwiseErrorCode.DEPENDENCY_NOT_DECLARED:\n case DashwiseErrorCode.TABLE_NOT_IN_CONTRACT:\n return new DependencyContractError(code, message, context, requestId);\n case DashwiseErrorCode.PROVIDER_TABLE_MISSING:\n return new ProviderTableMissingError(message, context, requestId);\n case DashwiseErrorCode.OPERATION_NOT_ALLOWED_BY_PROVIDER:\n return new OperationNotAllowedByProviderError(message, context, requestId);\n case DashwiseErrorCode.LINK_FIELD_NOT_FOUND:\n case DashwiseErrorCode.NOT_A_LINK_FIELD:\n case DashwiseErrorCode.JOIN_NOT_LINKED:\n return new JoinError(code, message, context, requestId);\n case DashwiseErrorCode.ACTION_NOT_EXPOSED:\n case DashwiseErrorCode.ACTION_NOT_DECLARED:\n return new DepActionError(code, message, 403, context, requestId);\n case DashwiseErrorCode.ACTION_INPUT_INVALID:\n return new DepActionError(code, message, 400, context, requestId);\n case DashwiseErrorCode.ACTION_OUTPUT_INVALID:\n return new DepActionError(code, message, 500, context, requestId);\n case DashwiseErrorCode.ACTION_RATE_LIMITED:\n return new DepActionError(code, message, 429, context, requestId);\n case DashwiseErrorCode.ACTION_EXECUTION_FAILED:\n // ACTION_EXECUTION_FAILED arrives as a 200 envelope from the\n // backend (the host succeeded; the action body crashed). The\n // _callAction helper unwraps the envelope and synthesizes this\n // via the factory call — status 200 reflects \"the transport was\n // fine; the failure is in the application layer\".\n return new DepActionError(code, message, 200, context, requestId);\n default:\n return new DashwiseError(code, message, {\n status,\n retriable: envelope?.retriable ?? false,\n context,\n requestId,\n });\n }\n}\n\nfunction codeFromStatus(status: number): string {\n if (status === 401) return DashwiseErrorCode.UNAUTHENTICATED;\n if (status === 403) return DashwiseErrorCode.FORBIDDEN;\n if (status === 404) return DashwiseErrorCode.ROW_NOT_FOUND;\n if (status >= 500) return DashwiseErrorCode.INTERNAL_ERROR;\n return 'HTTP_ERROR';\n}\n","/**\n * HTTP transport for @dashai/sdk.\n *\n * Wraps `globalThis.fetch` with:\n * - configurable base URL + installation scoping\n * - token attachment via the caller-supplied resolver\n * - timeout enforcement via `AbortController`\n * - response envelope parsing → typed `DashwiseError`\n * - 204 No Content handling\n *\n * No retries here — retries are policy and belong one layer up. The\n * `retriable` flag on `DashwiseError` is hinting to the caller, not\n * something the transport acts on automatically. (We'd rather a module\n * author opt into retry per-call than have the SDK silently double-fire\n * an idempotent-looking POST that wasn't actually idempotent.)\n */\n\nimport {\n DashwiseError,\n NetworkError,\n TimeoutError,\n fromBackendEnvelope,\n} from './errors.js';\nimport type { ClientConfig, FetchImpl, SlowQueryInfo } from './types.js';\n\nexport interface HttpTransport {\n /**\n * Make a request to the DashWise API.\n *\n * @param method HTTP verb.\n * @param path Path appended to the installation-scoped base URL,\n * starting with `/`. Example: `/db/tasks/list`.\n * @param body JSON-serializable body. Omit/pass `undefined` to skip\n * the body entirely.\n * @returns Parsed JSON response, or `undefined` for 204 No Content.\n * @throws `DashwiseError` (or a subclass) on any non-2xx response,\n * `NetworkError` on transport failure, `TimeoutError` on\n * aborted requests.\n */\n request<T = unknown>(method: string, path: string, body?: unknown): Promise<T>;\n\n /**\n * Phase 6 streaming (2026-05-19): low-level transport entry that\n * returns the unparsed `Response` so the caller can stream the body\n * chunk-by-chunk. Used by `qb.from(...).stream()` to consume the\n * backend's SSE endpoint.\n *\n * Differs from `request()`:\n * - No body parsing — caller owns the `Response.body` ReadableStream.\n * - Caller MUST handle non-2xx (read the error envelope from the\n * response body + throw the typed `DashwiseError`); this method\n * returns the Response regardless of status so error JSON can\n * be read off the stream.\n * - Optional `signal` parameter for caller-side cancellation\n * (combined with the transport's own timeout). Abort propagates\n * to fetch, which cancels the underlying network read.\n * - Timeout handling: still applies via the transport's\n * `timeoutMs` config, but ONLY to the headers-arrival phase.\n * Streaming bodies can take arbitrarily long; the stream\n * reader's own backpressure handles the long tail.\n */\n streamRaw(\n method: string,\n path: string,\n body?: unknown,\n signal?: AbortSignal,\n ): Promise<Response>;\n}\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst DEFAULT_SLOW_QUERY_THRESHOLD_MS = 500;\nconst TRAILING_SLASH = /\\/+$/;\nconst LEADING_SLASH = /^\\/+/;\n\n/**\n * Build the installation-scoped base URL. The runtime data API lives at\n * `/api/modules/<installation-id>` — every request from the SDK is\n * relative to that prefix.\n */\nfunction buildBaseUrl(baseUrl: string, installationId: number | string): string {\n if (!baseUrl) {\n throw new Error('@dashai/sdk: `baseUrl` is required');\n }\n const trimmed = baseUrl.replace(TRAILING_SLASH, '');\n return `${trimmed}/api/modules/${installationId}`;\n}\n\nfunction resolveFetch(custom: FetchImpl | undefined): FetchImpl {\n if (custom) return custom;\n if (typeof globalThis.fetch !== 'function') {\n throw new Error(\n '@dashai/sdk: no `fetch` available. On Node < 18, pass an explicit `fetch` in `createClient({...})`.',\n );\n }\n return globalThis.fetch.bind(globalThis);\n}\n\n/**\n * Parse a `Response` body, tolerating empty / non-JSON responses. Returns\n * `null` if there's no body or if the body fails to parse.\n *\n * We never throw from here — the caller decides what to do based on the\n * presence of an envelope.\n */\nasync function readBody(res: Response): Promise<unknown> {\n if (res.status === 204) return undefined;\n const contentType = res.headers.get('content-type') ?? '';\n if (!contentType.includes('application/json')) {\n // Non-JSON 200s shouldn't happen from DashWise, but handle them anyway.\n try {\n return await res.text();\n } catch {\n return null;\n }\n }\n try {\n return await res.json();\n } catch {\n return null;\n }\n}\n\n/**\n * Create an HTTP transport from the public client config.\n *\n * The returned `request` function captures the config + closes over it,\n * so the client can be shared across concurrent calls without rebuilding\n * the transport per call.\n */\nexport function createHttp(config: ClientConfig): HttpTransport {\n const base = buildBaseUrl(config.baseUrl, config.installationId);\n const doFetch = resolveFetch(config.fetch);\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const staticHeaders: Record<string, string> = {\n Accept: 'application/json',\n ...(config.headers ?? {}),\n };\n // Phase 6 slice 6.3 (2026-05-19): slow-query callback wiring.\n // Read once at transport construction — config is immutable after\n // createClient. If `onSlowQuery` is unset, the per-request hot path\n // skips the duration comparison entirely (zero overhead).\n const onSlowQuery = config.onSlowQuery;\n const slowQueryThresholdMs =\n config.slowQueryThresholdMs ?? DEFAULT_SLOW_QUERY_THRESHOLD_MS;\n\n /**\n * Fire the slow-query callback if (a) it's configured and (b) the\n * round-trip exceeded the threshold. Always-safe: any exception the\n * caller's callback throws is caught and silently dropped — a buggy\n * observability hook MUST NOT crash the query path. Same failure-\n * isolation contract the backend's `ModuleQueryLogService.record()`\n * uses.\n */\n function maybeFireSlowQuery(info: SlowQueryInfo): void {\n if (!onSlowQuery) return;\n if (info.durationMs <= slowQueryThresholdMs) return;\n try {\n onSlowQuery(info);\n } catch {\n // Swallow — observability is best-effort.\n }\n }\n\n async function request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const normalizedPath = `/${path.replace(LEADING_SLASH, '')}`;\n // Paths starting with `/api/` are treated as absolute (rooted at\n // baseUrl) instead of installation-scoped. Used by Phase 7's\n // `_callAction()` which hits `/api/modules/runtime/installations/...`\n // — a sibling namespace to the installation-scoped CRUD endpoints.\n // All existing call sites use installation-relative paths\n // (e.g. `/db/tasks/list`), so this is backward-compatible.\n const url = normalizedPath.startsWith('/api/')\n ? `${config.baseUrl.replace(/\\/+$/, '')}${normalizedPath}`\n : `${base}${normalizedPath}`;\n\n // Resolve token AFTER building URL so a failing resolver still gives\n // the consumer a useful error path-context. The resolver may be async\n // (e.g. session lookup); the same instance is allowed to mutate\n // between calls (token refresh).\n //\n // Precedence: a non-null `getToken()` result wins; otherwise fall back\n // to the static `apiKey` (Custom Modules Platform v1 — a deployed\n // module's long-lived `dwk_` key).\n const token =\n (config.getToken ? await config.getToken() : null) ?? config.apiKey ?? null;\n\n const headers: Record<string, string> = { ...staticHeaders };\n if (body !== undefined) {\n headers['Content-Type'] = 'application/json';\n }\n if (token) {\n headers['Authorization'] = `Bearer ${token}`;\n }\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n\n // Phase 6 slice 6.3: capture the round-trip start AFTER token\n // resolution (which can be slow if the resolver hits a network)\n // but BEFORE the fetch — measures what the consumer cares about:\n // the actual HTTP request's perceived latency.\n const start = Date.now();\n\n let res: Response;\n try {\n res = await doFetch(url, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n signal: controller.signal,\n });\n } catch (err) {\n clearTimeout(timer);\n const durationMs = Date.now() - start;\n if (isAbortError(err)) {\n maybeFireSlowQuery({\n method,\n path: normalizedPath,\n durationMs,\n status: 0,\n success: false,\n requestId: null,\n });\n throw new TimeoutError(`Request to ${method} ${normalizedPath} timed out`, timeoutMs);\n }\n maybeFireSlowQuery({\n method,\n path: normalizedPath,\n durationMs,\n status: 0,\n success: false,\n requestId: null,\n });\n throw new NetworkError(\n `Network failure on ${method} ${normalizedPath}: ${describeError(err)}`,\n err,\n );\n }\n clearTimeout(timer);\n\n const parsed = await readBody(res);\n const durationMs = Date.now() - start;\n\n // Phase 6 slice 6.2 (2026-05-19): capture the backend's\n // `x-request-id` response header so we can attach it to any\n // thrown `DashwiseError` as a debugging trace anchor. The\n // backend echoes this header on every query/explain response\n // (and will on more endpoints as Phase 6 rolls out); for\n // endpoints that don't echo it yet, we get `null` and the\n // error carries `requestId: null` — same semantic as a\n // client-side NetworkError / TimeoutError.\n const requestId = res.headers.get('x-request-id');\n\n if (!res.ok) {\n maybeFireSlowQuery({\n method,\n path: normalizedPath,\n durationMs,\n status: res.status,\n success: false,\n requestId,\n });\n const envelope = isEnvelope(parsed) ? parsed : null;\n throw fromBackendEnvelope(res.status, envelope, requestId);\n }\n\n maybeFireSlowQuery({\n method,\n path: normalizedPath,\n durationMs,\n status: res.status,\n success: true,\n requestId,\n });\n\n // 204 / empty body → caller gets `undefined` typed as `T`. The data\n // plane's `delete` is the only operation that legitimately produces\n // a void result; everything else returns a body.\n return parsed as T;\n }\n\n /**\n * Phase 6 streaming (2026-05-19): low-level streaming entry — see\n * `HttpTransport.streamRaw` JSDoc for the contract.\n *\n * Implementation mirrors `request()`'s setup (URL + token + static\n * headers + AbortController) but skips body parsing entirely. The\n * caller's `signal`, if provided, is combined with the transport's\n * own timeout controller so EITHER trigger cancels the fetch.\n */\n async function streamRaw(\n method: string,\n path: string,\n body?: unknown,\n signal?: AbortSignal,\n ): Promise<Response> {\n const normalizedPath = `/${path.replace(LEADING_SLASH, '')}`;\n const url = `${base}${normalizedPath}`;\n const token = config.getToken ? await config.getToken() : null;\n\n const headers: Record<string, string> = { ...staticHeaders };\n if (body !== undefined) {\n headers['Content-Type'] = 'application/json';\n }\n if (token) {\n headers['Authorization'] = `Bearer ${token}`;\n }\n\n // Combine the caller's signal with our timeout controller.\n // Either trigger cancels the fetch.\n const timeoutController = new AbortController();\n const timer = setTimeout(() => timeoutController.abort(), timeoutMs);\n const combinedController = new AbortController();\n if (signal) {\n if (signal.aborted) combinedController.abort();\n else signal.addEventListener('abort', () => combinedController.abort(), { once: true });\n }\n timeoutController.signal.addEventListener(\n 'abort',\n () => combinedController.abort(),\n { once: true },\n );\n\n // onSlowQuery wiring: measure round-trip from fetch start to\n // headers-arrival. Streaming responses linger after headers; we\n // fire `onSlowQuery` once when headers come back, NOT once per\n // chunk. The `success` flag reflects HTTP status at that point;\n // in-band SSE error events are observable by the caller separately.\n const start = Date.now();\n let res: Response;\n try {\n res = await doFetch(url, {\n method,\n headers,\n body: body === undefined ? undefined : JSON.stringify(body),\n signal: combinedController.signal,\n });\n } catch (err) {\n clearTimeout(timer);\n const durationMs = Date.now() - start;\n if (isAbortError(err)) {\n maybeFireSlowQuery({\n method,\n path: normalizedPath,\n durationMs,\n status: 0,\n success: false,\n requestId: null,\n });\n // If the caller-supplied signal aborted, surface that as a\n // standard AbortError (consumer can branch on `e.name`).\n // Otherwise it's our timeout firing.\n if (signal?.aborted) {\n const e = new Error('Aborted by caller');\n e.name = 'AbortError';\n throw e;\n }\n throw new TimeoutError(\n `Streaming request to ${method} ${normalizedPath} timed out before headers arrived`,\n timeoutMs,\n );\n }\n maybeFireSlowQuery({\n method,\n path: normalizedPath,\n durationMs,\n status: 0,\n success: false,\n requestId: null,\n });\n throw new NetworkError(\n `Network failure on ${method} ${normalizedPath}: ${describeError(err)}`,\n err,\n );\n }\n clearTimeout(timer);\n\n const requestId = res.headers.get('x-request-id');\n maybeFireSlowQuery({\n method,\n path: normalizedPath,\n durationMs: Date.now() - start,\n status: res.status,\n success: res.ok,\n requestId,\n });\n\n // Hand the Response back regardless of status — caller reads the\n // error envelope from the body (the standard JSON error path) OR\n // streams the body when ok.\n return res;\n }\n\n return { request, streamRaw };\n}\n\n// ── Helpers ─────────────────────────────────────────────────────────────\n\nfunction isAbortError(err: unknown): boolean {\n if (!err || typeof err !== 'object') return false;\n const e = err as { name?: string; code?: string };\n return e.name === 'AbortError' || e.code === 'ABORT_ERR';\n}\n\nfunction describeError(err: unknown): string {\n if (err instanceof Error) return err.message;\n if (typeof err === 'string') return err;\n try {\n return JSON.stringify(err);\n } catch {\n return '<unknown error>';\n }\n}\n\nfunction isEnvelope(value: unknown): value is {\n code?: string;\n message?: string;\n retriable?: boolean;\n context?: Record<string, unknown>;\n} {\n if (!value || typeof value !== 'object') return false;\n const v = value as Record<string, unknown>;\n // We accept the envelope if it has at least `code` OR `message` —\n // matches what `DomainError` filters emit from the backend.\n return typeof v.code === 'string' || typeof v.message === 'string';\n}\n\n// Re-export DashwiseError so consumers of the http module alone get the\n// full error model without a second import.\nexport { DashwiseError };\n","/**\n * `createClient()` — the public factory for talking to the DashWise\n * runtime data API.\n *\n * Returns a `Client` whose `db<Row>(slug)` method binds a table slug +\n * row type and produces a chainable `{ list, get, create, update, delete }`\n * surface.\n *\n * Two-layer use:\n * 1. Generated per-module typed wrappers call this and re-export a\n * typed `db.tasks` / `db.notes` / etc. — the user-facing API for\n * modules that ran `dashwise module generate`.\n * 2. Direct use for hand-authored scripts, integration tooling, custom\n * modules that don't run codegen — operate on\n * `Record<string, unknown>` rows with the generic `db<Row>(slug)`\n * shape.\n *\n * The HTTP path layout mirrors the existing runtime data plane in\n * `dashwise-backend/src/modules/modules/runtime/data/runtime-table.controller.ts`:\n *\n * POST /api/modules/<installation>/db/<table>/list\n * GET /api/modules/<installation>/db/<table>/<id>\n * POST /api/modules/<installation>/db/<table>\n * PATCH /api/modules/<installation>/db/<table>/<id>\n * DELETE /api/modules/<installation>/db/<table>/<id>\n */\n\nimport { makeDeps } from './deps.js';\nimport { fromBackendEnvelope } from './errors.js';\nimport { createHttp, type HttpTransport } from './http.js';\nimport type {\n BaseInsert,\n BaseRow,\n BaseUpdate,\n Client,\n ClientConfig,\n DatahubClient,\n DatahubListOpts,\n DatahubListResult,\n DatahubTableClient,\n Deps,\n ListOpts,\n Page,\n SortClause,\n TableClient,\n Where,\n} from './types.js';\n\n/**\n * Create a DashWise SDK client. The returned client is thread-safe and\n * can be cached for the lifetime of the process (or the Next.js request).\n *\n * @example\n * const client = createClient({\n * baseUrl: 'https://api.dashwise.io',\n * installationId: 'sandbox',\n * getToken: () => process.env.DASHWISE_TOKEN ?? null,\n * });\n *\n * const page = await client.db<TasksRow>('tasks').list({\n * filter: { done: false },\n * limit: 50,\n * });\n */\nexport function createClient(config: ClientConfig): Client {\n const transport = createHttp(config);\n return {\n db<\n Row extends BaseRow,\n Insert extends BaseInsert = BaseInsert,\n Update extends BaseUpdate = BaseUpdate,\n >(tableSlug: string): TableClient<Row, Insert, Update> {\n assertValidTableSlug(tableSlug);\n return makeTableClient<Row, Insert, Update>(transport, tableSlug);\n },\n\n deps(providerSlug: string): Deps {\n // Validation lives inside `makeDeps` so the same checks apply\n // whether deps is reached via `createClient` or via a test\n // harness that constructs the transport directly.\n return makeDeps(transport, providerSlug);\n },\n\n datahub: makeDatahubClient(transport),\n\n request<T = unknown>(method: string, path: string, body?: unknown): Promise<T> {\n return transport.request<T>(method, path, body);\n },\n\n streamRaw(\n method: string,\n path: string,\n body?: unknown,\n signal?: AbortSignal,\n ): Promise<Response> {\n return transport.streamRaw(method, path, body, signal);\n },\n\n async _callAction<TOutput = unknown>(\n providerSlug: string,\n actionName: string,\n input: unknown,\n opts?: { timeoutMs?: number; idempotencyKey?: string },\n ): Promise<TOutput> {\n assertValidModuleSlug(providerSlug);\n assertValidActionName(actionName);\n // The backend endpoint is rooted at\n // `<baseUrl>/api/modules/runtime/installations/<consumerId>/deps/<slug>/actions/<name>`\n // — a sibling namespace to the installation-scoped CRUD\n // endpoints. The transport's `request()` treats paths starting\n // with `/api/` as absolute (rooted at baseUrl) instead of\n // installation-scoped.\n const path =\n `/api/modules/runtime/installations/${config.installationId}/deps/${encodeURIComponent(\n providerSlug,\n )}/actions/${encodeURIComponent(actionName)}`;\n const body: Record<string, unknown> = { input };\n if (opts?.idempotencyKey !== undefined) {\n body.idempotency_key = opts.idempotencyKey;\n }\n if (opts?.timeoutMs !== undefined) {\n body.timeout_ms = opts.timeoutMs;\n }\n const envelope = await transport.request<CrossModuleActionEnvelope<TOutput>>(\n 'POST',\n path,\n body,\n );\n // The transport throws on HTTP 4xx/5xx with the envelope mapped\n // to typed errors via fromBackendEnvelope. A successful HTTP\n // status with `ok: false` is the action-body-failure path — we\n // synthesize a DepActionError so consumers have one place to\n // catch.\n if (envelope.ok === false) {\n const requestId = envelope.cross_module?.request_id ?? null;\n throw fromBackendEnvelope(\n 200,\n {\n code: envelope.error.code,\n message: envelope.error.message,\n context: envelope.error.trace\n ? { trace: envelope.error.trace }\n : undefined,\n },\n requestId,\n );\n }\n return envelope.result;\n },\n };\n}\n\ninterface CrossModuleActionEnvelopeOk<T> {\n ok: true;\n result: T;\n elapsed_ms: number;\n executor: string;\n cross_module: {\n caller_installation_id: number;\n provider_installation_id: number;\n provider_module_slug: string;\n provider_module_version: string;\n request_id: string;\n };\n}\n\ninterface CrossModuleActionEnvelopeErr {\n ok: false;\n error: { code: string; message: string; trace?: string };\n elapsed_ms: number;\n executor: string;\n cross_module: CrossModuleActionEnvelopeOk<unknown>['cross_module'];\n}\n\ntype CrossModuleActionEnvelope<T> =\n | CrossModuleActionEnvelopeOk<T>\n | CrossModuleActionEnvelopeErr;\n\nconst ACTION_NAME_REGEX = /^[a-zA-Z_$][a-zA-Z0-9_$]{0,63}$/;\nconst MODULE_SLUG_REGEX = /^[a-z][a-z0-9-]*[a-z0-9]$/;\n\nfunction assertValidModuleSlug(slug: string): void {\n if (!MODULE_SLUG_REGEX.test(slug)) {\n throw new Error(\n `Invalid provider module slug \"${slug}\" — must be kebab-case (^[a-z][a-z0-9-]*[a-z0-9]$).`,\n );\n }\n}\n\nfunction assertValidActionName(name: string): void {\n if (!ACTION_NAME_REGEX.test(name)) {\n throw new Error(\n `Invalid action name \"${name}\" — must be a JS identifier (letters/digits/underscore/$, starts non-digit, ≤64 chars).`,\n );\n }\n}\n\n/**\n * Module-slug character set matches the manifest validator's table-slug\n * rule (`^[a-z][a-z0-9_]*$`). Slugs are baked into URL paths, so\n * unsafe characters would route to the wrong resource (or 400).\n */\nconst TABLE_SLUG_REGEX = /^[a-z][a-z0-9_]*$/;\n\nfunction assertValidTableSlug(slug: string): void {\n if (typeof slug !== 'string' || !TABLE_SLUG_REGEX.test(slug)) {\n throw new Error(\n `@dashai/sdk: invalid table slug \"${slug}\". Slugs must match /^[a-z][a-z0-9_]*$/.`,\n );\n }\n}\n\n/**\n * Custom Modules Platform v1 (P1b) — Data Hub access surface. Hits the\n * runtime Data Hub bridge (`:installationId/datahub/tables/:tableId/rows…`),\n * which enforces the authenticating key's datahub grants. Table id (not\n * slug) keys the URL, matching the bridge route + the Data Hub's numeric\n * table identity.\n */\nfunction makeDatahubClient(transport: HttpTransport): DatahubClient {\n return {\n table<Row = Record<string, unknown>>(\n tableId: number,\n ): DatahubTableClient<Row> {\n assertValidTableId(tableId);\n const root = `/datahub/tables/${tableId}/rows`;\n return {\n async list(\n opts?: DatahubListOpts<Row> | Record<string, string>,\n ): Promise<DatahubListResult> {\n // Two input shapes: a typed `DatahubListOpts` (which we compile\n // to the Data Hub bridge's flat query protocol) or a raw\n // `Record<string, string>` of flat params (back-compat\n // passthrough). They're distinguished structurally — see\n // `isDatahubListOpts`. Widen `Row` to `unknown` here so the\n // guard + compiler don't fight generic variance; the wire shape\n // is identical regardless of the row type argument.\n const arg = opts as\n | DatahubListOpts<unknown>\n | Record<string, string>\n | undefined;\n const flat: Record<string, string> | undefined = isDatahubListOpts(\n arg,\n )\n ? compileDatahubListOpts(arg)\n : arg;\n const qs = flat ? new URLSearchParams(flat).toString() : '';\n const path = qs ? `${root}?${qs}` : root;\n return transport.request<DatahubListResult>('GET', path);\n },\n async get(rowId: number): Promise<Record<string, unknown>> {\n return transport.request<Record<string, unknown>>(\n 'GET',\n `${root}/${rowId}`,\n );\n },\n async create(\n body: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n return transport.request<Record<string, unknown>>('POST', root, body);\n },\n async update(\n rowId: number,\n body: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n return transport.request<Record<string, unknown>>(\n 'PATCH',\n `${root}/${rowId}`,\n body,\n );\n },\n async delete(rowId: number): Promise<{ success: true }> {\n return transport.request<{ success: true }>(\n 'DELETE',\n `${root}/${rowId}`,\n );\n },\n };\n },\n };\n}\n\nfunction assertValidTableId(tableId: number): void {\n if (!Number.isInteger(tableId) || tableId <= 0) {\n throw new Error(\n `@dashai/sdk: invalid Data Hub table id \"${tableId}\". Must be a positive integer.`,\n );\n }\n}\n\n/**\n * The keys that mark an argument to `datahub.table().list()` as a typed\n * {@link DatahubListOpts} rather than a raw flat-param record. If the\n * argument is a plain object carrying any of these, we compile it; any\n * other object is treated as a raw `Record<string, string>` passthrough\n * (back-compat).\n */\nconst DATAHUB_LIST_OPT_KEYS = new Set([\n 'filter',\n 'sort',\n 'search',\n 'limit',\n 'page',\n]);\n\n/**\n * Filter-clause keys that are logical grouping operators rather than\n * field names. Presence of either forces the JSON-tree (`filters=`)\n * compilation path, since the flat `filter__<field>__<op>` protocol\n * can't express grouping.\n */\nconst FILTER_GROUP_KEYS = new Set(['AND', 'OR']);\n\nfunction isDatahubListOpts(\n opts: DatahubListOpts<unknown> | Record<string, string> | undefined,\n): opts is DatahubListOpts<unknown> {\n if (opts === undefined || opts === null || typeof opts !== 'object') {\n return false;\n }\n // An empty object is ambiguous; treat it as no-op opts (compiles to an\n // empty query, same as the raw path would).\n return Object.keys(opts).some((k) => DATAHUB_LIST_OPT_KEYS.has(k));\n}\n\n/**\n * Compile a typed {@link DatahubListOpts} into the Data Hub bridge's\n * flat query protocol:\n * - simple filters → repeated `filter__<field>__<op>=<value>` params\n * - grouped filters (`AND` / `OR`) → a single `filters=<json>` tree\n * - `sort` → `order_by` (comma-joined, `-` prefix for desc)\n * - `search` → `search`\n * - `limit` → `size`\n * - `page` → `page`\n *\n * Mirrors how `client.db().list()` compiles `ListOpts` (and the\n * frontend `rows.api.ts` flat-param builder). Returns a flat string map\n * ready to feed `URLSearchParams`.\n */\nfunction compileDatahubListOpts(opts: DatahubListOpts<unknown>): Record<string, string> {\n const out: Record<string, string> = {};\n\n if (opts.filter !== undefined) {\n const where = opts.filter as Where<Record<string, unknown>>;\n if (hasFilterGrouping(where)) {\n // The flat `filter__field__op` syntax can't express AND/OR grouping;\n // use the backend's JSON-tree param — but translate the SDK's\n // `{ AND/OR: [...] }` shape into the wire shape the backend parser\n // expects (`{ filter_type, filters:[{field,type,value}], filter_groups }`).\n // A raw JSON.stringify of the SDK shape parses to an empty tree → the\n // whole filter would be silently dropped (all rows returned).\n out.filters = JSON.stringify(whereToBackendTree(where));\n } else {\n for (const [field, value] of Object.entries(where)) {\n if (value === undefined) continue;\n if (isFilterOpsObject(value)) {\n // Operator object: one flat param per operator on this field.\n for (const [op, opValue] of Object.entries(value)) {\n if (opValue === undefined) continue;\n out[`filter__${field}__${op}`] = stringifyFilterValue(opValue);\n }\n } else {\n // Bare primitive: shorthand for `{ equal: value }`.\n out[`filter__${field}__equal`] = stringifyFilterValue(value);\n }\n }\n }\n }\n\n if (opts.sort !== undefined && opts.sort.length > 0) {\n out.order_by = opts.sort\n .map((s: SortClause<unknown>) =>\n s.dir === 'desc' ? `-${s.field}` : s.field,\n )\n .join(',');\n }\n\n if (opts.search !== undefined) out.search = opts.search;\n if (typeof opts.limit === 'number') out.size = String(opts.limit);\n if (typeof opts.page === 'number') out.page = String(opts.page);\n\n // The typed surface addresses fields by their human NAME (the keys of the\n // generic `Row`), but the Data Hub bridge defaults to resolving refs as\n // `field_<id>` and 400s on a name. Whenever we emitted a name-based filter\n // or sort, tell the backend to resolve by user field name (mirrors the\n // frontend `rows.api.ts`). Harmless when no filter/sort was emitted.\n if (\n opts.filter !== undefined ||\n (opts.sort !== undefined && opts.sort.length > 0)\n ) {\n out.user_field_names = 'true';\n }\n\n return out;\n}\n\nfunction hasFilterGrouping(where: Where<Record<string, unknown>>): boolean {\n return Object.keys(where).some((k) => FILTER_GROUP_KEYS.has(k));\n}\n\n/** One leaf of the backend's JSON filter-tree (`filters=` param). */\ninterface BackendFilterLeaf {\n field: string;\n type: string;\n value: string;\n}\n/** The backend's recursive filter-tree wire shape. */\ninterface BackendFilterTree {\n filter_type: 'AND' | 'OR';\n filters: BackendFilterLeaf[];\n filter_groups: BackendFilterTree[];\n}\n\n/** True when a Where node is a logical group (`{ AND: [...] }` / `{ OR: [...] }`). */\nfunction isFilterGroupNode(node: Record<string, unknown>): boolean {\n return Object.keys(node).some((k) => FILTER_GROUP_KEYS.has(k));\n}\n\n/** Flatten a field-bag Where node (`{ field: value | FilterOps }`) into leaves. */\nfunction fieldLeaves(node: Record<string, unknown>): BackendFilterLeaf[] {\n const leaves: BackendFilterLeaf[] = [];\n for (const [field, value] of Object.entries(node)) {\n if (FILTER_GROUP_KEYS.has(field) || value === undefined) continue;\n if (isFilterOpsObject(value)) {\n for (const [op, opValue] of Object.entries(value)) {\n if (opValue === undefined) continue;\n leaves.push({ field, type: op, value: stringifyFilterValue(opValue) });\n }\n } else {\n // Bare primitive → `equal`.\n leaves.push({ field, type: 'equal', value: stringifyFilterValue(value) });\n }\n }\n return leaves;\n}\n\n/**\n * Translate the SDK's recursive `Where` tree into the backend's filter-tree\n * wire shape. A grouping node maps to `{ filter_type, filters:[leaves],\n * filter_groups:[nested groups] }`; a bare field-bag maps to an AND of its\n * leaves.\n */\nfunction whereToBackendTree(\n where: Where<Record<string, unknown>>,\n defaultType: 'AND' | 'OR' = 'AND',\n): BackendFilterTree {\n const obj = where as Record<string, unknown>;\n const groupKey = Object.keys(obj).find((k) => FILTER_GROUP_KEYS.has(k)) as\n | 'AND'\n | 'OR'\n | undefined;\n if (groupKey) {\n const children = (obj[groupKey] as Where<Record<string, unknown>>[]) ?? [];\n const filters: BackendFilterLeaf[] = [];\n const filter_groups: BackendFilterTree[] = [];\n for (const child of children) {\n const childObj = child as Record<string, unknown>;\n if (isFilterGroupNode(childObj)) {\n filter_groups.push(whereToBackendTree(child));\n } else {\n filters.push(...fieldLeaves(childObj));\n }\n }\n return { filter_type: groupKey, filters, filter_groups };\n }\n // No grouping at this node — AND its field leaves.\n return { filter_type: defaultType, filters: fieldLeaves(obj), filter_groups: [] };\n}\n\n/**\n * Distinguish a `FilterOps` operator object (`{ higher_than: 5 }`) from a\n * bare object value. We treat a plain object as a `FilterOps` bag; arrays\n * and `null` are bare values. This matches `FilterValue<V>`'s `V |\n * FilterOps` shape — the only object-typed bare values DashWise field\n * types carry (e.g. link-row arrays, file refs) are arrays or are filtered\n * by primitive ops anyway.\n */\nfunction isFilterOpsObject(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === 'object' &&\n value !== null &&\n !Array.isArray(value)\n );\n}\n\nfunction stringifyFilterValue(value: unknown): string {\n // Booleans/numbers stringify to their literal form; `null` becomes the\n // empty string (the backend reads an empty value for null-ish filters,\n // matching the frontend `f.value ?? ''` convention).\n if (value === null) return '';\n return String(value);\n}\n\nfunction makeTableClient<\n Row extends BaseRow,\n Insert extends BaseInsert,\n Update extends BaseUpdate,\n>(transport: HttpTransport, tableSlug: string): TableClient<Row, Insert, Update> {\n const root = `/db/${tableSlug}`;\n\n return {\n async list(opts?: ListOpts<Row>): Promise<Page<Row>> {\n // SDK Query Plane v1 Phase 2 slice 6 (2026-05-19): `.list()` now\n // compiles to a Query AST and posts to the unified `/query`\n // endpoint instead of `/db/<slug>/list`. The on-wire input\n // shape is `{ ast: QueryAst }`; the output `Page<Row>` envelope\n // is identical to what the legacy endpoint returned. Consumers\n // see no behavior change — same fields accepted, same response.\n //\n // Why route through /query: single read path going forward.\n // Future query-plane improvements (sub-query caching, observability,\n // slow-query warnings) light up `.list()` automatically without\n // touching this file again. The legacy `/db/<slug>/list` endpoint\n // stays in place for non-SDK consumers (sandbox iframes, AI\n // builder tooling that hits it directly).\n //\n // The other CRUD methods below (`.get` / `.create` / `.update` /\n // `.delete`) keep using `/db/<slug>/...` — the query plane is\n // read-only by design, and per-row reads + writes have no AST\n // representation in v1.\n const ast: Record<string, unknown> = {\n v: 1,\n from: { kind: 'owned', slug: tableSlug },\n };\n if (opts?.filter !== undefined) ast.where = opts.filter;\n if (opts?.sort !== undefined && opts.sort.length > 0) {\n ast.orderBy = opts.sort;\n }\n if (typeof opts?.limit === 'number') ast.limit = opts.limit;\n if (typeof opts?.offset === 'number') ast.offset = opts.offset;\n\n const result = await transport.request<Page<Row>>('POST', '/query', { ast });\n // Defence in depth: same Page-envelope coercion as before. The\n // query plane always returns a proper envelope today; this\n // fallback covers misconfigured proxies + future endpoint shape\n // drift.\n if (Array.isArray(result)) {\n return {\n rows: result as Row[],\n total: result.length,\n limit: opts?.limit ?? result.length,\n offset: opts?.offset ?? 0,\n };\n }\n return result;\n },\n\n async get(id: number): Promise<Row> {\n return transport.request<Row>('GET', `${root}/${id}`);\n },\n\n async create(body: Insert): Promise<Row> {\n return transport.request<Row>('POST', root, body);\n },\n\n async update(id: number, patch: Update): Promise<Row> {\n return transport.request<Row>('PATCH', `${root}/${id}`, patch);\n },\n\n async delete(id: number): Promise<void> {\n await transport.request<void>('DELETE', `${root}/${id}`);\n },\n };\n}\n","/**\n * `createDevClient()` — `createClient()`'s zero-config sibling for local dev.\n *\n * Resolves `baseUrl`, `installationId`, and `getToken` from a layered\n * config chain so a developer who has run `dashwise login` (and, for the\n * full local-dev experience, `dashwise init`) can do:\n *\n * ```ts\n * import { createDevClient } from '@dashai/sdk';\n * const client = createDevClient({ moduleSlug: 'my-tasks' });\n * ```\n *\n * …without copying tokens or installation ids around. The flow this\n * enables is the end-to-end \"two-command bootstrap\" the CLI's\n * `dashwise login` + `dashwise init` pair targets.\n *\n * ## Resolution chain\n *\n * For each field, the first non-empty source wins:\n *\n * 1. Explicit `overrides` argument (per-call escape hatch).\n * 2. Environment variables — `DASHWISE_API_URL` / `DASHWISE_API_TOKEN`\n * / `DASHWISE_INSTALLATION_ID` / `DASHWISE_RUNTIME_TOKEN` (HH-CC-LDI-5).\n * Standard for CI, Docker, prod-like setups; also the path\n * `dashwise dev` uses to inject per-module credentials into the\n * Next.js child process.\n * 3. The CLI's saved config at `$XDG_CONFIG_HOME/dashwise/auth.json`\n * (or platform default) — written by `dashwise login` (top-level\n * `apiUrl` + `token`) and `dashwise init` (per-module entry under\n * `modules[slug]`).\n *\n * ## Per-module local-dev tokens (HH-CC-LDI-5)\n *\n * When `overrides.moduleSlug` is set, the SDK looks up the per-module\n * entry in `auth.json`:\n *\n * ```jsonc\n * {\n * \"apiUrl\": \"http://localhost:3000\",\n * \"token\": \"dwc_...\", // CLI bearer (login)\n * \"modules\": {\n * \"my-tasks\": {\n * \"runtimeToken\": \"<JWT>\", // long-lived runtime token (LDI-2)\n * \"installationId\": 4242, // numeric install id (LDI-2)\n * \"expiresAt\": \"2026-08-22T...\" // informational only\n * }\n * }\n * }\n * ```\n *\n * Per-module entries are written by `dashwise init` (HH-CC-LDI-6) when\n * a developer provisions a local-dev install. The SDK prefers the\n * `runtimeToken` over the legacy CLI bearer (`token`) when both\n * exist, and sets `installationId` to the literal `'sandbox'` — the\n * URL placeholder the backend's `RuntimeTokenGuard` accepts (the\n * token resolves to the actual install on the server side).\n *\n * If `moduleSlug` is unset, OR the named module isn't in the\n * `modules` map, OR the entry lacks a `runtimeToken`, the resolver\n * falls back to the legacy chain (`token` field + `'local'` install\n * id, which the backend will reject — surfacing as a typed\n * `UnauthenticatedError` on the first request).\n *\n * ## Safety rails\n *\n * - **Production refusal.** When `NODE_ENV === 'production'`, the file\n * fallback is skipped. Prod deploys MUST set env vars explicitly;\n * accidentally shipping with `~/.config/dashwise/auth.json` baked into\n * a Docker image would be a credential leak.\n * - **Edge / browser refusal.** `fs` / `os` / `path` imports happen\n * lazily inside a try/catch with a Node-detection guard. In edge or\n * browser runtimes the file fallback is silently skipped — env vars\n * are still honored.\n * - **No throw on missing creds at construction time.** Same contract\n * as `createClient()` — the throw happens at the first request when\n * the resolver returns null AND the backend rejects the call. This\n * lets bundlers tree-shake the function into builds where it's only\n * called conditionally.\n *\n * ## When to use which\n *\n * - `createClient(config)` — production, edge runtime, anywhere you\n * want explicit control over auth resolution\n * - `createDevClient()` — local development, REPL exploration, ad-hoc\n * scripts where typing the env-var dance every time is friction\n *\n * Both return the same `Client` shape — switching is a one-line change.\n */\n\nimport { createClient } from './client.js';\nimport type { Client, ClientConfig, TokenResolver } from './types.js';\n\n/**\n * Subset of `ClientConfig` the caller can override on top of the\n * auto-resolved defaults. Anything omitted uses the resolution chain.\n *\n * `fetch`, `timeoutMs`, `headers`, `onSlowQuery`, `slowQueryThresholdMs`\n * are passed through unchanged when provided.\n */\nexport interface CreateDevClientOptions\n extends Partial<Omit<ClientConfig, 'getToken'>> {\n /**\n * Per-request token resolver. If set, overrides the auto-resolved\n * token entirely. Pass `() => null` to explicitly disable token\n * attachment (rare — only useful for hitting public endpoints).\n */\n getToken?: TokenResolver;\n\n /**\n * HH-CC-LDI-5 — module slug for per-module runtime-token lookup.\n *\n * When set, `createDevClient` reads\n * `~/.config/dashwise/auth.json#modules[<moduleSlug>]` looking for\n * a `runtimeToken`. If found, that token is used as the bearer\n * (overriding `DASHWISE_API_TOKEN` / file-level `token`) and the\n * SDK sends `installationId='sandbox'` — the URL placeholder\n * accepted by the backend's `RuntimeTokenGuard`. The runtime\n * token itself binds to a specific install on the server side.\n *\n * If `moduleSlug` is unset or the entry is missing, the legacy\n * resolution chain applies (CLI bearer + `'local'` installation\n * id, which the backend will 401 — surfacing as a typed\n * `UnauthenticatedError` on the first request).\n *\n * Typical usage: scaffolded modules read `module.json#module.slug`\n * and pass it here. The CLI's `dashwise dev` command also exports\n * it as the `DASHWISE_RUNTIME_TOKEN` env var so child processes\n * (e.g. `next dev`) can authenticate without re-reading the file.\n */\n moduleSlug?: string;\n}\n\n/**\n * Resolve config from env + saved CLI file + overrides, then hand off\n * to `createClient`. Synchronous — all sources are sync-readable.\n *\n * Throws only on truly unrecoverable problems (no `baseUrl` anywhere).\n * Missing token is fine at construction — the resolver returns null and\n * the backend's 401 surfaces a clear `UnauthenticatedError`.\n */\nexport function createDevClient(overrides: CreateDevClientOptions = {}): Client {\n const fileConfig = readCliConfigFile();\n\n const baseUrl =\n overrides.baseUrl ??\n readEnv('DASHWISE_API_URL') ??\n fileConfig?.apiUrl ??\n null;\n if (!baseUrl) {\n throw new Error(\n '@dashai/sdk: createDevClient() could not resolve a baseUrl. ' +\n 'Pass `{ baseUrl }` explicitly, set `DASHWISE_API_URL`, or run `dashwise login` ' +\n 'to create the CLI config file.',\n );\n }\n\n // HH-CC-LDI-5: resolve the per-module runtime token if either an\n // explicit `DASHWISE_RUNTIME_TOKEN` env (set by `dashwise dev`) or a\n // file-level `modules[slug].runtimeToken` entry (set by\n // `dashwise init`) is available. The env var wins, mirroring the\n // env > file precedence of every other field.\n //\n // When this resolves to non-null, it's preferred over the legacy\n // CLI bearer token (`token` field + `DASHWISE_API_TOKEN`). The two\n // tokens have different lifecycles + scopes — the bearer is the\n // user's long-lived CLI credential, the runtime token is a JWT\n // bound to a specific local-dev install.\n const moduleEntry = overrides.moduleSlug\n ? fileConfig?.modules?.[overrides.moduleSlug]\n : undefined;\n const runtimeToken =\n readEnv('DASHWISE_RUNTIME_TOKEN') ?? moduleEntry?.runtimeToken ?? null;\n\n // installationId: explicit override > env var > 'sandbox' if we\n // have a runtime token (URL placeholder for runtime-token auth) >\n // legacy 'local' fallback. The 'local' fallback exists for\n // backward compat with pre-LDI flows; the backend will 401 it,\n // surfacing a clear UnauthenticatedError the developer can act on.\n const installationId =\n overrides.installationId ??\n readEnv('DASHWISE_INSTALLATION_ID') ??\n (runtimeToken !== null ? 'sandbox' : 'local');\n\n // Token resolution: runtime token > API key > legacy bearer token.\n // Snapshot at construction (same rationale as the original\n // implementation — a developer would need to re-login + restart their\n // dev server for the token to change).\n //\n // Custom Modules Platform v1: `DASHWISE_API_KEY` (a scoped `dwk_`\n // service key) is the production-deploy credential. It sits below the\n // dev `runtimeToken` (so `dashwise dev` keeps working) but above the\n // legacy CLI bearer.\n const snapshotToken =\n runtimeToken ??\n readEnv('DASHWISE_API_KEY') ??\n readEnv('DASHWISE_API_TOKEN') ??\n fileConfig?.token ??\n null;\n const resolvedGetToken: TokenResolver =\n overrides.getToken ?? (() => snapshotToken);\n\n return createClient({\n ...overrides,\n baseUrl,\n installationId,\n getToken: resolvedGetToken,\n });\n}\n\n// ── Internals ───────────────────────────────────────────────────────────\n\n/** Minimal view of the CLI's `auth.json` — only the fields we use. */\ninterface CliConfigFileShape {\n apiUrl?: string;\n token?: string;\n /**\n * HH-CC-LDI-5 — per-module local-dev install metadata, keyed by\n * the module's slug (matches `module.json#module.slug`).\n *\n * Written by `dashwise init` (LDI-6); read here for the\n * per-module runtime-token lookup. The SDK only consumes\n * `runtimeToken`; `installationId` + `expiresAt` are\n * informational (the CLI uses them for `dashwise module\n * status` / token-rotation flows).\n */\n modules?: Record<string, CliConfigModuleEntry>;\n}\n\n/** Per-module entry within `auth.json#modules`. */\ninterface CliConfigModuleEntry {\n /** JWT runtime token minted by `POST /api/installations/dev`. */\n runtimeToken?: string;\n /** Numeric installation id the runtime token resolves to. */\n installationId?: number;\n /** ISO timestamp; informational only (not enforced client-side). */\n expiresAt?: string;\n}\n\n/**\n * Read an env var with empty-string treated as unset. Safe on edge /\n * browser builds where `process` may be a polyfill shim with no `env`.\n */\nfunction readEnv(key: string): string | undefined {\n if (typeof process === 'undefined' || !process.env) return undefined;\n const v = process.env[key];\n return typeof v === 'string' && v.length > 0 ? v : undefined;\n}\n\n/**\n * Detect whether we're in a Node-like runtime that can actually `import\n * 'node:fs'`. Edge runtime, Cloudflare Workers, Deno without compat,\n * and browsers all fail this check.\n */\nfunction isNodeRuntime(): boolean {\n if (typeof process === 'undefined') return false;\n if (!process.versions || typeof process.versions.node !== 'string') {\n return false;\n }\n return true;\n}\n\n/**\n * Load + parse `auth.json` from the CLI's config directory. Returns\n * `null` if:\n * - We're not in Node (edge / browser)\n * - `NODE_ENV === 'production'` (prod must use env vars; refusing the\n * file fallback is the safety rail against accidental credential\n * leaks into Docker images)\n * - The file doesn't exist (user hasn't run `dashwise login`)\n * - The file exists but is unreadable / unparseable (corrupt — caller\n * should re-login; we don't surface a noisy warning because the\n * env-var path is still valid)\n *\n * Mirrors the path resolution in `@dashai/cli`'s\n * `packages/cli/src/lib/config.ts#configPath()` — kept in sync by\n * convention since the SDK can't depend on the CLI.\n */\nfunction readCliConfigFile(): CliConfigFileShape | null {\n if (!isNodeRuntime()) return null;\n if (readEnv('NODE_ENV') === 'production') return null;\n try {\n // Lazy require so bundlers that don't tree-shake the function call\n // (e.g. esbuild without `--platform=node`) still drop the imports\n // when this branch is unreachable at build time.\n //\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const fs = require('node:fs') as typeof import('node:fs');\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const path = require('node:path') as typeof import('node:path');\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const os = require('node:os') as typeof import('node:os');\n\n const dir = resolveConfigDir(path, os);\n const file = path.join(dir, 'auth.json');\n if (!fs.existsSync(file)) return null;\n\n const raw = fs.readFileSync(file, 'utf-8');\n const parsed = JSON.parse(raw) as unknown;\n if (!isPlausibleFileShape(parsed)) return null;\n return parsed;\n } catch {\n // Any failure → fall through to env-var-only mode. We deliberately\n // don't log here: a missing / corrupt file is \"no fallback\n // available,\" not \"something is broken.\" If env vars are also\n // missing, the createClient-level error message will guide the\n // developer to run `dashwise login`.\n return null;\n }\n}\n\n/**\n * Resolve the CLI's config directory. Same priority as the CLI:\n * 1. `$XDG_CONFIG_HOME/dashwise/`\n * 2. `%APPDATA%\\dashwise\\` on Windows\n * 3. `~/.config/dashwise/` everywhere else\n */\nfunction resolveConfigDir(\n path: typeof import('node:path'),\n os: typeof import('node:os'),\n): string {\n const xdg = readEnv('XDG_CONFIG_HOME');\n if (xdg) return path.join(xdg, 'dashwise');\n if (os.platform() === 'win32') {\n const appdata = readEnv('APPDATA');\n if (appdata) return path.join(appdata, 'dashwise');\n }\n return path.join(os.homedir(), '.config', 'dashwise');\n}\n\nfunction isPlausibleFileShape(v: unknown): v is CliConfigFileShape {\n if (!v || typeof v !== 'object') return false;\n const o = v as Record<string, unknown>;\n // We accept anything that LOOKS like an auth.json. If `apiUrl` /\n // `token` are missing or wrong-typed, our resolution chain falls\n // through to the next source — same as if the file didn't exist.\n //\n // HH-CC-LDI-5: `modules` is a record-shaped optional. We don't\n // deep-validate per-entry shapes — if a `modules[slug]` is\n // garbage, the runtime-token resolver just returns null and the\n // legacy chain takes over. Forgiveness over strictness keeps the\n // SDK resilient to a partially-written `auth.json` (e.g. the CLI\n // crashed mid-write during `init`).\n const apiUrlOk = o.apiUrl === undefined || typeof o.apiUrl === 'string';\n const tokenOk = o.token === undefined || typeof o.token === 'string';\n const modulesOk =\n o.modules === undefined ||\n (typeof o.modules === 'object' && o.modules !== null);\n return apiUrlOk && tokenOk && modulesOk;\n}\n","/**\n * @dashai/sdk — public entry point.\n *\n * Two planes:\n * - **data**: typed table client (`createClient`, `db<Row>(slug)`,\n * `Where<Row>`, `Page<T>`, `DashwiseError` + subclasses).\n * Re-exported from the default barrel.\n * - **auth**: server / middleware / client helpers for session\n * management. Imported via subpaths so consumers don't pull in\n * React / `next/headers` if they only need data.\n *\n * Auth surface (all subpath-imported):\n * - `@dashai/sdk/auth/server` — `getServerSession`, `exchangeCode`, `signOut`\n * - `@dashai/sdk/auth/middleware` — `withAuth()` Next.js edge middleware factory\n * - `@dashai/sdk/auth/client` — `useSession`, `<AuthProvider>`, `<SignOutButton>`\n * - `@dashai/sdk/auth/types` — `Session`, `AuthOptions`, `AuthErrorCode`\n *\n * SemVer policy: every named export here AND every named export from\n * the `auth/*` subpaths is part of the stable API. Breaking changes\n * require a major bump; new optional fields, new types, and additional\n * named exports are minors.\n *\n * Distribution model (per the v1 plan in\n * `dashwise-devops-docs/plans/modules-p8-p10-execution-plan.md`):\n * - **AI builder sandbox**: SDK is baked into the E2B template image.\n * - **CLI / local dev**: workspace-local resolution via pnpm\n * `workspace:*` protocol OR tarball-into-`.dashwise/sdk-tarball.tgz`.\n * - **Published modules**: SDK is pre-bundled into the Lambda image\n * by `next build`; no runtime fetch required.\n *\n * npm publication is intentionally deferred — the SDK is consumed by\n * trusted, in-workspace paths, not by external developers (yet).\n *\n * @packageDocumentation\n */\n\nexport * from './data/index.js';\n\n/**\n * SDK package version. Replaced at build time by `tsup`'s `define`\n * substitution (see `tsup.config.ts`) with the value of `version`\n * from `packages/sdk/package.json`. Consumers can read this to\n * version-skew-detect against the manifest's required SDK range.\n *\n * In non-tsup contexts (Vitest, raw `tsc`), the bare `__SDK_VERSION__`\n * identifier resolves to a static `'dev'` fallback declared below.\n * Production builds always go through tsup so the build-time value\n * is what ships.\n */\ndeclare const __SDK_VERSION__: string;\nexport const VERSION: string =\n typeof __SDK_VERSION__ === 'string' ? __SDK_VERSION__ : 'dev';\n"]}
|
package/dist/query/index.d.cts
CHANGED
package/dist/query/index.d.ts
CHANGED
package/dist/react/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { L as ListOpts, P as Page, b as BaseRow, B as BaseInsert, c as BaseUpdate,
|
|
1
|
+
import { L as ListOpts, P as Page, b as BaseRow, B as BaseInsert, c as BaseUpdate, m as TableClient } from '../types-BwlzFHbq.cjs';
|
|
2
2
|
import { Query, AggQuery, QueryResult } from '../query/index.cjs';
|
|
3
3
|
|
|
4
4
|
/**
|
package/dist/react/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { L as ListOpts, P as Page, b as BaseRow, B as BaseInsert, c as BaseUpdate,
|
|
1
|
+
import { L as ListOpts, P as Page, b as BaseRow, B as BaseInsert, c as BaseUpdate, m as TableClient } from '../types-BwlzFHbq.js';
|
|
2
2
|
import { Query, AggQuery, QueryResult } from '../query/index.js';
|
|
3
3
|
|
|
4
4
|
/**
|