@kiri-orm/core 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/README.md +48 -3
  2. package/dist/types/client/create-client.d.ts +32 -0
  3. package/dist/types/client/index.d.ts +4 -0
  4. package/dist/types/client/model-handle.d.ts +148 -0
  5. package/dist/types/client/module.d.ts +54 -0
  6. package/dist/types/client/orm-client.d.ts +107 -0
  7. package/dist/types/connection.d.ts +40 -0
  8. package/dist/types/crud/aggregate-filter.d.ts +36 -0
  9. package/dist/types/crud/aggregate-paths.d.ts +74 -0
  10. package/dist/types/crud/aggregate-spec.d.ts +36 -0
  11. package/dist/types/crud/aggregate.d.ts +59 -0
  12. package/dist/types/crud/create-many.d.ts +42 -0
  13. package/dist/types/crud/errors.d.ts +16 -0
  14. package/dist/types/crud/index.d.ts +12 -0
  15. package/dist/types/crud/insert-many.d.ts +63 -0
  16. package/dist/types/crud/map-filter.d.ts +18 -0
  17. package/dist/types/crud/order.d.ts +58 -0
  18. package/dist/types/crud/paginate.d.ts +55 -0
  19. package/dist/types/crud/prepare-write.d.ts +55 -0
  20. package/dist/types/crud/repository-factory.d.ts +27 -0
  21. package/dist/types/crud/repository.d.ts +297 -0
  22. package/dist/types/crud/resolve-where.d.ts +24 -0
  23. package/dist/types/crud/row-mapping.d.ts +45 -0
  24. package/dist/types/crud/select.d.ts +74 -0
  25. package/dist/types/crud/sequence.d.ts +56 -0
  26. package/dist/types/crud/transaction.d.ts +19 -0
  27. package/dist/types/diagnostics/index.d.ts +1 -0
  28. package/dist/types/diagnostics/n-plus-one.d.ts +108 -0
  29. package/dist/types/dialect/date-bucket.d.ts +46 -0
  30. package/dist/types/dialect/index.d.ts +1 -0
  31. package/dist/types/domain/compile.d.ts +30 -0
  32. package/dist/types/domain/errors.d.ts +20 -0
  33. package/dist/types/domain/index.d.ts +4 -0
  34. package/dist/types/domain/parse.d.ts +30 -0
  35. package/dist/types/dto/field-schema.d.ts +12 -0
  36. package/dist/types/dto/index.d.ts +3 -0
  37. package/dist/types/dto/jsdoc-generator.d.ts +29 -0
  38. package/dist/types/dto/schema-generator.d.ts +59 -0
  39. package/dist/types/fields/auto-id.d.ts +27 -0
  40. package/dist/types/fields/cast-value.d.ts +19 -0
  41. package/dist/types/fields/computed-access.d.ts +22 -0
  42. package/dist/types/fields/default-for.d.ts +11 -0
  43. package/dist/types/fields/default-registry.d.ts +9 -0
  44. package/dist/types/fields/define-computed-field.d.ts +57 -0
  45. package/dist/types/fields/define-field.d.ts +35 -0
  46. package/dist/types/fields/errors.d.ts +30 -0
  47. package/dist/types/fields/index.d.ts +7 -0
  48. package/dist/types/fields/registry.d.ts +55 -0
  49. package/dist/types/fields/types/boolean.d.ts +5 -0
  50. package/dist/types/fields/types/char.d.ts +12 -0
  51. package/dist/types/fields/types/date.d.ts +10 -0
  52. package/dist/types/fields/types/datetime.d.ts +11 -0
  53. package/dist/types/fields/types/enum.d.ts +11 -0
  54. package/dist/types/fields/types/float.d.ts +11 -0
  55. package/dist/types/fields/types/integer.d.ts +11 -0
  56. package/dist/types/fields/types/json.d.ts +9 -0
  57. package/dist/types/fields/types/text.d.ts +10 -0
  58. package/dist/types/fields/types/uuid.d.ts +14 -0
  59. package/dist/types/fields/validate-value.d.ts +14 -0
  60. package/dist/types/global/connect.d.ts +29 -0
  61. package/dist/types/global/create-model.d.ts +189 -0
  62. package/dist/types/global/create-report.d.ts +32 -0
  63. package/dist/types/global/dto.d.ts +31 -0
  64. package/dist/types/global/glob.d.ts +12 -0
  65. package/dist/types/global/identity-scope.d.ts +18 -0
  66. package/dist/types/global/index.d.ts +12 -0
  67. package/dist/types/global/load-models.d.ts +31 -0
  68. package/dist/types/global/migrate.d.ts +68 -0
  69. package/dist/types/global/n-plus-one.d.ts +42 -0
  70. package/dist/types/global/sequences.d.ts +19 -0
  71. package/dist/types/global/state.d.ts +38 -0
  72. package/dist/types/global/sync-models.d.ts +11 -0
  73. package/dist/types/global/transaction.d.ts +22 -0
  74. package/dist/types/index.d.ts +16 -0
  75. package/dist/types/meta/index.d.ts +5 -0
  76. package/dist/types/meta/query.d.ts +34 -0
  77. package/dist/types/meta/reserved-tables.d.ts +10 -0
  78. package/dist/types/meta/schema.d.ts +18 -0
  79. package/dist/types/meta/snapshot.d.ts +35 -0
  80. package/dist/types/meta/sync-meta.d.ts +42 -0
  81. package/dist/types/meta/upsert.d.ts +81 -0
  82. package/dist/types/migrations/apply.d.ts +18 -0
  83. package/dist/types/migrations/describe.d.ts +11 -0
  84. package/dist/types/migrations/diff.d.ts +141 -0
  85. package/dist/types/migrations/errors.d.ts +23 -0
  86. package/dist/types/migrations/foreign-keys-plan.d.ts +27 -0
  87. package/dist/types/migrations/generate.d.ts +51 -0
  88. package/dist/types/migrations/index.d.ts +7 -0
  89. package/dist/types/migrations/render.d.ts +45 -0
  90. package/dist/types/migrations/runner.d.ts +118 -0
  91. package/dist/types/models/define-model.d.ts +52 -0
  92. package/dist/types/models/errors.d.ts +23 -0
  93. package/dist/types/models/index.d.ts +4 -0
  94. package/dist/types/models/inheritance.d.ts +73 -0
  95. package/dist/types/models/naming.d.ts +44 -0
  96. package/dist/types/models/primary-key.d.ts +39 -0
  97. package/dist/types/models/registry.d.ts +112 -0
  98. package/dist/types/relations/attach-detach.d.ts +76 -0
  99. package/dist/types/relations/cascade-delete.d.ts +29 -0
  100. package/dist/types/relations/commands.d.ts +84 -0
  101. package/dist/types/relations/define-relation.d.ts +106 -0
  102. package/dist/types/relations/eager-load.d.ts +28 -0
  103. package/dist/types/relations/errors.d.ts +21 -0
  104. package/dist/types/relations/foreign-keys.d.ts +76 -0
  105. package/dist/types/relations/index.d.ts +7 -0
  106. package/dist/types/relations/keys.d.ts +14 -0
  107. package/dist/types/relations/pivot-schema.d.ts +24 -0
  108. package/dist/types/relations/with-spec.d.ts +33 -0
  109. package/dist/types/reports/define-report.d.ts +37 -0
  110. package/dist/types/reports/errors.d.ts +9 -0
  111. package/dist/types/reports/index.d.ts +3 -0
  112. package/dist/types/reports/report-handle.d.ts +58 -0
  113. package/dist/types/schema/build-column.d.ts +18 -0
  114. package/dist/types/schema/column-builder-registry.d.ts +30 -0
  115. package/dist/types/schema/default-column-builders.d.ts +9 -0
  116. package/dist/types/schema/errors.d.ts +9 -0
  117. package/dist/types/schema/foreign-keys.d.ts +33 -0
  118. package/dist/types/schema/index.d.ts +6 -0
  119. package/dist/types/schema/introspect-foreign-keys.d.ts +23 -0
  120. package/dist/types/schema/sync.d.ts +63 -0
  121. package/dist/types/uow/entity.d.ts +80 -0
  122. package/dist/types/uow/errors.d.ts +8 -0
  123. package/dist/types/uow/hooks.d.ts +35 -0
  124. package/dist/types/uow/index.d.ts +5 -0
  125. package/dist/types/uow/unit-of-work.d.ts +142 -0
  126. package/dist/types/uow/with-unit-of-work.d.ts +23 -0
  127. package/package.json +20 -3
  128. package/src/connection.js +1 -1
  129. package/src/crud/insert-many.js +1 -1
  130. package/src/crud/repository.js +9 -1
@@ -0,0 +1,14 @@
1
+ /**
2
+ * A UUID, stored as a native `uuid` column on Postgres and as
3
+ * `char(36)` on SQLite (Knex's `table.uuid()` already handles that
4
+ * per-dialect difference - see schema/default-column-builders.js).
5
+ *
6
+ * A field named "id" with this type is auto-generated on create() via
7
+ * `crypto.randomUUID()` unless you supply your own value or your own
8
+ * `default` - see fields/auto-id.js.
9
+ */
10
+ export declare const uuidType: {
11
+ name: string;
12
+ validate(field: any, value: any): string[];
13
+ cast(field: any, value: any): string;
14
+ };
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Validates a runtime value against a field descriptor. Pure function:
3
+ * no DB, no mutation, just field + value in, error list out.
4
+ *
5
+ * Handles required/null/undefined itself so individual field types
6
+ * don't each need to reimplement that logic - a type's `validate`
7
+ * is only ever called with a genuinely present value.
8
+ *
9
+ * @param {import('./define-field.js').FieldDescriptor} field
10
+ * @param {unknown} value
11
+ * @param {import('./registry.js').FieldTypeRegistry} [registry]
12
+ * @returns {string[]} empty array means valid
13
+ */
14
+ export declare function validateValue(field: import('./define-field.js').FieldDescriptor, value: unknown, registry?: import('./registry.js').FieldTypeRegistry): string[];
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Sets the default connection every `createModel()`-defined Model
3
+ * uses. Accepts either a connection config (`{ dialect, filename }` /
4
+ * `{ dialect, connectionString }`, same as `createConnection()`) or an
5
+ * already-built Knex instance directly, for cases where the app needs
6
+ * to configure Knex itself beyond what `createConnection()` exposes.
7
+ *
8
+ * Call this once at startup, before performing any queries through a
9
+ * Model (defining models with `createModel()` doesn't need a
10
+ * connection yet - only actually running a query does, so model
11
+ * definitions and `connect()` can happen in either order at
12
+ * module-load time).
13
+ *
14
+ * @param {import('../connection.js').ConnectionConfig|import('knex').Knex} configOrConnection
15
+ * @returns {import('knex').Knex}
16
+ */
17
+ export declare function connect(configOrConnection: import('../connection.js').ConnectionConfig | import('knex').Knex): import('knex').Knex;
18
+ /**
19
+ * Returns the default connection set by `connect()`. Throws a clear
20
+ * error if `connect()` hasn't been called yet, rather than failing
21
+ * deep inside a query with a confusing "cannot read property of null".
22
+ *
23
+ * @returns {import('knex').Knex}
24
+ */
25
+ export declare function getConnection(): import('knex').Knex;
26
+ /**
27
+ * Closes the default connection, if one is set.
28
+ */
29
+ export declare function disconnect(): Promise<void>;
@@ -0,0 +1,189 @@
1
+ import { HOOK_NAMES } from "../uow/hooks.js";
2
+ /**
3
+ * Extends a model that some other package defined - Odoo's `_inherit`
4
+ * on an existing model. Adds fields and relations to it (or overrides
5
+ * their options: `{ title: { required: true } }` keeps the field's type
6
+ * and everything else), and can register hooks for it. Same model,
7
+ * same table; the additions are ordinary columns.
8
+ *
9
+ * Call order doesn't matter. If the model isn't defined yet, the
10
+ * extension waits and is applied the moment `createModel(name)` runs -
11
+ * which is what lets independent packages extend each other's models
12
+ * without agreeing on an import order.
13
+ *
14
+ * An override can change a field's options but not its `type`, and
15
+ * can't turn a stored field into a computed one (or back): either would
16
+ * silently change a column.
17
+ *
18
+ * Returns the SAME Model object `createModel(name)` returns - there is
19
+ * only ever one per model name, shared by everyone who calls either
20
+ * function for it - so it is usable straight away, whether
21
+ * `createModel(name)` ran before this or hasn't run yet:
22
+ *
23
+ * export const OrderInvoice = extendModel("invoice", {
24
+ * fields: { orderId: { type: "integer", required: true, unique: true } },
25
+ * relations: { order: { type: "belongsTo", model: "order", foreignKey: "orderId" } },
26
+ * });
27
+ * await OrderInvoice.create({ id: 1, orderId: 7, amountCents: 4200 });
28
+ *
29
+ * The model doesn't need to exist yet for this to work (the extension
30
+ * itself waits, same as always, until `createModel(name)` defines it -
31
+ * see ModelRegistry) - but every one of `OrderInvoice`'s methods does a
32
+ * real database read or write, so calling one before the base model is
33
+ * defined and `syncModels()` has run fails the way it always would.
34
+ *
35
+ * `extension.hooks` on a MIXIN (a name defined with `defineMixin`, not
36
+ * `createModel`) needs the mixin already defined - see `defineMixin()`'s
37
+ * docstring for why hooks on a mixin work differently from its fields.
38
+ *
39
+ * @param {string} name - the model to extend
40
+ * @param {Object} extension
41
+ * @param {Record<string, object>} [extension.fields]
42
+ * @param {Record<string, object>} [extension.relations]
43
+ * @param {string[]} [extension.mixins]
44
+ * @param {Partial<Record<typeof HOOK_NAMES[number], Function|Function[]>>} [extension.hooks]
45
+ * @param {string} [extension.origin] - the contributing package's name, for error messages and `schema.origins`
46
+ * @returns {Model}
47
+ */
48
+ export declare function extendModel(name: string, extension?: {
49
+ fields?: Record<string, object>;
50
+ relations?: Record<string, object>;
51
+ mixins?: string[];
52
+ hooks?: Partial<Record<typeof HOOK_NAMES[number], Function | Function[]>>;
53
+ origin?: string;
54
+ }): Model;
55
+ /**
56
+ * Defines an abstract model: fields and relations (and, unlike a plain
57
+ * `createModel()` schema, hooks too) that other models pull in with
58
+ * `mixins: [name]`. It has no table and no query methods of its own.
59
+ *
60
+ * A model picks up a mixin's hooks - alongside its fields and relations -
61
+ * at the moment IT is created, following whatever the mixin has at that
62
+ * point; they run before the model's own hooks of the same name. That
63
+ * makes the ordering requirement the mirror image of everything else in
64
+ * this file: `defineMixin(name, { hooks })` (or `extendModel(name, {
65
+ * hooks })` once the mixin already exists) must happen BEFORE
66
+ * `createModel(other, { mixins: [name] })`, not after. This is narrower
67
+ * than how a mixin's FIELDS behave - extending a mixin's fields later
68
+ * reaches every model already using it, because fields are just data
69
+ * folded into a descriptor on demand. A hook is a live registration
70
+ * against a running `HookRegistry`; reaching backwards into models that
71
+ * already resolved would mean either firing the same handler twice for
72
+ * models processed once already, or building a way to tell "already
73
+ * applied" apart from "new since last time" - real complexity for a
74
+ * pattern (adding a hook to a mixin after code already depends on it)
75
+ * that's rare in practice. Declare a mixin's hooks up front.
76
+ *
77
+ * @param {string} name
78
+ * @param {Object} definition
79
+ * @param {Record<string, object>} definition.fields
80
+ * @param {Record<string, object>} [definition.relations]
81
+ * @param {string[]} [definition.mixins]
82
+ * @param {Partial<Record<typeof HOOK_NAMES[number], Function|Function[]>>} [definition.hooks]
83
+ * @param {string} [definition.origin]
84
+ */
85
+ export declare function defineMixin(name: string, definition: {
86
+ fields: Record<string, object>;
87
+ relations?: Record<string, object>;
88
+ mixins?: string[];
89
+ hooks?: Partial<Record<typeof HOOK_NAMES[number], Function | Function[]>>;
90
+ origin?: string;
91
+ }): void;
92
+ export type Model = {
93
+ name: string;
94
+ schema: import('../models/define-model.js').ModelDescriptor;
95
+ create: (data: Record<string, unknown>, options?: {
96
+ trx?: object;
97
+ }) => Promise<object>;
98
+ createMany: (dataList: Record<string, unknown>[], options?: {
99
+ trx?: object;
100
+ chunkSize?: number;
101
+ }) => Promise<object[]>;
102
+ find: (filter?: Record<string, unknown> | unknown[], options?: object) => Promise<object[]>;
103
+ findOne: (filter?: Record<string, unknown> | unknown[], options?: object) => Promise<object | null>;
104
+ updateMany: (filter: Record<string, unknown> | unknown[], data: Record<string, unknown>) => Promise<number>;
105
+ deleteMany: (filter: Record<string, unknown> | unknown[]) => Promise<number>;
106
+ loadMany: (documents: object[], spec: string | string[] | object, options?: object) => Promise<object[]>;
107
+ load: (document: object, relationName: string, options?: object) => Promise<unknown>;
108
+ paginate: (filter?: Record<string, unknown> | unknown[], options?: object) => Promise<import('../crud/paginate.js').Page>;
109
+ aggregate: (filter?: Record<string, unknown> | unknown[], options?: object) => Promise<Array<Record<string, unknown>>>;
110
+ count: (filter?: Record<string, unknown> | unknown[], options?: object) => Promise<number>;
111
+ sum: (field: string, filter?: Record<string, unknown> | unknown[], options?: object) => Promise<number | null>;
112
+ avg: (field: string, filter?: Record<string, unknown> | unknown[], options?: object) => Promise<number | null>;
113
+ min: (field: string, filter?: Record<string, unknown> | unknown[], options?: object) => Promise<unknown>;
114
+ max: (field: string, filter?: Record<string, unknown> | unknown[], options?: object) => Promise<unknown>;
115
+ attach: (source: object | number | string, relationName: string, targetIds: unknown) => Promise<number>;
116
+ attachMany: (relationName: string, links: Array<{
117
+ source: object | number | string;
118
+ targets: unknown;
119
+ }>, options?: {
120
+ trx?: object;
121
+ }) => Promise<number>;
122
+ detach: (source: object | number | string, relationName: string, targetIds: unknown) => Promise<number>;
123
+ };
124
+ /**
125
+ * @typedef {Object} Model
126
+ * @property {string} name
127
+ * @property {import('../models/define-model.js').ModelDescriptor} schema
128
+ * @property {(data: Record<string, unknown>, options?: { trx?: object }) => Promise<object>} create
129
+ * @property {(dataList: Record<string, unknown>[], options?: { trx?: object, chunkSize?: number }) => Promise<object[]>} createMany
130
+ * @property {(filter?: Record<string, unknown>|unknown[], options?: object) => Promise<object[]>} find
131
+ * @property {(filter?: Record<string, unknown>|unknown[], options?: object) => Promise<object|null>} findOne
132
+ * @property {(filter: Record<string, unknown>|unknown[], data: Record<string, unknown>) => Promise<number>} updateMany
133
+ * @property {(filter: Record<string, unknown>|unknown[]) => Promise<number>} deleteMany
134
+ * @property {(documents: object[], spec: string|string[]|object, options?: object) => Promise<object[]>} loadMany
135
+ * @property {(document: object, relationName: string, options?: object) => Promise<unknown>} load
136
+ * @property {(filter?: Record<string, unknown>|unknown[], options?: object) => Promise<import('../crud/paginate.js').Page>} paginate
137
+ * @property {(filter?: Record<string, unknown>|unknown[], options?: object) => Promise<Array<Record<string, unknown>>>} aggregate
138
+ * @property {(filter?: Record<string, unknown>|unknown[], options?: object) => Promise<number>} count
139
+ * @property {(field: string, filter?: Record<string, unknown>|unknown[], options?: object) => Promise<number|null>} sum
140
+ * @property {(field: string, filter?: Record<string, unknown>|unknown[], options?: object) => Promise<number|null>} avg
141
+ * @property {(field: string, filter?: Record<string, unknown>|unknown[], options?: object) => Promise<unknown>} min
142
+ * @property {(field: string, filter?: Record<string, unknown>|unknown[], options?: object) => Promise<unknown>} max
143
+ * @property {(source: object|number|string, relationName: string, targetIds: unknown) => Promise<number>} attach
144
+ * @property {(relationName: string, links: Array<{ source: object|number|string, targets: unknown }>, options?: { trx?: object }) => Promise<number>} attachMany
145
+ * @property {(source: object|number|string, relationName: string, targetIds: unknown) => Promise<number>} detach
146
+ */
147
+ /**
148
+ * Defines a model against the shared default registry/connection and
149
+ * returns a `Model` object you can export and import anywhere - no
150
+ * `client`, `UnitOfWork`, or registry needs to be threaded through by
151
+ * hand at the call site, the same way a Mongoose model works once
152
+ * `mongoose.connect()` has been called once at startup.
153
+ *
154
+ * Every document `create()`/`find()`/`findOne()` returns is
155
+ * self-contained: it carries its own `.save()`/`.delete()` that know
156
+ * how to persist themselves using this Model's shared connection and
157
+ * hooks, with no external "unit of work" object needed. There is
158
+ * deliberately no identity map here - two `find()` calls for the same
159
+ * row return two DIFFERENT object instances, same as Mongoose. Dirty
160
+ * tracking doesn't need one: each document independently remembers
161
+ * its own as-loaded values (see `uow/entity.js`), so this is a real
162
+ * simplification, not a missing feature. For the cases that do need
163
+ * one, wrap the work in `withIdentityMap(fn)`: inside it every
164
+ * find/create returns one instance per row, scoped to that call (see
165
+ * identity-scope.js). A `UnitOfWork`/`createClient()` also has one.
166
+ *
167
+ * Hooks are declared inline, Mongoose-style, rather than through a
168
+ * separately-constructed `HookRegistry` the caller has to remember to
169
+ * pass around: `{ hooks: { beforeCreate(data) {...} } }`. Each hook
170
+ * name maps to one function or an array of functions (run in order).
171
+ *
172
+ * @param {string} name
173
+ * @param {Object} schema
174
+ * @param {string} [schema.table]
175
+ * @param {Record<string, object>} schema.fields
176
+ * @param {Record<string, object>} [schema.relations]
177
+ * @param {string[]} [schema.mixins] - abstract models (see defineMixin) whose fields this model includes
178
+ * @param {string} [schema.origin]
179
+ * @param {Partial<Record<typeof HOOK_NAMES[number], Function|Function[]>>} [schema.hooks]
180
+ * @returns {Model}
181
+ */
182
+ export declare function createModel(name: string, schema: {
183
+ table?: string;
184
+ fields: Record<string, object>;
185
+ relations?: Record<string, object>;
186
+ mixins?: string[];
187
+ origin?: string;
188
+ hooks?: Partial<Record<typeof HOOK_NAMES[number], Function | Function[]>>;
189
+ }): Model;
@@ -0,0 +1,32 @@
1
+ import { ReportHandle } from "../reports/report-handle.js";
2
+ /**
3
+ * Defines a report on the global API and returns its handle: a read-only, transient model
4
+ * whose rows are summaries - group keys plus aggregates - computed in ONE SQL statement. It has no
5
+ * table, is never synced or migrated, and is not part of the model registry.
6
+ *
7
+ * ```js
8
+ * export const SalesByCustomer = createReport("salesByCustomer", {
9
+ * from: "order",
10
+ * where: [["status", "!=", "cancelled"]],
11
+ * fields: {
12
+ * customerId: true,
13
+ * customerName: "customer.name",
14
+ * orders: { agg: "count" },
15
+ * revenue: { agg: "sum", of: "total" },
16
+ * items: { agg: "sum", of: "items.qty" },
17
+ * },
18
+ * orderBy: "-revenue",
19
+ * });
20
+ *
21
+ * await SalesByCustomer.find([["revenue", ">", 1000]], { limit: 10 });
22
+ * await SalesByCustomer.count();
23
+ * ```
24
+ *
25
+ * See defineReport() for what a definition may contain. The models it reads need not exist yet
26
+ * (they are looked up on first use), so reports can live in their own files.
27
+ *
28
+ * @param {string} name
29
+ * @param {object} definition
30
+ * @returns {ReportHandle}
31
+ */
32
+ export declare function createReport(name: string, definition: object): ReportHandle;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * DTO schemas (create/update/read) for one model registered via
3
+ * `createModel()`, using the default registry - the Mongoose-style
4
+ * API's equivalent of calling `generateDTOSchemas(model)` directly
5
+ * with an explicit `ModelRegistry`.
6
+ *
7
+ * @param {string} modelName
8
+ * @returns {{ create: object, update: object, read: object }}
9
+ */
10
+ export declare function generateModelDTOs(modelName: string): {
11
+ create: object;
12
+ update: object;
13
+ read: object;
14
+ };
15
+ /**
16
+ * DTO schemas for every model registered via `createModel()`.
17
+ *
18
+ * @returns {Record<string, { create: object, update: object, read: object }>}
19
+ */
20
+ export declare function generateAllModelDTOs(): Record<string, {
21
+ create: object;
22
+ update: object;
23
+ read: object;
24
+ }>;
25
+ /**
26
+ * JSDoc `@typedef` blocks for every model registered via
27
+ * `createModel()`, concatenated into one file-ready string.
28
+ *
29
+ * @returns {string}
30
+ */
31
+ export declare function generateModelJSDoc(): string;
@@ -0,0 +1,12 @@
1
+ /** @param {string} glob an absolute, forward-slash pattern */
2
+ export declare function globToRegExp(glob: string): RegExp;
3
+ /**
4
+ * Expands glob patterns to the files they match: absolute paths, sorted, no duplicates.
5
+ * Relative patterns are resolved against `cwd`. A `!pattern` removes files matched by
6
+ * the patterns before it.
7
+ *
8
+ * @param {string[]} patterns
9
+ * @param {string} cwd
10
+ * @returns {Promise<string[]>}
11
+ */
12
+ export declare function expandGlobs(patterns: string[], cwd: string): Promise<string[]>;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Runs `fn` with a fresh identity map. Returns whatever `fn` returns;
3
+ * a throw propagates. Nesting starts a new, independent map for the
4
+ * inner call (like a nested `withUnitOfWork`), rather than joining the
5
+ * outer one.
6
+ *
7
+ * @template T
8
+ * @param {() => Promise<T>|T} fn
9
+ * @returns {Promise<T>|T}
10
+ */
11
+ export declare function withIdentityMap<T>(fn: () => Promise<T> | T): Promise<T> | T;
12
+ /**
13
+ * The map for the current async context, or undefined when not inside
14
+ * `withIdentityMap()`. Keys are `${modelName}:${id}`.
15
+ *
16
+ * @returns {Map<string, object>|undefined}
17
+ */
18
+ export declare function currentIdentityMap(): Map<string, object> | undefined;
@@ -0,0 +1,12 @@
1
+ export { connect, getConnection, disconnect } from "./connect.js";
2
+ export { createModel, extendModel, defineMixin } from "./create-model.js";
3
+ export { loadModels } from "./load-models.js";
4
+ export { syncModels } from "./sync-models.js";
5
+ export { syncSequences } from "./sequences.js";
6
+ export { createReport } from "./create-report.js";
7
+ export { detectNPlusOne, assertNoNPlusOne, watchNPlusOne } from "./n-plus-one.js";
8
+ export { transaction } from "./transaction.js";
9
+ export { withIdentityMap } from "./identity-scope.js";
10
+ export { diffModels, migrateModels, getDefaultModelRegistry } from "./migrate.js";
11
+ export { generateModelDTOs, generateAllModelDTOs, generateModelJSDoc } from "./dto.js";
12
+ export { __resetGlobalStateForTests } from "./state.js";
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Imports every file matching `patterns`, for the side effect of each file's
3
+ * `createModel()` / `extendModel()` / `defineMixin()` calls registering into the
4
+ * default registry. This replaces the hand-written list of imports an app
5
+ * otherwise keeps in its database setup file: a new model is a new file, and
6
+ * nothing central has to be edited to know about it.
7
+ *
8
+ * await loadModels("./src/**\/*.model.js");
9
+ * await loadModels(["./modules/*\/models/*.js", "!**\/*.test.js"]);
10
+ *
11
+ * Order doesn't matter - the registry already lets a model wait for a mixin, a
12
+ * relation target or a base model that's defined later - so files are simply
13
+ * imported in sorted order. Importing is idempotent: Node loads a file once, so
14
+ * calling this again (or importing a model file by hand as well) never defines a
15
+ * model twice.
16
+ *
17
+ * Relative patterns resolve against `cwd`, which defaults to the process's
18
+ * working directory; pass `{ cwd: import.meta.dirname }` to anchor them to the
19
+ * calling file instead. Patterns use forward slashes (see glob.js for the syntax).
20
+ *
21
+ * Throws if nothing matches (almost always a wrong path or pattern; pass
22
+ * `{ allowEmpty: true }` to accept that) and names the file if one fails to load.
23
+ *
24
+ * @param {string|string[]} patterns
25
+ * @param {{ cwd?: string, allowEmpty?: boolean }} [options]
26
+ * @returns {Promise<string[]>} the files that were loaded (absolute paths)
27
+ */
28
+ export declare function loadModels(patterns: string | string[], options?: {
29
+ cwd?: string;
30
+ allowEmpty?: boolean;
31
+ }): Promise<string[]>;
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Diffs the models currently registered via `createModel()` against
3
+ * what's recorded in `_meta_fields` (same as `diffSchema()` elsewhere
4
+ * in this ORM), using the default connection/registry - the piece
5
+ * that was missing entirely: there was no way to reach the global
6
+ * API's internal registry to run a migration against it at all,
7
+ * meaning removing a field from a schema had no path to actually
8
+ * dropping the column, ever, through this API.
9
+ *
10
+ * @param {Object} [options]
11
+ * @param {Record<string, string>} [options.modelRenames]
12
+ * @param {Record<string, Record<string, string>>} [options.fieldRenames]
13
+ * @returns {Promise<import('../migrations/diff.js').DiffPlan>}
14
+ */
15
+ export declare function diffModels(options?: {
16
+ modelRenames?: Record<string, string>;
17
+ fieldRenames?: Record<string, Record<string, string>>;
18
+ }): Promise<import('../migrations/diff.js').DiffPlan>;
19
+ /**
20
+ * Diffs, then generates and applies a migration for every change
21
+ * between the currently-registered models and what's actually in the
22
+ * database - the one-call path for "I removed/renamed/added a field,
23
+ * make the database match."
24
+ *
25
+ * Same safety rule as `generateMigration()` everywhere else in this
26
+ * ORM: destructive changes (a dropped model or field) are refused
27
+ * unless `{ allowDestructive: true }` is passed explicitly. Field
28
+ * type changes are always refused, with no override - resolve those
29
+ * by hand (see `generateMigration()`'s docs for why).
30
+ *
31
+ * After applying, this also re-syncs (Phase 3/4's `sync()`) so
32
+ * `_meta_fields` reflects the new reality - a later call to
33
+ * `migrateModels()`/`diffModels()` will correctly report no changes
34
+ * rather than re-diffing against stale metadata.
35
+ *
36
+ * Pass `{ dryRun: true }` to get the plan and its human-readable
37
+ * `describePlan()` summary back WITHOUT applying anything - useful to
38
+ * review what would happen first.
39
+ *
40
+ * @param {Object} [options]
41
+ * @param {boolean} [options.allowDestructive]
42
+ * @param {boolean} [options.dryRun]
43
+ * @param {Record<string, string>} [options.modelRenames]
44
+ * @param {Record<string, Record<string, string>>} [options.fieldRenames]
45
+ * @returns {Promise<{ plan: import('../migrations/diff.js').DiffPlan, summary: string[], applied: boolean }>}
46
+ */
47
+ export declare function migrateModels(options?: {
48
+ allowDestructive?: boolean;
49
+ dryRun?: boolean;
50
+ modelRenames?: Record<string, string>;
51
+ fieldRenames?: Record<string, Record<string, string>>;
52
+ }): Promise<{
53
+ plan: import('../migrations/diff.js').DiffPlan;
54
+ summary: string[];
55
+ applied: boolean;
56
+ }>;
57
+ /**
58
+ * Escape hatch for anyone who wants to call the lower-level, explicit
59
+ * migration functions (`generateMigration`, `applyMigration`,
60
+ * `rollbackMigration`, `describePlan` - all already available from
61
+ * `@kiri-orm/core` directly, not re-exported again here to avoid a
62
+ * duplicate-export collision) with more control than
63
+ * `migrateModels()` gives - e.g. to inspect and modify a migration
64
+ * before applying it, or to roll one back.
65
+ *
66
+ * @returns {import('../models/registry.js').ModelRegistry}
67
+ */
68
+ export declare function getDefaultModelRegistry(): import('../models/registry.js').ModelRegistry;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Runs `fn` while watching the global connection, and returns what repeated: `{ result, findings }`.
3
+ * Each finding is `{ shape, sql, statement, count }` for a statement that ran `threshold`
4
+ * (default 5) or more times. Never throws for findings - see assertNoNPlusOne() for that.
5
+ *
6
+ * ```js
7
+ * const { findings } = await detectNPlusOne(async () => {
8
+ * for (const post of await Post.find()) await Post.load(post, "author"); // one query per post
9
+ * });
10
+ * ```
11
+ *
12
+ * A heuristic for development and tests: a legitimate loop repeats a statement too. Options:
13
+ * `threshold`, `windowMs`, `statements` (default `["select"]`).
14
+ *
15
+ * @template T
16
+ * @param {() => Promise<T>} fn
17
+ * @param {object} [options]
18
+ * @returns {Promise<{ result: T, findings: import('../diagnostics/n-plus-one.js').Finding[] }>}
19
+ */
20
+ export declare function detectNPlusOne<T>(fn: () => Promise<T>, options?: object): Promise<{
21
+ result: T;
22
+ findings: import('../diagnostics/n-plus-one.js').Finding[];
23
+ }>;
24
+ /**
25
+ * Like detectNPlusOne(), but throws an NPlusOneError (with `.findings`) if anything repeated, and
26
+ * otherwise returns what `fn` returned. For tests that guard a code path against regressing into N+1.
27
+ *
28
+ * @template T
29
+ * @param {() => Promise<T>} fn
30
+ * @param {object} [options]
31
+ * @returns {Promise<T>}
32
+ */
33
+ export declare function assertNoNPlusOne<T>(fn: () => Promise<T>, options?: object): Promise<T>;
34
+ /**
35
+ * A live watcher for development: warns on the console, once per statement, as soon as one repeats
36
+ * `threshold` times within `windowMs` (default 250ms). Returns the monitor; call `.detach()` to stop.
37
+ * Pass `onDetect(finding)` to do something other than console.warn.
38
+ *
39
+ * @param {object} [options]
40
+ * @returns {import('../diagnostics/n-plus-one.js').QueryMonitor}
41
+ */
42
+ export declare function watchNPlusOne(options?: object): import('../diagnostics/n-plus-one.js').QueryMonitor;
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Moves every auto-increment model's Postgres sequence past the ids already in its
3
+ * table. Run it after anything that inserts ids outside this ORM - a raw insert, a seed
4
+ * script, a restored dump - so the next auto-assigned id doesn't collide.
5
+ *
6
+ * Idempotent and never moves a sequence backwards. On SQLite it does nothing (a
7
+ * rowid alias continues from the highest id by itself). Pass `{ trx }` to run it inside
8
+ * a transaction.
9
+ *
10
+ * @param {{ trx?: import('knex').Knex.Transaction }} [options]
11
+ * @returns {Promise<Array<{ model: string, table: string, synced: boolean }>>}
12
+ */
13
+ export declare function syncSequences(options?: {
14
+ trx?: import('knex').Knex.Transaction;
15
+ }): Promise<Array<{
16
+ model: string;
17
+ table: string;
18
+ synced: boolean;
19
+ }>>;
@@ -0,0 +1,38 @@
1
+ import { ModelRegistry } from "../models/registry.js";
2
+ import { HookRegistry } from "../uow/hooks.js";
3
+ /**
4
+ * The state backing the Mongoose-style global API (`connect()`,
5
+ * `createModel()`, `syncModels()`). Exactly one of each, module-level,
6
+ * shared by every file that imports from this package - the same
7
+ * mechanism that makes `import { User } from './models/user.js'`
8
+ * usable from anywhere without threading a `client`/`db`/`registry`
9
+ * through every call site: every `createModel()` call, in any file,
10
+ * registers into THIS registry and reads from THIS connection,
11
+ * because it's the same module instance across the whole app (Node's
12
+ * module cache gives every importer the same object).
13
+ *
14
+ * This is genuinely global, mutable state - the trade-off Mongoose
15
+ * itself makes (`mongoose.connect()` sets its one default connection
16
+ * the same way). It means exactly one connection/schema-set per Node
17
+ * process using this API. Apps that need more than one distinct
18
+ * connection or a fully isolated per-request scope should use
19
+ * `createClient()`/`UnitOfWork` instead (see the client module),
20
+ * which take an explicit `ModelRegistry`/connection rather than
21
+ * sharing one implicitly.
22
+ */
23
+ export declare const state: {
24
+ connection: null;
25
+ registry: ModelRegistry;
26
+ hooks: HookRegistry;
27
+ wrappers: Map<any, any>;
28
+ models: Map<any, any>;
29
+ mixinHooks: Map<any, any>;
30
+ reports: Map<any, any>;
31
+ };
32
+ /**
33
+ * Resets all global state. Not part of the normal API surface - for
34
+ * tests only, so multiple test files (or multiple describe blocks
35
+ * within one file) can each start from a clean slate rather than
36
+ * colliding on model names registered by an earlier test.
37
+ */
38
+ export declare function __resetGlobalStateForTests(): void;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Syncs every model defined via `createModel()` against the default
3
+ * connection - tables, meta-tables, and belongsToMany pivot tables
4
+ * (Phases 3/4/7's `sync()`, run against the default registry).
5
+ *
6
+ * Always an explicit call, never implicit - same principle as `sync()`
7
+ * everywhere else in this ORM: schema changes are something the
8
+ * caller chooses to run, not something that happens as a side effect
9
+ * of defining a model or making a query.
10
+ */
11
+ export declare function syncModels(): Promise<import("../schema/sync.js").SyncResult>;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Runs `fn` inside a transaction on the default connection, passing
3
+ * the transaction object through so it can be handed to any Model
4
+ * method's `{ trx }` option (`Order.create(data, { trx })`) to
5
+ * include it in the same atomic unit. Every `Model` method - `create`,
6
+ * `find`, `findOne`, `updateMany`, `deleteMany`, `attach`, `detach`,
7
+ * and a document's own `save()`/`delete()` - accepts `{ trx }` for
8
+ * exactly this reason.
9
+ *
10
+ * Without this, a multi-step write across Models (e.g. creating an
11
+ * order plus each of its line items) has no way to be atomic: each
12
+ * `Model.create()` call would hit the default connection directly,
13
+ * with no way to roll every step back together if a later one fails.
14
+ *
15
+ * If `fn` throws (or returns a rejected promise), Knex rolls the
16
+ * transaction back automatically and the rejection propagates here.
17
+ *
18
+ * @template T
19
+ * @param {(trx: import('knex').Knex.Transaction) => Promise<T>} fn
20
+ * @returns {Promise<T>}
21
+ */
22
+ export declare function transaction<T>(fn: (trx: import('knex').Knex.Transaction) => Promise<T>): Promise<T>;
@@ -0,0 +1,16 @@
1
+ export { createConnection, closeConnection, DIALECTS } from "./connection.js";
2
+ export * from "./fields/index.js";
3
+ export * from "./models/index.js";
4
+ export * from "./schema/index.js";
5
+ export * from "./meta/index.js";
6
+ export * from "./crud/index.js";
7
+ export * from "./migrations/index.js";
8
+ export * from "./relations/index.js";
9
+ export * from "./domain/index.js";
10
+ export * from "./dialect/index.js";
11
+ export * from "./reports/index.js";
12
+ export * from "./diagnostics/index.js";
13
+ export * from "./uow/index.js";
14
+ export * from "./client/index.js";
15
+ export * from "./global/index.js";
16
+ export * from "./dto/index.js";
@@ -0,0 +1,5 @@
1
+ export { ensureMetaTables } from "./schema.js";
2
+ export { syncMeta } from "./sync-meta.js";
3
+ export { getModelMeta, getFieldsMeta, listModelsMeta } from "./query.js";
4
+ export { META_TABLE_PREFIX, META_MODELS_TABLE, META_FIELDS_TABLE } from "./reserved-tables.js";
5
+ export { snapshotModelMeta, restoreModelMeta } from "./snapshot.js";