@brickkit/effect 0.16.0-beta.11 → 0.16.0-beta.13

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.
@@ -2236,6 +2236,30 @@ function rateLimitStage(config, service) {
2236
2236
  })
2237
2237
  };
2238
2238
  }
2239
+ // src/omit-undefined.ts
2240
+ const isPlain = (value) => {
2241
+ if (typeof value !== "object" || value === null) return false;
2242
+ const proto = Object.getPrototypeOf(value);
2243
+ return proto === Object.prototype || proto === null;
2244
+ };
2245
+ /**
2246
+ * The value without the keys of plain objects that hold `undefined`, as
2247
+ * `JSON.stringify` and so core drop them. Schemas encode an `undefined` to
2248
+ * `null`, so a handler's `{ domain: row.domain ?? undefined }` would put
2249
+ * `"domain": null` on the wire. Array items, class instances, `Date` and the
2250
+ * rest are left as they are.
2251
+ */
2252
+ const omitUndefined = (value) => {
2253
+ if (Array.isArray(value)) return value.map(omitUndefined);
2254
+ if (!isPlain(value)) return value;
2255
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0).map(([key, item]) => [key, omitUndefined(item)]));
2256
+ };
2257
+ /**
2258
+ * Runs `run` on the value without its undefined keys. A schema that requires
2259
+ * such a key (`Schema.UndefinedOr`) refuses that, so it then runs on the value
2260
+ * as it came, and the key encodes as `null`.
2261
+ */
2262
+ const omittingUndefined = (run) => (value) => run(omitUndefined(value)).pipe(Effect.catch(() => run(value)));
2239
2263
  // src/sensitive.ts
2240
2264
  const MARK = "brickSensitive";
2241
2265
  /**
@@ -2903,7 +2927,7 @@ function stagesOf(config, host, action) {
2903
2927
  ...audit ? [audit] : [],
2904
2928
  ...check ? [{
2905
2929
  name: "output",
2906
- run: (call, next) => next(call).pipe(Effect.flatMap((result) => check[call.wire ? "json" : "value"](result, all).pipe(Effect.mapError((error) => invalid$1(name, "output", issuesOf(error, result))))))
2930
+ run: (call, next) => next(call).pipe(Effect.flatMap((result) => omittingUndefined((value) => check[call.wire ? "json" : "value"](value, all))(result).pipe(Effect.mapError((error) => invalid$1(name, "output", issuesOf(error, result))))))
2907
2931
  }] : [],
2908
2932
  {
2909
2933
  name: "execute",
@@ -4149,7 +4173,7 @@ function defineEvents(service, catalog) {
4149
4173
  *
4150
4174
  * @throws (as a defect) When the payload does not match.
4151
4175
  */
4152
- const encodePayload = (ref, payload) => Schema.encodeUnknownEffect(Schema.toCodecJson(ref.schema))(payload, { errors: "all" }).pipe(Effect.catch((error) => Effect.die(/* @__PURE__ */ new Error(`Event "${ref.name}" payload does not match its schema: ${error.message}`))));
4176
+ const encodePayload = (ref, payload) => omittingUndefined((value) => Schema.encodeUnknownEffect(Schema.toCodecJson(ref.schema))(value, { errors: "all" }))(payload).pipe(Effect.catch((error) => Effect.die(/* @__PURE__ */ new Error(`Event "${ref.name}" payload does not match its schema: ${error.message}`))));
4153
4177
  /** The payload of a delivery, decoded with the event's schema. */
4154
4178
  const decodePayload = (ref, payload) => Schema.decodeUnknownEffect(Schema.toCodecJson(ref.schema))(payload);
4155
4179
  /** The writes a resource's CRUD events report. Payloads are `CrudEventPayload`. */
@@ -4238,6 +4262,27 @@ const queueOnCommit = (effect, wanted) => Effect.flatMap(Effect.serviceOption(Op
4238
4262
  if (wanted(commits)) commits.push(effect);
4239
4263
  })
4240
4264
  }));
4265
+ /** The `@effect/sql` client of a drizzle Effect database, which owns its transactions. */
4266
+ const clientOf = (db) => {
4267
+ const client = db?.$client;
4268
+ return typeof client?.afterCommit === "function" ? client : void 0;
4269
+ };
4270
+ /**
4271
+ * Run `effect` once the outermost transaction on `db` has committed, whoever
4272
+ * opened it (`runInTransaction`, or the app's own drizzle `db.transaction`); at
4273
+ * once when none is open. Never when it rolls back. It runs without that
4274
+ * transaction, so what it forks never touches its connection.
4275
+ */
4276
+ const afterCommitOn = (db, effect) => clientOf(db)?.afterCommit(effect) ?? effect;
4277
+ /**
4278
+ * `effect` without the transaction `db`'s client has open in the fiber. A fiber
4279
+ * forked from inside a transaction inherits it, and fails once it ends (or
4280
+ * delivers from an uncommitted row while it is open).
4281
+ */
4282
+ const outsideTransaction = (db, effect) => {
4283
+ const client = clientOf(db);
4284
+ return client ? Effect.updateContext(effect, Context.omit(client.transactionService)) : effect;
4285
+ };
4241
4286
  /** `brick.token.<token>`: a bearer token carried as a subprotocol, since browsers can't set headers on a WebSocket. */
4242
4287
  const SOCKET_TOKEN_PROTOCOL = "brick.token.";
4243
4288
  /** Control messages, sent as frames whose event starts with `$`. */
@@ -4318,7 +4363,7 @@ function socketCodecs(schemas) {
4318
4363
  const refuse = (message) => Effect.die(new Error(message));
4319
4364
  if (!codec) return refuse("Invalid socket output");
4320
4365
  return Effect.gen(function* () {
4321
- const json = yield* codec.encode(data).pipe(Effect.catch(() => refuse("Invalid socket output")));
4366
+ const json = yield* omittingUndefined(codec.encode)(data).pipe(Effect.catch(() => refuse("Invalid socket output")));
4322
4367
  const frame = encodeFrame(event, json);
4323
4368
  if (byteLength(frame) > 65536) return yield* refuse("Socket output too large");
4324
4369
  return frame;
@@ -5752,7 +5797,7 @@ function makeDispatcher(config) {
5752
5797
  return {
5753
5798
  start: Effect.suspend(() => {
5754
5799
  if (worker || !options.timer) return Effect.void;
5755
- return pollUnref(tick, Schedule.fixed(options.intervalMs)).pipe(Effect.forkIn(scope), Effect.map((fiber) => {
5800
+ return outsideTransaction(db, pollUnref(tick, Schedule.fixed(options.intervalMs))).pipe(Effect.forkIn(scope), Effect.map((fiber) => {
5756
5801
  worker = fiber;
5757
5802
  }));
5758
5803
  }),
@@ -5763,7 +5808,7 @@ function makeDispatcher(config) {
5763
5808
  yield* turn.withPermits(1)(Effect.void);
5764
5809
  yield* settled;
5765
5810
  }),
5766
- notify: Effect.suspend(() => worker ? Effect.asVoid(Effect.forkIn(backgroundTick, scope)) : Effect.void),
5811
+ notify: Effect.suspend(() => worker ? Effect.asVoid(Effect.forkIn(outsideTransaction(db, backgroundTick), scope)) : Effect.void),
5767
5812
  drain: Effect.gen(function* () {
5768
5813
  let total = 0;
5769
5814
  for (;;) {
@@ -6064,7 +6109,7 @@ function createEvents(options, services, telemetry = false) {
6064
6109
  transaction: (db, eventContext, fn) => Effect.suspend(() => {
6065
6110
  const recorder = recorders.get(db);
6066
6111
  if (!recorder) return Effect.die(/* @__PURE__ */ new Error(NO_OUTBOX));
6067
- const notify = Effect.andThen(start, recorder.dispatcher.notify);
6112
+ const notify = afterCommitOn(db, Effect.andThen(start, recorder.dispatcher.notify));
6068
6113
  return runInTransaction(db, (tx) => fn(tx, (name, payload, options) => Effect.flatMap(insert(recorder, tx, eventContext, name, payload, options?.encoded), (recorded) => recorded ? onTransactionCommitOnce(notify) : Effect.void)));
6069
6114
  }),
6070
6115
  start,
@@ -8807,4 +8852,4 @@ function brick(options = {}) {
8807
8852
  }
8808
8853
  export { PLUGIN_KIND as $, toErrorResponse as $n, envSource as $t, onTransactionCommit as A, telemetryLayer as An, errorHelpers as At, scalarDocsHTML as B, signDashboardIdentity as Bn, defineStorage as Bt, scheduleTable as C, baseContext as Cn, kindOf as Ct, defineServiceSocket as D, Telemetry as Dn, RESET_STAGES as Dt, SocketDenied as E, SpanStore as En, HTTP_METHODS as Et, encodePayload as F, dashboardIdentity as Fn, hasSensitive as Ft, getPluginActionRoute as G, actionMeta as Gn, storageKey as Gt, copyControls as H, ATTR as Hn, memory as Ht, isCrudEvent as I, dashboardKey as In, redact as It, installPlugin as J, STANDARD_ERRORS as Jn, scopeFiles as Jt, getPluginEndpoints as K, BrickError as Kn, LOCAL_FILES_ROUTE as Kt, OPENAPI_DEFAULTS as L, dashboardMcpCaller as Ln, sensitivePointer as Lt, crudEventName as M, traceScheduleRun as Mn, runStages as Mt, crudEventSource as N, DASHBOARD_IDENTITY_HEADER as Nn, stagesOf as Nt, localBroker as O, recordWebhook as On, createAction as Ot, defineEvents as P, DASHBOARD_KEY_ENV as Pn, Sensitive as Pt, PLUGIN_COMMIT as Q, prefixedFailure as Qn, defineSecret as Qt, generateOpenApiSpec as R, dashboardUser as Rn, carryClientRequest as Rt, outboxTable as S, actorOf as Sn, jsonValue as St, defineRawSocket as T, defaultLogger as Tn, withoutNull as Tt, defineResourcePlugin as U, GLOBAL_SYMBOL as Un, redis as Ut, claimSegment as V, signDashboardMcp as Vn, frameworkStorage as Vt, defineServicePlugin as W, SPAN as Wn, requireStorage as Wt, internalsOf$1 as X, failureOfCause as Xn, StorageUnavailableError as Xt, validatePath as Y, ValidationError as Yn, StorageError as Yt, setInternals as Z, normalizeFailures as Zn, SecretRef as Zt, idSchema as _, inlineAuditOptions as _n, databaseValue as _t, Workflow as a, definitionSite as an, getActionRoute as at, stopAllEvents as b, recordAudit as bn, idSchema$1 as bt, WORKFLOW_TABLE as c, ownDeps as cn, getActionAccess as ct, createMcpHandler as d, UploadedFile as dn, ORDERED_TYPES as dt, listSecrets as en, toWireError as er, getGlobalRegistry as et, createMcpRegistry as f, UploadedFiles as fn, SORTABLE_TYPES as ft, defineResource as g, bindAuditTarget as gn, columnValue as gt, normalizeDashboard as h, auditTableOf as hn, columnSchema as ht, DurableDeferred as i, claimName as in, actionOwners as it, runInTransaction as j, traceRoute as jn, invalid$1 as jt, splitSeq as k, spanStore as kn, deny as kt, INTERNALS as l, useDeps as ln, setActionAccess as lt, DASHBOARD_MCP_TOOLS as m, auditTable as mn, checkJsonSchema as mt, Activity as n, resetSecrets as nn, exportArchitecture as nt, WorkflowEngine as o, depsOverride as on, isObjectSchema as ot, DASHBOARD_MCP_ROUTE as p, fileFields as pn, UNFILTERABLE_TYPES as pt, hasPlugin as q, DuplicateNameError as qn, s3 as qt, DurableClock as r, resolveSecrets as rn, DEFAULT_PREFIX as rt, workflowEngine as s, freezeAsBuiltDeps as sn, kebabCase as st, brick as t, overrideSecret as tn, resetGlobalRegistry as tt, UnknownToolError as u, withOverride as un, setActionAudit as ut, loadRecord as v, isAuditTable as vn, decodeCursor as vt, defineSchedule as w, createLogger as wn, reject as wt, defineListener as x, recordInline as xn, invalid as xt, Events as y, isInlineAudit as yn, encodeCursor as yt, requestLoggingPlugin as z, markDashboardArrival as zn, clientAddress as zt };
8809
8854
 
8810
- //# sourceMappingURL=server-CKevfoZj.js.map
8855
+ //# sourceMappingURL=server-BU2vMdOO.js.map