durable-db 0.14.1 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -249,7 +249,7 @@ An optional key accepts `undefined`, as its inferred TypeScript type (`{ photoKe
249
249
 
250
250
  ### `durable-db/type`
251
251
 
252
- `type` (from `durable-db`, `durable-db/db` or `durable-db/type`) is ArkType's `type()`: the same definitions, the same inferred types and editor errors — ArkType's own type-level parser, imported as types only — and the same error messages and JSON Schema, on a runtime of its own. ArkType builds its whole scope of keywords when it is imported, ~40 ms of CPU at every cold start of a worker and of every Durable Object; this one builds nothing until a definition is parsed (~2 ms to import, about ArkType's speed per validation without its JIT, which Workers refuse anyway).
252
+ `type` (from `durable-db`, `durable-db/db` or `durable-db/type`) is ArkType's `type()`: the same definitions, the same inferred types and editor errors — ArkType's own type-level parser, imported as types only — and the same error messages and JSON Schema, on a runtime of its own. ArkType builds its whole scope of keywords when it is imported, ~40 ms of CPU at every cold start of a worker and of every Durable Object; this one builds nothing until a definition is parsed (~2 ms to import, about ArkType's speed per validation without its JIT, which Workers refuse anyway), and parses a definition when its Type is first used — a call, any of its properties or methods, its use in another Type — not when `type()` is called, so the definitions a worker and each Durable Object evaluate as they start cost nothing until one is used. What it parses is the definition as it was at `type()`: `type()` copies its plain objects and arrays, at any depth, so one changed afterwards does not change what the Type checks. What a definition holds as a value is kept as it is — the values of `['===', …]`, a default (`[def, '=', value]`), a Type, a function, a RegExp, a Standard Schema, an instance of a class (read when the definition is parsed).
253
253
 
254
254
  ```ts
255
255
  import { type } from 'durable-db/type';
@@ -264,7 +264,7 @@ Invoice.toJsonSchema(); // JSON Schema (2020-12 or draft-07)
264
264
  Invoice['~standard']; // a Standard Schema, with its JSON Schema converter
265
265
  ```
266
266
 
267
- It has ArkType's keywords (`string.email`, `string.uuid`, `number.integer`, `string.numeric.parse`, `string.date.iso.parse`, …), bounds (`'string > 0'`, `'0 < number <= 10'`, `'number % 2'`), unions, intersections, literals, regexes, arrays, tuples (`['string', 'number?']`, `['string', '...', 'number[]']`), `Record<K, V>`, object keys (`'key?'`, `'[string]'`, `'+'`, `'...'`), defaults (`'number = 0'`), tuple expressions (`'[]'`, `'|'`, `'&'`, `'=>'`, `':'`, `'|>'`, `'@'`, `'==='`, `'instanceof'`, `'keyof'`) and a Type's methods (`array`, `or`, `and`, `merge`, `pick`, `omit`, `partial`, `required`, `keyof`, `get`, `optional`, `default`, `narrow`, `pipe`, `to`, `describe`, `configure`, `brand`, `onUndeclaredKey`, `props`, `assert`, `allows`, `from`, `toJsonSchema`). ArkType's scopes, generics, `match` and `fn` are not there: a definition it does not know fails with a `ParseError` naming it, never a validator that checks something else. `tests/type/conformance.test.ts` runs every supported definition through both against the same values. One difference is on purpose: a JSON Schema lists an object's `properties` in the order the keys were declared, where ArkType sorts them (its `required` list stays sorted). A Type of `durable-db/type` nests in ArkType's own definitions and the other way round.
267
+ It has ArkType's keywords (`string.email`, `string.uuid`, `number.integer`, `string.numeric.parse`, `string.date.iso.parse`, …), bounds (`'string > 0'`, `'0 < number <= 10'`, `'number % 2'`), unions, intersections, literals, regexes, arrays, tuples (`['string', 'number?']`, `['string', '...', 'number[]']`), `Record<K, V>`, object keys (`'key?'`, `'[string]'`, `'+'`, `'...'`), defaults (`'number = 0'`), tuple expressions (`'[]'`, `'|'`, `'&'`, `'=>'`, `':'`, `'|>'`, `'@'`, `'==='`, `'instanceof'`, `'keyof'`) and a Type's methods (`array`, `or`, `and`, `merge`, `pick`, `omit`, `partial`, `required`, `keyof`, `get`, `optional`, `default`, `narrow`, `pipe`, `to`, `describe`, `configure`, `brand`, `onUndeclaredKey`, `props`, `assert`, `allows`, `from`, `toJsonSchema`). ArkType's scopes, generics, `match` and `fn` are not there: a definition it does not know fails with a `ParseError` naming it — at the Type's first use; ArkType's types refuse it at compile time — never a validator that checks something else. `tests/type/conformance.test.ts` runs every supported definition through both against the same values. One difference is on purpose: a JSON Schema lists an object's `properties` in the order the keys were declared, where ArkType sorts them (its `required` list stays sorted). A Type of `durable-db/type` nests in ArkType's own definitions and the other way round.
268
268
 
269
269
  ### The `handler` function
270
270
 
@@ -274,7 +274,40 @@ Receives three arguments:
274
274
  |----------|------|-------------|
275
275
  | `db` | `Kysely<Schema>` | Type-safe Kysely query builder bound to your Drizzle schema |
276
276
  | `args` | inferred from `args` | Validated arguments |
277
- | `ctx` | `ActionContext` | Context with `env` (Cloudflare bindings) and `instanceKey` |
277
+ | `ctx` | `ActionContext` | Context with `env` (Cloudflare bindings), `instanceKey`, `outbox` ([the outbox](#the-outbox)) and `transaction` (a part that may fail on its own, below) |
278
+
279
+ ### One transaction
280
+
281
+ An action runs as one transaction of its Durable Object (`ctx.storage.transaction()`): when the handler resolves, its writes — and the messages it pushed to [the outbox](#the-outbox), with the alarm that delivers them — are committed together; when it throws, none of them are. A voucher and its lines, an invoice and its number: all or nothing.
282
+
283
+ ```ts
284
+ export const postVoucher = action({
285
+ args: { series: 'string', lines: [{ account: 'string', amountOre: 'number.integer' }, '[]'] },
286
+ handler: async (db, args, ctx) => {
287
+ const last = await db.selectFrom('vouchers').select((eb) => eb.fn.max('number').as('n')).where('series', '=', args.series).executeTakeFirst();
288
+ const voucher = await db.insertInto('vouchers').values({ series: args.series, number: (last?.n ?? 0) + 1 }).returningAll().executeTakeFirstOrThrow();
289
+ await db.insertInto('lines').values(args.lines.map((line) => ({ voucherId: voucher.id, ...line }))).execute();
290
+ ctx.outbox.push({ type: 'voucher-posted', id: voucher.id });
291
+ return voucher;
292
+ },
293
+ });
294
+ ```
295
+
296
+ - **No other call in between.** While an action runs, its object takes no other call: the runtime holds the next one until the action has resolved. So two actions never interleave — not at an `await` on another object or a `fetch`, not when several calls arrive while the object migrates —, and a read followed by a write (`max(number) + 1`, a balance) is never lost to another call.
297
+ - **A part that may fail on its own.** `ctx.transaction(async () => { … })` runs a part of the action as a savepoint: when it throws, its writes and the messages it pushed are rolled back, the error is the caller's to catch, and the action goes on. Two parts started at once run one after the other. An action called from another action of the same database runs as such a part, so it too is all or nothing.
298
+
299
+ ```ts
300
+ try {
301
+ await ctx.transaction(() => reserveSeat(db, args));
302
+ } catch {
303
+ await db.insertInto('waitlist').values(args).execute();
304
+ }
305
+ ```
306
+ - **Kysely's `db.transaction()`** is refused, naming `ctx.transaction()`: the action already is one, and a Durable Object refuses SQL's `BEGIN` and `SAVEPOINT` anyway.
307
+ - **An action holds its object.** An action that waits on I/O — another database's action, a `fetch` — holds its object for that long, every other call of it waiting. Keep slow work out of actions (call it from the worker, or [push it to the outbox](#the-outbox)). The runtime resets an object whose action runs for more than 30 s, and the action's writes are rolled back.
308
+ - **Across objects nothing is atomic.** An action of another database (another object, or another tenant's) runs as a transaction of its own and commits on its own: when the calling action then throws, what the other one wrote stays. Use the outbox for the step that must follow a commit.
309
+ - **Calls between objects, in one direction.** An action that calls another database's action holds its object while the other runs. A call back into an object waiting on it — `billing → ledger → billing`, at any depth — would wait for itself; it is refused at once with an `ActionCycleError` naming the chain (from `durable-db/registry`). Two requests that call two objects in opposite orders (`billing → ledger` and `ledger → billing` at the same moment) wait for each other until the runtime resets them: keep calls between databases in one direction, or make them from the worker.
310
+ - **What it costs.** A transaction is about 0.07 ms of an action's time in the object (local workerd).
278
311
 
279
312
  ### File organization
280
313
 
@@ -1019,6 +1052,8 @@ t.destroy();
1019
1052
 
1020
1053
  While a test database is live, an action called directly — from a page, a procedure, a job under test — runs against the newest live test database created with every table of the action's database.
1021
1054
 
1055
+ An action runs there as [in its Durable Object](#one-transaction): one transaction (`BEGIN … COMMIT`, rolled back when it throws), one at a time per test database — a run started while another runs waits for it —, `ctx.transaction()` and an action of the same database called from one as a savepoint, Kysely's `db.transaction()` refused, and a call back into a test database an action further out runs in refused with the `ActionCycleError` production gives. `t.runHandler(handler, args)` runs a handler whose args are already validated the same way, for a library that finds an action's handler itself.
1056
+
1022
1057
  ---
1023
1058
 
1024
1059
  ## Outerbase Studio Integration
@@ -1167,7 +1202,7 @@ export default async function deliver(envelopes: readonly OutboxEnvelope[], { en
1167
1202
  }
1168
1203
  ```
1169
1204
 
1170
- - **With the action's writes.** The messages are written to the object's `__outbox` table when the handler resolves, in the same synchronous block as its last writes — the Durable Object commits them together — and the alarm that delivers them is set with them. A handler that throws records none. An action called from another action of the same database shares its outbox.
1205
+ - **With the action's writes.** The messages are written to the object's `__outbox` table when the handler resolves, in [the action's transaction](#one-transaction), and the alarm that delivers them is set in it: committed with the action's writes, or — when it throws — none of them. A part of the action that is rolled back on its own (`ctx.transaction()`) takes the messages it pushed with it. An action called from another action of the same database shares its outbox.
1171
1206
  - **At least once, oldest first.** The alarm hands the sink the oldest messages that are due, by id, up to 100 in a call, and deletes what it delivered. A message may arrive twice — make what consumes it idempotent. No order is kept across a failure: a message that failed waits on its own backoff while the ones behind it go on.
1172
1207
  - **A failure counts only in an alarm that delivered another message.** What a call did not deliver is halved, and both halves are tried next in the same alarm, so a message the sink cannot take ends up the one of its call not delivered, and the rest are delivered: of 100 messages with one bad, the other 99 go in that alarm — unless the bad one is the oldest of the read and the sink fails every call that holds it: then it fails alone before anything was delivered and takes the sink for down, and the 99 go at the next try, 5 s later (see below). A group that fails moves no clock and counts nothing. A message that fails alone — the one of its call not delivered — waits on its own backoff (5 s, doubling, at most 5 minutes), and the failure counts toward `maxAttempts` only when the sink delivered another message in the same alarm, in that call or earlier. So an alarm in which the sink delivers nothing counts nothing, and an outage counts at most one failure a message.
1173
1208
  - **When the sink is down.** A failure alone before anything was delivered in its alarm cannot be told from an outage: it counts nothing, and the sink is taken for down. Until its next try nothing is read or called, and a message recorded meanwhile sets no alarm of its own. The try (5 s, doubling, at most 5 minutes) hands the sink the newest message alone and, if the sink does not take it, the one tried or recorded longest ago alone; one it neither takes nor answers in `{ dead }` goes behind every message recorded or tried before it, its count and backoff as they were, and one it answers in `{ dead }` is moved to `__outbox_dead`. The first try at which the sink takes one ends it, and the alarm goes on. So, over tries at which the sink takes nothing, every waiting message is handed alone by the try after as many tries as there are messages ahead of it; a message recorded meanwhile goes behind it (and is handed first, as the newest).
@@ -1210,8 +1245,8 @@ export const createUser = action({
1210
1245
 
1211
1246
  ### Routing behavior
1212
1247
 
1213
- - **Same database**: The call uses a direct fast path via AsyncLocalStorage (no RPC overhead). The registry detects that we're already inside the target DO and calls the handler directly.
1214
- - **Cross database**: The call routes through RPC to the other database's Durable Object, using the appropriate instance key based on the target database's strategy.
1248
+ - **Same database**: The call uses a direct fast path via AsyncLocalStorage (no RPC overhead). The registry detects that we're already inside the target DO and calls the handler directly, as a part of the caller's transaction (`ctx.transaction()`): when it throws, its writes are rolled back and the caller may go on.
1249
+ - **Cross database**: The call routes through RPC to the other database's Durable Object, using the appropriate instance key based on the target database's strategy. It is a transaction of its own there, and the caller's object waits for it: a call back into an object waiting on it is refused (`ActionCycleError`, see [One transaction](#one-transaction)).
1215
1250
 
1216
1251
  ---
1217
1252
 
@@ -1,4 +1,4 @@
1
- import { t as createTypeParser } from "./type-pAQ37iEL.js";
1
+ import { t as createTypeParser } from "./type-C7apBBQw.js";
2
2
  //#region src/db/actionArgs.ts
3
3
  /**
4
4
  * `type` (durable-db/type: ArkType's definitions and types), for an
package/dist/cli/bin.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { n as registerDbCommands } from "../cli-fxJ78Qvs.js";
2
+ import { n as registerDbCommands } from "../cli-B7-DcYWu.js";
3
3
  import { Command } from "commander";
4
4
  //#region src/cli/bin.ts
5
5
  const program = new Command();
@@ -1,7 +1,7 @@
1
1
  import { t as DatabaseSource } from "../discovery-gHeLq8jk.js";
2
2
  import { C as parseRenameSpec, g as SchemaRenameRequiredError, h as SchemaAmbiguity, m as RenameAnswer, n as Snapshot, t as MigrationResolution, u as MigrationRisk } from "../snapshot-D3_SNABU.js";
3
- import { l as DatabaseInfo } from "../defineDatabase-Dj5DOPUM.js";
4
- import "../index-B1J4Kjum.js";
3
+ import { l as DatabaseInfo } from "../defineDatabase-Cc3LtKhn.js";
4
+ import "../index-oTr2B0ap.js";
5
5
  import { Command } from "commander";
6
6
  import "vite";
7
7
  import "@babel/types";
package/dist/cli/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { c as getDatabaseEpochs, d as getInstanceKey, f as init_state, g as runningDevServer, l as getDevEpoch, m as loadDevState, o as generateEpoch, p as loadDevMigrations, s as getDatabaseEpoch, u as getDevPaths, v as saveDevState } from "../state-Bcux4tX1.js";
1
+ import { c as getDatabaseEpochs, d as getInstanceKey, f as init_state, g as runningDevServer, l as getDevEpoch, m as loadDevState, o as generateEpoch, p as loadDevMigrations, s as getDatabaseEpoch, u as getDevPaths, v as saveDevState } from "../state-k7CdHsWf.js";
2
2
  import { _ as parseRenameSpec, u as SchemaRenameRequiredError } from "../snapshot-4RsNw1yr.js";
3
- import { n as declaresSchema } from "../parser-DRqnF9bz.js";
4
- import { C as diffSchema, D as reportCliError, E as loadSchemaTables, O as selectDatabases, S as diffDatabases, T as loadSchema, _ as sift, a as reset, b as pushOne, c as status, d as generate, f as generateOne, g as replayWithRows, h as readAccepted, i as DevServerRunningError, l as MigrationFailsOnRowsError, m as accept, n as registerDbCommands, o as resetAndPush, p as ACCEPTED_FILE, r as validate, s as formatStatus, t as createDbCommand, u as UnsafeMigrationError, v as writeAccepted, w as discoverDatabases, x as UnknownDatabaseError, y as push } from "../cli-fxJ78Qvs.js";
3
+ import { n as declaresSchema } from "../parser-Bta8BJHy.js";
4
+ import { C as diffSchema, D as reportCliError, E as loadSchemaTables, O as selectDatabases, S as diffDatabases, T as loadSchema, _ as sift, a as reset, b as pushOne, c as status, d as generate, f as generateOne, g as replayWithRows, h as readAccepted, i as DevServerRunningError, l as MigrationFailsOnRowsError, m as accept, n as registerDbCommands, o as resetAndPush, p as ACCEPTED_FILE, r as validate, s as formatStatus, t as createDbCommand, u as UnsafeMigrationError, v as writeAccepted, w as discoverDatabases, x as UnknownDatabaseError, y as push } from "../cli-B7-DcYWu.js";
5
5
  init_state();
6
6
  export { ACCEPTED_FILE, DevServerRunningError, MigrationFailsOnRowsError, SchemaRenameRequiredError, UnknownDatabaseError, UnsafeMigrationError, accept, createDbCommand, declaresSchema, diffDatabases, diffSchema, discoverDatabases, formatStatus, generate, generateEpoch, generateOne, getDatabaseEpoch, getDatabaseEpochs, getDevEpoch, getDevPaths, getInstanceKey, loadDevMigrations, loadDevState, loadSchema, loadSchemaTables, parseRenameSpec, push, pushOne, readAccepted, registerDbCommands, replayWithRows, reportCliError, reset, resetAndPush, runningDevServer, saveDevState, selectDatabases, sift, status, validate, writeAccepted };
@@ -1,9 +1,9 @@
1
- import { i as init_debug, o as __exportAll, t as debugCli } from "./debug-BFOTDUja.js";
2
- import { _ as saveDevMigration, a as forgetDatabaseDevState, f as init_state, g as runningDevServer, i as clearDevMigrations, m as loadDevState, o as generateEpoch, p as loadDevMigrations, r as clearDatabaseDevState, s as getDatabaseEpoch, u as getDevPaths, v as saveDevState } from "./state-Bcux4tX1.js";
1
+ import { i as init_debug, s as __exportAll, t as debugCli } from "./debug-Di50ua4a.js";
2
+ import { _ as saveDevMigration, a as forgetDatabaseDevState, f as init_state, g as runningDevServer, i as clearDevMigrations, m as loadDevState, o as generateEpoch, p as loadDevMigrations, r as clearDatabaseDevState, s as getDatabaseEpoch, u as getDevPaths, v as saveDevState } from "./state-k7CdHsWf.js";
3
3
  import { t as guardReferencingRows } from "./referencingRows-B6rU7TDW.js";
4
4
  import { _ as parseRenameSpec, d as applyRenames, f as describeAmbiguity, g as obviousRenames, h as formatRename, i as generateSnapshotFromSchema, l as analyzeMigrationRisks, m as findAmbiguities, o as hashSnapshot, p as exampleRenames, r as generateMigrationStatements, s as snapshotsEqual, u as SchemaRenameRequiredError, v as renamesFromStatements, y as unusedRenames } from "./snapshot-4RsNw1yr.js";
5
5
  import { buildAndLoadSchema, generateCreateTableSQL, generateMigrationName, loadMigrationFiles, loadSnapshot, parseSqlMigration, saveSnapshot } from "./migrations/generator.js";
6
- import { c as readFile, l as resolveImportPath, n as declaresSchema, r as parseDatabaseFile, s as discoverDatabaseFiles, u as loadViteAliases } from "./parser-DRqnF9bz.js";
6
+ import { c as readFile, l as resolveImportPath, n as declaresSchema, r as parseDatabaseFile, s as discoverDatabaseFiles, u as loadViteAliases } from "./parser-Bta8BJHy.js";
7
7
  import * as fs from "node:fs";
8
8
  import * as path$1 from "node:path";
9
9
  import * as crypto from "node:crypto";
@@ -1,5 +1,5 @@
1
- import { s as __toCommonJS } from "../debug-BFOTDUja.js";
2
- import { f as init_state, y as state_exports } from "../state-Bcux4tX1.js";
1
+ import { c as __toCommonJS } from "../debug-Di50ua4a.js";
2
+ import { f as init_state, y as state_exports } from "../state-k7CdHsWf.js";
3
3
  //#region src/context/index.ts
4
4
  /**
5
5
  * Tenant ID resolver for framework integration.
@@ -1,5 +1,5 @@
1
1
  import { l as type } from "../index-bUUlOWfP.js";
2
- import { C as RelationType, E as relationsOf, S as RelationMap, T as relationOf, _ as RelatedSpec, a as ActionInfo, b as AnySchema, c as DatabaseDefinition, d as InferArgs, f as ParsedDatabaseFile, g as RelatedOptions, h as RelatedExpression, i as ActionContext, l as DatabaseInfo, m as Related, n as Action, o as ArgsSchema, p as AnyRelated, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely, v as RelatedWhere, w as Relations, x as Relation, y as createRelated } from "../defineDatabase-Dj5DOPUM.js";
2
+ import { C as RelationType, E as relationsOf, S as RelationMap, T as relationOf, _ as RelatedSpec, a as ActionInfo, b as AnySchema, c as DatabaseDefinition, d as InferArgs, f as ParsedDatabaseFile, g as RelatedOptions, h as RelatedExpression, i as ActionContext, l as DatabaseInfo, m as Related, n as Action, o as ArgsSchema, p as AnyRelated, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely, v as RelatedWhere, w as Relations, x as Relation, y as createRelated } from "../defineDatabase-Cc3LtKhn.js";
3
3
  import { a as OutboxMessage, c as OutboxSinkModule, d as tenantOfInstanceKey, i as OutboxEnvelope, l as outboxSink, n as Outbox, o as OutboxSink, r as OutboxDelivery, s as OutboxSinkContext, t as InstanceKeyOrigin, u as queueOutboxSink } from "../outbox-DpyNU99x.js";
4
- import { C as SqliteDurableObject, E as createKyselyFromSql, S as Migrations, T as SqlExecutor, _ as RemovedDatabaseError, a as QueryResult, b as MigrationAttemptInfo, c as DrizzleDefaultsPlugin, d as createDrizzlePlugins, f as createJsonPlugins, g as RemovedDatabaseDurableObject, h as DeleteClassMigration, i as KyselyPlugin, l as JsonPluginOptions, m as parseJsonValue, n as CompiledQuery, o as studio, p as dateSerializers, r as Kysely, s as DateSerializePlugin, t as CamelCasePlugin, u as SchemaPlugin, v as removedDatabaseMessage, w as CreateKyselyOptions, x as MigrationSchemaConflictError, y as Migration } from "../index-B1J4Kjum.js";
4
+ import { C as SqliteDurableObject, E as createKyselyFromSql, S as Migrations, T as SqlExecutor, _ as RemovedDatabaseError, a as QueryResult, b as MigrationAttemptInfo, c as DrizzleDefaultsPlugin, d as createDrizzlePlugins, f as createJsonPlugins, g as RemovedDatabaseDurableObject, h as DeleteClassMigration, i as KyselyPlugin, l as JsonPluginOptions, m as parseJsonValue, n as CompiledQuery, o as studio, p as dateSerializers, r as Kysely, s as DateSerializePlugin, t as CamelCasePlugin, u as SchemaPlugin, v as removedDatabaseMessage, w as CreateKyselyOptions, x as MigrationSchemaConflictError, y as Migration } from "../index-oTr2B0ap.js";
5
5
  export { type Action, type ActionConfig, type ActionContext, type ActionInfo, type AnyRelated, type AnySchema, type ArgsSchema, CamelCasePlugin, type CompiledQuery, type CreateKyselyOptions, type DatabaseConfig, type DatabaseDefinition, type DatabaseInfo, DateSerializePlugin, type DeleteClassMigration, DrizzleDefaultsPlugin, type DrizzleToKysely, type InferArgs, type InstanceKeyOrigin, type JsonPluginOptions, type Kysely, type KyselyPlugin, type Migration, type MigrationAttemptInfo, MigrationSchemaConflictError, type Migrations, type Outbox, type OutboxDelivery, type OutboxEnvelope, type OutboxMessage, type OutboxSink, type OutboxSinkContext, type OutboxSinkModule, type ParsedDatabaseFile, type QueryResult, type Related, RelatedExpression, type RelatedOptions, type RelatedSpec, type RelatedWhere, type Relation, type RelationMap, type RelationType, type Relations, RemovedDatabaseDurableObject, RemovedDatabaseError, SchemaPlugin, type SqlExecutor, SqliteDurableObject, createDrizzlePlugins, createJsonPlugins, createKyselyFromSql, createRelated, dateSerializers, defineDatabase, outboxSink, parseJsonValue, queueOutboxSink, relationOf, relationsOf, removedDatabaseMessage, studio, tenantOfInstanceKey, type };
package/dist/db/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import { i as init_debug, n as debugMigrations } from "../debug-BFOTDUja.js";
2
- import { a as createRelated, c as DrizzleDefaultsPlugin, d as createJsonPlugins, f as dateSerializers, h as relationsOf, i as RelatedExpression, l as SchemaPlugin, m as relationOf, n as defineDatabase, p as parseJsonValue, s as DateSerializePlugin, u as createDrizzlePlugins } from "../defineDatabase-_AusJf3r.js";
3
- import { r as type } from "../type-pAQ37iEL.js";
4
- import "../actionArgs-oUWwX6Xn.js";
5
- import { a as OUTBOX_DEAD_TABLE, c as OUTBOX_TABLE, d as outboxRetryDelay, f as outboxSink, h as tenantOfInstanceKey, i as OUTBOX_DEAD_DDL, l as createActionOutbox, m as settleOutboxDelivery, n as OUTBOX_ADDED_COLUMNS, o as OUTBOX_SINK_DDL, p as queueOutboxSink, r as OUTBOX_DDL, s as OUTBOX_SINK_TABLE, t as createKyselyFromSql, u as outboxErrorText } from "../kysely-C675L1b9.js";
1
+ import { a as setDebugSpec, i as init_debug, n as debugMigrations } from "../debug-Di50ua4a.js";
2
+ import { a as createRelated, c as DrizzleDefaultsPlugin, d as createJsonPlugins, f as dateSerializers, h as relationsOf, i as RelatedExpression, l as SchemaPlugin, m as relationOf, n as defineDatabase, p as parseJsonValue, s as DateSerializePlugin, u as createDrizzlePlugins } from "../defineDatabase-xd-9vnhm.js";
3
+ import { r as type } from "../type-C7apBBQw.js";
4
+ import "../actionArgs-BAmU_AIB.js";
5
+ import { a as OUTBOX_DEAD_TABLE, c as OUTBOX_TABLE, d as outboxRetryDelay, f as outboxSink, h as tenantOfInstanceKey, i as OUTBOX_DEAD_DDL, l as createActionOutbox, m as settleOutboxDelivery, n as OUTBOX_ADDED_COLUMNS, o as OUTBOX_SINK_DDL, p as queueOutboxSink, r as OUTBOX_DDL, s as OUTBOX_SINK_TABLE, t as createKyselyFromSql, u as outboxErrorText } from "../kysely-BUmrdN9f.js";
6
6
  import { t as guardReferencingRows } from "../referencingRows-B6rU7TDW.js";
7
7
  import { CamelCasePlugin } from "kysely";
8
8
  import { DurableObject } from "cloudflare:workers";
@@ -188,6 +188,7 @@ var SqliteDurableObject = class extends DurableObject {
188
188
  constructor(ctx, env) {
189
189
  super(ctx, env);
190
190
  this.sql = ctx.storage.sql;
191
+ setDebugSpec(env?.DEBUG);
191
192
  }
192
193
  /**
193
194
  * The name an outbox envelope gives this database: `databaseName`, else
@@ -256,28 +257,56 @@ var SqliteDurableObject = class extends DurableObject {
256
257
  this.sql.exec(`INSERT INTO ${OUTBOX_SINK_TABLE} (id, down_until, down_rounds) VALUES (1, ?, ?) ON CONFLICT(id) DO UPDATE SET down_until = excluded.down_until, down_rounds = excluded.down_rounds`, state.down_until, state.down_rounds);
257
258
  }
258
259
  /**
259
- * Runs an action with `ctx.outbox`. The messages it pushed are written when
260
- * it resolves — in the same synchronous block as its last writes, which the
261
- * Durable Object commits together — and the alarm that delivers them is set
262
- * with them: now, or, while the sink is taken for down, its next try, so a
263
- * message recorded during an outage adds no alarm (the try still makes at
264
- * most two sink calls). A handler that throws records nothing. An action
265
- * called from another action of this database runs on the caller's context,
266
- * and so on its outbox.
260
+ * Runs an action as one transaction (`ctx.storage.transaction()`): its
261
+ * writes, the messages it pushed to `ctx.outbox` and the alarm that delivers
262
+ * them are committed together when it resolves, and none of them when it
263
+ * throws. While it runs the object takes no other call — the runtime holds
264
+ * the next one until it resolves —, so two actions never interleave at an
265
+ * await, and an action that waits on I/O (another object, a fetch) holds
266
+ * its object for that long; after 30 s the runtime resets the object.
267
+ *
268
+ * `ctx.transaction(fn)` runs a part that may fail on its own: its writes and
269
+ * messages are rolled back when it throws, the rest of the action goes on
270
+ * (a savepoint). Two parts started at once run one after the other. An
271
+ * action called from another action of this database runs on the caller's
272
+ * context, in a part of its own.
273
+ *
274
+ * The messages are written to `__outbox` once the handler has resolved, and
275
+ * the alarm set to now — or, while the sink is taken for down, to its next
276
+ * try, so a message recorded during an outage adds no alarm (the try still
277
+ * makes at most two sink calls).
267
278
  */
268
- async runWithOutbox(ctx, run) {
269
- if (ctx.outbox) return run();
279
+ async runAction(ctx, run) {
280
+ const storage = this.ctx.storage;
281
+ if (ctx.outbox) return ctx.transaction ? ctx.transaction(run) : storage.transaction(() => run());
270
282
  const outbox = createActionOutbox(this.outboxSink !== null);
271
283
  ctx.outbox = outbox;
272
- const result = await run();
273
- const messages = outbox.take();
274
- if (messages.length > 0) {
275
- this.ensureOutboxTable();
276
- const now = Date.now();
277
- for (const message of messages) this.sql.exec(`INSERT INTO ${OUTBOX_TABLE} (instance_key, message, recorded_at) VALUES (?, ?, ?)`, ctx.instanceKey, message, now);
278
- await this.ctx.storage.setAlarm(Math.max(now, this.outboxSinkState().down_until));
284
+ ctx.transaction = (fn) => storage.transaction(async () => {
285
+ const mark = outbox.mark();
286
+ try {
287
+ return await fn();
288
+ } catch (error) {
289
+ outbox.rewind(mark);
290
+ throw error;
291
+ }
292
+ });
293
+ const outboxWasReady = this.outboxReady;
294
+ try {
295
+ return await storage.transaction(async () => {
296
+ const result = await run();
297
+ const messages = outbox.take();
298
+ if (messages.length > 0) {
299
+ this.ensureOutboxTable();
300
+ const now = Date.now();
301
+ for (const message of messages) this.sql.exec(`INSERT INTO ${OUTBOX_TABLE} (instance_key, message, recorded_at) VALUES (?, ?, ?)`, ctx.instanceKey, message, now);
302
+ await storage.setAlarm(Math.max(now, this.outboxSinkState().down_until));
303
+ }
304
+ return result;
305
+ });
306
+ } catch (error) {
307
+ if (!outboxWasReady) this.outboxReady = false;
308
+ throw error;
279
309
  }
280
- return result;
281
310
  }
282
311
  /**
283
312
  * Delivers the outbox, in at most 16 sink calls (`OUTBOX_CALLS_PER_ALARM`).
@@ -34,7 +34,19 @@ var __copyProps = (to, from, except, desc) => {
34
34
  var __toCommonJS = (mod) => __hasOwnProp.call(mod, "module.exports") ? mod["module.exports"] : __copyProps(__defProp({}, "__esModule", { value: true }), mod);
35
35
  //#endregion
36
36
  //#region src/utils/debug.ts
37
+ /**
38
+ * DEBUG as the runtime gave it to the caller — a Durable Object's `env.DEBUG`
39
+ * (its vars and secrets) — read by every debugger instead of
40
+ * `process.env.DEBUG`: in workerd the first read of `process` builds Node's
41
+ * whole process object, its streams with it (about 8 ms of CPU, at an
42
+ * object's first migration run). Anything but a string is no DEBUG. Set it
43
+ * before a debugger is first asked: each keeps what it read.
44
+ */
45
+ function setDebugSpec(spec) {
46
+ providedSpec = typeof spec === "string" ? spec : "";
47
+ }
37
48
  function readDebugEnv() {
49
+ if (providedSpec !== void 0) return providedSpec;
38
50
  if (typeof process !== "undefined" && process.env && process.env.DEBUG) return process.env.DEBUG;
39
51
  return "";
40
52
  }
@@ -92,11 +104,11 @@ function createDebug(namespace) {
92
104
  debug.extend = (subNamespace, delimiter = ":") => createDebug(`${namespace}${delimiter}${subNamespace}`);
93
105
  return debug;
94
106
  }
95
- var debugVite, debugCli, debugMigrations;
107
+ var providedSpec, debugVite, debugCli, debugMigrations;
96
108
  var init_debug = __esmMin((() => {
97
109
  debugVite = createDebug("database:vite");
98
110
  debugCli = createDebug("database:cli");
99
111
  debugMigrations = createDebug("database:migrations");
100
112
  }));
101
113
  //#endregion
102
- export { __esmMin as a, init_debug as i, debugMigrations as n, __exportAll as o, debugVite as r, __toCommonJS as s, debugCli as t };
114
+ export { setDebugSpec as a, __toCommonJS as c, init_debug as i, debugMigrations as n, __esmMin as o, debugVite as r, __exportAll as s, debugCli as t };
@@ -302,6 +302,18 @@ interface ActionContext<TEnv = unknown> {
302
302
  * writes, at least once; a handler that throws records none.
303
303
  */
304
304
  outbox: Outbox;
305
+ /**
306
+ * Runs a part of the action that may fail on its own. The action itself is
307
+ * one transaction — all of its writes, or none when it throws —; a part run
308
+ * here is rolled back alone when it throws (its writes and the messages it
309
+ * pushed), and the action can go on:
310
+ *
311
+ * try { await ctx.transaction(() => reserve(db, args)) } catch { await waitlist(db, args) }
312
+ *
313
+ * Two parts started at once run one after the other. An action called from
314
+ * another action of the same database runs as such a part.
315
+ */
316
+ transaction<T>(fn: () => Promise<T>): Promise<T>;
305
317
  }
306
318
  /**
307
319
  * Configuration for an action
@@ -1,8 +1,12 @@
1
- import { r as type } from "./type-pAQ37iEL.js";
2
- import { t as actionArgsType } from "./actionArgs-oUWwX6Xn.js";
3
- import { Table, getTableColumns, getTableName, is, isSQLWrapper } from "drizzle-orm";
4
- import { SQLiteSyncDialect, getTableConfig } from "drizzle-orm/sqlite-core";
1
+ import { r as type } from "./type-C7apBBQw.js";
2
+ import { t as actionArgsType } from "./actionArgs-BAmU_AIB.js";
3
+ import { getTableColumns } from "drizzle-orm/utils";
4
+ import { getTableConfig } from "drizzle-orm/sqlite-core/utils";
5
5
  import { AliasNode, CamelCasePlugin, ColumnNode, ColumnUpdateNode, DeleteQueryNode, IdentifierNode, InsertQueryNode, OperationNodeTransformer, PrimitiveValueListNode, ReferenceNode, SelectAllNode, SelectQueryNode, TableNode, UpdateQueryNode, ValueListNode, ValueNode, ValuesNode, expressionBuilder, sql } from "kysely";
6
+ import { SQLiteSyncDialect } from "drizzle-orm/sqlite-core/dialect";
7
+ import { Table, getTableName } from "drizzle-orm/table";
8
+ import { is } from "drizzle-orm/entity";
9
+ import { isSQLWrapper } from "drizzle-orm/sql/sql";
6
10
  import { toCamelCase, toSnakeCase } from "drizzle-orm/casing";
7
11
  //#region src/db/relations.ts
8
12
  const registries = /* @__PURE__ */ new WeakMap();
@@ -1,10 +1,10 @@
1
- import "./defineDatabase-Dj5DOPUM.js";
1
+ import "./defineDatabase-Cc3LtKhn.js";
2
2
  import { n as Outbox, o as OutboxSink } from "./outbox-DpyNU99x.js";
3
3
  import { SQLiteTableWithColumns } from "drizzle-orm/sqlite-core";
4
4
  import { CamelCasePlugin, CamelCasePlugin as CamelCasePlugin$1, CompiledQuery, Kysely, Kysely as Kysely$1, KyselyPlugin, KyselyPlugin as KyselyPlugin$1, PluginTransformQueryArgs, PluginTransformResultArgs, QueryResult, QueryResult as QueryResult$1, RootOperationNode, UnknownRow } from "kysely";
5
5
  import { DurableObject } from "cloudflare:workers";
6
6
  import { studio } from "@outerbase/browsable-durable-object";
7
- import { Table } from "drizzle-orm";
7
+ import { Table } from "drizzle-orm/table";
8
8
  //#region src/db/kysely.d.ts
9
9
  /**
10
10
  * SQL executor function type
@@ -232,18 +232,29 @@ declare abstract class SqliteDurableObject<Env = unknown> extends DurableObject<
232
232
  /** Writes the sink's row when it changed. */
233
233
  private writeOutboxSinkState;
234
234
  /**
235
- * Runs an action with `ctx.outbox`. The messages it pushed are written when
236
- * it resolves — in the same synchronous block as its last writes, which the
237
- * Durable Object commits together — and the alarm that delivers them is set
238
- * with them: now, or, while the sink is taken for down, its next try, so a
239
- * message recorded during an outage adds no alarm (the try still makes at
240
- * most two sink calls). A handler that throws records nothing. An action
241
- * called from another action of this database runs on the caller's context,
242
- * and so on its outbox.
235
+ * Runs an action as one transaction (`ctx.storage.transaction()`): its
236
+ * writes, the messages it pushed to `ctx.outbox` and the alarm that delivers
237
+ * them are committed together when it resolves, and none of them when it
238
+ * throws. While it runs the object takes no other call — the runtime holds
239
+ * the next one until it resolves —, so two actions never interleave at an
240
+ * await, and an action that waits on I/O (another object, a fetch) holds
241
+ * its object for that long; after 30 s the runtime resets the object.
242
+ *
243
+ * `ctx.transaction(fn)` runs a part that may fail on its own: its writes and
244
+ * messages are rolled back when it throws, the rest of the action goes on
245
+ * (a savepoint). Two parts started at once run one after the other. An
246
+ * action called from another action of this database runs on the caller's
247
+ * context, in a part of its own.
248
+ *
249
+ * The messages are written to `__outbox` once the handler has resolved, and
250
+ * the alarm set to now — or, while the sink is taken for down, to its next
251
+ * try, so a message recorded during an outage adds no alarm (the try still
252
+ * makes at most two sink calls).
243
253
  */
244
- protected runWithOutbox<T>(ctx: {
254
+ protected runAction<T>(ctx: {
245
255
  instanceKey: string;
246
256
  outbox?: Outbox;
257
+ transaction?: <R>(fn: () => Promise<R>) => Promise<R>;
247
258
  }, run: () => Promise<T>): Promise<T>;
248
259
  /**
249
260
  * Delivers the outbox, in at most 16 sink calls (`OUTBOX_CALLS_PER_ALARM`).
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { i as Type, l as type } from "./index-bUUlOWfP.js";
2
- import { C as RelationType, E as relationsOf, S as RelationMap, T as relationOf, _ as RelatedSpec, b as AnySchema, c as DatabaseDefinition, d as InferArgs, g as RelatedOptions, h as RelatedExpression, i as ActionContext, m as Related, n as Action, p as AnyRelated, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely, v as RelatedWhere, w as Relations, x as Relation, y as createRelated } from "./defineDatabase-Dj5DOPUM.js";
2
+ import { C as RelationType, E as relationsOf, S as RelationMap, T as relationOf, _ as RelatedSpec, b as AnySchema, c as DatabaseDefinition, d as InferArgs, g as RelatedOptions, h as RelatedExpression, i as ActionContext, m as Related, n as Action, p as AnyRelated, r as ActionConfig, s as DatabaseConfig, t as defineDatabase, u as DrizzleToKysely, v as RelatedWhere, w as Relations, x as Relation, y as createRelated } from "./defineDatabase-Cc3LtKhn.js";
3
3
  import { a as OutboxMessage, c as OutboxSinkModule, i as OutboxEnvelope, n as Outbox, o as OutboxSink, r as OutboxDelivery, s as OutboxSinkContext, t as InstanceKeyOrigin } from "./outbox-DpyNU99x.js";
4
4
  import { getTenantId, hasTenantId, setTenantIdResolver } from "./context/index.js";
5
5
  import { AnySQLiteColumn, blob, foreignKey, index, integer, numeric, primaryKey, real, table, text, uniqueIndex } from "./schema.js";
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { a as createRelated, h as relationsOf, i as RelatedExpression, m as relationOf, n as defineDatabase } from "./defineDatabase-_AusJf3r.js";
2
- import { r as type } from "./type-pAQ37iEL.js";
3
- import "./actionArgs-oUWwX6Xn.js";
1
+ import { a as createRelated, h as relationsOf, i as RelatedExpression, m as relationOf, n as defineDatabase } from "./defineDatabase-xd-9vnhm.js";
2
+ import { r as type } from "./type-C7apBBQw.js";
3
+ import "./actionArgs-BAmU_AIB.js";
4
4
  import { blob, foreignKey, index, integer, numeric, primaryKey, real, table, text, uniqueIndex } from "./schema.js";
5
5
  import { n as describeAction } from "./describeAction-CEKfxTQ4.js";
6
6
  import { getTenantId, hasTenantId, setTenantIdResolver } from "./context/index.js";
@@ -1,4 +1,4 @@
1
- import { l as SchemaPlugin, o as createRelatedPlugins, s as DateSerializePlugin, u as createDrizzlePlugins } from "./defineDatabase-_AusJf3r.js";
1
+ import { l as SchemaPlugin, o as createRelatedPlugins, s as DateSerializePlugin, u as createDrizzlePlugins } from "./defineDatabase-xd-9vnhm.js";
2
2
  import { CamelCasePlugin, Kysely, SqliteDialect, SqliteQueryCompiler } from "kysely";
3
3
  //#region src/db/outbox.ts
4
4
  /** A sink module's default export as a sink: a deliver function, or an object with one. */
@@ -249,7 +249,9 @@ function tenantOfInstanceKey(instanceKey, origin) {
249
249
  * The outbox of one action run: `push()` collects, and once the handler has
250
250
  * resolved `take()` hands the messages over to be written. A message must be
251
251
  * a JSON value; it is checked (serialized) when pushed, so a bad one fails
252
- * the action that pushed it rather than a delivery later.
252
+ * the action that pushed it rather than a delivery later. A part of the run
253
+ * that is rolled back on its own (`ctx.transaction()`, an action it calls)
254
+ * takes its messages with it: `rewind()` to the `mark()` it began at.
253
255
  */
254
256
  function createActionOutbox(sinkConfigured) {
255
257
  let messages = [];
@@ -264,6 +266,10 @@ function createActionOutbox(sinkConfigured) {
264
266
  const taken = messages;
265
267
  messages = [];
266
268
  return taken;
269
+ },
270
+ mark: () => messages.length,
271
+ rewind(mark) {
272
+ messages.length = Math.min(messages.length, mark);
267
273
  }
268
274
  };
269
275
  }
@@ -386,34 +392,15 @@ var CloudflareSqliteDriver = class {
386
392
  async acquireConnection() {
387
393
  return new CloudflareSqliteConnection(this.sql);
388
394
  }
389
- async beginTransaction(connection, settings) {
390
- if (settings.isolationLevel) throw new Error("SQLite does not support isolation levels");
391
- await connection.executeQuery(createCompiledQuery("BEGIN"));
392
- }
393
- async commitTransaction(connection) {
394
- await connection.executeQuery(createCompiledQuery("COMMIT"));
395
- }
396
- async rollbackTransaction(connection) {
397
- await connection.executeQuery(createCompiledQuery("ROLLBACK"));
395
+ async beginTransaction() {
396
+ throw new Error("[db] db.transaction() is not available: every action already runs as one transaction — all of its writes, or none when it throws. For a part that may fail on its own, use ctx.transaction(async () => { … }) (the handler's third argument): its writes are rolled back when it throws, and the action goes on.");
398
397
  }
398
+ async commitTransaction() {}
399
+ async rollbackTransaction() {}
399
400
  async releaseConnection() {}
400
401
  async destroy() {}
401
402
  };
402
403
  /**
403
- * Helper to create a CompiledQuery object
404
- */
405
- function createCompiledQuery(sql, parameters = []) {
406
- return {
407
- sql,
408
- parameters,
409
- query: {
410
- kind: "RawNode",
411
- sqlFragments: [sql],
412
- parameters: []
413
- }
414
- };
415
- }
416
- /**
417
404
  * A Kysely connection that wraps Cloudflare's SqlStorage
418
405
  */
419
406
  var CloudflareSqliteConnection = class {
@@ -1,5 +1,5 @@
1
- import { i as init_debug, n as debugMigrations } from "../debug-BFOTDUja.js";
2
- import { f as init_state, n as SCHEMA_TEMP_PREFIX } from "../state-Bcux4tX1.js";
1
+ import { i as init_debug, n as debugMigrations } from "../debug-Di50ua4a.js";
2
+ import { f as init_state, n as SCHEMA_TEMP_PREFIX } from "../state-k7CdHsWf.js";
3
3
  import { a as generateSnapshotId, i as generateSnapshotFromSchema, n as createEmptySnapshot, r as generateMigrationStatements, s as snapshotsEqual } from "../snapshot-4RsNw1yr.js";
4
4
  import * as fs from "node:fs";
5
5
  import * as path$1 from "node:path";
@@ -1,10 +1,7 @@
1
- import { i as init_debug, t as debugCli } from "./debug-BFOTDUja.js";
1
+ import { i as init_debug, t as debugCli } from "./debug-Di50ua4a.js";
2
+ import { createRequire } from "node:module";
2
3
  import * as fs from "node:fs";
3
4
  import * as path$1 from "node:path";
4
- import { parse } from "@babel/parser";
5
- import _traverse from "@babel/traverse";
6
- import _generate from "@babel/generator";
7
- import * as t from "@babel/types";
8
5
  //#region src/vite/modules/aliasResolver.ts
9
6
  init_debug();
10
7
  /**
@@ -218,8 +215,28 @@ function readFile(filePath) {
218
215
  //#endregion
219
216
  //#region src/vite/modules/parser.ts
220
217
  init_debug();
221
- const traverse = typeof _traverse === "function" ? _traverse : _traverse.default;
222
- const generate = typeof _generate === "function" ? _generate : _generate.default;
218
+ const require = createRequire(import.meta.url);
219
+ let parse;
220
+ let traverse;
221
+ let generate;
222
+ let t;
223
+ /**
224
+ * Babel (its parser, traverse, generator and types: about 40 ms to load) is
225
+ * required at the first parse, not with this module: the CLI's entry imports
226
+ * it (`declaresSchema`, the discovery `db` commands share), and a host CLI
227
+ * registers `db` for every command line it runs. Every function here that
228
+ * reads `t`, `parse`, `traverse` or `generate` is reached through one that
229
+ * calls this first.
230
+ */
231
+ function loadBabel() {
232
+ if (t) return;
233
+ const traverseModule = require("@babel/traverse");
234
+ const generatorModule = require("@babel/generator");
235
+ parse = require("@babel/parser").parse;
236
+ traverse = traverseModule.default ?? traverseModule;
237
+ generate = generatorModule.default ?? generatorModule;
238
+ t = require("@babel/types");
239
+ }
223
240
  /**
224
241
  * Shared Babel parser plugins used across all parsing in the Vite plugin.
225
242
  * Ensures consistent syntax support (TypeScript, JSX, decorators, etc.).
@@ -235,6 +252,7 @@ const BABEL_PARSER_PLUGINS = [
235
252
  * Parse a TypeScript/JavaScript file into an AST
236
253
  */
237
254
  function parseCode(code) {
255
+ loadBabel();
238
256
  return parse(code, {
239
257
  sourceType: "module",
240
258
  plugins: BABEL_PARSER_PLUGINS
@@ -244,6 +262,7 @@ function parseCode(code) {
244
262
  * Generate source code from an AST node
245
263
  */
246
264
  function generateCode(node) {
265
+ loadBabel();
247
266
  return generate(node).code;
248
267
  }
249
268
  /**