@walkeros/server-destination-gcp 4.8.1 → 4.8.2
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/CHANGELOG.md +25 -0
- package/README.md +4 -1
- package/dist/dev.d.mts +16 -3
- package/dist/dev.d.ts +16 -3
- package/dist/dev.js +1 -1
- package/dist/dev.js.map +1 -1
- package/dist/dev.mjs +1 -1
- package/dist/dev.mjs.map +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/schemas.js +1 -1
- package/dist/schemas.js.map +1 -1
- package/dist/schemas.mjs +1 -1
- package/dist/schemas.mjs.map +1 -1
- package/dist/walkerOS.json +486 -135
- package/package.json +4 -4
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/bigquery/config.ts","../src/pubsub/config.ts","../src/bigquery/push.ts","../src/bigquery/eventToRow.ts","../src/bigquery/writer.ts","../src/bigquery/pushBatch.ts","../src/bigquery/setup.ts","../src/bigquery/types/index.ts","../src/bigquery/index.ts","../src/pubsub/push.ts","../src/pubsub/setup.ts","../src/pubsub/types/index.ts","../src/pubsub/index.ts"],"sourcesContent":["import type { Config, Env, PartialConfig, Settings } from './types';\nimport type { BigQueryOptions } from '@google-cloud/bigquery';\nimport type { Logger } from '@walkeros/core';\nimport { BigQuery } from '@google-cloud/bigquery';\nimport { parseCredentials } from '../pubsub/config';\n\nexport function getConfig(\n partialConfig: PartialConfig = {},\n env: Env | undefined,\n logger: Logger.Instance,\n): Config {\n const settings = partialConfig.settings || ({} as Settings);\n const { projectId, bigquery } = settings;\n let { client, location, datasetId, tableId } = settings;\n\n if (!projectId) logger.throw('Config settings projectId missing');\n\n location = location || 'EU';\n datasetId = datasetId || 'walkerOS';\n tableId = tableId || 'events';\n\n const options: BigQueryOptions = { ...(bigquery || {}) };\n options.projectId = projectId;\n\n // `config.credentials` (parse-if-string) merges into the client options.\n // `settings.bigquery` stays the raw passthrough escape hatch.\n const parsed = parseCredentials(partialConfig.credentials, logger);\n // parseCredentials returns the object form (or undefined); a string can only\n // remain on the invalid-JSON path, which logger.throw already handles.\n const credentials =\n parsed !== undefined && typeof parsed !== 'string' ? parsed : undefined;\n if (credentials !== undefined) {\n options.credentials = credentials;\n }\n\n // Use BigQuery from env if available, otherwise use real BigQuery\n const BigQueryClass: NonNullable<Env['BigQuery']> = env?.BigQuery || BigQuery;\n client = client || new BigQueryClass(options);\n\n const settingsConfig: Settings = {\n ...settings,\n client,\n projectId,\n location,\n datasetId,\n tableId,\n // Stored so init() can thread the same SA to the Storage Write client.\n ...(credentials !== undefined ? { credentials } : {}),\n };\n\n return { ...partialConfig, settings: settingsConfig };\n}\n","import type {\n Config,\n Credentials,\n Env,\n PartialConfig,\n ServiceAccountCredentials,\n Settings,\n} from './types';\nimport type { Logger } from '@walkeros/core';\nimport { isObject } from '@walkeros/core';\nimport { PubSub } from '@google-cloud/pubsub';\n\ninterface ResolvedClientConfig {\n projectId: string;\n credentials?: ServiceAccountCredentials;\n apiEndpoint?: string;\n}\n\ninterface PartialPubSubSettings {\n client?: Settings['client'];\n projectId?: unknown;\n topic?: unknown;\n credentials?: Settings['credentials'];\n apiEndpoint?: Settings['apiEndpoint'];\n orderingKey?: Settings['orderingKey'];\n attributes?: Settings['attributes'];\n}\n\n/**\n * Validate and normalize the partial config into a runtime Config.\n *\n * Project ID precedence: when both `settings.projectId` and\n * `credentials.project_id` are set, the top-level `settings.projectId` wins.\n * This keeps the runtime publish target unambiguous.\n *\n * Mirrors BigQuery's getConfig: the env-injected (or default SDK) client\n * is constructed here so `Settings.client` is always populated before\n * push/destroy run.\n */\nexport function getConfig(\n partialConfig: PartialConfig = {},\n env: Env | undefined,\n logger: Logger.Instance,\n): Config {\n const empty: PartialPubSubSettings = {};\n const settings: PartialPubSubSettings = partialConfig.settings ?? empty;\n const projectId =\n typeof settings.projectId === 'string' ? settings.projectId : '';\n const topic = typeof settings.topic === 'string' ? settings.topic : '';\n\n if (!projectId) logger.throw('Config settings projectId missing');\n if (!topic) logger.throw('Config settings topic missing');\n\n const credentials = parseCredentials(\n resolveCredentials(partialConfig, logger),\n logger,\n );\n\n // Build the client once: prefer pre-supplied settings.client, then env-\n // injected constructor (tests/DI), then the real SDK.\n let client = settings.client;\n if (!client) {\n const Constructor = env?.PubSub ?? PubSub;\n const clientOptions = buildClientOptions({\n projectId,\n credentials,\n apiEndpoint: settings.apiEndpoint,\n });\n client = new Constructor(clientOptions);\n }\n\n const settingsConfig: Settings = {\n ...settings,\n client,\n projectId,\n topic,\n credentials,\n };\n\n return { ...partialConfig, settings: settingsConfig };\n}\n\n/**\n * Resolve credentials with precedence `config.credentials ?? settings.credentials`.\n *\n * Uses `??` (not `||`) so an explicitly-set empty value surfaces as a misconfig\n * rather than silently falling through. Warns once per instance when the\n * deprecated `settings.credentials` path supplies the value; this runs at the\n * init-time read site (`getConfig`), so no module-level once-flag is needed.\n */\nexport function resolveCredentials(\n partialConfig: PartialConfig,\n logger: Logger.Instance,\n): Credentials | undefined {\n if (partialConfig.credentials !== undefined) return partialConfig.credentials;\n const fromSettings = partialConfig.settings?.credentials;\n if (fromSettings !== undefined) {\n logger.warn('settings.credentials is deprecated; use config.credentials');\n return fromSettings;\n }\n return undefined;\n}\n\nexport function parseCredentials(\n raw: Settings['credentials'],\n logger: Logger.Instance,\n): Settings['credentials'] {\n if (raw === undefined) return undefined;\n if (typeof raw === 'string') {\n try {\n const parsed: unknown = JSON.parse(raw);\n if (!isServiceAccountCredentials(parsed)) {\n logger.throw('Invalid credentials JSON');\n return undefined;\n }\n return parsed;\n } catch {\n logger.throw('Invalid credentials JSON');\n return undefined;\n }\n }\n return raw;\n}\n\nfunction isServiceAccountCredentials(\n value: unknown,\n): value is ServiceAccountCredentials {\n if (!isObject(value)) return false;\n const candidate: { client_email?: unknown; private_key?: unknown } = value;\n return (\n typeof candidate.client_email === 'string' &&\n typeof candidate.private_key === 'string'\n );\n}\n\n/**\n * Resolve the constructor options for `new PubSub(...)`.\n *\n * Returns undefined when a pre-built `settings.client` is set; the caller\n * uses that client directly without invoking the SDK constructor.\n */\nexport function resolveClientConfig(\n settings: Settings,\n): ResolvedClientConfig | undefined {\n if (settings.client) return undefined;\n return buildClientOptions({\n projectId: settings.projectId,\n credentials: settings.credentials,\n apiEndpoint: settings.apiEndpoint,\n });\n}\n\ninterface ClientOptionsInput {\n projectId: string;\n credentials?: Settings['credentials'];\n apiEndpoint?: string;\n}\n\nfunction buildClientOptions(input: ClientOptionsInput): ResolvedClientConfig {\n const result: ResolvedClientConfig = { projectId: input.projectId };\n if (\n input.credentials !== undefined &&\n typeof input.credentials !== 'string'\n ) {\n result.credentials = input.credentials;\n }\n if (input.apiEndpoint) result.apiEndpoint = input.apiEndpoint;\n return result;\n}\n\nexport function isPubSubEnv(env: unknown): env is Env {\n if (!isObject(env)) return false;\n const candidate: { PubSub?: unknown } = env;\n return (\n candidate.PubSub === undefined || typeof candidate.PubSub === 'function'\n );\n}\n","import type { PushFn } from './types';\nimport { isObject } from '@walkeros/core';\nimport { eventToRow } from './eventToRow';\nimport { ensureWriter } from './writer';\n\nexport const push: PushFn = async function (\n event,\n { config, rule: _rule, data, logger },\n) {\n const settings = config.settings;\n if (!settings) return logger.throw('settings missing, init() not run');\n\n if (!settings.writer)\n return logger.throw('writer is missing, init() not run');\n\n // Self-heal a writer that the connection's `'error'` handler flagged broken:\n // exactly one re-open attempt before failing. On a failed re-open this throws,\n // routing the event to the DLQ in-band (instead of an out-of-band crash) and\n // feeding the collector's per-destination breaker. Breaker-gated: the\n // collector does not call push while the breaker is OPEN, so the re-open runs\n // at most once per admitted push, never in a loop.\n if (settings.writerBroken) await ensureWriter(settings, logger);\n\n const { writer, datasetId, tableId } = settings;\n\n if (!writer) return logger.throw('writer is missing, init() not run');\n if (!datasetId) return logger.throw('datasetId is missing');\n if (!tableId) return logger.throw('tableId is missing');\n\n const row = isObject(data) ? data : eventToRow(event);\n const rows = [row];\n\n logger.debug('Calling BigQuery Storage Write API', {\n dataset: datasetId,\n table: tableId,\n rowCount: rows.length,\n });\n\n let result;\n try {\n const pending = writer.appendRows(rows);\n result = await pending.getResult();\n } catch (err) {\n // Log the failure and rethrow the raw error to the collector/DLQ. Secret\n // redaction is standardized at the CLI logger handler; the raw error keeps\n // its `code` so the row stays DLQ-routable.\n logger.error('BigQuery row append threw', {\n error: err instanceof Error ? err.message : String(err),\n });\n throw err;\n }\n\n if (result.rowErrors && result.rowErrors.length > 0) {\n // Single-event push path: throw with row context so the caller sees the failure.\n const first = result.rowErrors[0];\n return logger.throw(\n `BigQuery row append failed: code=${first.code} message=${first.message}`,\n );\n }\n\n logger.debug('BigQuery Storage Write API response', {\n ok: true,\n offset: result.appendResult?.offset?.value,\n });\n};\n","import type { WalkerOS } from '@walkeros/core';\n\n/** Row shape passed to JSONWriter.appendRows. Values are JSON-serializable scalars or strings. */\nexport interface BigQueryRow {\n [key: string]: string | number | null;\n name: string;\n data: string | null;\n context: string | null;\n globals: string | null;\n custom: string | null;\n user: string | null;\n nested: string | null;\n consent: string | null;\n id: string;\n trigger: string;\n entity: string;\n action: string;\n timestamp: number;\n timing: number;\n source: string | null;\n}\n\nfunction jsonOrNull(value: unknown): string | null {\n if (value === undefined || value === null) return null;\n if (typeof value === 'object') {\n if (Array.isArray(value) && value.length === 0) return null;\n if (!Array.isArray(value) && Object.keys(value).length === 0) return null;\n return JSON.stringify(value);\n }\n return JSON.stringify(value);\n}\n\n/** Convert a walkerOS Event v4 into a 15-column BigQuery row in canonical order.\n *\n * Note: BQ Storage Write API encodes TIMESTAMP fields as INT64 microseconds\n * since epoch (the SDK calls Long.fromString on the value). ISO strings fail\n * with \"interior hyphen\" because Long.fromString sees the date hyphens as\n * non-numeric. Pass microseconds directly.\n */\nexport function eventToRow(event: WalkerOS.Event): BigQueryRow {\n return {\n name: event.name,\n data: jsonOrNull(event.data),\n context: jsonOrNull(event.context),\n globals: jsonOrNull(event.globals),\n custom: jsonOrNull(event.custom),\n user: jsonOrNull(event.user),\n nested: jsonOrNull(event.nested),\n consent: jsonOrNull(event.consent),\n id: event.id,\n trigger: event.trigger,\n entity: event.entity,\n action: event.action,\n timestamp: new Date(event.timestamp).getTime() * 1000, // microseconds since epoch\n timing: event.timing,\n source: jsonOrNull(event.source),\n };\n}\n","import type { Logger, ServiceAccount } from '@walkeros/core';\nimport type { BigQueryOptions } from '@google-cloud/bigquery';\nimport { managedwriter, adapt, protos } from '@google-cloud/bigquery-storage';\n\n// gax CallOptions, derived from the SDK's own method signature so we don't take\n// a direct dependency on `google-gax` (a transitive dep of bigquery-storage).\n// `getWriteStream(request, options?: CallOptions)` -> the optional 2nd param.\ntype CallOptions = NonNullable<\n Parameters<managedwriter.WriterClient['getWriteStream']>[1]\n>;\n\n// The SDK's StreamConnection instance returned by createStreamConnection.\n// Derived from the SDK method signature so we don't import the un-exported\n// StreamConnection class. The SDK kit's connection type.\nexport type StreamConnection = Awaited<\n ReturnType<managedwriter.WriterClient['createStreamConnection']>\n>;\n\n// SDK-derived shapes the structural types below speak in (types only).\ntype ClientOptions = NonNullable<\n ConstructorParameters<typeof managedwriter.WriterClient>[0]\n>;\ntype WriteStreamRequest = Parameters<\n managedwriter.WriterClient['getWriteStream']\n>[0];\ntype WriteStreamInfo = Awaited<\n ReturnType<managedwriter.WriterClient['getWriteStream']>\n>;\ntype TableSchema = NonNullable<WriteStreamInfo['tableSchema']>;\ntype ProtoDescriptor = ConstructorParameters<\n typeof managedwriter.JSONWriter\n>[0]['protoDescriptor'];\ntype RowList = Parameters<managedwriter.JSONWriter['appendRows']>[0];\ntype AppendResponse = Awaited<\n ReturnType<ReturnType<managedwriter.JSONWriter['appendRows']>['getResult']>\n>;\n\n/** The `{ off }` disposable returned by `onConnectionError`. */\nexport interface ConnectionListener {\n off(): void;\n}\n\n/** The connection surface the writer uses: its stream id and error hook. */\nexport interface WriteConnection {\n getStreamId(): string;\n onConnectionError(listener: (err: unknown) => void): ConnectionListener;\n}\n\n/** The fields of an append response that push and pushBatch read. */\nexport type AppendOutcome = Pick<AppendResponse, 'rowErrors' | 'appendResult'>;\n\n/** The row writer surface push and pushBatch use. */\nexport interface RowWriter {\n appendRows(rows: RowList): { getResult(): Promise<AppendOutcome> };\n close(): void;\n}\n\n/** The Storage Write client surface the writer uses. */\nexport interface WriteClient<C extends WriteConnection> {\n createStreamConnection(request: {\n destinationTable: string;\n streamId: string;\n }): Promise<C>;\n getWriteStream(\n request: WriteStreamRequest,\n options?: CallOptions,\n ): Promise<{ tableSchema?: TableSchema | null }>;\n close(): void;\n}\n\n/** Converts the table schema into the writer's proto descriptor. */\nexport interface SchemaAdapter {\n convertStorageSchemaToProto2Descriptor(\n schema: TableSchema,\n scope: string,\n ): ProtoDescriptor;\n}\n\n/**\n * The three Storage Write pieces the writer is built from. The connection type\n * ties a kit's client to the SAME kit's JSONWriter: the SDK JSONWriter only\n * accepts the SDK's own StreamConnection.\n */\nexport interface WriterKit<C extends WriteConnection> {\n WriterClient: new (options: ClientOptions) => WriteClient<C>;\n JSONWriter: new (args: {\n connection: C;\n protoDescriptor: ProtoDescriptor;\n }) => RowWriter;\n adapt: SchemaAdapter;\n}\n\n/**\n * The Storage Write API pieces a destination env may inject (tests, simulate).\n * Without `WriterClient`, each missing piece falls back to the SDK, so runtime\n * needs none of them. An injected `WriterClient` needs an injected\n * `JSONWriter`: its connection cannot feed the SDK writer.\n */\nexport interface WriterEnv {\n WriterClient?: WriterKit<WriteConnection>['WriterClient'];\n JSONWriter?: WriterKit<WriteConnection>['JSONWriter'];\n adapt?: SchemaAdapter;\n}\n\nexport interface OpenWriterArgs {\n projectId: string;\n datasetId: string;\n tableId: string;\n /**\n * Service-account credentials resolved from `config.credentials`. Forwarded\n * to the data-plane WriterClient so event writes authenticate with the\n * configured SA instead of falling back to ADC (which has no metadata server\n * to query on non-GCP runtimes, e.g. Scaleway). When both this and a\n * `settings.bigquery.credentials` are set, `config.credentials` wins, matching\n * the query client's resolution in getConfig, so one destination always\n * authenticates as a single identity across both clients.\n */\n credentials?: ServiceAccount;\n // Raw passthrough auth/client options for the WriterClient (the escape hatch).\n bigquery?: BigQueryOptions;\n /**\n * Deadline in ms for unary control-plane calls (the getWriteStream schema\n * fetch), derived from the standard per-step `config.timeout`. Never applied\n * to the appendRows stream: a gax deadline on a bidi stream bounds the WHOLE\n * stream lifetime, not one append. Per-delivery bounds live in the collector\n * (it races every push at `config.timeout`); the stream stays on the SDK\n * default so it can live for hours.\n */\n timeout?: number;\n /**\n * Handler for the connection's out-of-band `'error'` event. Attaching it (by\n * mere presence) prevents Node's uncaught-`'error'` throw on the detached\n * gRPC tick that crashed the process; the destination wires it to flag the\n * writer broken and route the error through `context.reportError`. MUST NOT\n * throw (it runs on a detached emitter tick).\n */\n onConnectionError?: (err: unknown) => void;\n /** Injected SDK pieces (the destination env); the SDK is the fallback. */\n env?: WriterEnv;\n}\n\nexport interface WriterHandles {\n writeClient: WriteClient<WriteConnection>;\n writer: RowWriter;\n // The StreamConnection the writer appends to. Held so closeWriter can remove\n // the connection-error listener it owns.\n connection: WriteConnection;\n // The `{ off }` disposable for the connection-error listener, removed in\n // closeWriter so a re-opened writer doesn't accumulate stale listeners.\n connectionErrorListener?: ConnectionListener;\n}\n\n/**\n * Open a long-lived JSONWriter on the table's _default stream.\n * Requires the dataset and table to already exist (run `walkeros setup` first).\n *\n * The SDK pieces come from `args.env` when injected (tests, simulate), else\n * from `@google-cloud/bigquery-storage`. Without an injected `WriterClient`\n * the SDK kit is used, with an injected `JSONWriter`/`adapt` taking their\n * place when given. An injected `WriterClient` needs an injected `JSONWriter`\n * (the SDK writer only accepts the SDK's own connection); without one, init\n * fails and the injected client is closed.\n *\n * Sequence (per SDK docs and empirical SDK probe):\n * 1. new WriterClient\n * 2. createStreamConnection\n * 3. attach the connection-error listener (so a detached stream `'error'`\n * is contained instead of crashing the process)\n * 4. getWriteStream(view: FULL) to retrieve the table schema\n * 5. adapt.convertStorageSchemaToProto2Descriptor → protoDescriptor\n * 6. new JSONWriter({ connection, protoDescriptor })\n */\nexport function openWriter(\n args: OpenWriterArgs,\n logger: Logger.Instance,\n): Promise<WriterHandles> {\n const { env } = args;\n if (!env?.WriterClient) {\n const sdkKit: WriterKit<StreamConnection> = {\n WriterClient: managedwriter.WriterClient,\n JSONWriter: env?.JSONWriter ?? managedwriter.JSONWriter,\n adapt: env?.adapt ?? adapt,\n };\n return openWith(sdkKit, args, logger);\n }\n const envKit: WriterKit<WriteConnection> = {\n WriterClient: env.WriterClient,\n JSONWriter: env.JSONWriter ?? MissingJSONWriter,\n adapt: env.adapt ?? adapt,\n };\n return openWith(envKit, args, logger);\n}\n\nconst MISSING_JSON_WRITER =\n 'BigQuery env: an injected WriterClient needs an injected JSONWriter; its connection cannot feed the SDK writer.';\n\n// The env kit's JSONWriter when an env injects a WriterClient without one.\n// Building it fails, so openWith's cleanup closes the injected client.\nclass MissingJSONWriter implements RowWriter {\n constructor() {\n throw new Error(MISSING_JSON_WRITER);\n }\n appendRows(): { getResult(): Promise<AppendOutcome> } {\n throw new Error(MISSING_JSON_WRITER);\n }\n close(): void {}\n}\n\nasync function openWith<C extends WriteConnection>(\n { WriterClient, JSONWriter, adapt: adaptFn }: WriterKit<C>,\n args: OpenWriterArgs,\n logger: Logger.Instance,\n): Promise<WriterHandles> {\n const {\n projectId,\n datasetId,\n tableId,\n credentials,\n bigquery,\n timeout,\n onConnectionError,\n } = args;\n const destinationTable = `projects/${projectId}/datasets/${datasetId}/tables/${tableId}`;\n\n logger.debug('Opening BigQuery Storage Write API writer', {\n destinationTable,\n });\n\n // gax call options carrying the deadline for UNARY control-plane calls\n // (the getWriteStream schema fetch). Never passed to createStreamConnection:\n // a CallOptions.timeout on the appendRows bidi stream is the stream's TOTAL\n // deadline, killing a healthy connection when it expires. The stream keeps\n // the SDK's own long-lived default; individual deliveries are bounded by the\n // collector's per-push race (config.timeout), not by a transport deadline.\n // Left undefined when no timeout is configured.\n const callOptions: CallOptions | undefined =\n timeout === undefined ? undefined : { timeout };\n\n // The WriterClient takes google-gax ClientOptions, which extend\n // GoogleAuthOptions: `projectId` + `credentials` (a JWTInput, i.e.\n // { client_email, private_key, ... }), the same auth surface as\n // BigQueryOptions on the query client. Spread the resolved `config.credentials`\n // last so it wins over any `settings.bigquery.credentials`, mirroring the query\n // client's resolution in getConfig (one identity per destination).\n const writeClient = new WriterClient({\n projectId,\n ...bigquery,\n ...(credentials !== undefined ? { credentials } : {}),\n });\n let connectionErrorListener: ConnectionListener | undefined;\n let connection: C | undefined;\n try {\n // Use streamId (not streamType) so the SDK resolves to the table's\n // implicit `_default` stream without calling CreateWriteStream. Passing\n // managedwriter.DefaultStream as streamType triggers a CreateWriteStream\n // call with type='DEFAULT', which BQ rejects as TYPE_UNSPECIFIED.\n connection = await writeClient.createStreamConnection({\n destinationTable,\n streamId: managedwriter.DefaultStream,\n });\n\n // Attach the connection-error listener on the StreamConnection (NOT the\n // inner gRPC `_connection`) BEFORE building the JSONWriter, so any `'error'`\n // the connection emits has a listener from the first tick onward. Without a\n // listener, Node throws the emitted error as an uncaughtException on a\n // detached tick, bypassing the collector's promise-path try/catch (the\n // crash this handler exists to prevent). `onConnectionError` is the SDK's\n // documented surface and returns an `{ off }` disposable; it adds an\n // `'error'` listener under the hood.\n if (onConnectionError) {\n connectionErrorListener = connection.onConnectionError((err) => {\n onConnectionError(err);\n });\n }\n\n const streamId = connection.getStreamId();\n const writeStream = await writeClient.getWriteStream(\n {\n streamId,\n view: protos.google.cloud.bigquery.storage.v1.WriteStreamView.FULL,\n },\n callOptions,\n );\n if (!writeStream.tableSchema) {\n throw new Error(\n `BigQuery write stream ${streamId} returned no tableSchema; cannot build proto descriptor`,\n );\n }\n const protoDescriptor = adaptFn.convertStorageSchemaToProto2Descriptor(\n writeStream.tableSchema,\n 'root',\n );\n const writer = new JSONWriter({\n connection,\n protoDescriptor,\n });\n\n return { writeClient, writer, connection, connectionErrorListener };\n } catch (err) {\n // Release any resources already opened by the partial init so we don't\n // leak gRPC handles (including the connection-error listener). closeWriter\n // swallows close errors and only logs.\n closeWriter({ writeClient, connectionErrorListener }, logger);\n throw err;\n }\n}\n\n// Structural subset of Settings that ensureWriter reads/writes. Kept local so\n// writer.ts doesn't import the full Settings type (which imports back from here).\nexport interface EnsureWriterSettings {\n writer?: RowWriter;\n writeClient?: WriteClient<WriteConnection>;\n connection?: WriteConnection;\n connectionErrorListener?: ConnectionListener;\n writerBroken?: boolean;\n lastStreamError?: Error;\n reopenWriter?: () => Promise<WriterHandles>;\n reopenInFlight?: Promise<void>;\n}\n\n/**\n * Single owner of the writer lifecycle on the push path. When the connection's\n * `'error'` handler has flagged the writer broken, attempt a lazy re-open\n * before failing:\n * - success: swap in the fresh handles, clear the broken flag, proceed.\n * - failure: stay broken, throw so the event is DLQ-routed.\n *\n * Self-heal is bounded along two independent axes:\n *\n * 1. ACROSS sequential passes, by the collector's breaker WITHOUT importing\n * `@walkeros/collector`: the skip gate does not call push while the breaker\n * is OPEN, admits exactly one probe when HALF-OPEN, and each failed re-open\n * throws (feeding the breaker's transport-failure accounting until it opens).\n * So once the breaker trips, no further re-opens are attempted.\n *\n * 2. WITHIN one pass, by the `reopenInFlight` memo. The breaker only opens\n * AFTER a pass records its failures, so in the first (most concurrent) pass\n * the breaker is still CLOSED and the collector fans the destination's\n * admitted events out with Promise.all. Without the memo, every concurrent\n * push would pass the `writerBroken` guard and each run its own\n * closeWriter+reopen, orphaning a gRPC connection + live 'error' listener\n * per redundant attempt. The memo collapses a concurrent burst into ONE\n * re-open that every caller awaits; a shared failure rejects into all of\n * them (each DLQ-routes correctly), and the memo clears in a finally so a\n * later push retries.\n *\n * A re-open's unary schema fetch is bounded by the gax CallOptions.timeout;\n * the re-open as a whole runs in-band on a push, under the collector's\n * per-delivery race. pushBatch shares this function, so it inherits both\n * bounds.\n */\nexport function ensureWriter(\n settings: EnsureWriterSettings,\n logger: Logger.Instance,\n): Promise<void> {\n if (!settings.writerBroken) return Promise.resolve();\n\n // A concurrent caller already started the re-open: join it instead of opening\n // a second connection (which would orphan one of them).\n if (settings.reopenInFlight) return settings.reopenInFlight;\n\n const lastError = settings.lastStreamError;\n logger.info('BigQuery writer broken; attempting one re-open before failing', {\n error: lastError ? lastError.message : 'unknown stream error',\n });\n\n const reopen = settings.reopenWriter;\n if (!reopen) {\n // No re-open hook (init never wired it): cannot self-heal, stay broken.\n return Promise.reject(\n new Error(\n 'BigQuery writer is broken and no re-open hook is configured: ' +\n (lastError ? lastError.message : 'unknown stream error'),\n ),\n );\n }\n\n const inFlight = (async () => {\n try {\n // Release the broken handles (incl. its connection-error listener) before\n // re-opening so we don't leak the old gRPC connection. Only the one\n // caller that started the memo runs this, so the old handles are closed\n // exactly once.\n closeWriter(\n {\n writer: settings.writer,\n writeClient: settings.writeClient,\n connectionErrorListener: settings.connectionErrorListener,\n },\n logger,\n );\n\n const handles = await reopen();\n settings.writeClient = handles.writeClient;\n settings.writer = handles.writer;\n settings.connection = handles.connection;\n settings.connectionErrorListener = handles.connectionErrorListener;\n settings.writerBroken = false;\n settings.lastStreamError = undefined;\n logger.info('BigQuery writer re-opened after a stream error');\n } finally {\n // Clear the memo so a later push after a FAILED re-open retries (on a\n // successful re-open writerBroken is already false, so the next push skips\n // ensureWriter entirely).\n settings.reopenInFlight = undefined;\n }\n })();\n\n settings.reopenInFlight = inFlight;\n return inFlight;\n}\n\n/** Close handles in safe order. Errors are logged, never thrown (called from destroy). */\nexport function closeWriter(\n handles: Partial<WriterHandles>,\n logger: Logger.Instance,\n): void {\n try {\n handles.connectionErrorListener?.off();\n } catch (err) {\n logger.warn('connection error listener removal failed', {\n error: String(err),\n });\n }\n try {\n handles.writer?.close();\n } catch (err) {\n logger.warn('writer.close failed', { error: String(err) });\n }\n try {\n handles.writeClient?.close();\n } catch (err) {\n logger.warn('writeClient.close failed', { error: String(err) });\n }\n}\n","import type { PushBatchFn } from './types';\nimport { isObject } from '@walkeros/core';\nimport { eventToRow } from './eventToRow';\nimport { ensureWriter } from './writer';\n\n/**\n * Batched push using a single appendRows call.\n *\n * Per-row failures (BigQuery's `rowErrors`) are reported back to the collector\n * as a BatchOutcome identifying the failed entries by index. The collector then\n * DLQs only those rows and counts the rest as delivered, so a later DLQ retry\n * does not re-write the already-succeeded rows (no duplicates). A whole-append\n * failure (the appendRows call itself rejects, or the writer is missing) still\n * throws, routing the entire batch to the DLQ.\n */\nexport const pushBatch: PushBatchFn = async (batch, { config, logger }) => {\n const settings = config.settings;\n if (!settings) return logger.throw('settings missing, init() not run');\n\n if (!settings.writer)\n return logger.throw('writer is missing, init() not run');\n\n // Self-heal a broken writer (one re-open attempt) before failing. On a failed\n // re-open this throws, routing the WHOLE batch to the DLQ in-band and feeding\n // the collector's per-destination breaker. Breaker-gated by the collector, so\n // the re-open runs at most once per admitted batch.\n if (settings.writerBroken) await ensureWriter(settings, logger);\n\n const { writer, datasetId, tableId } = settings;\n\n if (!writer) return logger.throw('writer is missing, init() not run');\n if (!datasetId) return logger.throw('datasetId is missing');\n if (!tableId) return logger.throw('tableId is missing');\n\n const rows = batch.entries.map((e) =>\n isObject(e.data) ? e.data : eventToRow(e.event),\n );\n\n if (rows.length === 0) return;\n\n try {\n logger.debug('Calling BigQuery Storage Write API (batch)', {\n dataset: datasetId,\n table: tableId,\n rowCount: rows.length,\n });\n const pending = writer.appendRows(rows);\n const result = await pending.getResult();\n\n if (result.rowErrors && result.rowErrors.length > 0) {\n const failed = result.rowErrors.length;\n // Operator-visible summary at INFO, each row error at ERROR.\n logger.info('BigQuery batch had partial failures', {\n ok: rows.length - failed,\n failed,\n rowCount: rows.length,\n });\n for (const re of result.rowErrors) {\n logger.error('BigQuery row append failed', {\n index: re.index,\n code: re.code,\n message: re.message,\n });\n }\n // Report per-row failures so the collector DLQs only the failed rows and\n // counts the succeeded rows as delivered. `re.index` is the row's\n // position in `rows`, which is built 1:1 from `batch.entries`, so it maps\n // directly to the collector's entry index. The per-row error preserves\n // the original BigQuery `code` and `message` for debugging from the DLQ.\n // The Storage Write SDK types `index` as a protobuf int64 (number, string,\n // or Long) and `message` as a nullable string, so both are normalized to\n // the strict BatchFailure shape here.\n const failures = result.rowErrors.map((re) => ({\n index: Number(re.index),\n error: Object.assign(new Error(re.message ?? 'BigQuery row error'), {\n code: re.code,\n }),\n }));\n\n return { failed: failures };\n }\n\n // Full success: keep at DEBUG to avoid noise on every batch.\n logger.debug('BigQuery batch append ok', {\n ok: rows.length,\n failed: 0,\n offset: result.appendResult?.offset?.value,\n });\n } catch (err) {\n // Log the failure and rethrow the raw error so the whole batch routes to the\n // DLQ. Secret redaction is standardized at the CLI logger handler.\n logger.error('BigQuery batch append threw', {\n error: err instanceof Error ? err.message : String(err),\n });\n throw err;\n }\n};\n","import type { DestinationServer } from '@walkeros/server-core';\nimport type {\n Env,\n QueryTable,\n Setup,\n SetupSchemaField,\n TableMetadataShape,\n Types,\n} from './types';\nimport type { LifecycleContext, Logger } from '@walkeros/core';\nimport { resolveSetup } from '@walkeros/core';\n\n// Setup is wired to the destination's `setup` slot which uses the broader\n// `DestinationServer.Config<Types>` (settings is optional). We runtime-narrow\n// instead of using the local Config alias so the assignment in index.ts\n// type-checks without contravariance issues.\ntype WideConfig = DestinationServer.Config<Types>;\n\n// Per Resolved Decision #2: only `name` is REQUIRED. All other columns\n// are NULLABLE for resilience against partial events / test fixtures.\nexport const DEFAULT_SCHEMA: SetupSchemaField[] = [\n { name: 'name', type: 'STRING', mode: 'REQUIRED' },\n { name: 'data', type: 'JSON', mode: 'NULLABLE' },\n { name: 'context', type: 'JSON', mode: 'NULLABLE' },\n { name: 'globals', type: 'JSON', mode: 'NULLABLE' },\n { name: 'custom', type: 'JSON', mode: 'NULLABLE' },\n { name: 'user', type: 'JSON', mode: 'NULLABLE' },\n { name: 'nested', type: 'JSON', mode: 'NULLABLE' },\n { name: 'consent', type: 'JSON', mode: 'NULLABLE' },\n { name: 'id', type: 'STRING', mode: 'NULLABLE' },\n { name: 'trigger', type: 'STRING', mode: 'NULLABLE' },\n { name: 'entity', type: 'STRING', mode: 'NULLABLE' },\n { name: 'action', type: 'STRING', mode: 'NULLABLE' },\n { name: 'timestamp', type: 'TIMESTAMP', mode: 'NULLABLE' },\n { name: 'timing', type: 'FLOAT64', mode: 'NULLABLE' },\n { name: 'source', type: 'JSON', mode: 'NULLABLE' },\n];\n\nexport const DEFAULT_SETUP: Required<Setup> = {\n location: 'EU',\n storageBillingModel: 'PHYSICAL',\n partitioning: { type: 'DAY', field: 'timestamp' },\n clustering: { fields: ['name', 'entity', 'action'] },\n schema: DEFAULT_SCHEMA,\n};\n\nexport interface SetupResult {\n datasetCreated: boolean;\n tableCreated: boolean;\n}\n\ntype DriftableTable = Pick<QueryTable, 'getMetadata'>;\n\ninterface PartitioningMeta {\n type?: string;\n field?: string;\n}\n\ninterface ClusteringMeta {\n fields?: string[];\n}\n\ninterface SchemaMeta {\n fields?: Array<{ name?: string; type?: string; mode?: string }>;\n}\n\nexport async function setup(\n ctx: LifecycleContext<WideConfig, Env>,\n): Promise<SetupResult | undefined> {\n const { config, logger } = ctx;\n const merged = resolveSetup(config.setup, DEFAULT_SETUP);\n if (!merged) {\n logger.debug('setup: skipped (config.setup is false or unset)');\n return;\n }\n // Fill any holes a partial user override left, so all fields are required.\n const options: Required<Setup> = {\n location: merged.location ?? DEFAULT_SETUP.location,\n storageBillingModel:\n merged.storageBillingModel ?? DEFAULT_SETUP.storageBillingModel,\n partitioning: merged.partitioning ?? DEFAULT_SETUP.partitioning,\n clustering: merged.clustering ?? DEFAULT_SETUP.clustering,\n schema: merged.schema ?? DEFAULT_SETUP.schema,\n };\n\n if (!config.settings) {\n logger.throw('setup: settings missing');\n return;\n }\n const { client, datasetId, tableId } = config.settings;\n if (!client) {\n logger.throw('setup: BigQuery client is missing');\n return;\n }\n if (!datasetId) {\n logger.throw('setup: datasetId is missing');\n return;\n }\n if (!tableId) {\n logger.throw('setup: tableId is missing');\n return;\n }\n\n const dataset = client.dataset(datasetId);\n\n // 1. Dataset\n let datasetCreated = false;\n const [datasetExists] = await dataset.exists();\n if (!datasetExists) {\n try {\n await dataset.create({\n location: options.location,\n storageBillingModel: options.storageBillingModel,\n });\n datasetCreated = true;\n logger.info('setup: dataset created', {\n datasetId,\n location: options.location,\n storageBillingModel: options.storageBillingModel,\n });\n } catch (err) {\n if (isAlreadyExists(err)) {\n logger.debug('setup: dataset already exists (race)', { datasetId });\n } else {\n throw err;\n }\n }\n } else {\n logger.debug('setup: dataset exists', { datasetId });\n }\n\n // 2. Table\n const table = dataset.table(tableId);\n let tableCreated = false;\n const [tableExists] = await table.exists();\n if (!tableExists) {\n try {\n await table.create({\n schema: { fields: options.schema },\n timePartitioning: {\n type: options.partitioning.type,\n field: options.partitioning.field,\n },\n clustering: { fields: options.clustering.fields },\n });\n tableCreated = true;\n logger.info('setup: table created', {\n datasetId,\n tableId,\n partitioning: options.partitioning,\n clustering: options.clustering,\n });\n } catch (err) {\n if (isAlreadyExists(err)) {\n logger.debug('setup: table already exists (race)', { tableId });\n } else {\n throw err;\n }\n }\n } else {\n logger.debug('setup: table exists', { datasetId, tableId });\n await detectDrift(table, options, logger);\n }\n\n return { datasetCreated, tableCreated };\n}\n\nfunction hasCode(err: unknown): err is { code: number } {\n if (typeof err !== 'object' || err === null) return false;\n if (!('code' in err)) return false;\n const obj: { code?: unknown } = err;\n return typeof obj.code === 'number';\n}\n\nfunction isAlreadyExists(err: unknown): boolean {\n return hasCode(err) && err.code === 409;\n}\n\nasync function detectDrift(\n table: DriftableTable,\n options: Required<Setup>,\n logger: Logger.Instance,\n): Promise<void> {\n let metadata: TableMetadataShape;\n try {\n const [meta] = await table.getMetadata();\n metadata = meta ?? {};\n } catch (err) {\n logger.debug('setup: drift check failed (non-fatal)', {\n error: err instanceof Error ? err.message : String(err),\n });\n return;\n }\n\n // Partition drift\n if (isPartitioningMeta(metadata.timePartitioning)) {\n const actual = metadata.timePartitioning;\n const declared = options.partitioning;\n if (actual.type !== declared.type || actual.field !== declared.field) {\n logger.warn('setup.drift', {\n field: 'timePartitioning',\n declared,\n actual,\n });\n }\n }\n\n // Clustering drift\n if (isClusteringMeta(metadata.clustering)) {\n const actualFields = metadata.clustering.fields ?? [];\n const declaredFields = options.clustering.fields;\n if (\n actualFields.length !== declaredFields.length ||\n actualFields.some((f, i) => f !== declaredFields[i])\n ) {\n logger.warn('setup.drift', {\n field: 'clustering',\n declared: { fields: declaredFields },\n actual: { fields: actualFields },\n });\n }\n }\n\n // Schema drift (column name, type, and mode; descriptions ignored)\n if (isSchemaMeta(metadata.schema)) {\n const actualFields = metadata.schema.fields ?? [];\n const declaredFields = options.schema;\n const driftDetected =\n actualFields.length !== declaredFields.length ||\n declaredFields.some((d, i) => {\n const a = actualFields[i];\n return (\n !a || a.name !== d.name || a.type !== d.type || a.mode !== d.mode\n );\n });\n if (driftDetected) {\n logger.warn('setup.drift', {\n field: 'schema',\n declared: declaredFields.map((f) => ({\n name: f.name,\n type: f.type,\n mode: f.mode,\n })),\n actual: actualFields.map((f) => ({\n name: f.name,\n type: f.type,\n mode: f.mode,\n })),\n });\n }\n }\n}\n\nfunction isPartitioningMeta(v: unknown): v is PartitioningMeta {\n return typeof v === 'object' && v !== null;\n}\n\nfunction isClusteringMeta(v: unknown): v is ClusteringMeta {\n return typeof v === 'object' && v !== null;\n}\n\nfunction isSchemaMeta(v: unknown): v is SchemaMeta {\n return typeof v === 'object' && v !== null;\n}\n","import type { DestinationServer } from '@walkeros/server-core';\nimport type {\n Mapping as WalkerOSMapping,\n Destination as CoreDestination,\n SetupFn as CoreSetupFn,\n Credential,\n ServiceAccount,\n} from '@walkeros/core';\nimport type { BigQueryOptions } from '@google-cloud/bigquery';\nimport type {\n WriterHandles,\n WriterEnv,\n WriteClient,\n WriteConnection,\n RowWriter,\n ConnectionListener,\n} from '../writer';\n\n/** Table metadata fields the setup drift check reads. */\nexport interface TableMetadataShape {\n timePartitioning?: unknown;\n clustering?: unknown;\n schema?: unknown;\n}\n\n/** The table surface `walkeros setup` calls. */\nexport interface QueryTable {\n exists(): Promise<[boolean, ...unknown[]]>;\n create(options: {\n schema: { fields: SetupSchemaField[] };\n timePartitioning: { type: string; field: string };\n clustering: { fields: string[] };\n }): Promise<unknown>;\n // Matches both real BigQuery Table.getMetadata() (returns [Metadata, ApiResponse])\n // and a mock returning [Metadata]. Only index 0 is consumed.\n getMetadata(): Promise<TableMetadataShape[]>;\n}\n\n/** The dataset surface `walkeros setup` calls. */\nexport interface QueryDataset {\n exists(): Promise<[boolean, ...unknown[]]>;\n create(options: {\n location: string;\n storageBillingModel: string;\n }): Promise<unknown>;\n table(tableId: string): QueryTable;\n}\n\n/**\n * The query client surface this destination calls (dataset and table\n * provisioning). A `BigQuery` from `@google-cloud/bigquery` satisfies it.\n */\nexport interface QueryClient {\n dataset(datasetId: string): QueryDataset;\n}\n\nexport interface Settings {\n client: QueryClient;\n projectId: string;\n datasetId: string;\n tableId: string;\n location?: string;\n bigquery?: BigQueryOptions;\n /**\n * Service-account credentials parsed from `config.credentials` at init.\n * Threaded to BOTH the query client (`new BigQuery`) and the data-plane\n * Storage Write client (`new WriterClient`) so event writes authenticate\n * with the configured SA instead of falling back to ADC on non-GCP runtimes.\n * Runtime-only (the raw `config.credentials` may be a JSON string).\n */\n credentials?: ServiceAccount;\n // Runtime-only handles populated by init(); not user-facing.\n writeClient?: WriteClient<WriteConnection>;\n writer?: RowWriter;\n // The StreamConnection the writer appends to. Held so the connection-error\n // listener can be removed on re-open/destroy. Runtime-only.\n connection?: WriteConnection;\n // The `{ off }` disposable for the connection-error listener. Runtime-only.\n connectionErrorListener?: ConnectionListener;\n /**\n * Set by the connection's `'error'` handler when the long-lived stream\n * errored out-of-band. The next push self-heals (one re-open attempt) before\n * failing; while set, push/pushBatch route the event to the DLQ. Runtime-only.\n */\n writerBroken?: boolean;\n /** The last out-of-band stream error, surfaced in the DLQ-routed message. Runtime-only. */\n lastStreamError?: Error;\n /**\n * Lazy re-open hook, wired by init(). Closes over the openWriter args plus\n * `reportError`/logger so the push path can self-heal a broken writer without\n * the destination needing the original init context. Runtime-only.\n */\n reopenWriter?: () => Promise<WriterHandles>;\n /**\n * The in-flight self-heal re-open, memoized so concurrent pushes admitted in\n * the same breaking pass (the collector fans out a destination's events with\n * Promise.all) await ONE re-open instead of each closing+re-opening, which\n * would orphan a gRPC connection + live 'error' listener per redundant\n * attempt. Cleared in a finally so a later push after a failed re-open\n * retries. Runtime-only.\n */\n reopenInFlight?: Promise<void>;\n}\n\nexport interface InitSettings {\n projectId: string;\n client?: QueryClient;\n datasetId?: string;\n tableId?: string;\n location?: string;\n bigquery?: BigQueryOptions;\n // Runtime-only handles populated by init(); not user-facing.\n writeClient?: WriteClient<WriteConnection>;\n writer?: RowWriter;\n connection?: WriteConnection;\n connectionErrorListener?: ConnectionListener;\n writerBroken?: boolean;\n lastStreamError?: Error;\n reopenWriter?: () => Promise<WriterHandles>;\n reopenInFlight?: Promise<void>;\n}\n\nexport interface Mapping {}\n\n/** Credentials value for this destination: JSON string or service account object. */\nexport type Credentials = Credential<ServiceAccount>;\n\n/**\n * Provisioning options for `walkeros setup destination.bigquery`.\n * Triggered only by the explicit CLI command. Idempotent, never auto-run.\n *\n * `projectId`, `datasetId`, `tableId` are read from `settings` (not duplicated here)\n * so a single source of truth governs both setup and runtime push.\n */\nexport interface Setup {\n /** Geographic location for the dataset. Default: 'EU'. */\n location?: string;\n /** Storage billing model. PHYSICAL is cheaper for compressible JSON. Default: 'PHYSICAL'. */\n storageBillingModel?: 'LOGICAL' | 'PHYSICAL';\n /** Time partitioning for the table. Default: { type: 'DAY', field: 'timestamp' }. */\n partitioning?: {\n type: 'DAY' | 'HOUR' | 'MONTH' | 'YEAR';\n field: string;\n };\n /** Clustering for cheap event-name filters. Default: { fields: ['name', 'entity', 'action'] }. */\n clustering?: { fields: string[] };\n /** Override the schema fields (15 columns by default, walkerOS Event v4 order). */\n schema?: SetupSchemaField[];\n}\n\n/** Single column in the BQ schema (subset of @google-cloud/bigquery's TableField). */\nexport interface SetupSchemaField {\n name: string;\n type: 'STRING' | 'JSON' | 'TIMESTAMP' | 'INT64' | 'BOOL' | 'FLOAT64';\n mode?: 'NULLABLE' | 'REQUIRED' | 'REPEATED';\n}\n\n// The Storage Write pieces (WriterClient, JSONWriter, adapt) come from\n// WriterEnv: mocks for tests/examples, optional at runtime.\nexport interface Env extends DestinationServer.Env, WriterEnv {\n BigQuery?: new (options?: BigQueryOptions) => QueryClient;\n}\n\nexport type Types = CoreDestination.Types<\n Settings,\n Mapping,\n Env,\n InitSettings,\n Setup,\n Credentials\n>;\n\nexport interface Destination extends DestinationServer.Destination<Types> {\n init: DestinationServer.InitFn<Types>;\n}\n\nexport type Config = {\n settings: Settings;\n} & DestinationServer.Config<Types>;\n\nexport type InitFn = DestinationServer.InitFn<Types>;\nexport type PushFn = DestinationServer.PushFn<Types>;\nexport type PushBatchFn = CoreDestination.PushBatchFn<Types>;\nexport type SetupFn = CoreSetupFn<Config, Env>;\n\nexport type PartialConfig = DestinationServer.PartialConfig<Types>;\n\nexport type PushEvents = DestinationServer.PushEvents<Mapping>;\n\nexport type Rule = WalkerOSMapping.Rule<Mapping>;\nexport type Rules = WalkerOSMapping.Rules<Rule>;\n","import type { Destination } from './types';\nimport { getConfig } from './config';\nimport { push } from './push';\nimport { pushBatch } from './pushBatch';\nimport { setup } from './setup';\nimport { openWriter, closeWriter } from './writer';\n\n// Types\nexport * as DestinationBigQuery from './types';\n\n// Timeout layering (who owns which bound):\n// - The COLLECTOR bounds every delivery: it races each push/pushBatch at\n// config.timeout (default 10s, packages/collector/src/destination.ts) and\n// converts a hung delivery into a counted DLQ failure. That is the\n// per-operation protection.\n// - This DESTINATION owns the connection lifecycle: broken-writer detection\n// via the connection 'error' listener, one lazy re-open on the next push\n// (ensureWriter), collapsed across concurrent pushes.\n// - The gax deadline below bounds UNARY control-plane calls only (the\n// getWriteStream schema fetch during open/re-open). It is never applied to\n// the appendRows bidi stream: a deadline there bounds the stream's total\n// lifetime and would kill a healthy connection on expiry. The stream keeps\n// the SDK's own long-lived AppendRows default.\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\nexport const destinationBigQuery: Destination = {\n type: 'gcp-bigquery',\n\n config: {},\n\n setup,\n\n async init({ config: partialConfig, env, logger, id, reportError }) {\n const config = getConfig(partialConfig, env, logger);\n\n // Deadline for unary control-plane calls, derived from the standard\n // per-step config.timeout (the same value the collector uses to race the\n // push). A positive number wins; 0/unset falls back to the default.\n const timeout =\n config.timeout && config.timeout > 0\n ? config.timeout\n : DEFAULT_TIMEOUT_MS;\n\n const { settings } = config;\n\n // Handler for the StreamConnection's out-of-band `'error'` event. Attaching\n // it prevents Node's uncaught-`'error'` crash on the detached gRPC tick. It\n // flags the writer broken (so the next push self-heals or DLQs in-band) and\n // routes the error through the Task-2 ORPHAN reportError seam (no event):\n // a redacted, ring-tapped log plus a connection-error counter bump. MUST\n // NOT throw (detached emitter tick).\n const onConnectionError = (err: unknown): void => {\n settings.writerBroken = true;\n settings.lastStreamError =\n err instanceof Error ? err : new Error(String(err));\n reportError?.(err);\n };\n\n // Lazy re-open hook used by ensureWriter on the push path to self-heal a\n // broken writer. Closes over the openWriter args + onConnectionError so the\n // fresh connection carries the same containment handler. The reused args\n // (projectId/datasetId/tableId/bigquery/timeout) are immutable post-init, so\n // a re-open targets the same table with the same auth and unary-call\n // deadline.\n settings.reopenWriter = () =>\n openWriter(\n {\n projectId: settings.projectId,\n datasetId: settings.datasetId,\n tableId: settings.tableId,\n credentials: settings.credentials,\n bigquery: settings.bigquery,\n timeout,\n onConnectionError,\n env,\n },\n logger,\n );\n\n // Open the long-lived JSONWriter on the _default stream.\n // Hard-fail when the dataset/table is missing.\n try {\n const { writer, writeClient, connection, connectionErrorListener } =\n await openWriter(\n {\n projectId: settings.projectId,\n datasetId: settings.datasetId,\n tableId: settings.tableId,\n credentials: settings.credentials,\n bigquery: settings.bigquery,\n timeout,\n onConnectionError,\n env,\n },\n logger,\n );\n settings.writer = writer;\n settings.writeClient = writeClient;\n settings.connection = connection;\n settings.connectionErrorListener = connectionErrorListener;\n } catch (err) {\n // Log the failure and rethrow the raw error. Secret redaction is\n // standardized at the CLI logger handler, which scrubs every line before\n // both stderr and the heartbeat ring, so the destination logs the message\n // as-is. The raw error keeps its `code` naturally, so it stays\n // NotFound-classifiable and DLQ-routable.\n const message = err instanceof Error ? err.message : String(err);\n if (isNotFound(err)) {\n const target = `${config.settings.datasetId}.${config.settings.tableId}`;\n const project = config.settings.projectId;\n logger.error(\n `BigQuery dataset or table not found: project=\"${project}\", target=\"${target}\". ` +\n `Run \"walkeros setup destination.${id}\" to create them.`,\n {\n project,\n target,\n error: message,\n },\n );\n } else {\n // Catch-all so init failures are never silent. The destination is the\n // layer with the most context about what was attempted (open writer,\n // resolve stream, build proto descriptor), so it logs here before\n // re-throwing.\n logger.error('BigQuery init failed', {\n error: message,\n });\n }\n throw err;\n }\n\n return config;\n },\n\n async push(event, context) {\n return await push(event, context);\n },\n\n pushBatch,\n\n async destroy({ config, logger }) {\n if (!config.settings) return;\n closeWriter(\n {\n writer: config.settings.writer,\n writeClient: config.settings.writeClient,\n connectionErrorListener: config.settings.connectionErrorListener,\n },\n logger,\n );\n },\n};\n\n// Type predicate for NOT_FOUND-class errors. The Storage Write API surfaces\n// missing datasets/tables as gRPC code 5 (NOT_FOUND) or HTTP 404.\nfunction isNotFound(err: unknown): boolean {\n if (typeof err !== 'object' || err === null) return false;\n if (!('code' in err)) return false;\n const obj: { code?: unknown } = err;\n // gRPC NOT_FOUND = 5; REST = 404\n return obj.code === 5 || obj.code === 404;\n}\n\nexport default destinationBigQuery;\n","import type { PushFn, Mapping, Settings } from './types';\nimport type { Mapping as WalkerOSMapping, Collector } from '@walkeros/core';\nimport { getMappingValue, isObject } from '@walkeros/core';\n\nconst NOT_FOUND_GRPC = 5;\nconst NOT_FOUND_HTTP = 404;\nconst PERMISSION_DENIED_GRPC = 7;\nconst UNAUTHENTICATED_GRPC = 16;\nconst PERMISSION_DENIED_HTTP = 403;\nconst UNAUTHENTICATED_HTTP = 401;\n\ninterface ErrorWithCode {\n code: number;\n}\n\nfunction hasNumericCode(err: unknown): err is ErrorWithCode {\n if (typeof err !== 'object' || err === null) return false;\n if (!('code' in err)) return false;\n const obj: { code?: unknown } = err;\n return typeof obj.code === 'number';\n}\n\nfunction isNotFound(err: unknown): boolean {\n return (\n hasNumericCode(err) &&\n (err.code === NOT_FOUND_GRPC || err.code === NOT_FOUND_HTTP)\n );\n}\n\nfunction isPermissionError(err: unknown): boolean {\n return (\n hasNumericCode(err) &&\n (err.code === PERMISSION_DENIED_GRPC ||\n err.code === UNAUTHENTICATED_GRPC ||\n err.code === PERMISSION_DENIED_HTTP ||\n err.code === UNAUTHENTICATED_HTTP)\n );\n}\n\ninterface AttributesShape {\n [key: string]: string;\n}\n\nfunction isStringRecord(value: unknown): value is AttributesShape {\n if (!isObject(value)) return false;\n const candidate: Record<string, unknown> = value;\n for (const key of Object.keys(candidate)) {\n if (typeof candidate[key] !== 'string') return false;\n }\n return true;\n}\n\nasync function resolveAttributes(\n event: Parameters<PushFn>[0],\n base: WalkerOSMapping.Map | undefined,\n override: WalkerOSMapping.Map | undefined,\n collector: Collector.Instance,\n): Promise<AttributesShape | undefined> {\n const result: AttributesShape = {};\n let touched = false;\n\n if (base) {\n for (const [key, value] of Object.entries(base)) {\n const resolved = await getMappingValue(event, value, { collector });\n if (typeof resolved === 'string') {\n result[key] = resolved;\n touched = true;\n } else if (resolved !== undefined && resolved !== null) {\n result[key] = String(resolved);\n touched = true;\n }\n }\n }\n\n if (override) {\n for (const [key, value] of Object.entries(override)) {\n const resolved = await getMappingValue(event, value, { collector });\n if (typeof resolved === 'string') {\n result[key] = resolved;\n touched = true;\n } else if (resolved !== undefined && resolved !== null) {\n result[key] = String(resolved);\n touched = true;\n }\n }\n }\n\n return touched ? result : undefined;\n}\n\nfunction isResolvedSettings(value: unknown): value is Settings {\n if (typeof value !== 'object' || value === null) return false;\n const candidate: { client?: unknown; projectId?: unknown; topic?: unknown } =\n value;\n return (\n candidate.client !== undefined &&\n typeof candidate.projectId === 'string' &&\n candidate.projectId.length > 0 &&\n typeof candidate.topic === 'string' &&\n candidate.topic.length > 0\n );\n}\n\nfunction isMapping(value: unknown): value is Mapping {\n return typeof value === 'object' && value !== null;\n}\n\nexport const push: PushFn = async function (\n event,\n { config, rule, data, collector, logger, id },\n) {\n const settings = config.settings;\n if (!isResolvedSettings(settings)) {\n return logger.throw('settings missing or incomplete, init() not run');\n }\n\n const { client, projectId, topic: defaultTopic } = settings;\n\n const ruleSettings: Mapping = isMapping(rule?.settings) ? rule.settings : {};\n\n const topicName =\n typeof ruleSettings.topic === 'string' && ruleSettings.topic.length > 0\n ? ruleSettings.topic\n : defaultTopic;\n\n // Resolve ordering key: per-rule overrides settings default. Both are\n // Mapping.Value resolved against the event.\n const orderingValue =\n ruleSettings.orderingKey !== undefined\n ? ruleSettings.orderingKey\n : settings.orderingKey;\n let orderingKey: string | undefined;\n if (orderingValue !== undefined) {\n const resolved = await getMappingValue(event, orderingValue, { collector });\n if (typeof resolved === 'string' && resolved.length > 0) {\n orderingKey = resolved;\n } else if (resolved !== undefined && resolved !== null) {\n orderingKey = String(resolved);\n }\n }\n\n // Topic handle is constructed inline. Setting messageOrdering on the\n // topic options enables per-key ordering for this publish.\n const topicHandle = client.topic(topicName, {\n messageOrdering: Boolean(orderingKey),\n });\n\n // Serialize the publish body: mapped data wins over the raw event.\n const body = isObject(data) && Object.keys(data).length > 0 ? data : event;\n const payload = Buffer.from(JSON.stringify(body));\n\n // Merge attributes: settings default + per-rule overrides.\n const baseAttrs = settings.attributes;\n const ruleAttrs = ruleSettings.attributes;\n const attributes = await resolveAttributes(\n event,\n baseAttrs,\n ruleAttrs,\n collector,\n );\n\n const message: {\n data: Buffer;\n attributes?: AttributesShape;\n orderingKey?: string;\n } = { data: payload };\n if (attributes && isStringRecord(attributes)) message.attributes = attributes;\n if (orderingKey) message.orderingKey = orderingKey;\n\n logger.debug('Pub/Sub publish', {\n topic: topicName,\n projectId,\n orderingKey,\n event: event.name,\n });\n\n try {\n await topicHandle.publishMessage(message);\n } catch (err) {\n // When a publish fails for an ordered key, the SDK halts subsequent\n // publishes for that key until resumePublishing is called. Resume\n // immediately so the next event for the same key is not blocked.\n if (orderingKey) {\n try {\n topicHandle.resumePublishing(orderingKey);\n } catch (resumeErr) {\n logger.debug('Pub/Sub resumePublishing failed', {\n orderingKey,\n error:\n resumeErr instanceof Error ? resumeErr.message : String(resumeErr),\n });\n }\n }\n\n if (isNotFound(err)) {\n logger.error(\n `Pub/Sub topic \"${topicName}\" not found in project \"${projectId}\". ` +\n `Run \"walkeros setup destination.${id}\" to create it.`,\n {\n topic: topicName,\n projectId,\n error: err instanceof Error ? err.message : String(err),\n },\n );\n } else if (isPermissionError(err)) {\n logger.error(\n `Pub/Sub publish denied for topic \"${topicName}\". Grant the runtime ` +\n `service account roles/pubsub.publisher on this topic.`,\n {\n topic: topicName,\n projectId,\n error: err instanceof Error ? err.message : String(err),\n },\n );\n } else {\n logger.error('Pub/Sub publish failed', {\n topic: topicName,\n projectId,\n event: event.name,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n throw err;\n }\n};\n","import type { DestinationServer } from '@walkeros/server-core';\nimport type { Env, Setup, Types } from './types';\nimport type { LifecycleContext, Logger } from '@walkeros/core';\nimport { resolveSetup } from '@walkeros/core';\nimport { parseCredentials, resolveCredentials } from './config';\nimport {\n PubSub,\n type PubSub as PubSubClient,\n type Topic,\n type TopicMetadata,\n} from '@google-cloud/pubsub';\n\n// Setup is wired to the destination's `setup` slot which uses the broader\n// `DestinationServer.Config<Types>` (settings is optional). We runtime-narrow\n// instead of using the local Config alias so the assignment in index.ts\n// type-checks without contravariance issues.\ntype WideConfig = DestinationServer.Config<Types>;\n\nconst NOT_FOUND_GRPC = 5;\nconst NOT_FOUND_HTTP = 404;\nconst ALREADY_EXISTS_GRPC = 6;\nconst ALREADY_EXISTS_HTTP = 409;\n\n// GCP region names accepted by Pub/Sub's messageStoragePolicy.allowedPersistenceRegions.\n// These are the canonical full names (e.g. 'europe-west1'), NOT the colloquial\n// abbreviations 'eu-west1' that the API rejects with INVALID_ARGUMENT.\nexport const DEFAULT_SETUP: Required<Pick<Setup, 'messageStoragePolicy'>> &\n Omit<Setup, 'messageStoragePolicy'> = {\n messageStoragePolicy: {\n allowedPersistenceRegions: ['europe-west1', 'europe-west3', 'europe-west4'],\n },\n};\n\nexport interface SetupResult {\n topicCreated: boolean;\n}\n\nfunction hasNumericCode(err: unknown): err is { code: number } {\n if (typeof err !== 'object' || err === null) return false;\n if (!('code' in err)) return false;\n const obj: { code?: unknown } = err;\n return typeof obj.code === 'number';\n}\n\nexport function isAlreadyExists(err: unknown): boolean {\n return (\n hasNumericCode(err) &&\n (err.code === ALREADY_EXISTS_GRPC || err.code === ALREADY_EXISTS_HTTP)\n );\n}\n\nexport function isNotFound(err: unknown): boolean {\n return (\n hasNumericCode(err) &&\n (err.code === NOT_FOUND_GRPC || err.code === NOT_FOUND_HTTP)\n );\n}\n\nexport async function setup(\n ctx: LifecycleContext<WideConfig, Env>,\n): Promise<SetupResult | undefined> {\n const { config, logger } = ctx;\n const merged = resolveSetup(config.setup, DEFAULT_SETUP);\n if (!merged) {\n logger.debug('setup: skipped (config.setup is false or unset)');\n return;\n }\n\n const settings = config.settings;\n if (!settings) {\n logger.throw('setup: settings missing');\n return;\n }\n const projectId =\n typeof settings.projectId === 'string' ? settings.projectId : '';\n const topicName = typeof settings.topic === 'string' ? settings.topic : '';\n if (!projectId) {\n logger.throw('setup: projectId is missing');\n return;\n }\n if (!topicName) {\n logger.throw('setup: topic is missing');\n return;\n }\n\n // Resolve the client. Prefer a pre-supplied SDK client; otherwise build one.\n // Setup needs the SDK's admin surface (exists, createTopic, metadata), which\n // an injected publisher (tests, simulate) does not carry. Track whether\n // setup created the client so we close only what we own.\n let createdClient = false;\n let client: PubSubClient | undefined =\n settings.client instanceof PubSub ? settings.client : undefined;\n if (settings.client && !client) {\n logger.debug(\n 'setup: settings.client is not a Pub/Sub SDK client; creating one for provisioning',\n );\n }\n if (!client) {\n const credentials = parseCredentials(\n resolveCredentials(config, logger),\n logger,\n );\n const clientOptions = {\n projectId,\n ...(credentials !== undefined && typeof credentials !== 'string'\n ? { credentials }\n : {}),\n ...(settings.apiEndpoint ? { apiEndpoint: settings.apiEndpoint } : {}),\n };\n client = new PubSub(clientOptions);\n createdClient = true;\n }\n\n const topic = client.topic(topicName);\n\n let topicCreated = false;\n const [exists] = await topic.exists();\n if (!exists) {\n // Build the TopicMetadata payload. The SDK's `pubsub.createTopic(name |\n // metadata)` is the only path that actually applies messageStoragePolicy\n // and friends at creation time. `topic.create(opts)` accepts only\n // CallOptions and silently drops topic metadata.\n const metadata: TopicMetadata = {\n name: `projects/${projectId}/topics/${topicName}`,\n };\n if (merged.messageStoragePolicy)\n metadata.messageStoragePolicy = merged.messageStoragePolicy;\n if (merged.messageRetentionDuration)\n metadata.messageRetentionDuration = {\n seconds: merged.messageRetentionDuration.seconds,\n };\n if (merged.kmsKeyName) metadata.kmsKeyName = merged.kmsKeyName;\n if (merged.labels) metadata.labels = merged.labels;\n\n try {\n await client.createTopic(metadata);\n topicCreated = true;\n logger.info('setup: topic created', {\n topic: topicName,\n projectId,\n messageStoragePolicy: metadata.messageStoragePolicy,\n });\n } catch (err) {\n if (isAlreadyExists(err)) {\n logger.debug('setup: topic already exists (race)', {\n topic: topicName,\n });\n } else {\n if (createdClient) {\n await safeClose(client, logger);\n }\n throw err;\n }\n }\n } else {\n logger.debug('setup: topic exists', { topic: topicName });\n await detectDrift(topic, merged, logger);\n }\n\n if (createdClient) {\n await safeClose(client, logger);\n }\n\n return { topicCreated };\n}\n\nasync function safeClose(\n client: { close: () => Promise<void> },\n logger: Logger.Instance,\n): Promise<void> {\n try {\n await client.close();\n } catch (err) {\n logger.debug('setup: client.close failed (non-fatal)', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n}\n\nasync function detectDrift(\n topic: Topic,\n declared: Setup,\n logger: Logger.Instance,\n): Promise<void> {\n let metadata: TopicMetadata;\n try {\n const [meta] = await topic.getMetadata();\n metadata = meta ?? {};\n } catch (err) {\n logger.debug('setup: drift check failed (non-fatal)', {\n error: err instanceof Error ? err.message : String(err),\n });\n return;\n }\n\n // Storage policy drift\n if (declared.messageStoragePolicy) {\n const declaredRegions =\n declared.messageStoragePolicy.allowedPersistenceRegions;\n const actualRegions =\n metadata.messageStoragePolicy?.allowedPersistenceRegions ?? [];\n if (\n declaredRegions.length !== actualRegions.length ||\n declaredRegions.some((r, i) => r !== actualRegions[i])\n ) {\n logger.warn('setup.drift', {\n field: 'messageStoragePolicy.allowedPersistenceRegions',\n declared: declaredRegions,\n actual: actualRegions,\n });\n }\n }\n\n // Retention drift\n if (declared.messageRetentionDuration) {\n const declaredSeconds = declared.messageRetentionDuration.seconds;\n const actualRaw = metadata.messageRetentionDuration?.seconds;\n const actualSeconds =\n typeof actualRaw === 'number'\n ? actualRaw\n : typeof actualRaw === 'string'\n ? Number(actualRaw)\n : undefined;\n if (actualSeconds !== declaredSeconds) {\n logger.warn('setup.drift', {\n field: 'messageRetentionDuration.seconds',\n declared: declaredSeconds,\n actual: actualSeconds ?? null,\n });\n }\n }\n\n // KMS key drift\n if (declared.kmsKeyName !== undefined) {\n if (metadata.kmsKeyName !== declared.kmsKeyName) {\n logger.warn('setup.drift', {\n field: 'kmsKeyName',\n declared: declared.kmsKeyName,\n actual: metadata.kmsKeyName ?? null,\n });\n }\n }\n\n // Labels drift (granular per key)\n if (declared.labels) {\n const actualLabels = metadata.labels ?? {};\n for (const [key, declaredValue] of Object.entries(declared.labels)) {\n const actualValue = actualLabels[key];\n if (actualValue !== declaredValue) {\n logger.warn('setup.drift', {\n field: `labels.${key}`,\n declared: declaredValue,\n actual: actualValue ?? null,\n });\n }\n }\n }\n}\n","import type {\n Mapping as WalkerOSMapping,\n Destination as CoreDestination,\n SetupFn as CoreSetupFn,\n Credential,\n ServiceAccount,\n} from '@walkeros/core';\nimport type { DestinationServer } from '@walkeros/server-core';\nimport type { ClientConfig, TopicMetadata } from '@google-cloud/pubsub';\n\nexport interface ServiceAccountCredentials {\n client_email: string;\n private_key: string;\n project_id?: string;\n}\n\n/** Credentials value for this destination: JSON string or service account object. */\nexport type Credentials = Credential<ServiceAccount>;\n\n/** The message `push` publishes. */\nexport interface PublishMessage {\n data: Buffer;\n attributes?: Record<string, string>;\n orderingKey?: string;\n}\n\n/** The part of a Pub/Sub topic handle `push` calls. */\nexport interface TopicPublisher {\n publishMessage(message: PublishMessage): Promise<string>;\n resumePublishing(orderingKey: string): void;\n}\n\n/**\n * The part of the Pub/Sub client `init`, `push` and `destroy` call. The SDK's\n * `PubSub` satisfies it, and so does an injected mock (tests, simulate)\n * without a cast. `setup` needs the admin surface and uses the SDK client.\n */\nexport interface PubSubPublisher {\n topic(name: string, options?: { messageOrdering?: boolean }): TopicPublisher;\n close(): Promise<void>;\n}\n\nexport interface Settings {\n // User-supplied OR populated by init(); single field for both. Mirrors BigQuery.\n client: PubSubPublisher;\n // Top-level always wins over credentials.project_id (documented in config.ts).\n projectId: string;\n topic: string;\n /** @deprecated use config.credentials */\n credentials?: string | ServiceAccountCredentials;\n // SDK term, kept verbatim.\n apiEndpoint?: string;\n // Mapping value resolved per-event. Undefined = no ordering. Truthy = ordering enabled.\n orderingKey?: WalkerOSMapping.Value;\n // Dynamic per-event attributes.\n attributes?: WalkerOSMapping.Map;\n}\n\nexport interface InitSettings {\n projectId: string;\n topic: string;\n client?: PubSubPublisher;\n /** @deprecated use config.credentials */\n credentials?: string | ServiceAccountCredentials;\n apiEndpoint?: string;\n orderingKey?: WalkerOSMapping.Value;\n attributes?: WalkerOSMapping.Map;\n}\n\nexport interface Mapping {\n topic?: string;\n orderingKey?: WalkerOSMapping.Value;\n // Per-rule attributes are merged on top of settings.attributes.\n attributes?: WalkerOSMapping.Map;\n}\n\n/**\n * Provisioning options for `walkeros setup destination.<id>`.\n * Triggered only by the explicit CLI command. Idempotent, never auto-run.\n *\n * `projectId` and `topic` are read from `Settings` (not duplicated here)\n * so a single source of truth governs both setup and runtime publish.\n *\n * Subscription provisioning is owned by the source side, not here.\n */\nexport interface Setup {\n /** Geographic regions for at-rest storage. Default: EU multi-region (['eu-west1','eu-west3','eu-west4']). */\n messageStoragePolicy?: { allowedPersistenceRegions: string[] };\n /** Topic-level retention. Default: undefined (project default). */\n messageRetentionDuration?: { seconds: number };\n /** CMEK key. Optional. */\n kmsKeyName?: string;\n /** Topic labels. Optional. */\n labels?: Record<string, string>;\n}\n\nexport interface Env extends DestinationServer.Env {\n PubSub?: new (options?: ClientConfig) => PubSubPublisher;\n}\n\nexport type Types = CoreDestination.Types<\n Settings,\n Mapping,\n Env,\n InitSettings,\n Setup,\n Credentials\n>;\n\nexport interface Destination extends DestinationServer.Destination<Types> {\n init: DestinationServer.InitFn<Types>;\n}\n\nexport type Config = {\n settings: Settings;\n} & DestinationServer.Config<Types>;\n\nexport type InitFn = DestinationServer.InitFn<Types>;\nexport type PushFn = DestinationServer.PushFn<Types>;\nexport type SetupFn = CoreSetupFn<Config, Env>;\n\nexport type PartialConfig = DestinationServer.PartialConfig<Types>;\n\n// Re-export SDK types used across the package for convenience.\nexport type { TopicMetadata };\n","import type { Destination } from './types';\nimport { getConfig } from './config';\nimport { push } from './push';\nimport { setup } from './setup';\n\n// Types re-export\nexport * as DestinationPubSub from './types';\n\nexport const destinationPubSub: Destination = {\n type: 'gcp-pubsub',\n\n config: {},\n\n setup,\n\n async init({ config: partialConfig, env, logger }) {\n return getConfig(partialConfig, env, logger);\n },\n\n async push(event, context) {\n return await push(event, context);\n },\n\n async destroy({ config }) {\n if (!config.settings) return;\n const { client } = config.settings;\n if (!client) return;\n try {\n await client.close();\n } catch {\n // Closing flushes outstanding publishes; swallow errors so a flush\n // failure does not leak the client. Detailed publish errors are\n // already surfaced by push().\n }\n },\n};\n\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S,UAAU,CAAC;AACzC,eAAW,CAAC,KAAK,aAAa,KAAK,OAAO,QAAQ,SAAS,MAAM,GAAG;AAClE,YAAM,cAAc,aAAa,GAAG;AACpC,UAAI,gBAAgB,eAAe;AACjC,eAAO,KAAK,eAAe;AAAA,UACzB,OAAO,UAAU,GAAG;AAAA,UACpB,UAAU;AAAA,UACV,QAAQ,eAAe;AAAA,QACzB,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF;;;ACjQA,IAAAC,iBAAA;;;ACQO,IAAM,oBAAiC;AAAA,EAC5C,MAAM;AAAA,EAEN,QAAQ,CAAC;AAAA,EAET,OAAAC;AAAA,EAEA,MAAM,KAAK,EAAE,QAAQ,eAAe,KAAK,OAAO,GAAG;AACjD,WAAO,UAAU,eAAe,KAAK,MAAM;AAAA,EAC7C;AAAA,EAEA,MAAM,KAAK,OAAO,SAAS;AACzB,WAAO,MAAMC,MAAK,OAAO,OAAO;AAAA,EAClC;AAAA,EAEA,MAAM,QAAQ,EAAE,OAAO,GAAG;AACxB,QAAI,CAAC,OAAO,SAAU;AACtB,UAAM,EAAE,OAAO,IAAI,OAAO;AAC1B,QAAI,CAAC,OAAQ;AACb,QAAI;AACF,YAAM,OAAO,MAAM;AAAA,IACrB,QAAQ;AAAA,IAIR;AAAA,EACF;AACF;","names":["getConfig","isObject","isObject","isObject","isObject","getConfig","isObject","isNotFound","push","resolveSetup","PubSub","DEFAULT_SETUP","hasNumericCode","isAlreadyExists","setup","resolveSetup","DEFAULT_SETUP","PubSub","isAlreadyExists","detectDrift","types_exports","setup","push"]}
|
|
1
|
+
{"version":3,"sources":["../src/bigquery/index.ts","../src/bigquery/config.ts","../src/pubsub/config.ts","../src/bigquery/push.ts","../src/bigquery/eventToRow.ts","../src/bigquery/writer.ts","../src/bigquery/pushBatch.ts","../src/bigquery/setup.ts","../src/bigquery/types/index.ts","../src/pubsub/push.ts","../src/pubsub/setup.ts","../src/pubsub/types/index.ts","../src/pubsub/index.ts"],"sourcesContent":["import type { Destination, Settings } from './types';\nimport { StepError } from '@walkeros/core';\nimport { getConfig } from './config';\nimport { push } from './push';\nimport { pushBatch } from './pushBatch';\nimport { setup } from './setup';\nimport { openWriter, closeWriter } from './writer';\n\n// Types\nexport * as DestinationBigQuery from './types';\n\n// Timeout layering (who owns which bound):\n// - The COLLECTOR bounds every delivery: it races each push/pushBatch at\n// config.timeout (default 10s, packages/collector/src/destination.ts) and\n// converts a hung delivery into a counted DLQ failure. That is the\n// per-operation protection.\n// - This DESTINATION owns the connection lifecycle: broken-writer detection\n// via the connection 'error' listener, one lazy re-open on the next push\n// (ensureWriter), collapsed across concurrent pushes.\n// - The gax deadline below bounds UNARY control-plane calls only (the\n// getWriteStream schema fetch during open/re-open). It is never applied to\n// the appendRows bidi stream: a deadline there bounds the stream's total\n// lifetime and would kill a healthy connection on expiry. The stream keeps\n// the SDK's own long-lived AppendRows default.\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\nexport const destinationBigQuery: Destination = {\n type: 'gcp-bigquery',\n\n config: {},\n\n setup,\n\n async init({ config: partialConfig, env, logger, id, reportError }) {\n const config = getConfig(partialConfig, env, logger);\n\n // Deadline for unary control-plane calls, derived from the standard\n // per-step config.timeout (the same value the collector uses to race the\n // push). A positive number wins; 0/unset falls back to the default.\n const timeout =\n config.timeout && config.timeout > 0\n ? config.timeout\n : DEFAULT_TIMEOUT_MS;\n\n const { settings } = config;\n\n // Handler for the StreamConnection's out-of-band `'error'` event. Attaching\n // it prevents Node's uncaught-`'error'` crash on the detached gRPC tick. It\n // flags the writer broken (so the next push self-heals or DLQs in-band) and\n // routes the error through the Task-2 ORPHAN reportError seam (no event):\n // a redacted, ring-tapped log plus a connection-error counter bump. MUST\n // NOT throw (detached emitter tick).\n const onConnectionError = (err: unknown): void => {\n settings.writerBroken = true;\n settings.lastStreamError =\n err instanceof Error ? err : new Error(String(err));\n reportError?.(err);\n };\n\n // Lazy re-open hook used by ensureWriter on the push path to self-heal a\n // broken writer. Closes over the openWriter args + onConnectionError so the\n // fresh connection carries the same containment handler. The reused args\n // (projectId/datasetId/tableId/bigquery/timeout) are immutable post-init, so\n // a re-open targets the same table with the same auth and unary-call\n // deadline.\n //\n // The same hook opens the writer at the first push, so init stays\n // offline: a missing dataset or table, or a failed connection, fails that\n // push with a StepError the collector reports.\n settings.reopenWriter = () =>\n openWriter(\n {\n projectId: settings.projectId,\n datasetId: settings.datasetId,\n tableId: settings.tableId,\n credentials: settings.credentials,\n bigquery: settings.bigquery,\n timeout,\n onConnectionError,\n env,\n },\n logger,\n ).catch((err: unknown) => {\n throw openError(err, settings, id);\n });\n\n return config;\n },\n\n async push(event, context) {\n return await push(event, context);\n },\n\n pushBatch,\n\n async destroy({ config, logger }) {\n if (!config.settings) return;\n closeWriter(\n {\n writer: config.settings.writer,\n writeClient: config.settings.writeClient,\n connectionErrorListener: config.settings.connectionErrorListener,\n },\n logger,\n );\n },\n};\n\n/**\n * A failed writer open as a StepError: a missing dataset or table is a setup\n * step the operator has to run (not retryable), anything else a connection\n * failure. The SDK's own error stays the cause.\n */\nfunction openError(err: unknown, settings: Settings, id: string): StepError {\n if (isNotFound(err))\n return new StepError(\n `BigQuery dataset or table not found: project=\"${settings.projectId}\", ` +\n `target=\"${settings.datasetId}.${settings.tableId}\". ` +\n `Run \"walkeros setup destination.${id}\" to create them.`,\n { code: 'config', cause: err },\n );\n return new StepError('BigQuery writer could not be opened', {\n code: 'transport',\n cause: err,\n });\n}\n\n// Type predicate for NOT_FOUND-class errors. The Storage Write API surfaces\n// missing datasets/tables as gRPC code 5 (NOT_FOUND) or HTTP 404.\nfunction isNotFound(err: unknown): boolean {\n if (typeof err !== 'object' || err === null) return false;\n if (!('code' in err)) return false;\n const obj: { code?: unknown } = err;\n // gRPC NOT_FOUND = 5; REST = 404\n return obj.code === 5 || obj.code === 404;\n}\n\nexport default destinationBigQuery;\n","import type { Config, Env, PartialConfig, Settings } from './types';\nimport type { BigQueryOptions } from '@google-cloud/bigquery';\nimport type { Logger } from '@walkeros/core';\nimport { StepError } from '@walkeros/core';\nimport { BigQuery } from '@google-cloud/bigquery';\nimport { parseCredentials } from '../pubsub/config';\n\nexport function getConfig(\n partialConfig: PartialConfig = {},\n env: Env | undefined,\n logger: Logger.Instance,\n): Config {\n const settings: Partial<Settings> = partialConfig.settings || {};\n const { projectId, bigquery } = settings;\n let { client, location, datasetId, tableId } = settings;\n\n if (!projectId)\n throw new StepError('Config settings projectId missing', {\n code: 'config',\n });\n\n location = location || 'EU';\n datasetId = datasetId || 'walkerOS';\n tableId = tableId || 'events';\n\n const options: BigQueryOptions = { ...(bigquery || {}) };\n options.projectId = projectId;\n\n // `config.credentials` (parse-if-string) merges into the client options.\n // `settings.bigquery` stays the raw passthrough escape hatch.\n const parsed = parseCredentials(partialConfig.credentials);\n // parseCredentials returns the object form (or undefined); an invalid JSON\n // string throws a config StepError.\n const credentials =\n parsed !== undefined && typeof parsed !== 'string' ? parsed : undefined;\n if (credentials !== undefined) {\n options.credentials = credentials;\n }\n\n // Use BigQuery from env if available, otherwise use real BigQuery\n const BigQueryClass: NonNullable<Env['BigQuery']> = env?.BigQuery || BigQuery;\n client = client || new BigQueryClass(options);\n\n const settingsConfig: Settings = {\n ...settings,\n client,\n projectId,\n location,\n datasetId,\n tableId,\n // Stored so init() can thread the same SA to the Storage Write client.\n ...(credentials !== undefined ? { credentials } : {}),\n };\n\n return { ...partialConfig, settings: settingsConfig };\n}\n","import type {\n Config,\n Credentials,\n Env,\n PartialConfig,\n ServiceAccountCredentials,\n Settings,\n} from './types';\nimport type { Logger } from '@walkeros/core';\nimport { isObject, StepError } from '@walkeros/core';\nimport { PubSub } from '@google-cloud/pubsub';\n\ninterface ResolvedClientConfig {\n projectId: string;\n credentials?: ServiceAccountCredentials;\n apiEndpoint?: string;\n}\n\ninterface PartialPubSubSettings {\n client?: Settings['client'];\n projectId?: unknown;\n topic?: unknown;\n credentials?: Settings['credentials'];\n apiEndpoint?: Settings['apiEndpoint'];\n orderingKey?: Settings['orderingKey'];\n attributes?: Settings['attributes'];\n}\n\n/**\n * Validate and normalize the partial config into a runtime Config.\n *\n * Project ID precedence: when both `settings.projectId` and\n * `credentials.project_id` are set, the top-level `settings.projectId` wins.\n * This keeps the runtime publish target unambiguous.\n *\n * Mirrors BigQuery's getConfig: the env-injected (or default SDK) client\n * is constructed here so `Settings.client` is always populated before\n * push/destroy run.\n */\nexport function getConfig(\n partialConfig: PartialConfig = {},\n env: Env | undefined,\n logger: Logger.Instance,\n): Config {\n const empty: PartialPubSubSettings = {};\n const settings: PartialPubSubSettings = partialConfig.settings ?? empty;\n const projectId =\n typeof settings.projectId === 'string' ? settings.projectId : '';\n const topic = typeof settings.topic === 'string' ? settings.topic : '';\n\n if (!projectId || !topic) {\n const missing = [\n ...(projectId ? [] : ['projectId']),\n ...(topic ? [] : ['topic']),\n ];\n throw new StepError(`Config settings ${missing.join(', ')} missing`, {\n code: 'config',\n });\n }\n\n const credentials = parseCredentials(\n resolveCredentials(partialConfig, logger),\n );\n\n // Build the client once: prefer pre-supplied settings.client, then env-\n // injected constructor (tests/DI), then the real SDK.\n let client = settings.client;\n if (!client) {\n const Constructor = env?.PubSub ?? PubSub;\n const clientOptions = buildClientOptions({\n projectId,\n credentials,\n apiEndpoint: settings.apiEndpoint,\n });\n client = new Constructor(clientOptions);\n }\n\n const settingsConfig: Settings = {\n ...settings,\n client,\n projectId,\n topic,\n credentials,\n };\n\n return { ...partialConfig, settings: settingsConfig };\n}\n\n/**\n * Resolve credentials with precedence `config.credentials ?? settings.credentials`.\n *\n * Uses `??` (not `||`) so an explicitly-set empty value surfaces as a misconfig\n * rather than silently falling through. Warns once per instance when the\n * deprecated `settings.credentials` path supplies the value; this runs at the\n * init-time read site (`getConfig`), so no module-level once-flag is needed.\n */\nexport function resolveCredentials(\n partialConfig: PartialConfig,\n logger: Logger.Instance,\n): Credentials | undefined {\n if (partialConfig.credentials !== undefined) return partialConfig.credentials;\n const fromSettings = partialConfig.settings?.credentials;\n if (fromSettings !== undefined) {\n logger.warn('settings.credentials is deprecated; use config.credentials');\n return fromSettings;\n }\n return undefined;\n}\n\nexport function parseCredentials(\n raw: Settings['credentials'],\n): Settings['credentials'] {\n if (raw === undefined) return undefined;\n if (typeof raw !== 'string') return raw;\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n throw new StepError('Invalid credentials JSON', {\n code: 'config',\n cause: err,\n });\n }\n if (!isServiceAccountCredentials(parsed))\n throw new StepError('Invalid credentials JSON', { code: 'config' });\n return parsed;\n}\n\nfunction isServiceAccountCredentials(\n value: unknown,\n): value is ServiceAccountCredentials {\n if (!isObject(value)) return false;\n const candidate: { client_email?: unknown; private_key?: unknown } = value;\n return (\n typeof candidate.client_email === 'string' &&\n typeof candidate.private_key === 'string'\n );\n}\n\n/**\n * Resolve the constructor options for `new PubSub(...)`.\n *\n * Returns undefined when a pre-built `settings.client` is set; the caller\n * uses that client directly without invoking the SDK constructor.\n */\nexport function resolveClientConfig(\n settings: Settings,\n): ResolvedClientConfig | undefined {\n if (settings.client) return undefined;\n return buildClientOptions({\n projectId: settings.projectId,\n credentials: settings.credentials,\n apiEndpoint: settings.apiEndpoint,\n });\n}\n\ninterface ClientOptionsInput {\n projectId: string;\n credentials?: Settings['credentials'];\n apiEndpoint?: string;\n}\n\nfunction buildClientOptions(input: ClientOptionsInput): ResolvedClientConfig {\n const result: ResolvedClientConfig = { projectId: input.projectId };\n if (\n input.credentials !== undefined &&\n typeof input.credentials !== 'string'\n ) {\n result.credentials = input.credentials;\n }\n if (input.apiEndpoint) result.apiEndpoint = input.apiEndpoint;\n return result;\n}\n\nexport function isPubSubEnv(env: unknown): env is Env {\n if (!isObject(env)) return false;\n const candidate: { PubSub?: unknown } = env;\n return (\n candidate.PubSub === undefined || typeof candidate.PubSub === 'function'\n );\n}\n","import type { PushFn } from './types';\nimport { isObject, StepError } from '@walkeros/core';\nimport { eventToRow } from './eventToRow';\nimport { appendError, ensureWriter } from './writer';\n\n// A silent rule has no row of its own: nothing to append.\nexport const push: PushFn = async function (event, context) {\n if (!context.rule?.silent) await append(event, context);\n};\n\nconst append: PushFn = async function (event, { config, data, logger }) {\n const settings = config.settings;\n if (!settings)\n throw new StepError('BigQuery settings missing, init() not run', {\n code: 'not-ready',\n });\n\n // Open the writer at the first push, or self-heal one that the connection's\n // `'error'` handler flagged broken: exactly one (re-)open attempt before\n // failing. A failed open throws, routing the event to the DLQ in-band\n // (instead of an out-of-band crash) and feeding the collector's\n // per-destination breaker. Breaker-gated: the collector does not call push\n // while the breaker is OPEN, so the open runs at most once per admitted\n // push, never in a loop.\n await ensureWriter(settings, logger);\n\n const { writer, datasetId, tableId } = settings;\n if (!writer)\n throw new StepError('BigQuery writer is missing', { code: 'not-ready' });\n\n const row = isObject(data) ? data : eventToRow(event);\n const rows = [row];\n\n logger.debug('Calling BigQuery Storage Write API', {\n dataset: datasetId,\n table: tableId,\n rowCount: rows.length,\n });\n\n let result;\n try {\n // `appendRows` answers synchronously; an injected writer (tests,\n // simulation) may answer with a promise, so its answer is awaited.\n const pending = await writer.appendRows(rows);\n result = await pending.getResult();\n } catch (err) {\n // The collector reports it and DLQ-routes the row; the SDK error (with\n // its `code`) stays the cause.\n throw new StepError('BigQuery row append threw', {\n code: 'transport',\n cause: err,\n });\n }\n\n // The server answered the append with an error status: nothing landed.\n const failed = appendError(result);\n if (failed) throw failed;\n\n if (result.rowErrors && result.rowErrors.length > 0)\n // The server rejected the row itself: a retry sends the same row. Its\n // message can quote the row, so only the code is named.\n throw new StepError(\n `BigQuery row append failed (code ${result.rowErrors[0].code})`,\n { code: 'transport', retryable: false },\n );\n\n logger.debug('BigQuery Storage Write API response', {\n ok: true,\n offset: result.appendResult?.offset?.value,\n });\n};\n","import type { WalkerOS } from '@walkeros/core';\n\n/** Row shape passed to JSONWriter.appendRows. Values are JSON-serializable scalars or strings. */\nexport interface BigQueryRow {\n [key: string]: string | number | null;\n name: string;\n data: string | null;\n context: string | null;\n globals: string | null;\n custom: string | null;\n user: string | null;\n nested: string | null;\n consent: string | null;\n id: string;\n trigger: string;\n entity: string;\n action: string;\n timestamp: number;\n timing: number;\n source: string | null;\n}\n\nfunction jsonOrNull(value: unknown): string | null {\n if (value === undefined || value === null) return null;\n if (typeof value === 'object') {\n if (Array.isArray(value) && value.length === 0) return null;\n if (!Array.isArray(value) && Object.keys(value).length === 0) return null;\n return JSON.stringify(value);\n }\n return JSON.stringify(value);\n}\n\n/** Convert a walkerOS Event v4 into a 15-column BigQuery row in canonical order.\n *\n * Note: BQ Storage Write API encodes TIMESTAMP fields as INT64 microseconds\n * since epoch (the SDK calls Long.fromString on the value). ISO strings fail\n * with \"interior hyphen\" because Long.fromString sees the date hyphens as\n * non-numeric. Pass microseconds directly.\n */\nexport function eventToRow(event: WalkerOS.Event): BigQueryRow {\n return {\n name: event.name,\n data: jsonOrNull(event.data),\n context: jsonOrNull(event.context),\n globals: jsonOrNull(event.globals),\n custom: jsonOrNull(event.custom),\n user: jsonOrNull(event.user),\n nested: jsonOrNull(event.nested),\n consent: jsonOrNull(event.consent),\n id: event.id,\n trigger: event.trigger,\n entity: event.entity,\n action: event.action,\n timestamp: new Date(event.timestamp).getTime() * 1000, // microseconds since epoch\n timing: event.timing,\n source: jsonOrNull(event.source),\n };\n}\n","import type { Logger, ServiceAccount } from '@walkeros/core';\nimport { StepError } from '@walkeros/core';\nimport type { BigQueryOptions } from '@google-cloud/bigquery';\nimport { managedwriter, adapt, protos } from '@google-cloud/bigquery-storage';\n\n// gax CallOptions, derived from the SDK's own method signature so we don't take\n// a direct dependency on `google-gax` (a transitive dep of bigquery-storage).\n// `getWriteStream(request, options?: CallOptions)` -> the optional 2nd param.\ntype CallOptions = NonNullable<\n Parameters<managedwriter.WriterClient['getWriteStream']>[1]\n>;\n\n// The SDK's StreamConnection instance returned by createStreamConnection.\n// Derived from the SDK method signature so we don't import the un-exported\n// StreamConnection class. The SDK kit's connection type.\nexport type StreamConnection = Awaited<\n ReturnType<managedwriter.WriterClient['createStreamConnection']>\n>;\n\n// SDK-derived shapes the structural types below speak in (types only).\ntype ClientOptions = NonNullable<\n ConstructorParameters<typeof managedwriter.WriterClient>[0]\n>;\ntype WriteStreamRequest = Parameters<\n managedwriter.WriterClient['getWriteStream']\n>[0];\ntype WriteStreamInfo = Awaited<\n ReturnType<managedwriter.WriterClient['getWriteStream']>\n>;\ntype TableSchema = NonNullable<WriteStreamInfo['tableSchema']>;\ntype ProtoDescriptor = ConstructorParameters<\n typeof managedwriter.JSONWriter\n>[0]['protoDescriptor'];\ntype RowList = Parameters<managedwriter.JSONWriter['appendRows']>[0];\ntype AppendResponse = Awaited<\n ReturnType<ReturnType<managedwriter.JSONWriter['appendRows']>['getResult']>\n>;\n\n/** The `{ off }` disposable returned by `onConnectionError`. */\nexport interface ConnectionListener {\n off(): void;\n}\n\n/** The connection surface the writer uses: its stream id and error hook. */\nexport interface WriteConnection {\n getStreamId(): string;\n onConnectionError(listener: (err: unknown) => void): ConnectionListener;\n}\n\n/** The fields of an append response that push and pushBatch read. */\nexport type AppendOutcome = Pick<\n AppendResponse,\n 'rowErrors' | 'appendResult' | 'error'\n>;\n\n/**\n * The gRPC statuses the Storage Write SDK retries itself (its stream\n * connection's `isRetryableError`): ABORTED, UNAVAILABLE, CANCELLED,\n * INTERNAL, DEADLINE_EXCEEDED.\n */\nconst RETRYABLE_STATUS = [10, 14, 1, 13, 4];\n\n/**\n * The failure of an append the server answered with an error status: a\n * quota, a dropped table, a lost permission. Nothing of it was written. The\n * status message can quote the rows, so only its code is named.\n */\nexport function appendError(outcome: AppendOutcome): StepError | undefined {\n if (!outcome.error) return undefined;\n const status = outcome.error.code ?? undefined;\n return new StepError(`BigQuery append failed (code ${status ?? 'unknown'})`, {\n code: 'transport',\n retryable: status !== undefined && RETRYABLE_STATUS.includes(status),\n });\n}\n\n/** The row writer surface push and pushBatch use. */\nexport interface RowWriter {\n appendRows(rows: RowList): { getResult(): Promise<AppendOutcome> };\n close(): void;\n}\n\n/** The Storage Write client surface the writer uses. */\nexport interface WriteClient<C extends WriteConnection> {\n createStreamConnection(request: {\n destinationTable: string;\n streamId: string;\n }): Promise<C>;\n getWriteStream(\n request: WriteStreamRequest,\n options?: CallOptions,\n ): Promise<{ tableSchema?: TableSchema | null }>;\n close(): void;\n}\n\n/** Converts the table schema into the writer's proto descriptor. */\nexport interface SchemaAdapter {\n convertStorageSchemaToProto2Descriptor(\n schema: TableSchema,\n scope: string,\n ): ProtoDescriptor;\n}\n\n/**\n * The three Storage Write pieces the writer is built from. The connection type\n * ties a kit's client to the SAME kit's JSONWriter: the SDK JSONWriter only\n * accepts the SDK's own StreamConnection.\n */\nexport interface WriterKit<C extends WriteConnection> {\n WriterClient: new (options: ClientOptions) => WriteClient<C>;\n JSONWriter: new (args: {\n connection: C;\n protoDescriptor: ProtoDescriptor;\n }) => RowWriter;\n adapt: SchemaAdapter;\n}\n\n/**\n * The Storage Write API pieces a destination env may inject (tests, simulate).\n * Without `WriterClient`, each missing piece falls back to the SDK, so runtime\n * needs none of them. An injected `WriterClient` needs an injected\n * `JSONWriter`: its connection cannot feed the SDK writer.\n */\nexport interface WriterEnv {\n WriterClient?: WriterKit<WriteConnection>['WriterClient'];\n JSONWriter?: WriterKit<WriteConnection>['JSONWriter'];\n adapt?: SchemaAdapter;\n}\n\nexport interface OpenWriterArgs {\n projectId: string;\n datasetId: string;\n tableId: string;\n /**\n * Service-account credentials resolved from `config.credentials`. Forwarded\n * to the data-plane WriterClient so event writes authenticate with the\n * configured SA instead of falling back to ADC (which has no metadata server\n * to query on non-GCP runtimes, e.g. Scaleway). When both this and a\n * `settings.bigquery.credentials` are set, `config.credentials` wins, matching\n * the query client's resolution in getConfig, so one destination always\n * authenticates as a single identity across both clients.\n */\n credentials?: ServiceAccount;\n // Raw passthrough auth/client options for the WriterClient (the escape hatch).\n bigquery?: BigQueryOptions;\n /**\n * Deadline in ms for unary control-plane calls (the getWriteStream schema\n * fetch), derived from the standard per-step `config.timeout`. Never applied\n * to the appendRows stream: a gax deadline on a bidi stream bounds the WHOLE\n * stream lifetime, not one append. Per-delivery bounds live in the collector\n * (it races every push at `config.timeout`); the stream stays on the SDK\n * default so it can live for hours.\n */\n timeout?: number;\n /**\n * Handler for the connection's out-of-band `'error'` event. Attaching it (by\n * mere presence) prevents Node's uncaught-`'error'` throw on the detached\n * gRPC tick that crashed the process; the destination wires it to flag the\n * writer broken and route the error through `context.reportError`. MUST NOT\n * throw (it runs on a detached emitter tick).\n */\n onConnectionError?: (err: unknown) => void;\n /** Injected SDK pieces (the destination env); the SDK is the fallback. */\n env?: WriterEnv;\n}\n\nexport interface WriterHandles {\n writeClient: WriteClient<WriteConnection>;\n writer: RowWriter;\n // The StreamConnection the writer appends to. Held so closeWriter can remove\n // the connection-error listener it owns.\n connection: WriteConnection;\n // The `{ off }` disposable for the connection-error listener, removed in\n // closeWriter so a re-opened writer doesn't accumulate stale listeners.\n connectionErrorListener?: ConnectionListener;\n}\n\n/**\n * Open a long-lived JSONWriter on the table's _default stream.\n * Requires the dataset and table to already exist (run `walkeros setup` first).\n *\n * The SDK pieces come from `args.env` when injected (tests, simulate), else\n * from `@google-cloud/bigquery-storage`. Without an injected `WriterClient`\n * the SDK kit is used, with an injected `JSONWriter`/`adapt` taking their\n * place when given. An injected `WriterClient` needs an injected `JSONWriter`\n * (the SDK writer only accepts the SDK's own connection); without one, init\n * fails and the injected client is closed.\n *\n * Sequence (per SDK docs and empirical SDK probe):\n * 1. new WriterClient\n * 2. createStreamConnection\n * 3. attach the connection-error listener (so a detached stream `'error'`\n * is contained instead of crashing the process)\n * 4. getWriteStream(view: FULL) to retrieve the table schema\n * 5. adapt.convertStorageSchemaToProto2Descriptor → protoDescriptor\n * 6. new JSONWriter({ connection, protoDescriptor })\n */\nexport function openWriter(\n args: OpenWriterArgs,\n logger: Logger.Instance,\n): Promise<WriterHandles> {\n const { env } = args;\n if (!env?.WriterClient) {\n const sdkKit: WriterKit<StreamConnection> = {\n WriterClient: managedwriter.WriterClient,\n JSONWriter: env?.JSONWriter ?? managedwriter.JSONWriter,\n adapt: env?.adapt ?? adapt,\n };\n return openWith(sdkKit, args, logger);\n }\n const envKit: WriterKit<WriteConnection> = {\n WriterClient: env.WriterClient,\n JSONWriter: env.JSONWriter ?? MissingJSONWriter,\n adapt: env.adapt ?? adapt,\n };\n return openWith(envKit, args, logger);\n}\n\nconst MISSING_JSON_WRITER =\n 'BigQuery env: an injected WriterClient needs an injected JSONWriter; its connection cannot feed the SDK writer.';\n\n// The env kit's JSONWriter when an env injects a WriterClient without one.\n// Building it fails, so openWith's cleanup closes the injected client.\nclass MissingJSONWriter implements RowWriter {\n constructor() {\n throw new Error(MISSING_JSON_WRITER);\n }\n appendRows(): { getResult(): Promise<AppendOutcome> } {\n throw new Error(MISSING_JSON_WRITER);\n }\n close(): void {}\n}\n\nasync function openWith<C extends WriteConnection>(\n { WriterClient, JSONWriter, adapt: adaptFn }: WriterKit<C>,\n args: OpenWriterArgs,\n logger: Logger.Instance,\n): Promise<WriterHandles> {\n const {\n projectId,\n datasetId,\n tableId,\n credentials,\n bigquery,\n timeout,\n onConnectionError,\n } = args;\n const destinationTable = `projects/${projectId}/datasets/${datasetId}/tables/${tableId}`;\n\n logger.debug('Opening BigQuery Storage Write API writer', {\n destinationTable,\n });\n\n // gax call options carrying the deadline for UNARY control-plane calls\n // (the getWriteStream schema fetch). Never passed to createStreamConnection:\n // a CallOptions.timeout on the appendRows bidi stream is the stream's TOTAL\n // deadline, killing a healthy connection when it expires. The stream keeps\n // the SDK's own long-lived default; individual deliveries are bounded by the\n // collector's per-push race (config.timeout), not by a transport deadline.\n // Left undefined when no timeout is configured.\n const callOptions: CallOptions | undefined =\n timeout === undefined ? undefined : { timeout };\n\n // The WriterClient takes google-gax ClientOptions, which extend\n // GoogleAuthOptions: `projectId` + `credentials` (a JWTInput, i.e.\n // { client_email, private_key, ... }), the same auth surface as\n // BigQueryOptions on the query client. Spread the resolved `config.credentials`\n // last so it wins over any `settings.bigquery.credentials`, mirroring the query\n // client's resolution in getConfig (one identity per destination).\n const writeClient = new WriterClient({\n projectId,\n ...bigquery,\n ...(credentials !== undefined ? { credentials } : {}),\n });\n let connectionErrorListener: ConnectionListener | undefined;\n let connection: C | undefined;\n try {\n // Use streamId (not streamType) so the SDK resolves to the table's\n // implicit `_default` stream without calling CreateWriteStream. Passing\n // managedwriter.DefaultStream as streamType triggers a CreateWriteStream\n // call with type='DEFAULT', which BQ rejects as TYPE_UNSPECIFIED.\n connection = await writeClient.createStreamConnection({\n destinationTable,\n streamId: managedwriter.DefaultStream,\n });\n\n // Attach the connection-error listener on the StreamConnection (NOT the\n // inner gRPC `_connection`) BEFORE building the JSONWriter, so any `'error'`\n // the connection emits has a listener from the first tick onward. Without a\n // listener, Node throws the emitted error as an uncaughtException on a\n // detached tick, bypassing the collector's promise-path try/catch (the\n // crash this handler exists to prevent). `onConnectionError` is the SDK's\n // documented surface and returns an `{ off }` disposable; it adds an\n // `'error'` listener under the hood.\n if (onConnectionError) {\n connectionErrorListener = connection.onConnectionError((err) => {\n onConnectionError(err);\n });\n }\n\n const streamId = connection.getStreamId();\n const writeStream = await writeClient.getWriteStream(\n {\n streamId,\n view: protos.google.cloud.bigquery.storage.v1.WriteStreamView.FULL,\n },\n callOptions,\n );\n if (!writeStream.tableSchema) {\n throw new Error(\n `BigQuery write stream ${streamId} returned no tableSchema; cannot build proto descriptor`,\n );\n }\n const protoDescriptor = adaptFn.convertStorageSchemaToProto2Descriptor(\n writeStream.tableSchema,\n 'root',\n );\n const writer = new JSONWriter({\n connection,\n protoDescriptor,\n });\n\n return { writeClient, writer, connection, connectionErrorListener };\n } catch (err) {\n // Release any resources already opened by the partial init so we don't\n // leak gRPC handles (including the connection-error listener). closeWriter\n // swallows close errors and only logs.\n closeWriter({ writeClient, connectionErrorListener }, logger);\n throw err;\n }\n}\n\n// Structural subset of Settings that ensureWriter reads/writes. Kept local so\n// writer.ts doesn't import the full Settings type (which imports back from here).\nexport interface EnsureWriterSettings {\n writer?: RowWriter;\n writeClient?: WriteClient<WriteConnection>;\n connection?: WriteConnection;\n connectionErrorListener?: ConnectionListener;\n writerBroken?: boolean;\n lastStreamError?: Error;\n reopenWriter?: () => Promise<WriterHandles>;\n reopenInFlight?: Promise<void>;\n}\n\n/**\n * Single owner of the writer lifecycle on the push path. The first push opens\n * the writer (init stays offline). When the connection's `'error'` handler has\n * flagged the writer broken, attempt a lazy re-open before failing:\n * - success: swap in the fresh handles, clear the broken flag, proceed.\n * - failure: stay broken, throw so the event is DLQ-routed.\n *\n * Self-heal is bounded along two independent axes:\n *\n * 1. ACROSS sequential passes, by the collector's breaker WITHOUT importing\n * `@walkeros/collector`: the skip gate does not call push while the breaker\n * is OPEN, admits exactly one probe when HALF-OPEN, and each failed re-open\n * throws (feeding the breaker's transport-failure accounting until it opens).\n * So once the breaker trips, no further re-opens are attempted.\n *\n * 2. WITHIN one pass, by the `reopenInFlight` memo. The breaker only opens\n * AFTER a pass records its failures, so in the first (most concurrent) pass\n * the breaker is still CLOSED and the collector fans the destination's\n * admitted events out with Promise.all. Without the memo, every concurrent\n * push would pass the `writerBroken` guard and each run its own\n * closeWriter+reopen, orphaning a gRPC connection + live 'error' listener\n * per redundant attempt. The memo collapses a concurrent burst into ONE\n * re-open that every caller awaits; a shared failure rejects into all of\n * them (each DLQ-routes correctly), and the memo clears in a finally so a\n * later push retries.\n *\n * A re-open's unary schema fetch is bounded by the gax CallOptions.timeout;\n * the re-open as a whole runs in-band on a push, under the collector's\n * per-delivery race. pushBatch shares this function, so it inherits both\n * bounds.\n */\nexport function ensureWriter(\n settings: EnsureWriterSettings,\n logger: Logger.Instance,\n): Promise<void> {\n const opening = !settings.writer;\n if (!opening && !settings.writerBroken) return Promise.resolve();\n\n // A concurrent caller already started the (re-)open: join it instead of\n // opening a second connection (which would orphan one of them).\n if (settings.reopenInFlight) return settings.reopenInFlight;\n\n const reopen = settings.reopenWriter;\n if (!reopen)\n // No open hook (init never wired it): cannot open or self-heal.\n return Promise.reject(\n new StepError('BigQuery writer is not initialized', {\n code: 'not-ready',\n }),\n );\n\n if (!opening)\n logger.info(\n 'BigQuery writer broken; attempting one re-open before failing',\n );\n\n const inFlight = (async () => {\n try {\n // Release the broken handles (incl. its connection-error listener) before\n // re-opening so we don't leak the old gRPC connection. Only the one\n // caller that started the memo runs this, so the old handles are closed\n // exactly once.\n closeWriter(\n {\n writer: settings.writer,\n writeClient: settings.writeClient,\n connectionErrorListener: settings.connectionErrorListener,\n },\n logger,\n );\n\n const handles = await reopen();\n settings.writeClient = handles.writeClient;\n settings.writer = handles.writer;\n settings.connection = handles.connection;\n settings.connectionErrorListener = handles.connectionErrorListener;\n settings.writerBroken = false;\n settings.lastStreamError = undefined;\n if (!opening)\n logger.info('BigQuery writer re-opened after a stream error');\n } finally {\n // Clear the memo so a later push after a FAILED re-open retries (on a\n // successful re-open writerBroken is already false, so the next push skips\n // ensureWriter entirely).\n settings.reopenInFlight = undefined;\n }\n })();\n\n settings.reopenInFlight = inFlight;\n return inFlight;\n}\n\n/** Close handles in safe order. Errors are logged, never thrown (called from destroy). */\nexport function closeWriter(\n handles: Partial<WriterHandles>,\n logger: Logger.Instance,\n): void {\n try {\n handles.connectionErrorListener?.off();\n } catch (err) {\n logger.warn('connection error listener removal failed', {\n error: String(err),\n });\n }\n try {\n handles.writer?.close();\n } catch (err) {\n logger.warn('writer.close failed', { error: String(err) });\n }\n try {\n handles.writeClient?.close();\n } catch (err) {\n logger.warn('writeClient.close failed', { error: String(err) });\n }\n}\n","import type { PushBatchFn } from './types';\nimport { isObject, StepError } from '@walkeros/core';\nimport { eventToRow } from './eventToRow';\nimport { appendError, ensureWriter } from './writer';\n\n/**\n * Batched push using a single appendRows call.\n *\n * Per-row failures (BigQuery's `rowErrors`) are reported back to the collector\n * as a BatchOutcome identifying the failed entries by index. The collector then\n * DLQs only those rows and counts the rest as delivered, so a later DLQ retry\n * does not re-write the already-succeeded rows (no duplicates). A whole-append\n * failure (the appendRows call itself rejects, or the writer cannot be opened)\n * still throws, routing the entire batch to the DLQ. The collector writes the\n * failure lines; this package writes none of its own.\n */\nexport const pushBatch: PushBatchFn = async (batch, { config, logger }) => {\n const settings = config.settings;\n if (!settings)\n throw new StepError('BigQuery settings missing, init() not run', {\n code: 'not-ready',\n });\n\n // A silent rule has no row of its own. Entry indexes stay those of the\n // flushed batch, which the collector maps failures back to.\n const sent = batch.entries.flatMap((entry, index) =>\n entry.rule?.silent ? [] : [{ entry, index }],\n );\n if (sent.length === 0) return;\n\n // Open the writer at the first push, or self-heal a broken one (one\n // re-open attempt) before failing. On a failed open this throws, routing the\n // WHOLE batch to the DLQ in-band and feeding the collector's\n // per-destination breaker. Breaker-gated by the collector, so the open runs\n // at most once per admitted batch.\n await ensureWriter(settings, logger);\n\n const { writer, datasetId, tableId } = settings;\n if (!writer)\n throw new StepError('BigQuery writer is missing', { code: 'not-ready' });\n\n const rows = sent.map(({ entry }) =>\n isObject(entry.data) ? entry.data : eventToRow(entry.event),\n );\n\n logger.debug('Calling BigQuery Storage Write API (batch)', {\n dataset: datasetId,\n table: tableId,\n rowCount: rows.length,\n });\n\n let result;\n try {\n // `appendRows` answers synchronously; an injected writer (tests,\n // simulation) may answer with a promise, so its answer is awaited.\n const pending = await writer.appendRows(rows);\n result = await pending.getResult();\n } catch (err) {\n // The whole batch routes to the DLQ; the collector reports it once.\n throw new StepError('BigQuery batch append threw', {\n code: 'transport',\n cause: err,\n });\n }\n\n // The server answered the append with an error status: no row landed, the\n // whole batch fails.\n const failed = appendError(result);\n if (failed) throw failed;\n\n if (result.rowErrors && result.rowErrors.length > 0) {\n // Report per-row failures so the collector DLQs only the failed rows and\n // counts the succeeded rows as delivered. `re.index` is the row's position\n // in `rows`, mapped back to the entry's index in the flushed batch. The\n // Storage Write SDK types `index` as a protobuf int64 (number, string, or\n // Long), normalized here. A row error's message can quote the row, so the\n // error names only its code.\n const failures = result.rowErrors.map((re) => ({\n index: sent[Number(re.index)]?.index ?? Number(re.index),\n error: new StepError(`BigQuery row append failed (code ${re.code})`, {\n code: 'transport',\n retryable: false,\n }),\n }));\n\n return { failed: failures };\n }\n\n // Full success: keep at DEBUG to avoid noise on every batch.\n logger.debug('BigQuery batch append ok', {\n ok: rows.length,\n failed: 0,\n offset: result.appendResult?.offset?.value,\n });\n};\n","import type { DestinationServer } from '@walkeros/server-core';\nimport type {\n Env,\n QueryTable,\n Setup,\n SetupSchemaField,\n TableMetadataShape,\n Types,\n} from './types';\nimport type { LifecycleContext, Logger } from '@walkeros/core';\nimport { resolveSetup } from '@walkeros/core';\n\n// Setup is wired to the destination's `setup` slot which uses the broader\n// `DestinationServer.Config<Types>` (settings is optional). We runtime-narrow\n// instead of using the local Config alias so the assignment in index.ts\n// type-checks without contravariance issues.\ntype WideConfig = DestinationServer.Config<Types>;\n\n// Per Resolved Decision #2: only `name` is REQUIRED. All other columns\n// are NULLABLE for resilience against partial events / test fixtures.\nexport const DEFAULT_SCHEMA: SetupSchemaField[] = [\n { name: 'name', type: 'STRING', mode: 'REQUIRED' },\n { name: 'data', type: 'JSON', mode: 'NULLABLE' },\n { name: 'context', type: 'JSON', mode: 'NULLABLE' },\n { name: 'globals', type: 'JSON', mode: 'NULLABLE' },\n { name: 'custom', type: 'JSON', mode: 'NULLABLE' },\n { name: 'user', type: 'JSON', mode: 'NULLABLE' },\n { name: 'nested', type: 'JSON', mode: 'NULLABLE' },\n { name: 'consent', type: 'JSON', mode: 'NULLABLE' },\n { name: 'id', type: 'STRING', mode: 'NULLABLE' },\n { name: 'trigger', type: 'STRING', mode: 'NULLABLE' },\n { name: 'entity', type: 'STRING', mode: 'NULLABLE' },\n { name: 'action', type: 'STRING', mode: 'NULLABLE' },\n { name: 'timestamp', type: 'TIMESTAMP', mode: 'NULLABLE' },\n { name: 'timing', type: 'FLOAT64', mode: 'NULLABLE' },\n { name: 'source', type: 'JSON', mode: 'NULLABLE' },\n];\n\nexport const DEFAULT_SETUP: Required<Setup> = {\n location: 'EU',\n storageBillingModel: 'PHYSICAL',\n partitioning: { type: 'DAY', field: 'timestamp' },\n clustering: { fields: ['name', 'entity', 'action'] },\n schema: DEFAULT_SCHEMA,\n};\n\nexport interface SetupResult {\n datasetCreated: boolean;\n tableCreated: boolean;\n}\n\ntype DriftableTable = Pick<QueryTable, 'getMetadata'>;\n\ninterface PartitioningMeta {\n type?: string;\n field?: string;\n}\n\ninterface ClusteringMeta {\n fields?: string[];\n}\n\ninterface SchemaMeta {\n fields?: Array<{ name?: string; type?: string; mode?: string }>;\n}\n\nexport async function setup(\n ctx: LifecycleContext<WideConfig, Env>,\n): Promise<SetupResult | undefined> {\n const { config, logger } = ctx;\n const merged = resolveSetup(config.setup, DEFAULT_SETUP);\n if (!merged) {\n logger.debug('setup: skipped (config.setup is false or unset)');\n return;\n }\n // Fill any holes a partial user override left, so all fields are required.\n const options: Required<Setup> = {\n location: merged.location ?? DEFAULT_SETUP.location,\n storageBillingModel:\n merged.storageBillingModel ?? DEFAULT_SETUP.storageBillingModel,\n partitioning: merged.partitioning ?? DEFAULT_SETUP.partitioning,\n clustering: merged.clustering ?? DEFAULT_SETUP.clustering,\n schema: merged.schema ?? DEFAULT_SETUP.schema,\n };\n\n if (!config.settings) {\n logger.throw('setup: settings missing');\n return;\n }\n const { client, datasetId, tableId } = config.settings;\n if (!client) {\n logger.throw('setup: BigQuery client is missing');\n return;\n }\n if (!datasetId) {\n logger.throw('setup: datasetId is missing');\n return;\n }\n if (!tableId) {\n logger.throw('setup: tableId is missing');\n return;\n }\n\n const dataset = client.dataset(datasetId);\n\n // 1. Dataset\n let datasetCreated = false;\n const [datasetExists] = await dataset.exists();\n if (!datasetExists) {\n try {\n await dataset.create({\n location: options.location,\n storageBillingModel: options.storageBillingModel,\n });\n datasetCreated = true;\n logger.info('setup: dataset created', {\n datasetId,\n location: options.location,\n storageBillingModel: options.storageBillingModel,\n });\n } catch (err) {\n if (isAlreadyExists(err)) {\n logger.debug('setup: dataset already exists (race)', { datasetId });\n } else {\n throw err;\n }\n }\n } else {\n logger.debug('setup: dataset exists', { datasetId });\n }\n\n // 2. Table\n const table = dataset.table(tableId);\n let tableCreated = false;\n const [tableExists] = await table.exists();\n if (!tableExists) {\n try {\n await table.create({\n schema: { fields: options.schema },\n timePartitioning: {\n type: options.partitioning.type,\n field: options.partitioning.field,\n },\n clustering: { fields: options.clustering.fields },\n });\n tableCreated = true;\n logger.info('setup: table created', {\n datasetId,\n tableId,\n partitioning: options.partitioning,\n clustering: options.clustering,\n });\n } catch (err) {\n if (isAlreadyExists(err)) {\n logger.debug('setup: table already exists (race)', { tableId });\n } else {\n throw err;\n }\n }\n } else {\n logger.debug('setup: table exists', { datasetId, tableId });\n await detectDrift(table, options, logger);\n }\n\n return { datasetCreated, tableCreated };\n}\n\nfunction hasCode(err: unknown): err is { code: number } {\n if (typeof err !== 'object' || err === null) return false;\n if (!('code' in err)) return false;\n const obj: { code?: unknown } = err;\n return typeof obj.code === 'number';\n}\n\nfunction isAlreadyExists(err: unknown): boolean {\n return hasCode(err) && err.code === 409;\n}\n\nasync function detectDrift(\n table: DriftableTable,\n options: Required<Setup>,\n logger: Logger.Instance,\n): Promise<void> {\n let metadata: TableMetadataShape;\n try {\n const [meta] = await table.getMetadata();\n metadata = meta ?? {};\n } catch (err) {\n logger.debug('setup: drift check failed (non-fatal)', {\n error: err instanceof Error ? err.message : String(err),\n });\n return;\n }\n\n // Partition drift\n if (isPartitioningMeta(metadata.timePartitioning)) {\n const actual = metadata.timePartitioning;\n const declared = options.partitioning;\n if (actual.type !== declared.type || actual.field !== declared.field) {\n logger.warn('setup.drift', {\n field: 'timePartitioning',\n declared,\n actual,\n });\n }\n }\n\n // Clustering drift\n if (isClusteringMeta(metadata.clustering)) {\n const actualFields = metadata.clustering.fields ?? [];\n const declaredFields = options.clustering.fields;\n if (\n actualFields.length !== declaredFields.length ||\n actualFields.some((f, i) => f !== declaredFields[i])\n ) {\n logger.warn('setup.drift', {\n field: 'clustering',\n declared: { fields: declaredFields },\n actual: { fields: actualFields },\n });\n }\n }\n\n // Schema drift (column name, type, and mode; descriptions ignored)\n if (isSchemaMeta(metadata.schema)) {\n const actualFields = metadata.schema.fields ?? [];\n const declaredFields = options.schema;\n const driftDetected =\n actualFields.length !== declaredFields.length ||\n declaredFields.some((d, i) => {\n const a = actualFields[i];\n return (\n !a || a.name !== d.name || a.type !== d.type || a.mode !== d.mode\n );\n });\n if (driftDetected) {\n logger.warn('setup.drift', {\n field: 'schema',\n declared: declaredFields.map((f) => ({\n name: f.name,\n type: f.type,\n mode: f.mode,\n })),\n actual: actualFields.map((f) => ({\n name: f.name,\n type: f.type,\n mode: f.mode,\n })),\n });\n }\n }\n}\n\nfunction isPartitioningMeta(v: unknown): v is PartitioningMeta {\n return typeof v === 'object' && v !== null;\n}\n\nfunction isClusteringMeta(v: unknown): v is ClusteringMeta {\n return typeof v === 'object' && v !== null;\n}\n\nfunction isSchemaMeta(v: unknown): v is SchemaMeta {\n return typeof v === 'object' && v !== null;\n}\n","import type { DestinationServer } from '@walkeros/server-core';\nimport type {\n Mapping as WalkerOSMapping,\n Destination as CoreDestination,\n SetupFn as CoreSetupFn,\n Credential,\n ServiceAccount,\n} from '@walkeros/core';\nimport type { BigQueryOptions } from '@google-cloud/bigquery';\nimport type {\n WriterHandles,\n WriterEnv,\n WriteClient,\n WriteConnection,\n RowWriter,\n ConnectionListener,\n} from '../writer';\n\n/** Table metadata fields the setup drift check reads. */\nexport interface TableMetadataShape {\n timePartitioning?: unknown;\n clustering?: unknown;\n schema?: unknown;\n}\n\n/** The table surface `walkeros setup` calls. */\nexport interface QueryTable {\n exists(): Promise<[boolean, ...unknown[]]>;\n create(options: {\n schema: { fields: SetupSchemaField[] };\n timePartitioning: { type: string; field: string };\n clustering: { fields: string[] };\n }): Promise<unknown>;\n // Matches both real BigQuery Table.getMetadata() (returns [Metadata, ApiResponse])\n // and a mock returning [Metadata]. Only index 0 is consumed.\n getMetadata(): Promise<TableMetadataShape[]>;\n}\n\n/** The dataset surface `walkeros setup` calls. */\nexport interface QueryDataset {\n exists(): Promise<[boolean, ...unknown[]]>;\n create(options: {\n location: string;\n storageBillingModel: string;\n }): Promise<unknown>;\n table(tableId: string): QueryTable;\n}\n\n/**\n * The query client surface this destination calls (dataset and table\n * provisioning). A `BigQuery` from `@google-cloud/bigquery` satisfies it.\n */\nexport interface QueryClient {\n dataset(datasetId: string): QueryDataset;\n}\n\nexport interface Settings {\n client: QueryClient;\n projectId: string;\n datasetId: string;\n tableId: string;\n location?: string;\n bigquery?: BigQueryOptions;\n /**\n * Service-account credentials parsed from `config.credentials` at init.\n * Threaded to BOTH the query client (`new BigQuery`) and the data-plane\n * Storage Write client (`new WriterClient`) so event writes authenticate\n * with the configured SA instead of falling back to ADC on non-GCP runtimes.\n * Runtime-only (the raw `config.credentials` may be a JSON string).\n */\n credentials?: ServiceAccount;\n // Runtime-only handles populated by init(); not user-facing.\n writeClient?: WriteClient<WriteConnection>;\n writer?: RowWriter;\n // The StreamConnection the writer appends to. Held so the connection-error\n // listener can be removed on re-open/destroy. Runtime-only.\n connection?: WriteConnection;\n // The `{ off }` disposable for the connection-error listener. Runtime-only.\n connectionErrorListener?: ConnectionListener;\n /**\n * Set by the connection's `'error'` handler when the long-lived stream\n * errored out-of-band. The next push self-heals (one re-open attempt) before\n * failing; while set, push/pushBatch route the event to the DLQ. Runtime-only.\n */\n writerBroken?: boolean;\n /** The last out-of-band stream error, surfaced in the DLQ-routed message. Runtime-only. */\n lastStreamError?: Error;\n /**\n * Lazy re-open hook, wired by init(). Closes over the openWriter args plus\n * `reportError`/logger so the push path can self-heal a broken writer without\n * the destination needing the original init context. Runtime-only.\n */\n reopenWriter?: () => Promise<WriterHandles>;\n /**\n * The in-flight self-heal re-open, memoized so concurrent pushes admitted in\n * the same breaking pass (the collector fans out a destination's events with\n * Promise.all) await ONE re-open instead of each closing+re-opening, which\n * would orphan a gRPC connection + live 'error' listener per redundant\n * attempt. Cleared in a finally so a later push after a failed re-open\n * retries. Runtime-only.\n */\n reopenInFlight?: Promise<void>;\n}\n\nexport interface InitSettings {\n projectId: string;\n client?: QueryClient;\n datasetId?: string;\n tableId?: string;\n location?: string;\n bigquery?: BigQueryOptions;\n // Runtime-only handles populated by init(); not user-facing.\n writeClient?: WriteClient<WriteConnection>;\n writer?: RowWriter;\n connection?: WriteConnection;\n connectionErrorListener?: ConnectionListener;\n writerBroken?: boolean;\n lastStreamError?: Error;\n reopenWriter?: () => Promise<WriterHandles>;\n reopenInFlight?: Promise<void>;\n}\n\nexport interface Mapping {}\n\n/** Credentials value for this destination: JSON string or service account object. */\nexport type Credentials = Credential<ServiceAccount>;\n\n/**\n * Provisioning options for `walkeros setup destination.bigquery`.\n * Triggered only by the explicit CLI command. Idempotent, never auto-run.\n *\n * `projectId`, `datasetId`, `tableId` are read from `settings` (not duplicated here)\n * so a single source of truth governs both setup and runtime push.\n */\nexport interface Setup {\n /** Geographic location for the dataset. Default: 'EU'. */\n location?: string;\n /** Storage billing model. PHYSICAL is cheaper for compressible JSON. Default: 'PHYSICAL'. */\n storageBillingModel?: 'LOGICAL' | 'PHYSICAL';\n /** Time partitioning for the table. Default: { type: 'DAY', field: 'timestamp' }. */\n partitioning?: {\n type: 'DAY' | 'HOUR' | 'MONTH' | 'YEAR';\n field: string;\n };\n /** Clustering for cheap event-name filters. Default: { fields: ['name', 'entity', 'action'] }. */\n clustering?: { fields: string[] };\n /** Override the schema fields (15 columns by default, walkerOS Event v4 order). */\n schema?: SetupSchemaField[];\n}\n\n/** Single column in the BQ schema (subset of @google-cloud/bigquery's TableField). */\nexport interface SetupSchemaField {\n name: string;\n type: 'STRING' | 'JSON' | 'TIMESTAMP' | 'INT64' | 'BOOL' | 'FLOAT64';\n mode?: 'NULLABLE' | 'REQUIRED' | 'REPEATED';\n}\n\n// The Storage Write pieces (WriterClient, JSONWriter, adapt) come from\n// WriterEnv: mocks for tests/examples, optional at runtime.\nexport interface Env extends DestinationServer.Env, WriterEnv {\n BigQuery?: new (options?: BigQueryOptions) => QueryClient;\n}\n\nexport type Types = CoreDestination.Types<\n Settings,\n Mapping,\n Env,\n InitSettings,\n Setup,\n Credentials\n>;\n\nexport interface Destination extends DestinationServer.Destination<Types> {\n init: DestinationServer.InitFn<Types>;\n}\n\nexport type Config = {\n settings: Settings;\n} & DestinationServer.Config<Types>;\n\nexport type InitFn = DestinationServer.InitFn<Types>;\nexport type PushFn = DestinationServer.PushFn<Types>;\nexport type PushBatchFn = CoreDestination.PushBatchFn<Types>;\nexport type SetupFn = CoreSetupFn<Config, Env>;\n\nexport type PartialConfig = DestinationServer.PartialConfig<Types>;\n\nexport type PushEvents = DestinationServer.PushEvents<Mapping>;\n\nexport type Rule = WalkerOSMapping.Rule<Mapping>;\nexport type Rules = WalkerOSMapping.Rules<Rule>;\n","import type { PushFn, Mapping, Settings } from './types';\nimport type { Mapping as WalkerOSMapping, Collector } from '@walkeros/core';\nimport { getMappingValue, isObject, StepError } from '@walkeros/core';\n\nconst NOT_FOUND_GRPC = 5;\nconst NOT_FOUND_HTTP = 404;\nconst PERMISSION_DENIED_GRPC = 7;\nconst UNAUTHENTICATED_GRPC = 16;\nconst PERMISSION_DENIED_HTTP = 403;\nconst UNAUTHENTICATED_HTTP = 401;\n\n/**\n * The gRPC codes the Pub/Sub SDK itself retries a publish on (CANCELLED,\n * UNKNOWN, DEADLINE_EXCEEDED, RESOURCE_EXHAUSTED, ABORTED, INTERNAL,\n * UNAVAILABLE, its publisher client config). Any other gRPC code, such as\n * INVALID_ARGUMENT for an oversize message, fails the same way again.\n */\nconst RETRYABLE_GRPC = [1, 2, 4, 8, 10, 13, 14];\n\n/** gRPC codes run from 0 to 16; a larger one is the HTTP status of a REST call. */\nconst MAX_GRPC_CODE = 16;\n\ninterface ErrorWithCode {\n code: number;\n}\n\nfunction hasNumericCode(err: unknown): err is ErrorWithCode {\n if (typeof err !== 'object' || err === null) return false;\n if (!('code' in err)) return false;\n const obj: { code?: unknown } = err;\n return typeof obj.code === 'number';\n}\n\nfunction isNotFound(err: unknown): boolean {\n return (\n hasNumericCode(err) &&\n (err.code === NOT_FOUND_GRPC || err.code === NOT_FOUND_HTTP)\n );\n}\n\nfunction isPermissionError(err: unknown): boolean {\n return (\n hasNumericCode(err) &&\n (err.code === PERMISSION_DENIED_GRPC ||\n err.code === UNAUTHENTICATED_GRPC ||\n err.code === PERMISSION_DENIED_HTTP ||\n err.code === UNAUTHENTICATED_HTTP)\n );\n}\n\ninterface AttributesShape {\n [key: string]: string;\n}\n\nfunction isStringRecord(value: unknown): value is AttributesShape {\n if (!isObject(value)) return false;\n const candidate: Record<string, unknown> = value;\n for (const key of Object.keys(candidate)) {\n if (typeof candidate[key] !== 'string') return false;\n }\n return true;\n}\n\nasync function resolveAttributes(\n event: Parameters<PushFn>[0],\n base: WalkerOSMapping.Map | undefined,\n override: WalkerOSMapping.Map | undefined,\n collector: Collector.Instance,\n): Promise<AttributesShape | undefined> {\n const result: AttributesShape = {};\n let touched = false;\n\n if (base) {\n for (const [key, value] of Object.entries(base)) {\n const resolved = await getMappingValue(event, value, { collector });\n if (typeof resolved === 'string') {\n result[key] = resolved;\n touched = true;\n } else if (resolved !== undefined && resolved !== null) {\n result[key] = String(resolved);\n touched = true;\n }\n }\n }\n\n if (override) {\n for (const [key, value] of Object.entries(override)) {\n const resolved = await getMappingValue(event, value, { collector });\n if (typeof resolved === 'string') {\n result[key] = resolved;\n touched = true;\n } else if (resolved !== undefined && resolved !== null) {\n result[key] = String(resolved);\n touched = true;\n }\n }\n }\n\n return touched ? result : undefined;\n}\n\nfunction isResolvedSettings(value: unknown): value is Settings {\n if (typeof value !== 'object' || value === null) return false;\n const candidate: { client?: unknown; projectId?: unknown; topic?: unknown } =\n value;\n return (\n candidate.client !== undefined &&\n typeof candidate.projectId === 'string' &&\n candidate.projectId.length > 0 &&\n typeof candidate.topic === 'string' &&\n candidate.topic.length > 0\n );\n}\n\nfunction isMapping(value: unknown): value is Mapping {\n return typeof value === 'object' && value !== null;\n}\n\n// A silent rule has no message of its own: nothing to publish.\nexport const push: PushFn = async function (event, context) {\n if (!context.rule?.silent) await publish(event, context);\n};\n\nconst publish: PushFn = async function (\n event,\n { config, rule, data, collector, logger, id },\n) {\n const settings = config.settings;\n if (!isResolvedSettings(settings))\n throw new StepError(\n 'Pub/Sub settings missing or incomplete, init() not run',\n {\n code: 'not-ready',\n },\n );\n\n const { client, projectId, topic: defaultTopic } = settings;\n\n const ruleSettings: Mapping = isMapping(rule?.settings) ? rule.settings : {};\n\n const topicName =\n typeof ruleSettings.topic === 'string' && ruleSettings.topic.length > 0\n ? ruleSettings.topic\n : defaultTopic;\n\n // Resolve ordering key: per-rule overrides settings default. Both are\n // Mapping.Value resolved against the event.\n const orderingValue =\n ruleSettings.orderingKey !== undefined\n ? ruleSettings.orderingKey\n : settings.orderingKey;\n let orderingKey: string | undefined;\n if (orderingValue !== undefined) {\n const resolved = await getMappingValue(event, orderingValue, { collector });\n if (typeof resolved === 'string' && resolved.length > 0) {\n orderingKey = resolved;\n } else if (resolved !== undefined && resolved !== null) {\n orderingKey = String(resolved);\n }\n }\n\n // Topic handle is constructed inline. Setting messageOrdering on the\n // topic options enables per-key ordering for this publish.\n const topicHandle = client.topic(topicName, {\n messageOrdering: Boolean(orderingKey),\n });\n\n // Serialize the publish body: mapped data wins over the raw event.\n const body = isObject(data) && Object.keys(data).length > 0 ? data : event;\n const payload = Buffer.from(JSON.stringify(body));\n\n // Merge attributes: settings default + per-rule overrides.\n const baseAttrs = settings.attributes;\n const ruleAttrs = ruleSettings.attributes;\n const attributes = await resolveAttributes(\n event,\n baseAttrs,\n ruleAttrs,\n collector,\n );\n\n const message: {\n data: Buffer;\n attributes?: AttributesShape;\n orderingKey?: string;\n } = { data: payload };\n if (attributes && isStringRecord(attributes)) message.attributes = attributes;\n if (orderingKey) message.orderingKey = orderingKey;\n\n logger.debug('Pub/Sub publish', {\n topic: topicName,\n projectId,\n event: event.name,\n });\n\n try {\n await topicHandle.publishMessage(message);\n } catch (err) {\n // When a publish fails for an ordered key, the SDK halts subsequent\n // publishes for that key until resumePublishing is called. Resume\n // immediately so the next event for the same key is not blocked.\n if (orderingKey) {\n try {\n topicHandle.resumePublishing(orderingKey);\n } catch (resumeErr) {\n logger.debug('Pub/Sub resumePublishing failed', {\n topic: topicName,\n error:\n resumeErr instanceof Error ? resumeErr.message : String(resumeErr),\n });\n }\n }\n\n // The collector reports it; the SDK error (with its `code`) stays the\n // cause. A missing topic and a denied publish are setup steps the\n // operator has to take, not retried.\n if (isNotFound(err))\n throw new StepError(\n `Pub/Sub topic \"${topicName}\" not found in project \"${projectId}\". ` +\n `Run \"walkeros setup destination.${id}\" to create it.`,\n { code: 'config', cause: err },\n );\n if (isPermissionError(err))\n throw new StepError(\n `Pub/Sub publish denied for topic \"${topicName}\". Grant the runtime ` +\n `service account roles/pubsub.publisher on this topic.`,\n { code: 'config', cause: err },\n );\n // Retryable as the SDK's own retry decides: by the gRPC code, or by the\n // HTTP status of a REST call; without a code, a transport failure.\n if (!hasNumericCode(err))\n throw new StepError('Pub/Sub publish failed', {\n code: 'transport',\n cause: err,\n });\n throw new StepError(`Pub/Sub publish failed (code ${err.code})`, {\n code: 'transport',\n ...(err.code > MAX_GRPC_CODE\n ? { status: err.code }\n : { retryable: RETRYABLE_GRPC.includes(err.code) }),\n cause: err,\n });\n }\n};\n","import type { DestinationServer } from '@walkeros/server-core';\nimport type { Env, Setup, Types } from './types';\nimport type { LifecycleContext, Logger } from '@walkeros/core';\nimport { resolveSetup } from '@walkeros/core';\nimport { parseCredentials, resolveCredentials } from './config';\nimport {\n PubSub,\n type PubSub as PubSubClient,\n type Topic,\n type TopicMetadata,\n} from '@google-cloud/pubsub';\n\n// Setup is wired to the destination's `setup` slot which uses the broader\n// `DestinationServer.Config<Types>` (settings is optional). We runtime-narrow\n// instead of using the local Config alias so the assignment in index.ts\n// type-checks without contravariance issues.\ntype WideConfig = DestinationServer.Config<Types>;\n\nconst NOT_FOUND_GRPC = 5;\nconst NOT_FOUND_HTTP = 404;\nconst ALREADY_EXISTS_GRPC = 6;\nconst ALREADY_EXISTS_HTTP = 409;\n\n// GCP region names accepted by Pub/Sub's messageStoragePolicy.allowedPersistenceRegions.\n// These are the canonical full names (e.g. 'europe-west1'), NOT the colloquial\n// abbreviations 'eu-west1' that the API rejects with INVALID_ARGUMENT.\nexport const DEFAULT_SETUP: Required<Pick<Setup, 'messageStoragePolicy'>> &\n Omit<Setup, 'messageStoragePolicy'> = {\n messageStoragePolicy: {\n allowedPersistenceRegions: ['europe-west1', 'europe-west3', 'europe-west4'],\n },\n};\n\nexport interface SetupResult {\n topicCreated: boolean;\n}\n\nfunction hasNumericCode(err: unknown): err is { code: number } {\n if (typeof err !== 'object' || err === null) return false;\n if (!('code' in err)) return false;\n const obj: { code?: unknown } = err;\n return typeof obj.code === 'number';\n}\n\nexport function isAlreadyExists(err: unknown): boolean {\n return (\n hasNumericCode(err) &&\n (err.code === ALREADY_EXISTS_GRPC || err.code === ALREADY_EXISTS_HTTP)\n );\n}\n\nexport function isNotFound(err: unknown): boolean {\n return (\n hasNumericCode(err) &&\n (err.code === NOT_FOUND_GRPC || err.code === NOT_FOUND_HTTP)\n );\n}\n\nexport async function setup(\n ctx: LifecycleContext<WideConfig, Env>,\n): Promise<SetupResult | undefined> {\n const { config, logger } = ctx;\n const merged = resolveSetup(config.setup, DEFAULT_SETUP);\n if (!merged) {\n logger.debug('setup: skipped (config.setup is false or unset)');\n return;\n }\n\n const settings = config.settings;\n if (!settings) {\n logger.throw('setup: settings missing');\n return;\n }\n const projectId =\n typeof settings.projectId === 'string' ? settings.projectId : '';\n const topicName = typeof settings.topic === 'string' ? settings.topic : '';\n if (!projectId) {\n logger.throw('setup: projectId is missing');\n return;\n }\n if (!topicName) {\n logger.throw('setup: topic is missing');\n return;\n }\n\n // Resolve the client. Prefer a pre-supplied SDK client; otherwise build one.\n // Setup needs the SDK's admin surface (exists, createTopic, metadata), which\n // an injected publisher (tests, simulate) does not carry. Track whether\n // setup created the client so we close only what we own.\n let createdClient = false;\n let client: PubSubClient | undefined =\n settings.client instanceof PubSub ? settings.client : undefined;\n if (settings.client && !client) {\n logger.debug(\n 'setup: settings.client is not a Pub/Sub SDK client; creating one for provisioning',\n );\n }\n if (!client) {\n const credentials = parseCredentials(resolveCredentials(config, logger));\n const clientOptions = {\n projectId,\n ...(credentials !== undefined && typeof credentials !== 'string'\n ? { credentials }\n : {}),\n ...(settings.apiEndpoint ? { apiEndpoint: settings.apiEndpoint } : {}),\n };\n client = new PubSub(clientOptions);\n createdClient = true;\n }\n\n const topic = client.topic(topicName);\n\n let topicCreated = false;\n const [exists] = await topic.exists();\n if (!exists) {\n // Build the TopicMetadata payload. The SDK's `pubsub.createTopic(name |\n // metadata)` is the only path that actually applies messageStoragePolicy\n // and friends at creation time. `topic.create(opts)` accepts only\n // CallOptions and silently drops topic metadata.\n const metadata: TopicMetadata = {\n name: `projects/${projectId}/topics/${topicName}`,\n };\n if (merged.messageStoragePolicy)\n metadata.messageStoragePolicy = merged.messageStoragePolicy;\n if (merged.messageRetentionDuration)\n metadata.messageRetentionDuration = {\n seconds: merged.messageRetentionDuration.seconds,\n };\n if (merged.kmsKeyName) metadata.kmsKeyName = merged.kmsKeyName;\n if (merged.labels) metadata.labels = merged.labels;\n\n try {\n await client.createTopic(metadata);\n topicCreated = true;\n logger.info('setup: topic created', {\n topic: topicName,\n projectId,\n messageStoragePolicy: metadata.messageStoragePolicy,\n });\n } catch (err) {\n if (isAlreadyExists(err)) {\n logger.debug('setup: topic already exists (race)', {\n topic: topicName,\n });\n } else {\n if (createdClient) {\n await safeClose(client, logger);\n }\n throw err;\n }\n }\n } else {\n logger.debug('setup: topic exists', { topic: topicName });\n await detectDrift(topic, merged, logger);\n }\n\n if (createdClient) {\n await safeClose(client, logger);\n }\n\n return { topicCreated };\n}\n\nasync function safeClose(\n client: { close: () => Promise<void> },\n logger: Logger.Instance,\n): Promise<void> {\n try {\n await client.close();\n } catch (err) {\n logger.debug('setup: client.close failed (non-fatal)', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n}\n\nasync function detectDrift(\n topic: Topic,\n declared: Setup,\n logger: Logger.Instance,\n): Promise<void> {\n let metadata: TopicMetadata;\n try {\n const [meta] = await topic.getMetadata();\n metadata = meta ?? {};\n } catch (err) {\n logger.debug('setup: drift check failed (non-fatal)', {\n error: err instanceof Error ? err.message : String(err),\n });\n return;\n }\n\n // Storage policy drift\n if (declared.messageStoragePolicy) {\n const declaredRegions =\n declared.messageStoragePolicy.allowedPersistenceRegions;\n const actualRegions =\n metadata.messageStoragePolicy?.allowedPersistenceRegions ?? [];\n if (\n declaredRegions.length !== actualRegions.length ||\n declaredRegions.some((r, i) => r !== actualRegions[i])\n ) {\n logger.warn('setup.drift', {\n field: 'messageStoragePolicy.allowedPersistenceRegions',\n declared: declaredRegions,\n actual: actualRegions,\n });\n }\n }\n\n // Retention drift\n if (declared.messageRetentionDuration) {\n const declaredSeconds = declared.messageRetentionDuration.seconds;\n const actualRaw = metadata.messageRetentionDuration?.seconds;\n const actualSeconds =\n typeof actualRaw === 'number'\n ? actualRaw\n : typeof actualRaw === 'string'\n ? Number(actualRaw)\n : undefined;\n if (actualSeconds !== declaredSeconds) {\n logger.warn('setup.drift', {\n field: 'messageRetentionDuration.seconds',\n declared: declaredSeconds,\n actual: actualSeconds ?? null,\n });\n }\n }\n\n // KMS key drift\n if (declared.kmsKeyName !== undefined) {\n if (metadata.kmsKeyName !== declared.kmsKeyName) {\n logger.warn('setup.drift', {\n field: 'kmsKeyName',\n declared: declared.kmsKeyName,\n actual: metadata.kmsKeyName ?? null,\n });\n }\n }\n\n // Labels drift (granular per key)\n if (declared.labels) {\n const actualLabels = metadata.labels ?? {};\n for (const [key, declaredValue] of Object.entries(declared.labels)) {\n const actualValue = actualLabels[key];\n if (actualValue !== declaredValue) {\n logger.warn('setup.drift', {\n field: `labels.${key}`,\n declared: declaredValue,\n actual: actualValue ?? null,\n });\n }\n }\n }\n}\n","import type {\n Mapping as WalkerOSMapping,\n Destination as CoreDestination,\n SetupFn as CoreSetupFn,\n Credential,\n ServiceAccount,\n} from '@walkeros/core';\nimport type { DestinationServer } from '@walkeros/server-core';\nimport type { ClientConfig, TopicMetadata } from '@google-cloud/pubsub';\n\nexport interface ServiceAccountCredentials {\n client_email: string;\n private_key: string;\n project_id?: string;\n}\n\n/** Credentials value for this destination: JSON string or service account object. */\nexport type Credentials = Credential<ServiceAccount>;\n\n/** The message `push` publishes. */\nexport interface PublishMessage {\n data: Buffer;\n attributes?: Record<string, string>;\n orderingKey?: string;\n}\n\n/** The part of a Pub/Sub topic handle `push` calls. */\nexport interface TopicPublisher {\n publishMessage(message: PublishMessage): Promise<string>;\n resumePublishing(orderingKey: string): void;\n}\n\n/**\n * The part of the Pub/Sub client `init`, `push` and `destroy` call. The SDK's\n * `PubSub` satisfies it, and so does an injected mock (tests, simulate)\n * without a cast. `setup` needs the admin surface and uses the SDK client.\n */\nexport interface PubSubPublisher {\n topic(name: string, options?: { messageOrdering?: boolean }): TopicPublisher;\n close(): Promise<void>;\n}\n\nexport interface Settings {\n // User-supplied OR populated by init(); single field for both. Mirrors BigQuery.\n client: PubSubPublisher;\n // Top-level always wins over credentials.project_id (documented in config.ts).\n projectId: string;\n topic: string;\n /** @deprecated use config.credentials */\n credentials?: string | ServiceAccountCredentials;\n // SDK term, kept verbatim.\n apiEndpoint?: string;\n // Mapping value resolved per-event. Undefined = no ordering. Truthy = ordering enabled.\n orderingKey?: WalkerOSMapping.Value;\n // Dynamic per-event attributes.\n attributes?: WalkerOSMapping.Map;\n}\n\nexport interface InitSettings {\n projectId: string;\n topic: string;\n client?: PubSubPublisher;\n /** @deprecated use config.credentials */\n credentials?: string | ServiceAccountCredentials;\n apiEndpoint?: string;\n orderingKey?: WalkerOSMapping.Value;\n attributes?: WalkerOSMapping.Map;\n}\n\nexport interface Mapping {\n topic?: string;\n orderingKey?: WalkerOSMapping.Value;\n // Per-rule attributes are merged on top of settings.attributes.\n attributes?: WalkerOSMapping.Map;\n}\n\n/**\n * Provisioning options for `walkeros setup destination.<id>`.\n * Triggered only by the explicit CLI command. Idempotent, never auto-run.\n *\n * `projectId` and `topic` are read from `Settings` (not duplicated here)\n * so a single source of truth governs both setup and runtime publish.\n *\n * Subscription provisioning is owned by the source side, not here.\n */\nexport interface Setup {\n /** Geographic regions for at-rest storage. Default: EU multi-region (['eu-west1','eu-west3','eu-west4']). */\n messageStoragePolicy?: { allowedPersistenceRegions: string[] };\n /** Topic-level retention. Default: undefined (project default). */\n messageRetentionDuration?: { seconds: number };\n /** CMEK key. Optional. */\n kmsKeyName?: string;\n /** Topic labels. Optional. */\n labels?: Record<string, string>;\n}\n\nexport interface Env extends DestinationServer.Env {\n PubSub?: new (options?: ClientConfig) => PubSubPublisher;\n}\n\nexport type Types = CoreDestination.Types<\n Settings,\n Mapping,\n Env,\n InitSettings,\n Setup,\n Credentials\n>;\n\nexport interface Destination extends DestinationServer.Destination<Types> {\n init: DestinationServer.InitFn<Types>;\n}\n\nexport type Config = {\n settings: Settings;\n} & DestinationServer.Config<Types>;\n\nexport type InitFn = DestinationServer.InitFn<Types>;\nexport type PushFn = DestinationServer.PushFn<Types>;\nexport type SetupFn = CoreSetupFn<Config, Env>;\n\nexport type PartialConfig = DestinationServer.PartialConfig<Types>;\n\n// Re-export SDK types used across the package for convenience.\nexport type { TopicMetadata };\n","import type { Destination } from './types';\nimport { getConfig } from './config';\nimport { push } from './push';\nimport { setup } from './setup';\n\n// Types re-export\nexport * as DestinationPubSub from './types';\n\nexport const destinationPubSub: Destination = {\n type: 'gcp-pubsub',\n\n config: {},\n\n setup,\n\n async init({ config: partialConfig, env, logger }) {\n return getConfig(partialConfig, env, logger);\n },\n\n async push(event, context) {\n return await push(event, context);\n },\n\n async destroy({ config }) {\n if (!config.settings) return;\n const { client } = config.settings;\n if (!client) return;\n try {\n await client.close();\n } catch {\n // Closing flushes outstanding publishes; swallow errors so a flush\n // failure does not leak the client. Detailed publish errors are\n // already surfaced by push().\n }\n },\n};\n\nexport default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AAQ,iBAAiB;AAAA,MAC3B,CAAC;AAAA,IACH;AAAA,EACF;AAGA,MAAI,SAAS,eAAe,QAAW;AACrC,QAAI,SAAS,eAAe,SAAS,YAAY;AAC/C,aAAO,KAAK,eAAe;AAAA,QACzB,OAAO;AAAA,QACP,UAAU,SAAS;AAAA,QACnB,QAAQ,SAAS,cAAc;AAAA,MACjC,CAAC;AAAA,IACH;AAAA,EACF;AAGA,MAAI,SAAS,QAAQ;AACnB,UAAM,eAAe,SAAS,UAAU,CAAC;AACzC,eAAW,CAAC,KAAK,aAAa,KAAK,OAAO,QAAQ,SAAS,MAAM,GAAG;AAClE,YAAM,cAAc,aAAa,GAAG;AACpC,UAAI,gBAAgB,eAAe;AACjC,eAAO,KAAK,eAAe;AAAA,UACzB,OAAO,UAAU,GAAG;AAAA,UACpB,UAAU;AAAA,UACV,QAAQ,eAAe;AAAA,QACzB,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF;;;AC9PA,IAAAC,iBAAA;;;ACQO,IAAM,oBAAiC;AAAA,EAC5C,MAAM;AAAA,EAEN,QAAQ,CAAC;AAAA,EAET,OAAAC;AAAA,EAEA,MAAM,KAAK,EAAE,QAAQ,eAAe,KAAK,OAAO,GAAG;AACjD,WAAO,UAAU,eAAe,KAAK,MAAM;AAAA,EAC7C;AAAA,EAEA,MAAM,KAAK,OAAO,SAAS;AACzB,WAAO,MAAMC,MAAK,OAAO,OAAO;AAAA,EAClC;AAAA,EAEA,MAAM,QAAQ,EAAE,OAAO,GAAG;AACxB,QAAI,CAAC,OAAO,SAAU;AACtB,UAAM,EAAE,OAAO,IAAI,OAAO;AAC1B,QAAI,CAAC,OAAQ;AACb,QAAI;AACF,YAAM,OAAO,MAAM;AAAA,IACrB,QAAQ;AAAA,IAIR;AAAA,EACF;AACF;","names":["StepError","StepError","getConfig","StepError","isObject","StepError","StepError","StepError","isObject","isObject","StepError","StepError","isObject","getConfig","StepError","isObject","StepError","isNotFound","push","resolveSetup","PubSub","DEFAULT_SETUP","hasNumericCode","isAlreadyExists","setup","resolveSetup","DEFAULT_SETUP","PubSub","isAlreadyExists","detectDrift","types_exports","setup","push"]}
|
package/dist/schemas.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var mod,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,schemas_exports={};((target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})})(schemas_exports,{mapping:()=>mapping,pubsubMapping:()=>mapping2,pubsubSettings:()=>settings2,pubsubSetup:()=>setup,settings:()=>settings}),module.exports=(mod=schemas_exports,((to,from,except,desc)=>{if(from&&"object"==typeof from||"function"==typeof from)for(let key of __getOwnPropNames(from))__hasOwnProp.call(to,key)||key===except||__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to})(__defProp({},"__esModule",{value:!0}),mod));var import_dev3=require("@walkeros/core/dev"),import_dev=require("@walkeros/core/dev"),SettingsSchema=import_dev.z.object({client:import_dev.z.any().describe("Google Cloud BigQuery client instance (like new BigQuery({ projectId, keyFilename }))").optional(),projectId:import_dev.z.string().min(1).describe("Google Cloud Project ID (like my-gcp-project)"),datasetId:import_dev.z.string().min(1).default("walkerOS").describe("BigQuery dataset ID where events will be stored (like walker_events)"),tableId:import_dev.z.string().min(1).default("events").describe("BigQuery table ID for event storage (like events)"),location:import_dev.z.string().default("EU").describe("Geographic location for the BigQuery dataset (like US)"),bigquery:import_dev.z.any().describe('Additional BigQuery client configuration options (like { keyFilename: "path/to/key.json" })').optional()}),MappingSchema=require("@walkeros/core/dev").z.object({}),settings=(0,import_dev3.zodToSchema)(SettingsSchema),mapping=(0,import_dev3.zodToSchema)(MappingSchema),import_dev7=require("@walkeros/core/dev"),import_dev4=require("@walkeros/core/dev"),SettingsSchema2=import_dev4.z.object({client:import_dev4.z.any().describe("Google Cloud Pub/Sub client instance (like new PubSub({ projectId, keyFilename }))").optional(),projectId:import_dev4.z.string().min(1).describe("Google Cloud Project ID (like my-gcp-project)"),topic:import_dev4.z.string().min(1).describe("Pub/Sub topic short name (like events). The full resource name projects/<projectId>/topics/<topic> is built by the SDK."),credentials:import_dev4.z.any().describe("Service account credentials as a JSON string or an object with client_email and private_key. Default: Application Default Credentials (ADC). (deprecated: use config.credentials)").optional(),apiEndpoint:import_dev4.z.string().describe("Override Pub/Sub API endpoint. Useful for the local emulator (like localhost:8085).").optional(),orderingKey:import_dev4.z.any().describe("Mapping value resolved per-event. Truthy enables per-key ordering for the publish.").optional(),attributes:import_dev4.z.any().describe("Default per-event attribute map merged into every published message. Mapping.Map shape.").optional()}),import_dev5=require("@walkeros/core/dev"),MappingSchema2=import_dev5.z.object({topic:import_dev5.z.string().describe("Per-rule topic override. Falls back to settings.topic if absent.").optional(),orderingKey:import_dev5.z.any().describe("Per-rule ordering-key Mapping.Value. Overrides settings.orderingKey when set.").optional(),attributes:import_dev5.z.any().describe("Per-rule attribute Mapping.Map merged on top of settings.attributes.").optional()}),import_dev6=require("@walkeros/core/dev"),SetupSchema=import_dev6.z.object({messageStoragePolicy:import_dev6.z.object({allowedPersistenceRegions:import_dev6.z.array(import_dev6.z.string()).describe("Geographic regions for at-rest message storage. Default: EU multi-region (eu-west1, eu-west3, eu-west4).")}).describe("Topic-level message storage policy.").optional(),messageRetentionDuration:import_dev6.z.object({seconds:import_dev6.z.number().describe("Retention window in seconds. Default: project default.")}).describe("Topic-level retention configuration.").optional(),kmsKeyName:import_dev6.z.string().describe("Customer-managed encryption key (CMEK) resource name. Optional.").optional(),labels:import_dev6.z.record(import_dev6.z.string(),import_dev6.z.string()).describe("Topic labels for organization and billing.").optional()}),settings2=(0,import_dev7.zodToSchema)(SettingsSchema2),mapping2=(0,import_dev7.zodToSchema)(MappingSchema2),setup=(0,import_dev7.zodToSchema)(SetupSchema);//# sourceMappingURL=schemas.js.map
|
|
1
|
+
"use strict";var mod,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,schemas_exports={};((target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})})(schemas_exports,{mapping:()=>mapping,pubsubMapping:()=>mapping2,pubsubSettings:()=>settings2,pubsubSetup:()=>setup,settings:()=>settings}),module.exports=(mod=schemas_exports,((to,from,except,desc)=>{if(from&&"object"==typeof from||"function"==typeof from)for(let key of __getOwnPropNames(from))__hasOwnProp.call(to,key)||key===except||__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to})(__defProp({},"__esModule",{value:!0}),mod));var import_dev3=require("@walkeros/core/dev"),import_dev=require("@walkeros/core/dev"),SettingsSchema=import_dev.z.object({client:import_dev.z.any().describe("Google Cloud BigQuery client instance (like new BigQuery({ projectId, keyFilename }))").optional(),projectId:import_dev.z.string().min(1).describe("Google Cloud Project ID (like my-gcp-project)"),datasetId:import_dev.z.string().min(1).default("walkerOS").describe("BigQuery dataset ID where events will be stored (like walker_events)"),tableId:import_dev.z.string().min(1).default("events").describe("BigQuery table ID for event storage (like events)"),location:import_dev.z.string().default("EU").describe("Geographic location for the BigQuery dataset (like US)"),bigquery:import_dev.z.any().describe('Additional BigQuery client configuration options (like { keyFilename: "path/to/key.json" })').optional()}).strict(),MappingSchema=require("@walkeros/core/dev").z.object({}),settings=(0,import_dev3.zodToSchema)(SettingsSchema),mapping=(0,import_dev3.zodToSchema)(MappingSchema),import_dev7=require("@walkeros/core/dev"),import_dev4=require("@walkeros/core/dev"),SettingsSchema2=import_dev4.z.object({client:import_dev4.z.any().describe("Google Cloud Pub/Sub client instance (like new PubSub({ projectId, keyFilename }))").optional(),projectId:import_dev4.z.string().min(1).describe("Google Cloud Project ID (like my-gcp-project)"),topic:import_dev4.z.string().min(1).describe("Pub/Sub topic short name (like events). The full resource name projects/<projectId>/topics/<topic> is built by the SDK."),credentials:import_dev4.z.any().describe("Service account credentials as a JSON string or an object with client_email and private_key. Default: Application Default Credentials (ADC). (deprecated: use config.credentials)").optional(),apiEndpoint:import_dev4.z.string().describe("Override Pub/Sub API endpoint. Useful for the local emulator (like localhost:8085).").optional(),orderingKey:import_dev4.z.any().describe("Mapping value resolved per-event. Truthy enables per-key ordering for the publish.").optional(),attributes:import_dev4.z.any().describe("Default per-event attribute map merged into every published message. Mapping.Map shape.").optional()}).strict(),import_dev5=require("@walkeros/core/dev"),MappingSchema2=import_dev5.z.object({topic:import_dev5.z.string().describe("Per-rule topic override. Falls back to settings.topic if absent.").optional(),orderingKey:import_dev5.z.any().describe("Per-rule ordering-key Mapping.Value. Overrides settings.orderingKey when set.").optional(),attributes:import_dev5.z.any().describe("Per-rule attribute Mapping.Map merged on top of settings.attributes.").optional()}),import_dev6=require("@walkeros/core/dev"),SetupSchema=import_dev6.z.object({messageStoragePolicy:import_dev6.z.object({allowedPersistenceRegions:import_dev6.z.array(import_dev6.z.string()).describe("Geographic regions for at-rest message storage. Default: EU multi-region (eu-west1, eu-west3, eu-west4).")}).describe("Topic-level message storage policy.").optional(),messageRetentionDuration:import_dev6.z.object({seconds:import_dev6.z.number().describe("Retention window in seconds. Default: project default.")}).describe("Topic-level retention configuration.").optional(),kmsKeyName:import_dev6.z.string().describe("Customer-managed encryption key (CMEK) resource name. Optional.").optional(),labels:import_dev6.z.record(import_dev6.z.string(),import_dev6.z.string()).describe("Topic labels for organization and billing.").optional()}),settings2=(0,import_dev7.zodToSchema)(SettingsSchema2),mapping2=(0,import_dev7.zodToSchema)(MappingSchema2),setup=(0,import_dev7.zodToSchema)(SetupSchema);//# sourceMappingURL=schemas.js.map
|
package/dist/schemas.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/schemas.ts","../src/bigquery/schemas/index.ts","../src/bigquery/schemas/settings.ts","../src/bigquery/schemas/mapping.ts","../src/pubsub/schemas/index.ts","../src/pubsub/schemas/settings.ts","../src/pubsub/schemas/mapping.ts","../src/pubsub/schemas/setup.ts"],"sourcesContent":["// Browser-safe schema-only exports\n// This file exports ONLY schemas without any Node.js dependencies\nexport { settings, mapping } from './bigquery/schemas';\nexport {\n settings as pubsubSettings,\n mapping as pubsubMapping,\n setup as pubsubSetup,\n} from './pubsub/schemas';\n","import { zodToSchema } from '@walkeros/core/dev';\nimport { SettingsSchema } from './settings';\nimport { MappingSchema } from './mapping';\n\nexport { SettingsSchema, type Settings } from './settings';\nexport { MappingSchema, type Mapping } from './mapping';\n\n// JSON Schema\nexport const settings = zodToSchema(SettingsSchema);\nexport const mapping = zodToSchema(MappingSchema);\n","import { z } from '@walkeros/core/dev';\n\nexport const SettingsSchema = z.object({\n
|
|
1
|
+
{"version":3,"sources":["../src/schemas.ts","../src/bigquery/schemas/index.ts","../src/bigquery/schemas/settings.ts","../src/bigquery/schemas/mapping.ts","../src/pubsub/schemas/index.ts","../src/pubsub/schemas/settings.ts","../src/pubsub/schemas/mapping.ts","../src/pubsub/schemas/setup.ts"],"sourcesContent":["// Browser-safe schema-only exports\n// This file exports ONLY schemas without any Node.js dependencies\nexport { settings, mapping } from './bigquery/schemas';\nexport {\n settings as pubsubSettings,\n mapping as pubsubMapping,\n setup as pubsubSetup,\n} from './pubsub/schemas';\n","import { zodToSchema } from '@walkeros/core/dev';\nimport { SettingsSchema } from './settings';\nimport { MappingSchema } from './mapping';\n\nexport { SettingsSchema, type Settings } from './settings';\nexport { MappingSchema, type Mapping } from './mapping';\n\n// JSON Schema\nexport const settings = zodToSchema(SettingsSchema);\nexport const mapping = zodToSchema(MappingSchema);\n","import { z } from '@walkeros/core/dev';\n\nexport const SettingsSchema = z\n .object({\n client: z\n .any()\n .describe(\n 'Google Cloud BigQuery client instance (like new BigQuery({ projectId, keyFilename }))',\n )\n .optional(),\n projectId: z\n .string()\n .min(1)\n .describe('Google Cloud Project ID (like my-gcp-project)'),\n datasetId: z\n .string()\n .min(1)\n .default('walkerOS')\n .describe(\n 'BigQuery dataset ID where events will be stored (like walker_events)',\n ),\n tableId: z\n .string()\n .min(1)\n .default('events')\n .describe('BigQuery table ID for event storage (like events)'),\n location: z\n .string()\n .default('EU')\n .describe('Geographic location for the BigQuery dataset (like US)'),\n bigquery: z\n .any()\n .describe(\n 'Additional BigQuery client configuration options (like { keyFilename: \"path/to/key.json\" })',\n )\n .optional(),\n })\n .strict();\n\nexport type Settings = z.infer<typeof SettingsSchema>;\n","import { z } from '@walkeros/core/dev';\n\n/**\n * GCP BigQuery Mapping Schema\n * BigQuery has no event-level mapping configuration\n */\nexport const MappingSchema = z.object({});\n\n/**\n * Type inference from MappingSchema\n */\nexport type Mapping = z.infer<typeof MappingSchema>;\n","import { zodToSchema } from '@walkeros/core/dev';\nimport { SettingsSchema } from './settings';\nimport { MappingSchema } from './mapping';\nimport { SetupSchema } from './setup';\n\nexport { SettingsSchema, type Settings } from './settings';\nexport { MappingSchema, type Mapping } from './mapping';\nexport { SetupSchema, type Setup } from './setup';\n\n// JSON Schema\nexport const settings = zodToSchema(SettingsSchema);\nexport const mapping = zodToSchema(MappingSchema);\nexport const setup = zodToSchema(SetupSchema);\n","import { z } from '@walkeros/core/dev';\n\nexport const SettingsSchema = z\n .object({\n client: z\n .any()\n .describe(\n 'Google Cloud Pub/Sub client instance (like new PubSub({ projectId, keyFilename }))',\n )\n .optional(),\n projectId: z\n .string()\n .min(1)\n .describe('Google Cloud Project ID (like my-gcp-project)'),\n topic: z\n .string()\n .min(1)\n .describe(\n 'Pub/Sub topic short name (like events). The full resource name projects/<projectId>/topics/<topic> is built by the SDK.',\n ),\n credentials: z\n .any()\n .describe(\n 'Service account credentials as a JSON string or an object with client_email and private_key. Default: Application Default Credentials (ADC). (deprecated: use config.credentials)',\n )\n .optional(),\n apiEndpoint: z\n .string()\n .describe(\n 'Override Pub/Sub API endpoint. Useful for the local emulator (like localhost:8085).',\n )\n .optional(),\n orderingKey: z\n .any()\n .describe(\n 'Mapping value resolved per-event. Truthy enables per-key ordering for the publish.',\n )\n .optional(),\n attributes: z\n .any()\n .describe(\n 'Default per-event attribute map merged into every published message. Mapping.Map shape.',\n )\n .optional(),\n })\n .strict();\n\nexport type Settings = z.infer<typeof SettingsSchema>;\n","import { z } from '@walkeros/core/dev';\n\n/**\n * GCP Pub/Sub Mapping Schema\n *\n * Per-rule overrides for topic, orderingKey, and attributes.\n */\nexport const MappingSchema = z.object({\n topic: z\n .string()\n .describe(\n 'Per-rule topic override. Falls back to settings.topic if absent.',\n )\n .optional(),\n orderingKey: z\n .any()\n .describe(\n 'Per-rule ordering-key Mapping.Value. Overrides settings.orderingKey when set.',\n )\n .optional(),\n attributes: z\n .any()\n .describe(\n 'Per-rule attribute Mapping.Map merged on top of settings.attributes.',\n )\n .optional(),\n});\n\n/**\n * Type inference from MappingSchema\n */\nexport type Mapping = z.infer<typeof MappingSchema>;\n","import { z } from '@walkeros/core/dev';\n\n/**\n * GCP Pub/Sub Setup Schema\n *\n * Provisioning options for `walkeros setup destination.<id>`. Idempotent topic\n * creation. Subscription provisioning is owned by the source side.\n */\nexport const SetupSchema = z.object({\n messageStoragePolicy: z\n .object({\n allowedPersistenceRegions: z\n .array(z.string())\n .describe(\n 'Geographic regions for at-rest message storage. Default: EU multi-region (eu-west1, eu-west3, eu-west4).',\n ),\n })\n .describe('Topic-level message storage policy.')\n .optional(),\n messageRetentionDuration: z\n .object({\n seconds: z\n .number()\n .describe('Retention window in seconds. Default: project default.'),\n })\n .describe('Topic-level retention configuration.')\n .optional(),\n kmsKeyName: z\n .string()\n .describe('Customer-managed encryption key (CMEK) resource name. Optional.')\n .optional(),\n labels: z\n .record(z.string(), z.string())\n .describe('Topic labels for organization and billing.')\n .optional(),\n});\n\nexport type Setup = z.infer<typeof SetupSchema>;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA,uBAAAA;AAAA,EAAA,sBAAAC;AAAA,EAAA;AAAA;AAAA;AAAA;;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AACd,CAAC,EACA,OAAO;;;AC7CV,IAAAC,cAAkB;AAOX,IAAMC,iBAAgB,cAAE,OAAO;AAAA,EACpC,OAAO,cACJ,OAAO,EACP;AAAA,IACC;AAAA,EACF,EACC,SAAS;AAAA,EACZ,aAAa,cACV,IAAI,EACJ;AAAA,IACC;AAAA,EACF,EACC,SAAS;AAAA,EACZ,YAAY,cACT,IAAI,EACJ;AAAA,IACC;AAAA,EACF,EACC,SAAS;AACd,CAAC;;;AC1BD,IAAAC,cAAkB;AAQX,IAAM,cAAc,cAAE,OAAO;AAAA,EAClC,sBAAsB,cACnB,OAAO;AAAA,IACN,2BAA2B,cACxB,MAAM,cAAE,OAAO,CAAC,EAChB;AAAA,MACC;AAAA,IACF;AAAA,EACJ,CAAC,EACA,SAAS,qCAAqC,EAC9C,SAAS;AAAA,EACZ,0BAA0B,cACvB,OAAO;AAAA,IACN,SAAS,cACN,OAAO,EACP,SAAS,wDAAwD;AAAA,EACtE,CAAC,EACA,SAAS,sCAAsC,EAC/C,SAAS;AAAA,EACZ,YAAY,cACT,OAAO,EACP,SAAS,iEAAiE,EAC1E,SAAS;AAAA,EACZ,QAAQ,cACL,OAAO,cAAE,OAAO,GAAG,cAAE,OAAO,CAAC,EAC7B,SAAS,4CAA4C,EACrD,SAAS;AACd,CAAC;;;AHzBM,IAAMC,gBAAW,yBAAYC,eAAc;AAC3C,IAAMC,eAAU,yBAAYC,cAAa;AACzC,IAAM,YAAQ,yBAAY,WAAW;","names":["mapping","settings","import_dev","import_dev","import_dev","import_dev","SettingsSchema","import_dev","MappingSchema","import_dev","settings","SettingsSchema","mapping","MappingSchema"]}
|
package/dist/schemas.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{zodToSchema}from"@walkeros/core/dev";import{z}from"@walkeros/core/dev";var SettingsSchema=z.object({client:z.any().describe("Google Cloud BigQuery client instance (like new BigQuery({ projectId, keyFilename }))").optional(),projectId:z.string().min(1).describe("Google Cloud Project ID (like my-gcp-project)"),datasetId:z.string().min(1).default("walkerOS").describe("BigQuery dataset ID where events will be stored (like walker_events)"),tableId:z.string().min(1).default("events").describe("BigQuery table ID for event storage (like events)"),location:z.string().default("EU").describe("Geographic location for the BigQuery dataset (like US)"),bigquery:z.any().describe('Additional BigQuery client configuration options (like { keyFilename: "path/to/key.json" })').optional()});import{z as z2}from"@walkeros/core/dev";var MappingSchema=z2.object({}),settings=zodToSchema(SettingsSchema),mapping=zodToSchema(MappingSchema);import{zodToSchema as zodToSchema2}from"@walkeros/core/dev";import{z as z3}from"@walkeros/core/dev";var SettingsSchema2=z3.object({client:z3.any().describe("Google Cloud Pub/Sub client instance (like new PubSub({ projectId, keyFilename }))").optional(),projectId:z3.string().min(1).describe("Google Cloud Project ID (like my-gcp-project)"),topic:z3.string().min(1).describe("Pub/Sub topic short name (like events). The full resource name projects/<projectId>/topics/<topic> is built by the SDK."),credentials:z3.any().describe("Service account credentials as a JSON string or an object with client_email and private_key. Default: Application Default Credentials (ADC). (deprecated: use config.credentials)").optional(),apiEndpoint:z3.string().describe("Override Pub/Sub API endpoint. Useful for the local emulator (like localhost:8085).").optional(),orderingKey:z3.any().describe("Mapping value resolved per-event. Truthy enables per-key ordering for the publish.").optional(),attributes:z3.any().describe("Default per-event attribute map merged into every published message. Mapping.Map shape.").optional()});import{z as z4}from"@walkeros/core/dev";var MappingSchema2=z4.object({topic:z4.string().describe("Per-rule topic override. Falls back to settings.topic if absent.").optional(),orderingKey:z4.any().describe("Per-rule ordering-key Mapping.Value. Overrides settings.orderingKey when set.").optional(),attributes:z4.any().describe("Per-rule attribute Mapping.Map merged on top of settings.attributes.").optional()});import{z as z5}from"@walkeros/core/dev";var SetupSchema=z5.object({messageStoragePolicy:z5.object({allowedPersistenceRegions:z5.array(z5.string()).describe("Geographic regions for at-rest message storage. Default: EU multi-region (eu-west1, eu-west3, eu-west4).")}).describe("Topic-level message storage policy.").optional(),messageRetentionDuration:z5.object({seconds:z5.number().describe("Retention window in seconds. Default: project default.")}).describe("Topic-level retention configuration.").optional(),kmsKeyName:z5.string().describe("Customer-managed encryption key (CMEK) resource name. Optional.").optional(),labels:z5.record(z5.string(),z5.string()).describe("Topic labels for organization and billing.").optional()}),settings2=zodToSchema2(SettingsSchema2),mapping2=zodToSchema2(MappingSchema2),setup=zodToSchema2(SetupSchema);export{mapping,mapping2 as pubsubMapping,settings2 as pubsubSettings,setup as pubsubSetup,settings};//# sourceMappingURL=schemas.mjs.map
|
|
1
|
+
import{createRequire}from"module";createRequire(import.meta.url);import{zodToSchema}from"@walkeros/core/dev";import{z}from"@walkeros/core/dev";var SettingsSchema=z.object({client:z.any().describe("Google Cloud BigQuery client instance (like new BigQuery({ projectId, keyFilename }))").optional(),projectId:z.string().min(1).describe("Google Cloud Project ID (like my-gcp-project)"),datasetId:z.string().min(1).default("walkerOS").describe("BigQuery dataset ID where events will be stored (like walker_events)"),tableId:z.string().min(1).default("events").describe("BigQuery table ID for event storage (like events)"),location:z.string().default("EU").describe("Geographic location for the BigQuery dataset (like US)"),bigquery:z.any().describe('Additional BigQuery client configuration options (like { keyFilename: "path/to/key.json" })').optional()}).strict();import{z as z2}from"@walkeros/core/dev";var MappingSchema=z2.object({}),settings=zodToSchema(SettingsSchema),mapping=zodToSchema(MappingSchema);import{zodToSchema as zodToSchema2}from"@walkeros/core/dev";import{z as z3}from"@walkeros/core/dev";var SettingsSchema2=z3.object({client:z3.any().describe("Google Cloud Pub/Sub client instance (like new PubSub({ projectId, keyFilename }))").optional(),projectId:z3.string().min(1).describe("Google Cloud Project ID (like my-gcp-project)"),topic:z3.string().min(1).describe("Pub/Sub topic short name (like events). The full resource name projects/<projectId>/topics/<topic> is built by the SDK."),credentials:z3.any().describe("Service account credentials as a JSON string or an object with client_email and private_key. Default: Application Default Credentials (ADC). (deprecated: use config.credentials)").optional(),apiEndpoint:z3.string().describe("Override Pub/Sub API endpoint. Useful for the local emulator (like localhost:8085).").optional(),orderingKey:z3.any().describe("Mapping value resolved per-event. Truthy enables per-key ordering for the publish.").optional(),attributes:z3.any().describe("Default per-event attribute map merged into every published message. Mapping.Map shape.").optional()}).strict();import{z as z4}from"@walkeros/core/dev";var MappingSchema2=z4.object({topic:z4.string().describe("Per-rule topic override. Falls back to settings.topic if absent.").optional(),orderingKey:z4.any().describe("Per-rule ordering-key Mapping.Value. Overrides settings.orderingKey when set.").optional(),attributes:z4.any().describe("Per-rule attribute Mapping.Map merged on top of settings.attributes.").optional()});import{z as z5}from"@walkeros/core/dev";var SetupSchema=z5.object({messageStoragePolicy:z5.object({allowedPersistenceRegions:z5.array(z5.string()).describe("Geographic regions for at-rest message storage. Default: EU multi-region (eu-west1, eu-west3, eu-west4).")}).describe("Topic-level message storage policy.").optional(),messageRetentionDuration:z5.object({seconds:z5.number().describe("Retention window in seconds. Default: project default.")}).describe("Topic-level retention configuration.").optional(),kmsKeyName:z5.string().describe("Customer-managed encryption key (CMEK) resource name. Optional.").optional(),labels:z5.record(z5.string(),z5.string()).describe("Topic labels for organization and billing.").optional()}),settings2=zodToSchema2(SettingsSchema2),mapping2=zodToSchema2(MappingSchema2),setup=zodToSchema2(SetupSchema);export{mapping,mapping2 as pubsubMapping,settings2 as pubsubSettings,setup as pubsubSetup,settings};//# sourceMappingURL=schemas.mjs.map
|