"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }

















var _chunkF5B36GL7cjs = require('../chunk-F5B36GL7.cjs');
require('../chunk-ZR76ZGYS.cjs');
require('../chunk-WPDQXB7R.cjs');






var _chunkZFY5J2EPcjs = require('../chunk-ZFY5J2EP.cjs');





var _chunk65RINRXEcjs = require('../chunk-65RINRXE.cjs');


var _chunkLPXB254Rcjs = require('../chunk-LPXB254R.cjs');
require('../chunk-AGERRJ32.cjs');
require('../chunk-FUBHHHK5.cjs');


var _chunk6LJAZ5R4cjs = require('../chunk-6LJAZ5R4.cjs');
require('../chunk-SR3KQE7Q.cjs');


var _chunkQ5CW77ITcjs = require('../chunk-Q5CW77IT.cjs');
require('../chunk-NIYZDWMW.cjs');
require('../chunk-LNDVGTPQ.cjs');
require('../chunk-MMUXNMJF.cjs');


var _chunkL47L3ZWJcjs = require('../chunk-L47L3ZWJ.cjs');
require('../chunk-HDQ2JUQT.cjs');

// src/serve-test-suite/mod.ts
var _net = require('net');
var _url = require('url');
var _nodeserver = require('@hono/node-server');
var _nodews = require('@hono/node-ws');
var _invariant = require('invariant'); var _invariant2 = _interopRequireDefault(_invariant);

// fixtures/driver-test-suite/access-control.ts
var _errors = require('rivetkit/errors');
var accessControlEvents = {
  allowedEvent: _chunk65RINRXEcjs.event.call(void 0, {
    canSubscribe: (c) => {
      c.state.lastCanSubscribeConnId = c.conn.id;
      return true;
    }
  }),
  blockedEvent: _chunk65RINRXEcjs.event.call(void 0, {
    canSubscribe: (c) => {
      c.state.lastCanSubscribeConnId = c.conn.id;
      return false;
    }
  })
};
var accessControlQueues = {
  allowedQueue: _chunk65RINRXEcjs.queue.call(void 0, {
    canPublish: (c) => {
      c.state.lastCanPublishConnId = c.conn.id;
      return true;
    }
  }),
  blockedQueue: _chunk65RINRXEcjs.queue.call(void 0, {
    canPublish: (c) => {
      c.state.lastCanPublishConnId = c.conn.id;
      return false;
    }
  })
};
var accessControlActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: {
    lastCanPublishConnId: "",
    lastCanSubscribeConnId: ""
  },
  events: accessControlEvents,
  queues: accessControlQueues,
  onBeforeConnect: (_c, params) => {
    if ((params == null ? void 0 : params.allowRequest) === false || (params == null ? void 0 : params.allowWebSocket) === false) {
      throw new (0, _errors.Forbidden)();
    }
  },
  onRequest(_c, request) {
    const url = new URL(request.url);
    if (url.pathname === "/status") {
      return Response.json({ ok: true });
    }
    return new Response("Not Found", { status: 404 });
  },
  onWebSocket(_c, websocket) {
    websocket.send(JSON.stringify({ type: "welcome" }));
  },
  actions: {
    allowedAction: (_c, value) => {
      return `allowed:${value}`;
    },
    allowedGetLastCanPublishConnId: (c) => {
      return c.state.lastCanPublishConnId;
    },
    allowedGetLastCanSubscribeConnId: (c) => {
      return c.state.lastCanSubscribeConnId;
    },
    allowedReceiveQueue: async (c) => {
      const [message] = await c.queue.tryNext({
        names: ["allowedQueue"]
      });
      return _nullishCoalesce((message == null ? void 0 : message.body), () => ( null));
    },
    allowedReceiveAnyQueue: async (c) => {
      const [message] = await c.queue.tryNext();
      return _nullishCoalesce((message == null ? void 0 : message.body), () => ( null));
    },
    allowedBroadcastAllowedEvent: (c, value) => {
      c.broadcast("allowedEvent", { value });
    },
    allowedBroadcastBlockedEvent: (c, value) => {
      c.broadcast("blockedEvent", { value });
    },
    allowedBroadcastUndefinedEvent: (c, value) => {
      c.broadcast("undefinedEvent", { value });
    }
  }
});
var accessControlNoQueuesActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: {},
  actions: {
    readAnyQueue: async (c) => {
      const [message] = await c.queue.tryNext();
      return _nullishCoalesce((message == null ? void 0 : message.body), () => ( null));
    }
  }
});

// fixtures/driver-test-suite/action-inputs.ts
var inputActor = _chunk65RINRXEcjs.actor.call(void 0, {
  createState: (c, input) => {
    return {
      initialInput: input,
      onCreateInput: void 0
    };
  },
  onCreate: (c, input) => {
    c.state.onCreateInput = input;
  },
  actions: {
    getInputs: (c) => {
      return {
        initialInput: c.state.initialInput,
        onCreateInput: c.state.onCreateInput
      };
    }
  }
});

// fixtures/driver-test-suite/action-timeout.ts
var shortTimeoutActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: { value: 0 },
  options: {
    actionTimeout: 50
    // 50ms timeout
  },
  actions: {
    quickAction: async (c) => {
      return "quick response";
    },
    slowAction: async (c) => {
      await new Promise((resolve) => setTimeout(resolve, 100));
      return "slow response";
    }
  }
});
var longTimeoutActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: { value: 0 },
  options: {
    actionTimeout: 200
    // 200ms timeout
  },
  actions: {
    delayedAction: async (c) => {
      await new Promise((resolve) => setTimeout(resolve, 100));
      return "delayed response";
    }
  }
});
var defaultTimeoutActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: { value: 0 },
  actions: {
    normalAction: async (c) => {
      await new Promise((resolve) => setTimeout(resolve, 50));
      return "normal response";
    }
  }
});
var syncTimeoutActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: { value: 0 },
  options: {
    actionTimeout: 50
    // 50ms timeout
  },
  actions: {
    syncAction: (c) => {
      return "sync response";
    }
  }
});

// fixtures/driver-test-suite/action-types.ts
var syncActionActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: { value: 0 },
  actions: {
    // Simple synchronous action that returns a value directly
    increment: (c, amount = 1) => {
      c.state.value += amount;
      return c.state.value;
    },
    // Synchronous action that returns an object
    getInfo: (c) => {
      return {
        currentValue: c.state.value,
        timestamp: Date.now()
      };
    },
    // Synchronous action with no return value (void)
    reset: (c) => {
      c.state.value = 0;
    }
  }
});
var asyncActionActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: { value: 0, data: null },
  actions: {
    // Async action with a delay
    delayedIncrement: async (c, amount = 1) => {
      await Promise.resolve();
      c.state.value += amount;
      return c.state.value;
    },
    // Async action that simulates an API call
    fetchData: async (c, id) => {
      await Promise.resolve();
      const data = { id, timestamp: Date.now() };
      c.state.data = data;
      return data;
    },
    // Async action with error handling
    asyncWithError: async (c, shouldError) => {
      await Promise.resolve();
      if (shouldError) {
        throw new (0, _chunkL47L3ZWJcjs.UserError)("Intentional error");
      }
      return "Success";
    }
  }
});
var promiseActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: { results: [] },
  actions: {
    // Action that returns a resolved promise
    resolvedPromise: (c) => {
      return Promise.resolve("resolved value");
    },
    // Action that returns a promise that resolves after a delay
    delayedPromise: (c) => {
      return new Promise((resolve) => {
        c.state.results.push("delayed");
        resolve("delayed value");
      });
    },
    // Action that returns a rejected promise
    rejectedPromise: (c) => {
      return Promise.reject(new (0, _chunkL47L3ZWJcjs.UserError)("promised rejection"));
    },
    // Action to check the collected results
    getResults: (c) => {
      return c.state.results;
    }
  }
});

// fixtures/driver-test-suite/actor-db-raw.ts
function firstRowValue(row) {
  if (!row) {
    return void 0;
  }
  const values = Object.values(row);
  return values.length > 0 ? values[0] : void 0;
}
function toSafeInteger(value) {
  if (typeof value === "bigint") {
    return Number(value);
  }
  if (typeof value === "number") {
    return Number.isFinite(value) ? Math.trunc(value) : 0;
  }
  if (typeof value === "string") {
    const parsed = Number.parseInt(value, 10);
    return Number.isFinite(parsed) ? parsed : 0;
  }
  return 0;
}
function normalizeRowIds(rowIds) {
  const normalized = rowIds.map((id) => Math.trunc(id)).filter((id) => Number.isFinite(id) && id > 0);
  return Array.from(new Set(normalized));
}
function makePayload(size) {
  const normalizedSize = Math.max(0, Math.trunc(size));
  return "x".repeat(normalizedSize);
}
var dbActorRaw = _chunk65RINRXEcjs.actor.call(void 0, {
  state: {
    disconnectInsertEnabled: false,
    disconnectInsertDelayMs: 0
  },
  db: _chunk6LJAZ5R4cjs.db.call(void 0, {
    onMigrate: async (db3) => {
      await db3.execute(`
				CREATE TABLE IF NOT EXISTS test_data (
					id INTEGER PRIMARY KEY AUTOINCREMENT,
					value TEXT NOT NULL,
					payload TEXT NOT NULL DEFAULT '',
					created_at INTEGER NOT NULL
				)
			`);
    }
  }),
  onDisconnect: async (c) => {
    if (!c.state.disconnectInsertEnabled) {
      return;
    }
    if (c.state.disconnectInsertDelayMs > 0) {
      await new Promise(
        (resolve) => setTimeout(resolve, c.state.disconnectInsertDelayMs)
      );
    }
    await c.db.execute(
      `INSERT INTO test_data (value, payload, created_at) VALUES ('__disconnect__', '', ${Date.now()})`
    );
  },
  actions: {
    configureDisconnectInsert: (c, enabled, delayMs) => {
      c.state.disconnectInsertEnabled = enabled;
      c.state.disconnectInsertDelayMs = Math.max(
        0,
        Math.floor(delayMs)
      );
    },
    getDisconnectInsertCount: async (c) => {
      var _a;
      const results = await c.db.execute(
        `SELECT COUNT(*) as count FROM test_data WHERE value = '__disconnect__'`
      );
      return _nullishCoalesce(((_a = results[0]) == null ? void 0 : _a.count), () => ( 0));
    },
    reset: async (c) => {
      await c.db.execute(`DELETE FROM test_data`);
    },
    insertValue: async (c, value) => {
      await c.db.execute(
        `INSERT INTO test_data (value, payload, created_at) VALUES ('${value}', '', ${Date.now()})`
      );
      const results = await c.db.execute(
        `SELECT last_insert_rowid() as id`
      );
      return { id: results[0].id };
    },
    getValues: async (c) => {
      const results = await c.db.execute(
        `SELECT * FROM test_data ORDER BY id`
      );
      return results;
    },
    getValue: async (c, id) => {
      var _a;
      const results = await c.db.execute(
        `SELECT value FROM test_data WHERE id = ${id}`
      );
      return _nullishCoalesce(((_a = results[0]) == null ? void 0 : _a.value), () => ( null));
    },
    getCount: async (c) => {
      const results = await c.db.execute(
        `SELECT COUNT(*) as count FROM test_data`
      );
      return results[0].count;
    },
    rawSelectCount: async (c) => {
      const results = await c.db.execute(
        `SELECT COUNT(*) as count FROM test_data`
      );
      return results[0].count;
    },
    insertMany: async (c, count) => {
      if (count <= 0) {
        return { count: 0 };
      }
      const now = Date.now();
      const values = [];
      for (let i = 0; i < count; i++) {
        values.push(`('User ${i}', '', ${now})`);
      }
      await c.db.execute(
        `INSERT INTO test_data (value, payload, created_at) VALUES ${values.join(", ")}`
      );
      return { count };
    },
    updateValue: async (c, id, value) => {
      await c.db.execute(
        `UPDATE test_data SET value = '${value}' WHERE id = ${id}`
      );
      return { success: true };
    },
    deleteValue: async (c, id) => {
      await c.db.execute(`DELETE FROM test_data WHERE id = ${id}`);
    },
    transactionCommit: async (c, value) => {
      await c.db.execute(
        `BEGIN; INSERT INTO test_data (value, payload, created_at) VALUES ('${value}', '', ${Date.now()}); COMMIT;`
      );
    },
    transactionRollback: async (c, value) => {
      await c.db.execute(
        `BEGIN; INSERT INTO test_data (value, payload, created_at) VALUES ('${value}', '', ${Date.now()}); ROLLBACK;`
      );
    },
    insertPayloadOfSize: async (c, size) => {
      const payload = "x".repeat(size);
      await c.db.execute(
        `INSERT INTO test_data (value, payload, created_at) VALUES ('payload', '${payload}', ${Date.now()})`
      );
      const results = await c.db.execute(
        `SELECT last_insert_rowid() as id`
      );
      return { id: results[0].id, size };
    },
    getPayloadSize: async (c, id) => {
      var _a;
      const results = await c.db.execute(
        `SELECT length(payload) as size FROM test_data WHERE id = ${id}`
      );
      return _nullishCoalesce(((_a = results[0]) == null ? void 0 : _a.size), () => ( 0));
    },
    insertPayloadRows: async (c, count, payloadSize) => {
      const normalizedCount = Math.max(0, Math.trunc(count));
      if (normalizedCount === 0) {
        return { count: 0 };
      }
      const payload = makePayload(payloadSize);
      const now = Date.now();
      for (let i = 0; i < normalizedCount; i++) {
        await c.db.execute(
          `INSERT INTO test_data (value, payload, created_at) VALUES ('bulk-${i}', '${payload}', ${now})`
        );
      }
      return { count: normalizedCount };
    },
    roundRobinUpdateValues: async (c, rowIds, iterations) => {
      const normalizedRowIds = normalizeRowIds(rowIds);
      const normalizedIterations = Math.max(0, Math.trunc(iterations));
      if (normalizedRowIds.length === 0 || normalizedIterations === 0) {
        const emptyRows = [];
        return emptyRows;
      }
      for (let i = 0; i < normalizedIterations; i++) {
        const rowId = _nullishCoalesce(normalizedRowIds[i % normalizedRowIds.length], () => ( 0));
        await c.db.execute(
          `UPDATE test_data SET value = 'v-${i}' WHERE id = ${rowId}`
        );
      }
      return await c.db.execute(
        `SELECT id, value FROM test_data WHERE id IN (${normalizedRowIds.join(",")}) ORDER BY id`
      );
    },
    getPageCount: async (c) => {
      const rows = await c.db.execute(
        "PRAGMA page_count"
      );
      return toSafeInteger(firstRowValue(rows[0]));
    },
    vacuum: async (c) => {
      await c.db.execute("VACUUM");
    },
    integrityCheck: async (c) => {
      const rows = await c.db.execute(
        "PRAGMA integrity_check"
      );
      const value = firstRowValue(rows[0]);
      return String(_nullishCoalesce(value, () => ( "")));
    },
    runMixedWorkload: async (c, seedCount, churnCount) => {
      const normalizedSeedCount = Math.max(1, Math.trunc(seedCount));
      const normalizedChurnCount = Math.max(0, Math.trunc(churnCount));
      const now = Date.now();
      for (let i = 0; i < normalizedSeedCount; i++) {
        const payload = makePayload(1024 + i % 5 * 128);
        await c.db.execute(
          `INSERT OR REPLACE INTO test_data (id, value, payload, created_at) VALUES (${i + 1}, 'seed-${i}', '${payload}', ${now})`
        );
      }
      for (let i = 0; i < normalizedChurnCount; i++) {
        const id = i % normalizedSeedCount + 1;
        if (i % 9 === 0) {
          await c.db.execute(`DELETE FROM test_data WHERE id = ${id}`);
        } else {
          const payload = makePayload(768 + i % 7 * 96);
          await c.db.execute(
            `INSERT OR REPLACE INTO test_data (id, value, payload, created_at) VALUES (${id}, 'upd-${i}', '${payload}', ${now + i})`
          );
        }
      }
    },
    repeatUpdate: async (c, id, count) => {
      let value = "";
      if (count <= 0) {
        return { value };
      }
      const statements = ["BEGIN"];
      for (let i = 0; i < count; i++) {
        value = `Updated ${i}`;
        statements.push(
          `UPDATE test_data SET value = '${value}' WHERE id = ${id}`
        );
      }
      statements.push("COMMIT");
      await c.db.execute(statements.join("; "));
      return { value };
    },
    multiStatementInsert: async (c, value) => {
      var _a;
      await c.db.execute(
        `BEGIN; INSERT INTO test_data (value, payload, created_at) VALUES ('${value}', '', ${Date.now()}); UPDATE test_data SET value = '${value}-updated' WHERE id = last_insert_rowid(); COMMIT;`
      );
      const results = await c.db.execute(
        `SELECT value FROM test_data ORDER BY id DESC LIMIT 1`
      );
      return _nullishCoalesce(((_a = results[0]) == null ? void 0 : _a.value), () => ( null));
    },
    triggerSleep: (c) => {
      c.sleep();
    }
  },
  options: {
    sleepTimeout: 100
  }
});

// fixtures/driver-test-suite/db/migrations.ts
var migrations = {
  journal: {
    entries: [
      {
        idx: 0,
        when: 17e11,
        tag: "0000_init",
        breakpoints: false
      }
    ]
  },
  migrations: {
    m0000: `
			CREATE TABLE IF NOT EXISTS test_data (
				id INTEGER PRIMARY KEY AUTOINCREMENT,
				value TEXT NOT NULL,
				payload TEXT NOT NULL DEFAULT '',
				created_at INTEGER NOT NULL
			);
		`
  }
};

// fixtures/driver-test-suite/db/schema.ts
var testData = _chunkZFY5J2EPcjs.sqliteTable.call(void 0, "test_data", {
  id: _chunkZFY5J2EPcjs.integer.call(void 0, "id").primaryKey({ autoIncrement: true }),
  value: _chunkZFY5J2EPcjs.text.call(void 0, "value").notNull(),
  payload: _chunkZFY5J2EPcjs.text.call(void 0, "payload").notNull().default(""),
  createdAt: _chunkZFY5J2EPcjs.integer.call(void 0, "created_at").notNull()
});
var schema = {
  testData
};

// fixtures/driver-test-suite/actor-db-drizzle.ts
function firstRowValue2(row) {
  if (!row) {
    return void 0;
  }
  const values = Object.values(row);
  return values.length > 0 ? values[0] : void 0;
}
function toSafeInteger2(value) {
  if (typeof value === "bigint") {
    return Number(value);
  }
  if (typeof value === "number") {
    return Number.isFinite(value) ? Math.trunc(value) : 0;
  }
  if (typeof value === "string") {
    const parsed = Number.parseInt(value, 10);
    return Number.isFinite(parsed) ? parsed : 0;
  }
  return 0;
}
function normalizeRowIds2(rowIds) {
  const normalized = rowIds.map((id) => Math.trunc(id)).filter((id) => Number.isFinite(id) && id > 0);
  return Array.from(new Set(normalized));
}
function makePayload2(size) {
  const normalizedSize = Math.max(0, Math.trunc(size));
  return "x".repeat(normalizedSize);
}
var dbActorDrizzle = _chunk65RINRXEcjs.actor.call(void 0, {
  state: {
    disconnectInsertEnabled: false,
    disconnectInsertDelayMs: 0
  },
  db: _chunkZFY5J2EPcjs.db.call(void 0, {
    schema,
    migrations
  }),
  onDisconnect: async (c) => {
    if (!c.state.disconnectInsertEnabled) {
      return;
    }
    if (c.state.disconnectInsertDelayMs > 0) {
      await new Promise(
        (resolve) => setTimeout(resolve, c.state.disconnectInsertDelayMs)
      );
    }
    await c.db.execute(
      `INSERT INTO test_data (value, payload, created_at) VALUES ('__disconnect__', '', ${Date.now()})`
    );
  },
  actions: {
    configureDisconnectInsert: (c, enabled, delayMs) => {
      c.state.disconnectInsertEnabled = enabled;
      c.state.disconnectInsertDelayMs = Math.max(
        0,
        Math.floor(delayMs)
      );
    },
    getDisconnectInsertCount: async (c) => {
      var _a;
      const results = await c.db.execute(
        `SELECT COUNT(*) as count FROM test_data WHERE value = '__disconnect__'`
      );
      return _nullishCoalesce(((_a = results[0]) == null ? void 0 : _a.count), () => ( 0));
    },
    reset: async (c) => {
      await c.db.execute(`DELETE FROM test_data`);
    },
    insertValue: async (c, value) => {
      await c.db.execute(
        `INSERT INTO test_data (value, payload, created_at) VALUES ('${value}', '', ${Date.now()})`
      );
      const results = await c.db.execute(
        `SELECT last_insert_rowid() as id`
      );
      return { id: results[0].id };
    },
    getValues: async (c) => {
      const results = await c.db.execute(
        `SELECT * FROM test_data ORDER BY id`
      );
      return results;
    },
    getValue: async (c, id) => {
      var _a;
      const results = await c.db.execute(
        `SELECT value FROM test_data WHERE id = ${id}`
      );
      return _nullishCoalesce(((_a = results[0]) == null ? void 0 : _a.value), () => ( null));
    },
    getCount: async (c) => {
      const results = await c.db.execute(
        `SELECT COUNT(*) as count FROM test_data`
      );
      return results[0].count;
    },
    rawSelectCount: async (c) => {
      var _a;
      const results = await c.db.execute(
        `SELECT COUNT(*) as count FROM test_data`
      );
      return _nullishCoalesce(((_a = results[0]) == null ? void 0 : _a.count), () => ( 0));
    },
    insertMany: async (c, count) => {
      if (count <= 0) {
        return { count: 0 };
      }
      const now = Date.now();
      const values = [];
      for (let i = 0; i < count; i++) {
        values.push(`('User ${i}', '', ${now})`);
      }
      await c.db.execute(
        `INSERT INTO test_data (value, payload, created_at) VALUES ${values.join(", ")}`
      );
      return { count };
    },
    updateValue: async (c, id, value) => {
      await c.db.execute(
        `UPDATE test_data SET value = '${value}' WHERE id = ${id}`
      );
      return { success: true };
    },
    deleteValue: async (c, id) => {
      await c.db.execute(`DELETE FROM test_data WHERE id = ${id}`);
    },
    transactionCommit: async (c, value) => {
      await c.db.execute(
        `BEGIN; INSERT INTO test_data (value, payload, created_at) VALUES ('${value}', '', ${Date.now()}); COMMIT;`
      );
    },
    transactionRollback: async (c, value) => {
      await c.db.execute(
        `BEGIN; INSERT INTO test_data (value, payload, created_at) VALUES ('${value}', '', ${Date.now()}); ROLLBACK;`
      );
    },
    insertPayloadOfSize: async (c, size) => {
      const payload = "x".repeat(size);
      await c.db.execute(
        `INSERT INTO test_data (value, payload, created_at) VALUES ('payload', '${payload}', ${Date.now()})`
      );
      const results = await c.db.execute(
        `SELECT last_insert_rowid() as id`
      );
      return { id: results[0].id, size };
    },
    getPayloadSize: async (c, id) => {
      var _a;
      const results = await c.db.execute(
        `SELECT length(payload) as size FROM test_data WHERE id = ${id}`
      );
      return _nullishCoalesce(((_a = results[0]) == null ? void 0 : _a.size), () => ( 0));
    },
    insertPayloadRows: async (c, count, payloadSize) => {
      const normalizedCount = Math.max(0, Math.trunc(count));
      if (normalizedCount === 0) {
        return { count: 0 };
      }
      const payload = makePayload2(payloadSize);
      const now = Date.now();
      for (let i = 0; i < normalizedCount; i++) {
        await c.db.execute(
          `INSERT INTO test_data (value, payload, created_at) VALUES ('bulk-${i}', '${payload}', ${now})`
        );
      }
      return { count: normalizedCount };
    },
    roundRobinUpdateValues: async (c, rowIds, iterations) => {
      const normalizedRowIds = normalizeRowIds2(rowIds);
      const normalizedIterations = Math.max(0, Math.trunc(iterations));
      if (normalizedRowIds.length === 0 || normalizedIterations === 0) {
        const emptyRows = [];
        return emptyRows;
      }
      for (let i = 0; i < normalizedIterations; i++) {
        const rowId = _nullishCoalesce(normalizedRowIds[i % normalizedRowIds.length], () => ( 0));
        await c.db.execute(
          `UPDATE test_data SET value = 'v-${i}' WHERE id = ${rowId}`
        );
      }
      return await c.db.execute(
        `SELECT id, value FROM test_data WHERE id IN (${normalizedRowIds.join(",")}) ORDER BY id`
      );
    },
    getPageCount: async (c) => {
      const rows = await c.db.execute(
        "PRAGMA page_count"
      );
      return toSafeInteger2(firstRowValue2(rows[0]));
    },
    vacuum: async (c) => {
      await c.db.execute("VACUUM");
    },
    integrityCheck: async (c) => {
      const rows = await c.db.execute(
        "PRAGMA integrity_check"
      );
      const value = firstRowValue2(rows[0]);
      return String(_nullishCoalesce(value, () => ( "")));
    },
    runMixedWorkload: async (c, seedCount, churnCount) => {
      const normalizedSeedCount = Math.max(1, Math.trunc(seedCount));
      const normalizedChurnCount = Math.max(0, Math.trunc(churnCount));
      const now = Date.now();
      for (let i = 0; i < normalizedSeedCount; i++) {
        const payload = makePayload2(1024 + i % 5 * 128);
        await c.db.execute(
          `INSERT OR REPLACE INTO test_data (id, value, payload, created_at) VALUES (${i + 1}, 'seed-${i}', '${payload}', ${now})`
        );
      }
      for (let i = 0; i < normalizedChurnCount; i++) {
        const id = i % normalizedSeedCount + 1;
        if (i % 9 === 0) {
          await c.db.execute(`DELETE FROM test_data WHERE id = ${id}`);
        } else {
          const payload = makePayload2(768 + i % 7 * 96);
          await c.db.execute(
            `INSERT OR REPLACE INTO test_data (id, value, payload, created_at) VALUES (${id}, 'upd-${i}', '${payload}', ${now + i})`
          );
        }
      }
    },
    repeatUpdate: async (c, id, count) => {
      let value = "";
      if (count <= 0) {
        return { value };
      }
      const statements = ["BEGIN"];
      for (let i = 0; i < count; i++) {
        value = `Updated ${i}`;
        statements.push(
          `UPDATE test_data SET value = '${value}' WHERE id = ${id}`
        );
      }
      statements.push("COMMIT");
      await c.db.execute(statements.join("; "));
      return { value };
    },
    multiStatementInsert: async (c, value) => {
      var _a;
      await c.db.execute(
        `BEGIN; INSERT INTO test_data (value, payload, created_at) VALUES ('${value}', '', ${Date.now()}); UPDATE test_data SET value = '${value}-updated' WHERE id = last_insert_rowid(); COMMIT;`
      );
      const results = await c.db.execute(
        `SELECT value FROM test_data ORDER BY id DESC LIMIT 1`
      );
      return _nullishCoalesce(((_a = results[0]) == null ? void 0 : _a.value), () => ( null));
    },
    triggerSleep: (c) => {
      c.sleep();
    }
  },
  options: {
    sleepTimeout: 100
  }
});

// fixtures/driver-test-suite/db-lifecycle.ts
var clientActorIds = /* @__PURE__ */ new WeakMap();
var createCounts = /* @__PURE__ */ new Map();
var migrateCounts = /* @__PURE__ */ new Map();
var cleanupCounts = /* @__PURE__ */ new Map();
function increment(map, actorId) {
  map.set(actorId, (_nullishCoalesce(map.get(actorId), () => ( 0))) + 1);
}
function getCounts(actorId) {
  return {
    create: _nullishCoalesce(createCounts.get(actorId), () => ( 0)),
    migrate: _nullishCoalesce(migrateCounts.get(actorId), () => ( 0)),
    cleanup: _nullishCoalesce(cleanupCounts.get(actorId), () => ( 0))
  };
}
var baseProvider = _chunk6LJAZ5R4cjs.db.call(void 0, {
  onMigrate: async (dbHandle) => {
    await dbHandle.execute(`
			CREATE TABLE IF NOT EXISTS lifecycle_data (
				id INTEGER PRIMARY KEY AUTOINCREMENT,
				value TEXT NOT NULL,
				created_at INTEGER NOT NULL
			)
		`);
  }
});
var lifecycleProvider = {
  createClient: async (ctx) => {
    const client = await baseProvider.createClient(ctx);
    clientActorIds.set(client, ctx.actorId);
    increment(createCounts, ctx.actorId);
    return client;
  },
  onMigrate: async (client) => {
    const actorId = clientActorIds.get(client);
    if (actorId) {
      increment(migrateCounts, actorId);
    }
    await baseProvider.onMigrate(client);
  },
  onDestroy: async (client) => {
    var _a;
    const actorId = clientActorIds.get(client);
    if (actorId) {
      increment(cleanupCounts, actorId);
    }
    await ((_a = baseProvider.onDestroy) == null ? void 0 : _a.call(baseProvider, client));
  }
};
var failingLifecycleProvider = {
  createClient: async (ctx) => {
    const client = await baseProvider.createClient(ctx);
    clientActorIds.set(client, ctx.actorId);
    increment(createCounts, ctx.actorId);
    return client;
  },
  onMigrate: async (client) => {
    const actorId = clientActorIds.get(client);
    if (actorId) {
      increment(migrateCounts, actorId);
    }
    throw new Error("forced migrate failure");
  },
  onDestroy: async (client) => {
    var _a;
    const actorId = clientActorIds.get(client);
    if (actorId) {
      increment(cleanupCounts, actorId);
    }
    await ((_a = baseProvider.onDestroy) == null ? void 0 : _a.call(baseProvider, client));
  }
};
var dbLifecycle = _chunk65RINRXEcjs.actor.call(void 0, {
  db: lifecycleProvider,
  actions: {
    getActorId: (c) => c.actorId,
    ping: () => "pong",
    insertValue: async (c, value) => {
      await c.db.execute(
        "INSERT INTO lifecycle_data (value, created_at) VALUES (?, ?)",
        value,
        Date.now()
      );
    },
    getCount: async (c) => {
      var _a;
      const results = await c.db.execute(
        `SELECT COUNT(*) as count FROM lifecycle_data`
      );
      return _nullishCoalesce(((_a = results[0]) == null ? void 0 : _a.count), () => ( 0));
    },
    triggerSleep: (c) => {
      c.sleep();
    },
    triggerDestroy: (c) => {
      c.destroy();
    }
  },
  options: {
    sleepTimeout: 100
  }
});
var dbLifecycleFailing = _chunk65RINRXEcjs.actor.call(void 0, {
  db: failingLifecycleProvider,
  actions: {
    ping: () => "pong"
  }
});
var dbLifecycleObserver = _chunk65RINRXEcjs.actor.call(void 0, {
  actions: {
    getCounts: (_c, actorId) => {
      return getCounts(actorId);
    }
  }
});

// fixtures/driver-test-suite/actor-onstatechange.ts
var onStateChangeActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: {
    value: 0,
    changeCount: 0
  },
  actions: {
    // Action that modifies state - should trigger onStateChange
    setValue: (c, newValue) => {
      c.state.value = newValue;
      return c.state.value;
    },
    // Action that modifies state multiple times - should trigger onStateChange for each change
    incrementMultiple: (c, times) => {
      for (let i = 0; i < times; i++) {
        c.state.value++;
      }
      return c.state.value;
    },
    // Action that doesn't modify state - should NOT trigger onStateChange
    getValue: (c) => {
      return c.state.value;
    },
    // Action that reads and returns without modifying - should NOT trigger onStateChange
    getDoubled: (c) => {
      const doubled = c.state.value * 2;
      return doubled;
    },
    // Get the count of how many times onStateChange was called
    getChangeCount: (c) => {
      return c.state.changeCount;
    },
    // Reset change counter for testing
    resetChangeCount: (c) => {
      c.state.changeCount = 0;
    }
  },
  // Track onStateChange calls
  onStateChange: (c) => {
    c.state.changeCount++;
  }
});

// fixtures/driver-test-suite/conn-params.ts
var counterWithParams = _chunk65RINRXEcjs.actor.call(void 0, {
  state: { count: 0, initializers: [] },
  createConnState: (c, params) => {
    return {
      name: params.name || "anonymous"
    };
  },
  onConnect: (c, conn) => {
    c.state.initializers.push(conn.state.name);
  },
  actions: {
    increment: (c, x) => {
      c.state.count += x;
      c.broadcast("newCount", {
        count: c.state.count,
        by: c.conn.state.name
      });
      return c.state.count;
    },
    getInitializers: (c) => {
      return c.state.initializers;
    }
  }
});

// fixtures/driver-test-suite/conn-state.ts
var connStateActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: {
    sharedCounter: 0,
    disconnectionCount: 0
  },
  // Define connection state
  createConnState: (c, params) => {
    return {
      username: (params == null ? void 0 : params.username) || "anonymous",
      role: (params == null ? void 0 : params.role) || "user",
      counter: 0,
      createdAt: Date.now(),
      noCount: _nullishCoalesce((params == null ? void 0 : params.noCount), () => ( false))
    };
  },
  // Lifecycle hook when a connection is established
  onConnect: (c, conn) => {
    c.broadcast("userConnected", {
      id: conn.id,
      username: "anonymous",
      role: "user"
    });
  },
  // Lifecycle hook when a connection is closed
  onDisconnect: (c, conn) => {
    var _a;
    if (!((_a = conn.state) == null ? void 0 : _a.noCount)) {
      c.state.disconnectionCount += 1;
      c.broadcast("userDisconnected", {
        id: conn.id
      });
    }
  },
  actions: {
    // Action to increment the connection's counter
    incrementConnCounter: (c, amount = 1) => {
      c.conn.state.counter += amount;
    },
    // Action to increment the shared counter
    incrementSharedCounter: (c, amount = 1) => {
      c.state.sharedCounter += amount;
      return c.state.sharedCounter;
    },
    // Get the connection state
    getConnectionState: (c) => {
      return { id: c.conn.id, ...c.conn.state };
    },
    // Check all active connections
    getConnectionIds: (c) => {
      return c.conns.entries().filter((c2) => {
        var _a;
        return !((_a = c2[1].state) == null ? void 0 : _a.noCount);
      }).map((x) => x[0]).toArray();
    },
    // Get disconnection count
    getDisconnectionCount: (c) => {
      return c.state.disconnectionCount;
    },
    // Get all active connection states
    getAllConnectionStates: (c) => {
      return c.conns.entries().map(([id, conn]) => ({ id, ...conn.state })).toArray();
    },
    // Send message to a specific connection with matching ID
    sendToConnection: (c, targetId, message) => {
      if (c.conns.has(targetId)) {
        c.conns.get(targetId).send("directMessage", { from: c.conn.id, message });
        return true;
      } else {
        return false;
      }
    },
    // Update connection state (simulated for tests)
    updateConnection: (c, updates) => {
      if (updates.username) c.conn.state.username = updates.username;
      if (updates.role) c.conn.state.role = updates.role;
      return c.conn.state;
    },
    disconnectSelf: (c, reason) => {
      c.conn.disconnect(_nullishCoalesce(reason, () => ( "test.disconnect")));
      return true;
    }
  }
});

// fixtures/driver-test-suite/counter.ts
var counter = _chunk65RINRXEcjs.actor.call(void 0, {
  state: { count: 0 },
  actions: {
    increment: (c, x) => {
      c.state.count += x;
      c.broadcast("newCount", c.state.count);
      return c.state.count;
    },
    setCount: (c, x) => {
      c.state.count = x;
      c.broadcast("newCount", x);
      return c.state.count;
    },
    getCount: (c) => {
      return c.state.count;
    },
    getKey: (c) => {
      return c.key;
    }
  }
});

// fixtures/driver-test-suite/counter-conn.ts
var counterConn = _chunk65RINRXEcjs.actor.call(void 0, {
  state: {
    connectionCount: 0
  },
  connState: { count: 0 },
  onConnect: (c, conn) => {
    c.state.connectionCount += 1;
  },
  onDisconnect: (c, conn) => {
    c.state.connectionCount -= 1;
  },
  actions: {
    increment: (c, x) => {
      c.conn.state.count += x;
      c.broadcast("newCount", c.conn.state.count);
    },
    setCount: (c, x) => {
      c.conn.state.count = x;
      c.broadcast("newCount", x);
    },
    getCount: (c) => {
      return c.conn.state.count;
    },
    getConnectionCount: (c) => {
      return c.state.connectionCount;
    }
  }
});

// fixtures/driver-test-suite/destroy.ts
var destroyObserver = _chunk65RINRXEcjs.actor.call(void 0, {
  state: { destroyedActors: [] },
  actions: {
    notifyDestroyed: (c, actorKey) => {
      c.state.destroyedActors.push(actorKey);
    },
    wasDestroyed: (c, actorKey) => {
      return c.state.destroyedActors.includes(actorKey);
    },
    reset: (c) => {
      c.state.destroyedActors = [];
    }
  }
});
var destroyActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: { value: 0, key: "" },
  onWake: (c) => {
    c.state.key = c.key.join("/");
  },
  onDestroy: async (c) => {
    const client = c.client();
    const observer = client.destroyObserver.getOrCreate(["observer"]);
    await observer.notifyDestroyed(c.state.key);
  },
  actions: {
    setValue: async (c, newValue) => {
      c.state.value = newValue;
      await c.saveState({ immediate: true });
      return c.state.value;
    },
    getValue: (c) => {
      return c.state.value;
    },
    destroy: (c) => {
      c.destroy();
    }
  }
});

// fixtures/driver-test-suite/error-handling.ts
var errorHandlingActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: {
    errorLog: []
  },
  actions: {
    // Action that throws a UserError with just a message
    throwSimpleError: () => {
      throw new (0, _chunkL47L3ZWJcjs.UserError)("Simple error message");
    },
    // Action that throws a UserError with code and metadata
    throwDetailedError: () => {
      throw new (0, _chunkL47L3ZWJcjs.UserError)("Detailed error message", {
        code: "detailed_error",
        metadata: {
          reason: "test",
          timestamp: Date.now()
        }
      });
    },
    // Action that throws an internal error
    throwInternalError: () => {
      throw new Error("This is an internal error");
    },
    // Action that returns successfully
    successfulAction: () => {
      return "success";
    },
    // Action that times out (simulated with a long delay)
    timeoutAction: async (c) => {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve("This should not be reached if timeout works");
        }, 1e4);
      });
    },
    // Action with configurable delay to test timeout edge cases
    delayedAction: async (c, delayMs) => {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve(`Completed after ${delayMs}ms`);
        }, delayMs);
      });
    },
    // Log an error for inspection
    logError: (c, error) => {
      c.state.errorLog.push(error);
      return c.state.errorLog;
    },
    // Get the error log
    getErrorLog: (c) => {
      return c.state.errorLog;
    },
    // Clear the error log
    clearErrorLog: (c) => {
      c.state.errorLog = [];
      return true;
    }
  },
  options: {
    actionTimeout: 500
    // 500ms timeout for actions
  }
});
var customTimeoutActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: {},
  actions: {
    quickAction: async () => {
      await new Promise((resolve) => setTimeout(resolve, 50));
      return "Quick action completed";
    },
    slowAction: async () => {
      await new Promise((resolve) => setTimeout(resolve, 300));
      return "Slow action completed";
    }
  },
  options: {
    actionTimeout: 200
    // 200ms timeout
  }
});

// fixtures/driver-test-suite/file-system-hibernation-cleanup.ts
var fileSystemHibernationCleanupActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: {
    wakeCount: 0,
    sleepCount: 0,
    disconnectWakeCounts: []
  },
  createConnState: () => ({}),
  onWake: (c) => {
    c.state.wakeCount += 1;
  },
  onSleep: (c) => {
    c.state.sleepCount += 1;
  },
  onDisconnect: (c, conn) => {
    if (conn.isHibernatable) {
      c.state.disconnectWakeCounts.push(c.state.wakeCount);
    }
  },
  actions: {
    ping: () => "pong",
    triggerSleep: (c) => {
      c.sleep();
    },
    getCounts: (c) => ({
      wakeCount: c.state.wakeCount,
      sleepCount: c.state.sleepCount
    }),
    getDisconnectWakeCounts: (c) => c.state.disconnectWakeCounts
  },
  options: {
    sleepTimeout: 500
  }
});

// fixtures/driver-test-suite/inline-client.ts
var inlineClientActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: { messages: [] },
  actions: {
    // Action that uses client to call another actor (stateless)
    callCounterIncrement: async (c, amount) => {
      const client = c.client();
      const result = await client.counter.getOrCreate(["inline-test"]).increment(amount);
      c.state.messages.push(
        `Called counter.increment(${amount}), result: ${result}`
      );
      return result;
    },
    // Action that uses client to get counter state (stateless)
    getCounterState: async (c) => {
      const client = c.client();
      const count = await client.counter.getOrCreate(["inline-test"]).getCount();
      c.state.messages.push(`Got counter state: ${count}`);
      return count;
    },
    // Action that uses client with .connect() for stateful communication
    connectToCounterAndIncrement: async (c, amount) => {
      const client = c.client();
      const handle = client.counter.getOrCreate(["inline-test-stateful"]);
      const connection = handle.connect();
      const events = [];
      connection.on("newCount", (count) => {
        events.push(count);
      });
      const result1 = await connection.increment(amount);
      const result2 = await connection.increment(amount * 2);
      await connection.dispose();
      c.state.messages.push(
        `Connected to counter, incremented by ${amount} and ${amount * 2}, results: ${result1}, ${result2}, events: ${JSON.stringify(events)}`
      );
      return { result1, result2, events };
    },
    // Get all messages from this actor's state
    getMessages: (c) => {
      return c.state.messages;
    },
    // Clear messages
    clearMessages: (c) => {
      c.state.messages = [];
    }
  }
});

// fixtures/driver-test-suite/kv.ts
var kvActor = _chunk65RINRXEcjs.actor.call(void 0, {
  actions: {
    putText: async (c, key, value) => {
      await c.kv.put(key, value);
      return true;
    },
    getText: async (c, key) => {
      return await c.kv.get(key);
    },
    listText: async (c, prefix) => {
      const results = await c.kv.list(prefix, { keyType: "text" });
      return results.map(([key, value]) => ({
        key,
        value
      }));
    },
    roundtripArrayBuffer: async (c, key, values) => {
      const buffer = new Uint8Array(values).buffer;
      await c.kv.put(key, buffer, { type: "arrayBuffer" });
      const result = await c.kv.get(key, { type: "arrayBuffer" });
      if (!result) {
        return null;
      }
      return Array.from(new Uint8Array(result));
    }
  }
});

// fixtures/driver-test-suite/large-payloads.ts
var largePayloadActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: {},
  actions: {
    /**
     * Accepts a large request payload and returns its size
     */
    processLargeRequest: (c, data) => {
      return {
        itemCount: data.items.length,
        firstItem: data.items[0],
        lastItem: data.items[data.items.length - 1]
      };
    },
    /**
     * Returns a large response payload
     */
    getLargeResponse: (c, itemCount) => {
      const items = [];
      for (let i = 0; i < itemCount; i++) {
        items.push(`Item ${i} with some additional text to increase size`);
      }
      return { items };
    },
    /**
     * Echo back the request data
     */
    echo: (c, data) => {
      return data;
    }
  }
});
var largePayloadConnActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: {},
  connState: {
    lastRequestSize: 0
  },
  actions: {
    /**
     * Accepts a large request payload and returns its size
     */
    processLargeRequest: (c, data) => {
      c.conn.state.lastRequestSize = data.items.length;
      return {
        itemCount: data.items.length,
        firstItem: data.items[0],
        lastItem: data.items[data.items.length - 1]
      };
    },
    /**
     * Returns a large response payload
     */
    getLargeResponse: (c, itemCount) => {
      const items = [];
      for (let i = 0; i < itemCount; i++) {
        items.push(`Item ${i} with some additional text to increase size`);
      }
      return { items };
    },
    /**
     * Echo back the request data
     */
    echo: (c, data) => {
      return data;
    },
    /**
     * Get the last request size
     */
    getLastRequestSize: (c) => {
      return c.conn.state.lastRequestSize;
    }
  }
});

// fixtures/driver-test-suite/lifecycle.ts
var counterWithLifecycle = _chunk65RINRXEcjs.actor.call(void 0, {
  state: {
    count: 0,
    events: []
  },
  createConnState: (c, params) => ({
    joinTime: Date.now()
  }),
  onWake: (c) => {
    c.state.events.push("onWake");
  },
  onBeforeConnect: (c, params) => {
    if (params == null ? void 0 : params.trackLifecycle) c.state.events.push("onBeforeConnect");
  },
  onConnect: (c, conn) => {
    var _a;
    if ((_a = conn.params) == null ? void 0 : _a.trackLifecycle) c.state.events.push("onConnect");
  },
  onDisconnect: (c, conn) => {
    var _a;
    if ((_a = conn.params) == null ? void 0 : _a.trackLifecycle) c.state.events.push("onDisconnect");
  },
  actions: {
    getEvents: (c) => {
      return c.state.events;
    },
    increment: (c, x) => {
      c.state.count += x;
      return c.state.count;
    }
  }
});

// fixtures/driver-test-suite/metadata.ts
var metadataActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: {
    lastMetadata: null,
    actorName: "",
    // Store tags and region in state for testing since they may not be
    // available in the context in all environments
    storedTags: {},
    storedRegion: null
  },
  onWake: (c) => {
    c.state.actorName = c.name;
  },
  actions: {
    // Set up test tags - this will be called by tests to simulate tags
    setupTestTags: (c, tags) => {
      c.state.storedTags = tags;
      return tags;
    },
    // Set up test region - this will be called by tests to simulate region
    setupTestRegion: (c, region) => {
      c.state.storedRegion = region;
      return region;
    },
    // Get all available metadata
    getMetadata: (c) => {
      const metadata = {
        name: c.name,
        tags: c.state.storedTags,
        region: c.state.storedRegion
      };
      c.state.lastMetadata = metadata;
      return metadata;
    },
    // Get the actor name
    getActorName: (c) => {
      return c.name;
    },
    // Get a specific tag by key
    getTag: (c, key) => {
      return c.state.storedTags[key] || null;
    },
    // Get all tags
    getTags: (c) => {
      return c.state.storedTags;
    },
    // Get the region
    getRegion: (c) => {
      return c.state.storedRegion;
    },
    // Get the stored actor name (from onWake)
    getStoredActorName: (c) => {
      return c.state.actorName;
    },
    // Get last retrieved metadata
    getLastMetadata: (c) => {
      return c.state.lastMetadata;
    }
  }
});

// fixtures/driver-test-suite/queue.ts
var queueSchemas = {
  greeting: _chunk65RINRXEcjs.queue.call(void 0, ),
  self: _chunk65RINRXEcjs.queue.call(void 0, ),
  a: _chunk65RINRXEcjs.queue.call(void 0, ),
  b: _chunk65RINRXEcjs.queue.call(void 0, ),
  c: _chunk65RINRXEcjs.queue.call(void 0, ),
  one: _chunk65RINRXEcjs.queue.call(void 0, ),
  two: _chunk65RINRXEcjs.queue.call(void 0, ),
  missing: _chunk65RINRXEcjs.queue.call(void 0, ),
  abort: _chunk65RINRXEcjs.queue.call(void 0, ),
  tasks: _chunk65RINRXEcjs.queue.call(void 0, ),
  timeout: _chunk65RINRXEcjs.queue.call(void 0, ),
  nowait: _chunk65RINRXEcjs.queue.call(void 0, ),
  twice: _chunk65RINRXEcjs.queue.call(void 0, )
};
var queueActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: {},
  queues: queueSchemas,
  actions: {
    receiveOne: async (c, name, opts) => {
      const messages = await c.queue.next({
        names: [name],
        count: opts == null ? void 0 : opts.count,
        timeout: opts == null ? void 0 : opts.timeout
      });
      const message = messages[0];
      if (!message) {
        return null;
      }
      return { name: message.name, body: message.body };
    },
    receiveMany: async (c, names, opts) => {
      const messages = await c.queue.next({
        names,
        count: opts == null ? void 0 : opts.count,
        timeout: opts == null ? void 0 : opts.timeout
      });
      return messages.map((message) => ({
        name: message.name,
        body: message.body
      }));
    },
    receiveRequest: async (c, request) => {
      const messages = await c.queue.next(request);
      return messages.map((message) => ({
        name: message.name,
        body: message.body
      }));
    },
    tryReceiveMany: async (c, request) => {
      const messages = await c.queue.tryNext(request);
      return messages.map((message) => ({
        name: message.name,
        body: message.body
      }));
    },
    receiveWithIterator: async (c, name) => {
      for await (const message of c.queue.iter({ names: [name] })) {
        return { name: message.name, body: message.body };
      }
      return null;
    },
    receiveWithAsyncIterator: async (c) => {
      for await (const message of c.queue.iter()) {
        return { name: message.name, body: message.body };
      }
      return null;
    },
    sendToSelf: async (c, name, body) => {
      const client = c.client();
      const handle = client.queueActor.getForId(c.actorId);
      await handle.send(name, body);
      return true;
    },
    waitForAbort: async (c) => {
      setTimeout(() => {
        c.destroy();
      }, 10);
      await c.queue.next({ names: ["abort"], timeout: 1e4 });
      return true;
    },
    waitForSignalAbort: async (c) => {
      const controller = new AbortController();
      controller.abort();
      try {
        await c.queue.next({
          names: ["abort"],
          timeout: 1e4,
          signal: controller.signal
        });
        return { ok: false };
      } catch (error) {
        const actorError = error;
        return { group: actorError.group, code: actorError.code };
      }
    },
    waitForActorAbortWithSignal: async (c) => {
      const controller = new AbortController();
      setTimeout(() => {
        c.destroy();
      }, 10);
      try {
        await c.queue.next({
          names: ["abort"],
          timeout: 1e4,
          signal: controller.signal
        });
        return { ok: false };
      } catch (error) {
        const actorError = error;
        return { group: actorError.group, code: actorError.code };
      }
    },
    iterWithSignalAbort: async (c) => {
      const controller = new AbortController();
      controller.abort();
      for await (const _message of c.queue.iter({
        names: ["abort"],
        signal: controller.signal
      })) {
        return { ok: false };
      }
      return { ok: true };
    },
    receiveAndComplete: async (c, name) => {
      const messages = await c.queue.next({ names: [name], completable: true });
      const message = messages[0];
      if (!message) {
        return null;
      }
      await message.complete({ echo: message.body });
      return { name: message.name, body: message.body };
    },
    receiveWithoutComplete: async (c, name) => {
      const messages = await c.queue.next({ names: [name], completable: true });
      const message = messages[0];
      if (!message) {
        return null;
      }
      return { name: message.name, body: message.body };
    },
    receiveManualThenNextWithoutComplete: async (c, name) => {
      const messages = await c.queue.next({ names: [name], completable: true });
      const message = messages[0];
      if (!message) {
        return { ok: false, reason: "no_message" };
      }
      try {
        await c.queue.next({ names: [name], timeout: 0 });
        c.destroy();
        return { ok: false, reason: "next_succeeded" };
      } catch (error) {
        c.destroy();
        const actorError = error;
        return { group: actorError.group, code: actorError.code };
      }
    },
    receiveAndCompleteTwice: async (c, name) => {
      const messages = await c.queue.next({ names: [name], completable: true });
      const message = messages[0];
      if (!message) {
        return null;
      }
      await message.complete({ ok: true });
      try {
        await message.complete({ ok: true });
        return { ok: false };
      } catch (error) {
        const actorError = error;
        return { group: actorError.group, code: actorError.code };
      }
    },
    receiveWithoutCompleteMethod: async (c, name) => {
      const messages = await c.queue.next({ names: [name], completable: true });
      const message = messages[0];
      return {
        hasComplete: message !== void 0 && typeof message.complete === "function"
      };
    }
  }
});
var queueLimitedActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: {},
  queues: {
    message: _chunk65RINRXEcjs.queue.call(void 0, ),
    oversize: _chunk65RINRXEcjs.queue.call(void 0, )
  },
  actions: {},
  options: {
    maxQueueSize: 1,
    maxQueueMessageSize: 64
  }
});

// fixtures/driver-test-suite/raw-http.ts
var _hono = require('hono');
var rawHttpActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: {
    requestCount: 0
  },
  onRequest(ctx, request) {
    const url = new URL(request.url);
    const method = request.method;
    ctx.state.requestCount++;
    if (url.pathname === "/api/hello") {
      return new Response(
        JSON.stringify({ message: "Hello from actor!" }),
        {
          headers: { "Content-Type": "application/json" }
        }
      );
    }
    if (url.pathname === "/api/echo" && method === "POST") {
      return new Response(request.body, {
        headers: request.headers
      });
    }
    if (url.pathname === "/api/state") {
      return new Response(
        JSON.stringify({
          requestCount: ctx.state.requestCount
        }),
        {
          headers: { "Content-Type": "application/json" }
        }
      );
    }
    if (url.pathname === "/api/headers") {
      const headers = {};
      request.headers.forEach((value, key) => {
        headers[key] = value;
      });
      return new Response(JSON.stringify(headers), {
        headers: { "Content-Type": "application/json" }
      });
    }
    return new Response("Not Found", { status: 404 });
  },
  actions: {}
});
var rawHttpNoHandlerActor = _chunk65RINRXEcjs.actor.call(void 0, {
  actions: {}
});
var rawHttpVoidReturnActor = _chunk65RINRXEcjs.actor.call(void 0, {
  onRequest(ctx, request) {
    return void 0;
  },
  actions: {}
});
var rawHttpHonoActor = _chunk65RINRXEcjs.actor.call(void 0, {
  createVars() {
    const router = new (0, _hono.Hono)();
    router.get(
      "/",
      (c) => c.json({ message: "Welcome to Hono actor!" })
    );
    router.get(
      "/users",
      (c) => c.json([
        { id: 1, name: "Alice" },
        { id: 2, name: "Bob" }
      ])
    );
    router.get("/users/:id", (c) => {
      const id = c.req.param("id");
      return c.json({
        id: parseInt(id),
        name: id === "1" ? "Alice" : "Bob"
      });
    });
    router.post("/users", async (c) => {
      const body = await c.req.json();
      return c.json({ id: 3, ...body }, 201);
    });
    router.put("/users/:id", async (c) => {
      const id = c.req.param("id");
      const body = await c.req.json();
      return c.json({ id: parseInt(id), ...body });
    });
    router.delete("/users/:id", (c) => {
      const id = c.req.param("id");
      return c.json({ message: `User ${id} deleted` });
    });
    return { router };
  },
  onRequest(ctx, request) {
    return ctx.vars.router.fetch(request);
  },
  actions: {}
});

// fixtures/driver-test-suite/raw-http-request-properties.ts
var rawHttpRequestPropertiesActor = _chunk65RINRXEcjs.actor.call(void 0, {
  actions: {},
  onRequest(ctx, request) {
    const url = new URL(request.url);
    const method = request.method;
    const headers = {};
    request.headers.forEach((value, key) => {
      headers[key] = value;
    });
    const handleBody = async () => {
      if (!request.body) {
        return null;
      }
      const contentType = request.headers.get("content-type") || "";
      try {
        if (contentType.includes("application/json")) {
          const text2 = await request.text();
          return text2 ? JSON.parse(text2) : null;
        } else {
          const text2 = await request.text();
          return text2 || null;
        }
      } catch (error) {
        return null;
      }
    };
    if (method === "HEAD") {
      return new Response(null, {
        status: 200
      });
    }
    if (method === "OPTIONS") {
      return new Response(null, {
        status: 204
      });
    }
    return handleBody().then((body) => {
      const responseData = {
        // URL properties
        url: request.url,
        pathname: url.pathname,
        search: url.search,
        searchParams: Object.fromEntries(url.searchParams.entries()),
        hash: url.hash,
        // Method
        method: request.method,
        // Headers
        headers,
        // Body
        body,
        bodyText: typeof body === "string" ? body : body === null && request.body !== null ? "" : null,
        // Additional properties that might be available
        // Note: Some properties like cache, credentials, mode, etc.
        // might not be available in all environments
        cache: request.cache || null,
        credentials: request.credentials || null,
        mode: request.mode || null,
        redirect: request.redirect || null,
        referrer: request.referrer || null
      };
      return new Response(JSON.stringify(responseData), {
        headers: { "Content-Type": "application/json" }
      });
    });
  }
});

// fixtures/driver-test-suite/raw-websocket.ts
var rawWebSocketActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: {
    connectionCount: 0,
    messageCount: 0
  },
  onWebSocket(ctx, websocket) {
    ctx.state.connectionCount = ctx.state.connectionCount + 1;
    console.log(
      `[ACTOR] New connection, count: ${ctx.state.connectionCount}`
    );
    websocket.send(
      JSON.stringify({
        type: "welcome",
        connectionCount: ctx.state.connectionCount
      })
    );
    console.log("[ACTOR] Sent welcome message");
    websocket.addEventListener("message", (event2) => {
      var _a;
      ctx.state.messageCount = ctx.state.messageCount + 1;
      console.log(
        `[ACTOR] Message received, total count: ${ctx.state.messageCount}, data:`,
        event2.data
      );
      const data = event2.data;
      if (typeof data === "string") {
        try {
          const parsed = JSON.parse(data);
          if (parsed.type === "ping") {
            websocket.send(
              JSON.stringify({
                type: "pong",
                timestamp: Date.now()
              })
            );
          } else if (parsed.type === "getStats") {
            console.log(
              `[ACTOR] Sending stats - connections: ${ctx.state.connectionCount}, messages: ${ctx.state.messageCount}`
            );
            websocket.send(
              JSON.stringify({
                type: "stats",
                connectionCount: ctx.state.connectionCount,
                messageCount: ctx.state.messageCount
              })
            );
          } else if (parsed.type === "getRequestInfo") {
            const url = ((_a = ctx.request) == null ? void 0 : _a.url) || "ws://actor/websocket";
            const urlObj = new URL(url);
            websocket.send(
              JSON.stringify({
                type: "requestInfo",
                url,
                pathname: urlObj.pathname,
                search: urlObj.search
              })
            );
          } else {
            websocket.send(data);
          }
        } catch (e) {
          websocket.send(data);
        }
      } else {
        websocket.send(data);
      }
    });
    websocket.addEventListener("close", () => {
      ctx.state.connectionCount = ctx.state.connectionCount - 1;
      console.log(
        `[ACTOR] Connection closed, count: ${ctx.state.connectionCount}`
      );
    });
  },
  actions: {
    getStats(ctx) {
      return {
        connectionCount: ctx.state.connectionCount,
        messageCount: ctx.state.messageCount
      };
    }
  }
});
var rawWebSocketBinaryActor = _chunk65RINRXEcjs.actor.call(void 0, {
  onWebSocket(ctx, websocket) {
    websocket.addEventListener("message", (event2) => {
      const data = event2.data;
      if (data instanceof ArrayBuffer || data instanceof Uint8Array) {
        const bytes = new Uint8Array(data);
        const reversed = new Uint8Array(bytes.length);
        for (let i = 0; i < bytes.length; i++) {
          reversed[i] = bytes[bytes.length - 1 - i];
        }
        websocket.send(reversed);
      }
    });
  },
  actions: {}
});

// fixtures/driver-test-suite/request-access.ts
var requestAccessActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: {
    // Track request info from different hooks
    onBeforeConnectRequest: {
      hasRequest: false,
      requestUrl: null,
      requestMethod: null,
      requestHeaders: {}
    },
    createConnStateRequest: {
      hasRequest: false,
      requestUrl: null,
      requestMethod: null,
      requestHeaders: {}
    },
    onRequestRequest: {
      hasRequest: false,
      requestUrl: null,
      requestMethod: null,
      requestHeaders: {}
    },
    onWebSocketRequest: {
      hasRequest: false,
      requestUrl: null,
      requestMethod: null,
      requestHeaders: {}
    }
  },
  createConnState: (c, params) => {
    let requestInfo = null;
    if ((params == null ? void 0 : params.trackRequest) && c.request) {
      const headers = {};
      c.request.headers.forEach((value, key) => {
        headers[key] = value;
      });
      requestInfo = {
        hasRequest: true,
        requestUrl: c.request.url,
        requestMethod: c.request.method,
        requestHeaders: headers
      };
    }
    return {
      trackRequest: (params == null ? void 0 : params.trackRequest) || false,
      requestInfo
    };
  },
  onConnect: (c, conn) => {
    if (conn.state.requestInfo) {
      c.state.createConnStateRequest = conn.state.requestInfo;
    }
  },
  onBeforeConnect: (c, params) => {
    if (params == null ? void 0 : params.trackRequest) {
      if (c.request) {
        c.state.onBeforeConnectRequest.hasRequest = true;
        c.state.onBeforeConnectRequest.requestUrl = c.request.url;
        c.state.onBeforeConnectRequest.requestMethod = c.request.method;
        const headers = {};
        c.request.headers.forEach((value, key) => {
          headers[key] = value;
        });
        c.state.onBeforeConnectRequest.requestHeaders = headers;
      } else {
        c.state.onBeforeConnectRequest.hasRequest = false;
      }
    }
  },
  onRequest: (c, request) => {
    c.state.onRequestRequest.hasRequest = true;
    c.state.onRequestRequest.requestUrl = request.url;
    c.state.onRequestRequest.requestMethod = request.method;
    const headers = {};
    request.headers.forEach((value, key) => {
      headers[key] = value;
    });
    c.state.onRequestRequest.requestHeaders = headers;
    return new Response(
      JSON.stringify({
        hasRequest: true,
        requestUrl: request.url,
        requestMethod: request.method,
        requestHeaders: headers
      }),
      {
        status: 200,
        headers: { "Content-Type": "application/json" }
      }
    );
  },
  onWebSocket: (c, websocket) => {
    if (!c.request) throw "Missing request";
    c.state.onWebSocketRequest.hasRequest = true;
    c.state.onWebSocketRequest.requestUrl = c.request.url;
    c.state.onWebSocketRequest.requestMethod = c.request.method;
    const headers = {};
    c.request.headers.forEach((value, key) => {
      headers[key] = value;
    });
    c.state.onWebSocketRequest.requestHeaders = headers;
    websocket.send(
      JSON.stringify({
        hasRequest: true,
        requestUrl: c.request.url,
        requestMethod: c.request.method,
        requestHeaders: headers
      })
    );
    websocket.addEventListener("message", (event2) => {
      websocket.send(event2.data);
    });
  },
  actions: {
    getRequestInfo: (c) => {
      return {
        onBeforeConnect: c.state.onBeforeConnectRequest,
        createConnState: c.state.createConnStateRequest,
        onRequest: c.state.onRequestRequest,
        onWebSocket: c.state.onWebSocketRequest
      };
    }
  }
});

// fixtures/driver-test-suite/reject-connection.ts
var rejectConnectionActor = _chunk65RINRXEcjs.actor.call(void 0, {
  onBeforeConnect: async (_c, params) => {
    if (params == null ? void 0 : params.reject) {
      await new Promise((resolve) => setTimeout(resolve, 500));
      throw new (0, _chunkL47L3ZWJcjs.UserError)("Rejected connection", {
        code: "rejected"
      });
    }
  },
  actions: {
    ping: () => "pong"
  }
});

// fixtures/driver-test-suite/scheduled.ts
var scheduled = _chunk65RINRXEcjs.actor.call(void 0, {
  state: {
    lastRun: 0,
    scheduledCount: 0,
    taskHistory: []
  },
  actions: {
    // Schedule using 'at' with specific timestamp
    scheduleTaskAt: (c, timestamp) => {
      c.schedule.at(timestamp, "onScheduledTask");
      return timestamp;
    },
    // Schedule using 'after' with delay
    scheduleTaskAfter: (c, delayMs) => {
      c.schedule.after(delayMs, "onScheduledTask");
      return Date.now() + delayMs;
    },
    // Schedule with a task ID for ordering tests
    scheduleTaskAfterWithId: (c, taskId, delayMs) => {
      c.schedule.after(delayMs, "onScheduledTaskWithId", taskId);
      return { taskId, scheduledFor: Date.now() + delayMs };
    },
    // Original method for backward compatibility
    scheduleTask: (c, delayMs) => {
      const timestamp = Date.now() + delayMs;
      c.schedule.at(timestamp, "onScheduledTask");
      return timestamp;
    },
    // Getters for state
    getLastRun: (c) => {
      return c.state.lastRun;
    },
    getScheduledCount: (c) => {
      return c.state.scheduledCount;
    },
    getTaskHistory: (c) => {
      return c.state.taskHistory;
    },
    clearHistory: (c) => {
      c.state.taskHistory = [];
      c.state.scheduledCount = 0;
      c.state.lastRun = 0;
      return true;
    },
    // Scheduled task handlers
    onScheduledTask: (c) => {
      c.state.lastRun = Date.now();
      c.state.scheduledCount++;
      c.broadcast("scheduled", {
        time: c.state.lastRun,
        count: c.state.scheduledCount
      });
    },
    onScheduledTaskWithId: (c, taskId) => {
      c.state.lastRun = Date.now();
      c.state.scheduledCount++;
      c.state.taskHistory.push(taskId);
      c.broadcast("scheduledWithId", {
        taskId,
        time: c.state.lastRun,
        count: c.state.scheduledCount
      });
    }
  }
});

// fixtures/driver-test-suite/stateless.ts
var statelessActor = _chunk65RINRXEcjs.actor.call(void 0, {
  actions: {
    ping: () => "pong",
    echo: (c, message) => message,
    getActorId: (c) => c.actorId,
    // Try to access state - should throw StateNotEnabled
    tryGetState: (c) => {
      try {
        const state = c.state;
        return { success: true, state };
      } catch (error) {
        return { success: false, error: error.message };
      }
    },
    // Try to access db - should throw DatabaseNotEnabled
    tryGetDb: (c) => {
      try {
        const db3 = c.db;
        return { success: true, db: db3 };
      } catch (error) {
        return { success: false, error: error.message };
      }
    }
  }
});

// fixtures/driver-test-suite/vars.ts
var staticVarActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: { value: 0 },
  connState: { hello: "world" },
  vars: { counter: 42, name: "test-actor" },
  actions: {
    getVars: (c) => {
      return c.vars;
    },
    getName: (c) => {
      return c.vars.name;
    }
  }
});
var nestedVarActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: { value: 0 },
  connState: { hello: "world" },
  vars: {
    counter: 42,
    nested: {
      value: "original",
      array: [1, 2, 3],
      obj: { key: "value" }
    }
  },
  actions: {
    getVars: (c) => {
      return c.vars;
    },
    modifyNested: (c) => {
      c.vars.nested.value = "modified";
      c.vars.nested.array.push(4);
      c.vars.nested.obj.key = "new-value";
      return c.vars;
    }
  }
});
var dynamicVarActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: { value: 0 },
  connState: { hello: "world" },
  createVars: () => {
    return {
      random: Math.random(),
      computed: `Actor-${Math.floor(Math.random() * 1e3)}`
    };
  },
  actions: {
    getVars: (c) => {
      return c.vars;
    }
  }
});
var uniqueVarActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: { value: 0 },
  connState: { hello: "world" },
  createVars: () => {
    return {
      id: Math.floor(Math.random() * 1e6)
    };
  },
  actions: {
    getVars: (c) => {
      return c.vars;
    }
  }
});
var driverCtxActor = _chunk65RINRXEcjs.actor.call(void 0, {
  state: { value: 0 },
  connState: { hello: "world" },
  createVars: (c, driverCtx) => {
    return {
      hasDriverCtx: Boolean(driverCtx == null ? void 0 : driverCtx.isTest)
    };
  },
  actions: {
    getVars: (c) => {
      return c.vars;
    }
  }
});

// fixtures/driver-test-suite/registry.ts
var registry = _chunk65RINRXEcjs.setup.call(void 0, {
  use: {
    // From counter.ts
    counter,
    // From counter-conn.ts
    counterConn,
    // From lifecycle.ts
    counterWithLifecycle,
    // From scheduled.ts
    scheduled,
    // From sleep.ts
    sleep: _chunkF5B36GL7cjs.sleep,
    sleepWithLongRpc: _chunkF5B36GL7cjs.sleepWithLongRpc,
    sleepWithRawHttp: _chunkF5B36GL7cjs.sleepWithRawHttp,
    sleepWithRawWebSocket: _chunkF5B36GL7cjs.sleepWithRawWebSocket,
    sleepWithNoSleepOption: _chunkF5B36GL7cjs.sleepWithNoSleepOption,
    // From error-handling.ts
    errorHandlingActor,
    customTimeoutActor,
    // From inline-client.ts
    inlineClientActor,
    // From kv.ts
    kvActor,
    // From queue.ts
    queueActor,
    queueLimitedActor,
    // From action-inputs.ts
    inputActor,
    // From action-timeout.ts
    shortTimeoutActor,
    longTimeoutActor,
    defaultTimeoutActor,
    syncTimeoutActor,
    // From action-types.ts
    syncActionActor,
    asyncActionActor,
    promiseActor,
    // From conn-params.ts
    counterWithParams,
    // From conn-state.ts
    connStateActor,
    // From metadata.ts
    metadataActor,
    // From vars.ts
    staticVarActor,
    nestedVarActor,
    dynamicVarActor,
    uniqueVarActor,
    driverCtxActor,
    // From raw-http.ts
    rawHttpActor,
    rawHttpNoHandlerActor,
    rawHttpVoidReturnActor,
    rawHttpHonoActor,
    // From raw-http-request-properties.ts
    rawHttpRequestPropertiesActor,
    // From raw-websocket.ts
    rawWebSocketActor,
    rawWebSocketBinaryActor,
    // From reject-connection.ts
    rejectConnectionActor,
    // From request-access.ts
    requestAccessActor,
    // From actor-onstatechange.ts
    onStateChangeActor,
    // From destroy.ts
    destroyActor,
    destroyObserver,
    // From hibernation.ts
    hibernationActor: _chunkF5B36GL7cjs.hibernationActor,
    // From file-system-hibernation-cleanup.ts
    fileSystemHibernationCleanupActor,
    // From large-payloads.ts
    largePayloadActor,
    largePayloadConnActor,
    // From run.ts
    runWithTicks: _chunkF5B36GL7cjs.runWithTicks,
    runWithQueueConsumer: _chunkF5B36GL7cjs.runWithQueueConsumer,
    runWithEarlyExit: _chunkF5B36GL7cjs.runWithEarlyExit,
    runWithError: _chunkF5B36GL7cjs.runWithError,
    runWithoutHandler: _chunkF5B36GL7cjs.runWithoutHandler,
    // From workflow.ts
    workflowCounterActor: _chunkF5B36GL7cjs.workflowCounterActor,
    workflowQueueActor: _chunkF5B36GL7cjs.workflowQueueActor,
    workflowAccessActor: _chunkF5B36GL7cjs.workflowAccessActor,
    workflowSleepActor: _chunkF5B36GL7cjs.workflowSleepActor,
    workflowStopTeardownActor: _chunkF5B36GL7cjs.workflowStopTeardownActor,
    // From actor-db-raw.ts
    dbActorRaw,
    // From actor-db-drizzle.ts
    dbActorDrizzle,
    // From db-lifecycle.ts
    dbLifecycle,
    dbLifecycleFailing,
    dbLifecycleObserver,
    // From stateless.ts
    statelessActor,
    // From access-control.ts
    accessControlActor,
    accessControlNoQueuesActor
  }
});

// src/serve-test-suite/mod.ts
async function getPort() {
  const MIN_PORT = 1e4;
  const MAX_PORT = 65535;
  const getRandomPort = () => Math.floor(Math.random() * (MAX_PORT - MIN_PORT + 1)) + MIN_PORT;
  let port = getRandomPort();
  let maxAttempts = 10;
  while (maxAttempts > 0) {
    try {
      const server = await new Promise((resolve, reject) => {
        const server2 = _net.createServer.call(void 0, );
        server2.once("error", (err) => {
          if (err.code === "EADDRINUSE") {
            reject(new Error(`Port ${port} is in use`));
          } else {
            reject(err);
          }
        });
        server2.once("listening", () => {
          resolve(server2);
        });
        server2.listen(port);
      });
      await new Promise((resolve) => {
        server.close(() => resolve());
      });
      return port;
    } catch (e2) {
      maxAttempts--;
      if (maxAttempts <= 0) {
        break;
      }
      port = getRandomPort();
    }
  }
  throw new Error("Could not find an available port after multiple attempts");
}
async function serveTestSuite() {
  var _a;
  registry.config.test = { ...registry.config.test, enabled: true };
  registry.config.inspector = {
    enabled: true,
    token: () => "token"
  };
  const port = await getPort();
  registry.config.managerPort = port;
  registry.config.serverless = {
    ...registry.config.serverless,
    publicEndpoint: `http://127.0.0.1:${port}`
  };
  const driver = await _chunkLPXB254Rcjs.createFileSystemOrMemoryDriver.call(void 0, true, {
    path: `/tmp/rivetkit-test-suite-${crypto.randomUUID()}`
  });
  registry.config.driver = driver;
  let upgradeWebSocket;
  const parsedConfig = registry.parseConfig();
  const managerDriver = (_a = driver.manager) == null ? void 0 : _a.call(driver, parsedConfig);
  _invariant2.default.call(void 0, managerDriver, "missing manager driver");
  const { router } = _chunkQ5CW77ITcjs.buildManagerRouter.call(void 0, 
    parsedConfig,
    managerDriver,
    () => upgradeWebSocket
  );
  const nodeWebSocket = _nodews.createNodeWebSocket.call(void 0, { app: router });
  upgradeWebSocket = nodeWebSocket.upgradeWebSocket;
  managerDriver.setGetUpgradeWebSocket(() => upgradeWebSocket);
  const server = _nodeserver.serve.call(void 0, {
    fetch: router.fetch,
    hostname: "127.0.0.1",
    port
  });
  _invariant2.default.call(void 0, 
    nodeWebSocket.injectWebSocket !== void 0,
    "should have injectWebSocket"
  );
  nodeWebSocket.injectWebSocket(server);
  const endpoint = `http://127.0.0.1:${port}`;
  _chunkF5B36GL7cjs.logger.call(void 0, ).info({ msg: "test suite server listening", port });
  return {
    endpoint,
    namespace: "default",
    runnerName: "default",
    close: async () => {
      await new Promise(
        (resolve) => server.close(() => resolve(void 0))
      );
    }
  };
}
async function runCli() {
  const result = await serveTestSuite();
  process.stdout.write(
    `${JSON.stringify({
      endpoint: result.endpoint,
      namespace: result.namespace,
      runnerName: result.runnerName
    })}
`
  );
  const shutdown = async () => {
    await result.close();
    process.exit(0);
  };
  process.on("SIGINT", shutdown);
  process.on("SIGTERM", shutdown);
}
var mainPath = process.argv[1];
if (mainPath && mainPath === _url.fileURLToPath.call(void 0, import.meta.url)) {
  runCli().catch((err) => {
    _chunkF5B36GL7cjs.logger.call(void 0, ).error({ msg: "serve-test-suite failed", error: err });
    process.exit(1);
  });
}


exports.serveTestSuite = serveTestSuite;
//# sourceMappingURL=mod.cjs.map