@duraxis/core 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -53,3 +53,5 @@ export type { PhysicalAccess, PhysicalPlan, ExplainResult } from "./query/planne
53
53
  export { ResourceScope, ResourceExhaustedError, OperationCancelledError, DEFAULT_RESOURCE_LIMITS, resourceLimits, estimateBytes, materialize, } from "./resources/resource-manager.js";
54
54
  export type { ResourceLimits, ResourceAmounts, ResourceReservation, Resource, } from "./resources/resource-manager.js";
55
55
  export type { CursorKeyring } from "./query/model/cursor.js";
56
+ export { defineDuraxisConfig, isDuraxisConfiguration, selectDuraxisConnection, normalizeDuraxisConnection, duraxisDriverContext, validateConnectionName, createDatabase, } from "./config.js";
57
+ export type { DuraxisConfiguration, DuraxisConnectionOptions, DuraxisConnectionsOptions, DuraxisDriverContext, EntityDiscoveryOptions, ConfigEntity, } from "./config.js";
package/dist/index.js CHANGED
@@ -1,5 +1,8 @@
1
1
  import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
2
2
  import { assertStorageKey } from "@duraxis/storage";
3
+ import { existsSync } from "node:fs";
4
+ import { dirname, isAbsolute, resolve } from "node:path";
5
+ import { fileURLToPath } from "node:url";
3
6
  // src/resources/resource-manager.ts
4
7
  var DEFAULT_RESOURCE_LIMITS = Object.freeze({
5
8
  maxQueuedOperations: 64,
@@ -1656,14 +1659,14 @@ function hasValue(value) {
1656
1659
  }
1657
1660
  function secondaryIndexBounds(index, options) {
1658
1661
  const hasEquality = options.eq !== void 0;
1659
- const legacy = [
1662
+ const tupleBounds = [
1660
1663
  options.gt,
1661
1664
  options.gte,
1662
1665
  options.lt,
1663
1666
  options.lte
1664
1667
  ].filter((value) => value !== void 0);
1665
- if (hasEquality && (options.prefix || options.range || legacy.length)) throw new Error("Equality cannot be combined with index ranges");
1666
- if (options.range && legacy.length) throw new Error("Use either range or tuple range shorthands");
1668
+ if (hasEquality && (options.prefix || options.range || tupleBounds.length)) throw new Error("Equality cannot be combined with index ranges");
1669
+ if (options.range && tupleBounds.length) throw new Error("Use either range or tuple range shorthands");
1667
1670
  const orders = indexFields(index).map((part) => part.order);
1668
1671
  const encode = (values) => {
1669
1672
  if (values.length == 0 || values.length > orders.length) throw new Error("Invalid compound key arity");
@@ -1679,13 +1682,13 @@ function secondaryIndexBounds(index, options) {
1679
1682
  }
1680
1683
  let prefix = options.prefix ?? [];
1681
1684
  let range = options.range;
1682
- if (legacy.length) {
1685
+ if (tupleBounds.length) {
1683
1686
  if (options.prefix) throw new Error("Tuple range shorthands already contain their prefix");
1684
- const arity = legacy[0].length;
1685
- if (arity == 0 || legacy.some((value) => value.length != arity)) throw new Error("Index range arity mismatch");
1686
- prefix = legacy[0].slice(0, -1);
1687
+ const arity = tupleBounds[0].length;
1688
+ if (arity == 0 || tupleBounds.some((value) => value.length != arity)) throw new Error("Index range arity mismatch");
1689
+ prefix = tupleBounds[0].slice(0, -1);
1687
1690
  const encodedPrefix = prefix.length ? encode(prefix) : /* @__PURE__ */ new Uint8Array();
1688
- for (const value of legacy.slice(1)) {
1691
+ for (const value of tupleBounds.slice(1)) {
1689
1692
  const other = value.slice(0, -1);
1690
1693
  if (compareBytes(encodedPrefix, other.length ? encode(other) : /* @__PURE__ */ new Uint8Array()) != 0) throw new Error("Compound range bounds must share an equality prefix");
1691
1694
  }
@@ -2596,7 +2599,7 @@ function hmac(key, value) {
2596
2599
  function queryHash(key, query) {
2597
2600
  return hmac(key, canonical(shape(query)));
2598
2601
  }
2599
- function encodeLegacyCursor(generation, schema, query, row, signingKey) {
2602
+ function cursorEnvelope(generation, schema, query, row, signingKey) {
2600
2603
  if (query.collection != schema.name) throw new Error("Cursor collection mismatch");
2601
2604
  const values = (query.orderBy ?? []).map(({ field }) => {
2602
2605
  if (field == "$id") return row.id;
@@ -2606,46 +2609,13 @@ function encodeLegacyCursor(generation, schema, query, row, signingKey) {
2606
2609
  if (value === null || typeof value == "string" || typeof value == "number" || typeof value == "boolean") return value;
2607
2610
  throw new Error(`Cannot encode cursor value for ${field}`);
2608
2611
  });
2609
- const envelope = {
2610
- version: 2,
2612
+ return {
2613
+ version: 3,
2611
2614
  generation,
2612
2615
  queryHash: queryHash(signingKey, query),
2613
2616
  values,
2614
2617
  id: row.id
2615
2618
  };
2616
- const payload = canonical(envelope);
2617
- return Buffer.from(JSON.stringify({
2618
- payload: envelope,
2619
- signature: hmac(signingKey, payload)
2620
- })).toString("base64url");
2621
- }
2622
- function decodeLegacyCursor(cursor, generation, schema, query, signingKey) {
2623
- let parsed;
2624
- try {
2625
- parsed = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
2626
- } catch {
2627
- throw new Error("Invalid query cursor");
2628
- }
2629
- if (!parsed || typeof parsed != "object" || Array.isArray(parsed)) throw new Error("Invalid query cursor");
2630
- const record = parsed;
2631
- const envelope = record.payload;
2632
- if (!envelope || envelope.version != 2 || typeof record.signature != "string") throw new Error("Invalid query cursor payload");
2633
- const expectedSignature = hmac(signingKey, canonical(envelope));
2634
- const actual = Buffer.from(record.signature, "hex");
2635
- const expected = Buffer.from(expectedSignature, "hex");
2636
- if (actual.length != expected.length || !timingSafeEqual(actual, expected)) throw new Error("Invalid query cursor signature");
2637
- if (envelope.generation != generation) throw new Error("Query cursor snapshot generation is unavailable");
2638
- if (envelope.queryHash != queryHash(signingKey, query) || query.collection != schema.name) throw new Error("Query cursor is incompatible with this query");
2639
- const orderBy = query.orderBy ?? [];
2640
- if (!Array.isArray(envelope.values) || envelope.values.length != orderBy.length || typeof envelope.id != "string") throw new Error("Invalid query cursor payload");
2641
- return {
2642
- id: envelope.id,
2643
- values: envelope.values.map((item, index) => {
2644
- if (item && typeof item == "object" && "missing" in item) return void 0;
2645
- if (fieldDefinition(schema, orderBy[index].field)?.type == "date" && typeof item == "string") return new Date(item);
2646
- return item;
2647
- })
2648
- };
2649
2619
  }
2650
2620
  function cursorKeys(value) {
2651
2621
  if (value instanceof Uint8Array) {
@@ -2665,7 +2635,7 @@ function cursorKeys(value) {
2665
2635
  function encodeQueryCursor(generation, schema, query, row, keys, namespace = "") {
2666
2636
  const ring = cursorKeys(keys);
2667
2637
  const key = ring.keys[ring.activeKeyId];
2668
- const legacy = JSON.parse(Buffer.from(encodeLegacyCursor(generation, schema, query, row, key), "base64url").toString());
2638
+ const envelope = cursorEnvelope(generation, schema, query, row, key);
2669
2639
  const nonce = randomBytes(12);
2670
2640
  const cipher = createCipheriv("aes-256-gcm", key, nonce);
2671
2641
  cipher.setAAD(Buffer.from(canonical({
@@ -2674,7 +2644,7 @@ function encodeQueryCursor(generation, schema, query, row, keys, namespace = "")
2674
2644
  namespace
2675
2645
  })));
2676
2646
  const payload = JSON.stringify({
2677
- ...legacy.payload,
2647
+ ...envelope,
2678
2648
  version: 3,
2679
2649
  namespace,
2680
2650
  expiresAt: Date.now() + (ring.ttlMs ?? 9e5)
@@ -2700,10 +2670,7 @@ function decodeQueryCursor(cursor, generation, schema, query, keys, namespace =
2700
2670
  throw new Error("Invalid query cursor");
2701
2671
  }
2702
2672
  if (!outer || typeof outer != "object" || Array.isArray(outer)) throw new Error("Invalid query cursor");
2703
- if (outer.version !== 3) {
2704
- if (!namespace && ring.allowLegacySigned && ring.legacySigningKey) return decodeLegacyCursor(cursor, generation, schema, query, ring.legacySigningKey);
2705
- throw new Error("Legacy signed cursors are disabled; restart pagination");
2706
- }
2673
+ if (outer.version !== 3) throw new Error("Unsupported cursor format; restart pagination");
2707
2674
  if (Object.keys(outer).sort().join(",") != "ciphertext,keyId,nonce,tag,version" || typeof outer.keyId != "string" || !Object.hasOwn(ring.keys, outer.keyId)) throw new Error("Invalid query cursor");
2708
2675
  const binary = (value) => {
2709
2676
  if (typeof value != "string" || !/^[A-Za-z0-9_-]+$/.test(value)) throw new Error("Invalid query cursor");
@@ -5218,6 +5185,160 @@ var ReferenceQueryExecutor = class {
5218
5185
  return this.executor.page(context, query, new CollectionScan(query.collection));
5219
5186
  }
5220
5187
  };
5221
- export { AccessPathEnumerator, BPlusTree, BPlusTreeNodeCache, BPlusTreeNodeStore, BPlusTreeValidator, CollectionScan, CommitOutcomeUnknownError, DEFAULT_RESOURCE_LIMITS, Difference, DuraxisDatabase, Filter, ForeignKeyManager, ForeignKeyViolationError, GarbageCollector, Intersection, InvalidForeignKeyDefinitionError, Limit, ManifestReachabilityScanner, ManifestSnapshotReader, OperationCancelledError, PlanCompiler, PredicateAnalyzer, PrimaryIndex, PrimaryLookup, Projection, QueryContext, QueryExecutor, QueryMemoryLimitError, RecoveryManager, ReferenceQueryExecutor, ReferencedRecordNotFoundError, ReferencedRecordRestrictedError, ResourceExhaustedError, ResourceScope, RuleBasedPlanner, SecondaryIndexManager, SecondaryIndexRangeScan, SecondaryIndexScan, Sort, Transaction, TransactionConflictError, TransactionStateError, Union, UniqueIndexLookup, UniqueIndexViolationError, compareBytes, compareIndexScalars, compareRows, compositePrefixBounds, decodeDocument, decodeQueryCursor, encodeCompositeKey, encodeDocument, encodeIdentifier, encodeQueryCursor, encodeScalar, encodeSecondaryKey, estimateBytes, evaluatePredicate, explainPhysicalPlan, fieldDefinition, indexFields, indexId, indexRangeBounds, indexedValue, materialize, normalizeCollection, parseRecordKey, prefixBounds, prefixSuccessor, recordKey, resourceLimits, secondaryIndexBounds, validateCollection, validateDocument, validateQuery };
5188
+ // src/config.ts
5189
+ var CONFIGURATION = Symbol.for("@duraxis/core/configuration");
5190
+ function isDuraxisConfiguration(value) {
5191
+ return typeof value === "object" && value !== null && Reflect.get(value, CONFIGURATION) === true;
5192
+ }
5193
+ function validateConnections(config) {
5194
+ if (!config.connections || typeof config.connections !== "object" || Array.isArray(config.connections)) throw new TypeError("Invalid Duraxis connections map");
5195
+ const prefixes = /* @__PURE__ */ new Set();
5196
+ for (const name of Object.keys(config.connections)) {
5197
+ validateConnectionName(name);
5198
+ const prefix = name.toUpperCase().replace(/-/g, "_");
5199
+ if (prefixes.has(prefix)) throw new Error("Connection names collide after environment variable normalization");
5200
+ prefixes.add(prefix);
5201
+ if (!config.connections[name] || typeof config.connections[name] !== "object") throw new TypeError(`Invalid Duraxis connection: ${name}`);
5202
+ const connection = config.connections[name];
5203
+ if (Object.keys(config.connections).length > 1 && connection.autoLoadEntities && (connection.autoLoadEntities === true || !connection.autoLoadEntities.directories?.length) && connection.entities === void 0) throw new Error(`Connection ${name} requires explicit discovery directories or entities in a multi-connection configuration`);
5204
+ }
5205
+ }
5206
+ function defineDuraxisConfig(config) {
5207
+ if (!config || typeof config !== "object") throw new TypeError("Invalid Duraxis configuration");
5208
+ if ("connections" in config) {
5209
+ validateConnections(config);
5210
+ const names = Object.keys(config.connections);
5211
+ if (!names.length) throw new Error("At least one Duraxis connection is required");
5212
+ for (const name of names) validateConnectionName(name);
5213
+ selectDuraxisConnection(config);
5214
+ } else if (!config || !config.driver) throw new Error("A Duraxis storage driver is required");
5215
+ Object.defineProperty(config, CONFIGURATION, { value: true });
5216
+ return config;
5217
+ }
5218
+ function validateConnectionName(name) {
5219
+ if (!/^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/.test(name) || [
5220
+ "constructor",
5221
+ "prototype",
5222
+ "__proto__"
5223
+ ].includes(name)) throw new Error("Invalid Duraxis connection name");
5224
+ return name;
5225
+ }
5226
+ function selectDuraxisConnection(config, name) {
5227
+ if (!("connections" in config)) {
5228
+ if (name && name !== (config.name ?? "default")) throw new Error(`Unknown Duraxis connection: ${name}`);
5229
+ return config;
5230
+ }
5231
+ validateConnections(config);
5232
+ const selected = name ?? config.defaultConnection ?? Object.keys(config.connections).sort()[0];
5233
+ validateConnectionName(selected);
5234
+ if (!Object.hasOwn(config.connections, selected)) throw new Error(`Unknown Duraxis connection: ${selected}`);
5235
+ return {
5236
+ ...config.connections[selected],
5237
+ name: selected
5238
+ };
5239
+ }
5240
+ function duraxisDriverContext(options) {
5241
+ const directory = options.location ? dirname(options.location instanceof URL || options.location.startsWith("file:") ? fileURLToPath(options.location) : resolve(options.location)) : resolve(options.baseDirectory ?? ".");
5242
+ let root = directory;
5243
+ if (options.baseDirectory) root = resolve(directory, options.baseDirectory);
5244
+ else while (!existsSync(resolve(root, "package.json")) && dirname(root) !== root) root = dirname(root);
5245
+ if (dirname(root) === root && !existsSync(resolve(root, "package.json"))) root = directory;
5246
+ const name = validateConnectionName(options.name ?? "default");
5247
+ const prefix = name === "default" ? "DURAXIS" : `DURAXIS_${name.toUpperCase().replace(/-/g, "_")}`;
5248
+ const env = Object.fromEntries([
5249
+ "NAMESPACE",
5250
+ "STORAGE_DIRECTORY",
5251
+ "S3_BUCKET",
5252
+ "S3_PREFIX",
5253
+ "S3_ENDPOINT"
5254
+ ].map((key) => [key, process.env[`${prefix}_${key}`]]));
5255
+ return {
5256
+ root,
5257
+ directory,
5258
+ env,
5259
+ resolvePath: (path) => isAbsolute(path) ? path : resolve(root, path)
5260
+ };
5261
+ }
5262
+ function normalizeDuraxisConnection(options) {
5263
+ if (!options || typeof options.driver !== "function" && (typeof options.driver !== "object" || !options.driver)) throw new TypeError("Invalid Duraxis driver");
5264
+ if (options.migrations !== void 0 && typeof options.migrations !== "boolean" && (typeof options.migrations !== "object" || options.migrations === null || Array.isArray(options.migrations))) throw new TypeError("Invalid Duraxis migrations configuration");
5265
+ if (typeof options.migrations === "object") {
5266
+ for (const key of ["directory", "snapshots"]) if (options.migrations[key] !== void 0 && (typeof options.migrations[key] !== "string" || !options.migrations[key].trim())) throw new TypeError(`Invalid migration ${key}`);
5267
+ if (options.migrations.format !== void 0 && ![
5268
+ "ts",
5269
+ "js",
5270
+ "mts",
5271
+ "mjs"
5272
+ ].includes(options.migrations.format)) throw new TypeError("Invalid migration format");
5273
+ }
5274
+ if (options.schema && ![
5275
+ "create",
5276
+ "validate",
5277
+ "validate-managed"
5278
+ ].includes(options.schema.mode)) throw new TypeError("Invalid schema mode");
5279
+ if (options.autoLoadEntities !== void 0 && typeof options.autoLoadEntities !== "boolean" && (typeof options.autoLoadEntities !== "object" || !options.autoLoadEntities || Array.isArray(options.autoLoadEntities))) throw new TypeError("Invalid entity discovery options");
5280
+ if (typeof options.autoLoadEntities === "object" && options.autoLoadEntities.directories !== void 0 && (!Array.isArray(options.autoLoadEntities.directories) || !options.autoLoadEntities.directories.length || options.autoLoadEntities.directories.some((path) => typeof path !== "string" || !path.trim()))) throw new TypeError("Entity directories must be a nonempty array of paths");
5281
+ const context = duraxisDriverContext(options);
5282
+ if (options.migrations && options.schema?.mode === "create") throw new Error("Migrations require schema validation; automatic creation is disabled");
5283
+ const migrationOptions = typeof options.migrations === "object" ? options.migrations : {};
5284
+ const base = options.name && options.name !== "default" ? `duraxis/${validateConnectionName(options.name)}` : "duraxis";
5285
+ const database = {
5286
+ ...options.name && options.name !== "default" ? { namespace: options.name } : {},
5287
+ ...options.database,
5288
+ ...context.env.NAMESPACE !== void 0 ? { namespace: context.env.NAMESPACE } : {}
5289
+ };
5290
+ if (options.cursorKeyEnv) {
5291
+ const key = process.env[options.cursorKeyEnv];
5292
+ if (!key || !/^[a-fA-F0-9]{64}$/.test(key)) throw new Error(`Provision ${options.cursorKeyEnv} as 32 secret bytes encoded as hex`);
5293
+ database.cursorEncryption = {
5294
+ activeKeyId: "configured",
5295
+ keys: { configured: Buffer.from(key, "hex") }
5296
+ };
5297
+ }
5298
+ return {
5299
+ ...options,
5300
+ context,
5301
+ database,
5302
+ schema: options.schema ?? { mode: options.migrations ? "validate-managed" : "validate" },
5303
+ migrations: options.migrations ? {
5304
+ directory: context.resolvePath(migrationOptions.directory ?? `${base}/migrations`),
5305
+ snapshots: context.resolvePath(migrationOptions.snapshots ?? `${base}/snapshots`),
5306
+ format: migrationOptions.format ?? (options.location?.toString().match(/\.[cm]?js$/) ? "mjs" : "mts")
5307
+ } : void 0
5308
+ };
5309
+ }
5310
+ var ConfiguredDatabase = class extends DuraxisDatabase {
5311
+ owned;
5312
+ constructor(options, owned) {
5313
+ super(options);
5314
+ this.owned = owned;
5315
+ }
5316
+ close(options = {}) {
5317
+ return super.close({
5318
+ closeStorage: this.owned,
5319
+ ...options
5320
+ });
5321
+ }
5322
+ };
5323
+ async function createDatabase(config, name) {
5324
+ const options = normalizeDuraxisConnection(selectDuraxisConnection(config, name));
5325
+ const owned = options.closeStorage ?? typeof options.driver === "function";
5326
+ const driver = typeof options.driver === "function" ? await options.driver(options.context) : options.driver;
5327
+ try {
5328
+ if (!driver || driver.capabilities?.boundedReads !== true) throw new Error("Duraxis storage requires verified bounded-read support");
5329
+ return new ConfiguredDatabase({
5330
+ ...options.database,
5331
+ storage: driver
5332
+ }, owned);
5333
+ } catch (cause) {
5334
+ if (owned && driver?.close) try {
5335
+ await driver.close();
5336
+ } catch (cleanup) {
5337
+ throw new AggregateError([cause, cleanup], "Database initialization and cleanup failed");
5338
+ }
5339
+ throw cause;
5340
+ }
5341
+ }
5342
+ export { AccessPathEnumerator, BPlusTree, BPlusTreeNodeCache, BPlusTreeNodeStore, BPlusTreeValidator, CollectionScan, CommitOutcomeUnknownError, DEFAULT_RESOURCE_LIMITS, Difference, DuraxisDatabase, Filter, ForeignKeyManager, ForeignKeyViolationError, GarbageCollector, Intersection, InvalidForeignKeyDefinitionError, Limit, ManifestReachabilityScanner, ManifestSnapshotReader, OperationCancelledError, PlanCompiler, PredicateAnalyzer, PrimaryIndex, PrimaryLookup, Projection, QueryContext, QueryExecutor, QueryMemoryLimitError, RecoveryManager, ReferenceQueryExecutor, ReferencedRecordNotFoundError, ReferencedRecordRestrictedError, ResourceExhaustedError, ResourceScope, RuleBasedPlanner, SecondaryIndexManager, SecondaryIndexRangeScan, SecondaryIndexScan, Sort, Transaction, TransactionConflictError, TransactionStateError, Union, UniqueIndexLookup, UniqueIndexViolationError, compareBytes, compareIndexScalars, compareRows, compositePrefixBounds, createDatabase, decodeDocument, decodeQueryCursor, defineDuraxisConfig, duraxisDriverContext, encodeCompositeKey, encodeDocument, encodeIdentifier, encodeQueryCursor, encodeScalar, encodeSecondaryKey, estimateBytes, evaluatePredicate, explainPhysicalPlan, fieldDefinition, indexFields, indexId, indexRangeBounds, indexedValue, isDuraxisConfiguration, materialize, normalizeCollection, normalizeDuraxisConnection, parseRecordKey, prefixBounds, prefixSuccessor, recordKey, resourceLimits, secondaryIndexBounds, selectDuraxisConnection, validateCollection, validateConnectionName, validateDocument, validateQuery };
5222
5343
 
5223
5344
  //# sourceMappingURL=index.js.map