@cyphra/migrator 0.1.0 → 0.2.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.
- package/LICENSE +21 -0
- package/README.md +2 -0
- package/dist/index.d.ts +161 -2
- package/dist/index.js +635 -5
- package/dist/index.js.map +1 -1
- package/package.json +31 -10
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Cyphra contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
package/dist/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Session } from 'neo4j-driver';
|
|
2
2
|
import { CyphraClient } from '@cyphra/runtime';
|
|
3
|
-
import { SchemaDocument } from '@cyphra/schema';
|
|
3
|
+
import { SchemaDocument, SchemaModel } from '@cyphra/schema';
|
|
4
4
|
import { CompiledCypher } from '@cyphra/query';
|
|
5
5
|
|
|
6
6
|
/**
|
|
@@ -41,6 +41,13 @@ type MigrationDb = {
|
|
|
41
41
|
batchSize: number;
|
|
42
42
|
params?: Record<string, unknown>;
|
|
43
43
|
}): Promise<void>;
|
|
44
|
+
/**
|
|
45
|
+
* Execute a Cypher statement given as **trusted text** (used by generated migrations for DDL, which
|
|
46
|
+
* cannot be parameterized). Pass values through `params`, never by string concatenation.
|
|
47
|
+
*
|
|
48
|
+
* @returns Rows as plain JS objects (integers → number, temporals → Date).
|
|
49
|
+
*/
|
|
50
|
+
execute(text: string, params?: Record<string, unknown>): Promise<Record<string, unknown>[]>;
|
|
44
51
|
/** Structural / data helpers (validated identifiers only). */
|
|
45
52
|
readonly migrate: MigrationMigrateHelpers;
|
|
46
53
|
};
|
|
@@ -153,6 +160,147 @@ declare function applyConstraintStatements(client: CyphraClient, statements: rea
|
|
|
153
160
|
*/
|
|
154
161
|
declare function schemaIntegrationHints(doc: SchemaDocument): string[];
|
|
155
162
|
|
|
163
|
+
/**
|
|
164
|
+
* Schema diffing: compare two {@link SchemaModel}s (the snapshot taken at the last migration and the
|
|
165
|
+
* current schema) and plan the migration that takes a database from one to the other.
|
|
166
|
+
*
|
|
167
|
+
* Neo4j is schemaless, so the plan has two parts:
|
|
168
|
+
* - **DDL**: uniqueness constraints and range indexes, named exactly like `cyphra push` names them.
|
|
169
|
+
* - **Data steps**: backfills for new defaults, guards for newly required fields, and
|
|
170
|
+
* (commented-out) destructive cleanups for removed fields and models.
|
|
171
|
+
*
|
|
172
|
+
* @packageDocumentation
|
|
173
|
+
*/
|
|
174
|
+
|
|
175
|
+
/** One named schema object (constraint or index) and the statement that creates it. */
|
|
176
|
+
type DdlObject = {
|
|
177
|
+
readonly name: string;
|
|
178
|
+
readonly kind: "constraint" | "index";
|
|
179
|
+
readonly create: string;
|
|
180
|
+
};
|
|
181
|
+
/**
|
|
182
|
+
* Constraints and range indexes implied by a schema model. Names match
|
|
183
|
+
* {@link import("./push.js").constraintStatementsFromSchema} so `push` and migrations interoperate.
|
|
184
|
+
*/
|
|
185
|
+
declare function ddlObjectsFromModel(model: SchemaModel): DdlObject[];
|
|
186
|
+
/** A step of the planned migration. */
|
|
187
|
+
type MigrationStep = {
|
|
188
|
+
/** Statement executed as-is. */
|
|
189
|
+
readonly kind: "statement";
|
|
190
|
+
readonly comment: string;
|
|
191
|
+
readonly cypher: string;
|
|
192
|
+
readonly params?: Readonly<Record<string, unknown>>;
|
|
193
|
+
} | {
|
|
194
|
+
/** Fails the migration if the query returns a non-zero `count`. */
|
|
195
|
+
readonly kind: "guard";
|
|
196
|
+
readonly comment: string;
|
|
197
|
+
readonly countCypher: string;
|
|
198
|
+
readonly message: string;
|
|
199
|
+
} | {
|
|
200
|
+
/** Destructive statement emitted commented-out: the author must opt in. */
|
|
201
|
+
readonly kind: "destructive";
|
|
202
|
+
readonly comment: string;
|
|
203
|
+
readonly cypher: string;
|
|
204
|
+
};
|
|
205
|
+
type MigrationPlan = {
|
|
206
|
+
readonly steps: readonly MigrationStep[];
|
|
207
|
+
/** Things a human should review (type changes, likely renames, …). */
|
|
208
|
+
readonly warnings: readonly string[];
|
|
209
|
+
};
|
|
210
|
+
/** An empty schema, used as the "previous" side for a project's first migration. */
|
|
211
|
+
declare const EMPTY_SCHEMA_MODEL: SchemaModel;
|
|
212
|
+
/**
|
|
213
|
+
* Plan the migration from `prev` to `next`.
|
|
214
|
+
*
|
|
215
|
+
* @param prev - Schema at the last migration ({@link EMPTY_SCHEMA_MODEL} for the first one).
|
|
216
|
+
* @param next - Current schema.
|
|
217
|
+
*/
|
|
218
|
+
declare function diffSchemaModels(prev: SchemaModel, next: SchemaModel): MigrationPlan;
|
|
219
|
+
/** `true` when the plan has nothing to do. */
|
|
220
|
+
declare function isEmptyPlan(plan: MigrationPlan): boolean;
|
|
221
|
+
|
|
222
|
+
/** Options for {@link renderMigrationSource}. */
|
|
223
|
+
type RenderMigrationOptions = {
|
|
224
|
+
/** Migration name (also the file stem). */
|
|
225
|
+
readonly name: string;
|
|
226
|
+
/** Module to import `defineMigration` from (default `"cyphra"`). */
|
|
227
|
+
readonly runtimeImport?: string;
|
|
228
|
+
};
|
|
229
|
+
/**
|
|
230
|
+
* Render a migration module (`.mjs`) for a {@link MigrationPlan}.
|
|
231
|
+
* Destructive steps are emitted commented-out; warnings become a review note at the top.
|
|
232
|
+
*/
|
|
233
|
+
declare function renderMigrationSource(plan: MigrationPlan, opts: RenderMigrationOptions): string;
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* Database introspection for `cyphra pull`: read labels, relationship types, property types,
|
|
237
|
+
* constraints and indexes from a live Neo4j database and turn them into a `.cyphra` schema.
|
|
238
|
+
*
|
|
239
|
+
* Split in two so the conversion is testable without a database:
|
|
240
|
+
* {@link introspectDatabase} (queries) → {@link schemaFromIntrospection} (pure).
|
|
241
|
+
*
|
|
242
|
+
* @packageDocumentation
|
|
243
|
+
*/
|
|
244
|
+
|
|
245
|
+
type IntrospectedProperty = {
|
|
246
|
+
readonly propertyName: string;
|
|
247
|
+
readonly propertyTypes: readonly string[];
|
|
248
|
+
readonly mandatory: boolean;
|
|
249
|
+
};
|
|
250
|
+
type IntrospectionResult = {
|
|
251
|
+
/** One entry per label combination (`db.schema.nodeTypeProperties`). */
|
|
252
|
+
readonly nodeTypes: readonly {
|
|
253
|
+
readonly labels: readonly string[];
|
|
254
|
+
readonly properties: readonly IntrospectedProperty[];
|
|
255
|
+
}[];
|
|
256
|
+
/** One entry per relationship type (`db.schema.relTypeProperties`). */
|
|
257
|
+
readonly relTypes: readonly {
|
|
258
|
+
readonly type: string;
|
|
259
|
+
readonly properties: readonly IntrospectedProperty[];
|
|
260
|
+
/** Sampled (start labels, end labels) combinations. */
|
|
261
|
+
readonly endpoints: readonly {
|
|
262
|
+
readonly from: readonly string[];
|
|
263
|
+
readonly to: readonly string[];
|
|
264
|
+
}[];
|
|
265
|
+
}[];
|
|
266
|
+
readonly constraints: readonly {
|
|
267
|
+
readonly name: string;
|
|
268
|
+
readonly type: string;
|
|
269
|
+
readonly entityType: string;
|
|
270
|
+
readonly labelsOrTypes: readonly string[];
|
|
271
|
+
readonly properties: readonly string[];
|
|
272
|
+
}[];
|
|
273
|
+
readonly indexes: readonly {
|
|
274
|
+
readonly name: string;
|
|
275
|
+
readonly type: string;
|
|
276
|
+
readonly entityType: string;
|
|
277
|
+
readonly labelsOrTypes: readonly string[];
|
|
278
|
+
readonly properties: readonly string[];
|
|
279
|
+
readonly owningConstraint: string | null;
|
|
280
|
+
}[];
|
|
281
|
+
};
|
|
282
|
+
/** Edges sampled per relationship type to discover its endpoint labels. */
|
|
283
|
+
declare const ENDPOINT_SAMPLE_SIZE = 10000;
|
|
284
|
+
/**
|
|
285
|
+
* Read the database's implicit schema. Read-only; samples at most {@link ENDPOINT_SAMPLE_SIZE}
|
|
286
|
+
* edges per relationship type.
|
|
287
|
+
*/
|
|
288
|
+
declare function introspectDatabase(client: CyphraClient): Promise<IntrospectionResult>;
|
|
289
|
+
/**
|
|
290
|
+
* Convert introspection results into a `.cyphra` {@link SchemaDocument}.
|
|
291
|
+
*
|
|
292
|
+
* - Properties: required when present on every node of the label; types mapped from Neo4j's.
|
|
293
|
+
* - Single-property uniqueness constraints become `@id` (property `id` or constraint `…_id`) / `@unique`;
|
|
294
|
+
* single-property range indexes become `@index`.
|
|
295
|
+
* - Every sampled `(start)-[:TYPE]->(end)` pair becomes an `OUT` field on the start node and an `IN`
|
|
296
|
+
* field (`…By`) on the end node, both to-many. Relationship types with properties also get a
|
|
297
|
+
* `relationship { … }` model.
|
|
298
|
+
*/
|
|
299
|
+
declare function schemaFromIntrospection(input: IntrospectionResult): {
|
|
300
|
+
doc: SchemaDocument;
|
|
301
|
+
warnings: string[];
|
|
302
|
+
};
|
|
303
|
+
|
|
156
304
|
/** Neo4j label used to record applied migrations. */
|
|
157
305
|
declare const CYPHRA_MIGRATION_LABEL = "__CyphraMigration";
|
|
158
306
|
/**
|
|
@@ -174,5 +322,16 @@ declare function isMigrationApplied(session: Session, name: string): Promise<boo
|
|
|
174
322
|
* @param checksum - Content checksum (e.g. SHA-256 hex).
|
|
175
323
|
*/
|
|
176
324
|
declare function recordMigration(session: Session, name: string, checksum: string): Promise<void>;
|
|
325
|
+
type AppliedMigration = {
|
|
326
|
+
readonly name: string;
|
|
327
|
+
readonly checksum: string | null;
|
|
328
|
+
readonly appliedAt: Date | null;
|
|
329
|
+
};
|
|
330
|
+
/**
|
|
331
|
+
* List applied migrations, oldest first.
|
|
332
|
+
*
|
|
333
|
+
* @param session - Open session.
|
|
334
|
+
*/
|
|
335
|
+
declare function listAppliedMigrations(session: Session): Promise<AppliedMigration[]>;
|
|
177
336
|
|
|
178
|
-
export { CYPHRA_MIGRATION_LABEL, type LoadedMigration, type MigrationDb, type MigrationDefinition, type MigrationMigrateHelpers, applyConstraintStatements, compileRenameLabel, compileRenameProperty, constraintStatementsFromSchema, createMigrationDb, defineMigration, ensureMigrationInfrastructure, indexStatementsFromSchema, isMigrationApplied, recordMigration, runPendingMigrations, schemaIntegrationHints, wrapInTransactions };
|
|
337
|
+
export { type AppliedMigration, CYPHRA_MIGRATION_LABEL, type DdlObject, EMPTY_SCHEMA_MODEL, ENDPOINT_SAMPLE_SIZE, type IntrospectedProperty, type IntrospectionResult, type LoadedMigration, type MigrationDb, type MigrationDefinition, type MigrationMigrateHelpers, type MigrationPlan, type MigrationStep, type RenderMigrationOptions, applyConstraintStatements, compileRenameLabel, compileRenameProperty, constraintStatementsFromSchema, createMigrationDb, ddlObjectsFromModel, defineMigration, diffSchemaModels, ensureMigrationInfrastructure, indexStatementsFromSchema, introspectDatabase, isEmptyPlan, isMigrationApplied, listAppliedMigrations, recordMigration, renderMigrationSource, runPendingMigrations, schemaFromIntrospection, schemaIntegrationHints, wrapInTransactions };
|
package/dist/index.js
CHANGED
|
@@ -13,6 +13,9 @@ function defineMigration(def) {
|
|
|
13
13
|
return def;
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
+
// src/migrationDb.ts
|
|
17
|
+
import { toNative } from "@cyphra/runtime";
|
|
18
|
+
|
|
16
19
|
// src/rename.ts
|
|
17
20
|
var IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
18
21
|
function assertIdent(name, label) {
|
|
@@ -59,12 +62,16 @@ function createMigrationDb(client, session) {
|
|
|
59
62
|
await session.run(text, params);
|
|
60
63
|
}
|
|
61
64
|
};
|
|
62
|
-
|
|
65
|
+
const execute = async (text, params = {}) => {
|
|
66
|
+
const result = await session.run(text, params);
|
|
67
|
+
return result.records.map((r) => toNative(r.toObject()));
|
|
68
|
+
};
|
|
69
|
+
return { run, runInTransactionBatches, execute, migrate };
|
|
63
70
|
}
|
|
64
71
|
|
|
65
72
|
// src/push.ts
|
|
66
|
-
function isScalarWithDecorator(field,
|
|
67
|
-
return field.kind === "Scalar" && field.decorators.some((d) => d.name ===
|
|
73
|
+
function isScalarWithDecorator(field, dec2) {
|
|
74
|
+
return field.kind === "Scalar" && field.decorators.some((d) => d.name === dec2);
|
|
68
75
|
}
|
|
69
76
|
function hasDecoratorName(field, name) {
|
|
70
77
|
return field.decorators.some((d) => d.name === name);
|
|
@@ -173,8 +180,8 @@ async function isMigrationApplied(session, name) {
|
|
|
173
180
|
`MATCH (m:__CyphraMigration { name: $name }) RETURN m AS m LIMIT 1`,
|
|
174
181
|
{ name }
|
|
175
182
|
);
|
|
176
|
-
const
|
|
177
|
-
return
|
|
183
|
+
const q2 = await result;
|
|
184
|
+
return q2.records.length > 0;
|
|
178
185
|
}
|
|
179
186
|
async function recordMigration(session, name, checksum) {
|
|
180
187
|
const r = await session.run(
|
|
@@ -189,6 +196,19 @@ async function recordMigration(session, name, checksum) {
|
|
|
189
196
|
);
|
|
190
197
|
await r;
|
|
191
198
|
}
|
|
199
|
+
async function listAppliedMigrations(session) {
|
|
200
|
+
const result = await session.run(
|
|
201
|
+
`MATCH (m:__CyphraMigration) RETURN m.name AS name, m.checksum AS checksum, m.appliedAt AS appliedAt ORDER BY m.appliedAt, m.name`
|
|
202
|
+
);
|
|
203
|
+
return result.records.map((r) => {
|
|
204
|
+
const at = r.get("appliedAt");
|
|
205
|
+
return {
|
|
206
|
+
name: r.get("name"),
|
|
207
|
+
checksum: r.get("checksum") ?? null,
|
|
208
|
+
appliedAt: at?.toStandardDate ? at.toStandardDate() : null
|
|
209
|
+
};
|
|
210
|
+
});
|
|
211
|
+
}
|
|
192
212
|
|
|
193
213
|
// src/runner.ts
|
|
194
214
|
async function runPendingMigrations(client, ordered) {
|
|
@@ -228,19 +248,629 @@ function schemaIntegrationHints(doc) {
|
|
|
228
248
|
}
|
|
229
249
|
return hints;
|
|
230
250
|
}
|
|
251
|
+
|
|
252
|
+
// src/diff.ts
|
|
253
|
+
function q(id) {
|
|
254
|
+
return "`" + id.replace(/`/g, "``") + "`";
|
|
255
|
+
}
|
|
256
|
+
function constraintName(name) {
|
|
257
|
+
return name.replace(/[^A-Za-z0-9_]/g, "_");
|
|
258
|
+
}
|
|
259
|
+
function ddlObjectsFromModel(model) {
|
|
260
|
+
const out = [];
|
|
261
|
+
for (const n of model.nodes) {
|
|
262
|
+
const scalars = n.fields.filter((f) => f.kind === "scalar");
|
|
263
|
+
for (const f of scalars) {
|
|
264
|
+
const target = `FOR (n:${q(n.label)})`;
|
|
265
|
+
if (f.id) {
|
|
266
|
+
const name = constraintName(`${n.label}_${f.name}_id`);
|
|
267
|
+
out.push({
|
|
268
|
+
name,
|
|
269
|
+
kind: "constraint",
|
|
270
|
+
create: `CREATE CONSTRAINT ${name} IF NOT EXISTS ${target} REQUIRE n.${q(f.name)} IS UNIQUE`
|
|
271
|
+
});
|
|
272
|
+
} else if (f.unique) {
|
|
273
|
+
const name = constraintName(`${n.label}_${f.name}_unique`);
|
|
274
|
+
out.push({
|
|
275
|
+
name,
|
|
276
|
+
kind: "constraint",
|
|
277
|
+
create: `CREATE CONSTRAINT ${name} IF NOT EXISTS ${target} REQUIRE n.${q(f.name)} IS UNIQUE`
|
|
278
|
+
});
|
|
279
|
+
} else if (f.index) {
|
|
280
|
+
const name = constraintName(`${n.label}_${f.name}_idx`);
|
|
281
|
+
out.push({
|
|
282
|
+
name,
|
|
283
|
+
kind: "index",
|
|
284
|
+
create: `CREATE RANGE INDEX ${name} IF NOT EXISTS ${target} ON (n.${q(f.name)})`
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
for (const r of model.relationships) {
|
|
290
|
+
const target = `FOR ()-[r:${q(r.relType)}]-()`;
|
|
291
|
+
for (const f of r.properties) {
|
|
292
|
+
if (f.unique) {
|
|
293
|
+
const name = constraintName(`${r.name}_${f.name}_rel_unique`);
|
|
294
|
+
out.push({
|
|
295
|
+
name,
|
|
296
|
+
kind: "constraint",
|
|
297
|
+
create: `CREATE CONSTRAINT ${name} IF NOT EXISTS ${target} REQUIRE r.${q(f.name)} IS UNIQUE`
|
|
298
|
+
});
|
|
299
|
+
} else if (f.index) {
|
|
300
|
+
const name = constraintName(`${r.name}_${f.name}_rel_idx`);
|
|
301
|
+
out.push({
|
|
302
|
+
name,
|
|
303
|
+
kind: "index",
|
|
304
|
+
create: `CREATE RANGE INDEX ${name} IF NOT EXISTS ${target} ON (r.${q(f.name)})`
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
return out;
|
|
310
|
+
}
|
|
311
|
+
var EMPTY_SCHEMA_MODEL = { version: 1, nodes: [], relationships: [] };
|
|
312
|
+
function scalarsOf(n) {
|
|
313
|
+
return new Map(
|
|
314
|
+
n.fields.filter((f) => f.kind === "scalar").map((f) => [f.name, f])
|
|
315
|
+
);
|
|
316
|
+
}
|
|
317
|
+
function typeLabel(f) {
|
|
318
|
+
return f.list ? `${f.type}[]` : f.optional ? `${f.type}?` : f.type;
|
|
319
|
+
}
|
|
320
|
+
function defaultExpression(f) {
|
|
321
|
+
const d = f.default;
|
|
322
|
+
if (!d) return null;
|
|
323
|
+
if (d.kind === "literal") {
|
|
324
|
+
if (f.type === "Int") return { expr: `toInteger($value)`, params: { value: d.value } };
|
|
325
|
+
return { expr: "$value", params: { value: d.value } };
|
|
326
|
+
}
|
|
327
|
+
if (d.fn === "now") return { expr: f.type === "Date" ? "date()" : "datetime()" };
|
|
328
|
+
if (d.fn === "uuid") return { expr: "randomUUID()" };
|
|
329
|
+
return {
|
|
330
|
+
expr: "randomUUID()",
|
|
331
|
+
note: "cuid() cannot be generated in Cypher; existing nodes get a UUID instead"
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
function nodeDataSteps(label, model, name, before, after, steps, warnings) {
|
|
335
|
+
const ref = `n.${q(name)}`;
|
|
336
|
+
const match = `MATCH (n:${q(label)}) WHERE ${ref} IS NULL`;
|
|
337
|
+
const nowRequired = !after.optional && !after.list;
|
|
338
|
+
const wasRequired = before ? !before.optional && !before.list : false;
|
|
339
|
+
if (before && before.type !== after.type) {
|
|
340
|
+
warnings.push(
|
|
341
|
+
`${model}.${name} changed type ${typeLabel(before)} \u2192 ${typeLabel(after)}; existing values are not converted. Add a conversion step (e.g. SET ${ref} = toInteger(${ref})) if needed.`
|
|
342
|
+
);
|
|
343
|
+
}
|
|
344
|
+
if (before && before.list !== after.list) {
|
|
345
|
+
warnings.push(
|
|
346
|
+
`${model}.${name} changed between list and single value; convert existing data manually.`
|
|
347
|
+
);
|
|
348
|
+
}
|
|
349
|
+
const def = defaultExpression(after);
|
|
350
|
+
if (def && (!before || nowRequired && !wasRequired)) {
|
|
351
|
+
steps.push({
|
|
352
|
+
kind: "statement",
|
|
353
|
+
comment: `Backfill ${model}.${name} with its default on existing nodes${def.note ? ` (${def.note})` : ""}.`,
|
|
354
|
+
cypher: `${match} SET ${ref} = ${def.expr}`,
|
|
355
|
+
...def.params ? { params: def.params } : {}
|
|
356
|
+
});
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
if (nowRequired && !wasRequired) {
|
|
360
|
+
steps.push({
|
|
361
|
+
kind: "guard",
|
|
362
|
+
comment: `${model}.${name} is now required and has no default: make sure no existing node lacks it.`,
|
|
363
|
+
countCypher: `${match} RETURN count(n) AS count`,
|
|
364
|
+
message: `${model}.${name} is required but some existing ${label} nodes do not have it. Backfill them in this migration before the guard (or add a @default).`
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
function diffSchemaModels(prev, next) {
|
|
369
|
+
const drops = [];
|
|
370
|
+
const creates = [];
|
|
371
|
+
const steps = [];
|
|
372
|
+
const warnings = [];
|
|
373
|
+
const before = new Map(ddlObjectsFromModel(prev).map((o) => [o.name, o]));
|
|
374
|
+
const after = new Map(ddlObjectsFromModel(next).map((o) => [o.name, o]));
|
|
375
|
+
for (const [name, o] of before) {
|
|
376
|
+
const n = after.get(name);
|
|
377
|
+
if (!n || n.create !== o.create) {
|
|
378
|
+
drops.push({
|
|
379
|
+
kind: "statement",
|
|
380
|
+
comment: `Drop ${o.kind} ${name}.`,
|
|
381
|
+
cypher: `DROP ${o.kind === "constraint" ? "CONSTRAINT" : "INDEX"} ${name} IF EXISTS`
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
for (const [name, o] of after) {
|
|
386
|
+
const p = before.get(name);
|
|
387
|
+
if (!p || p.create !== o.create) {
|
|
388
|
+
creates.push({ kind: "statement", comment: `Create ${o.kind} ${name}.`, cypher: o.create });
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
const prevNodes = new Map(prev.nodes.map((n) => [n.name, n]));
|
|
392
|
+
const nextNodes = new Map(next.nodes.map((n) => [n.name, n]));
|
|
393
|
+
const removedNodes = prev.nodes.filter((n) => !nextNodes.has(n.name));
|
|
394
|
+
const addedNodes = next.nodes.filter((n) => !prevNodes.has(n.name));
|
|
395
|
+
for (const r of removedNodes) {
|
|
396
|
+
steps.push({
|
|
397
|
+
kind: "destructive",
|
|
398
|
+
comment: `Model ${r.name} was removed. Uncomment to delete its nodes (or rename the label instead: db.migrate.renameLabel).`,
|
|
399
|
+
cypher: `MATCH (n:${q(r.label)}) DETACH DELETE n`
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
if (removedNodes.length && addedNodes.length) {
|
|
403
|
+
warnings.push(
|
|
404
|
+
`Models removed (${removedNodes.map((n) => n.name).join(", ")}) and added (${addedNodes.map((n) => n.name).join(", ")}): if this is a rename, replace the generated steps with db.migrate.renameLabel({ from, to }).`
|
|
405
|
+
);
|
|
406
|
+
}
|
|
407
|
+
for (const n of next.nodes) {
|
|
408
|
+
const p = prevNodes.get(n.name);
|
|
409
|
+
if (!p) continue;
|
|
410
|
+
const ps = scalarsOf(p);
|
|
411
|
+
const ns = scalarsOf(n);
|
|
412
|
+
const removed = [...ps.keys()].filter((k) => !ns.has(k));
|
|
413
|
+
const added = [...ns.keys()].filter((k) => !ps.has(k));
|
|
414
|
+
for (const [name, f] of ns) {
|
|
415
|
+
nodeDataSteps(n.label, n.name, name, ps.get(name), f, steps, warnings);
|
|
416
|
+
}
|
|
417
|
+
for (const name of removed) {
|
|
418
|
+
steps.push({
|
|
419
|
+
kind: "destructive",
|
|
420
|
+
comment: `${n.name}.${name} was removed. Uncomment to delete the property from existing nodes.`,
|
|
421
|
+
cypher: `MATCH (n:${q(n.label)}) WHERE n.${q(name)} IS NOT NULL REMOVE n.${q(name)}`
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
if (removed.length && added.length) {
|
|
425
|
+
warnings.push(
|
|
426
|
+
`${n.name}: fields removed (${removed.join(", ")}) and added (${added.join(", ")}). If this is a rename, use db.migrate.renameProperty({ label: ${JSON.stringify(n.label)}, from, to }) instead of the generated steps.`
|
|
427
|
+
);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
const prevRels = new Map(prev.relationships.map((r) => [r.name, r]));
|
|
431
|
+
for (const r of next.relationships) {
|
|
432
|
+
const p = prevRels.get(r.name);
|
|
433
|
+
if (!p) continue;
|
|
434
|
+
relationshipDataSteps(p, r, steps, warnings);
|
|
435
|
+
}
|
|
436
|
+
return { steps: [...drops, ...steps, ...creates], warnings };
|
|
437
|
+
}
|
|
438
|
+
function relationshipDataSteps(prev, next, steps, warnings) {
|
|
439
|
+
if (prev.relType !== next.relType) {
|
|
440
|
+
warnings.push(
|
|
441
|
+
`Relationship ${next.name} changed type :${prev.relType} \u2192 :${next.relType}; existing edges are not retyped.`
|
|
442
|
+
);
|
|
443
|
+
return;
|
|
444
|
+
}
|
|
445
|
+
const ps = new Map(prev.properties.map((f) => [f.name, f]));
|
|
446
|
+
for (const f of next.properties) {
|
|
447
|
+
const p = ps.get(f.name);
|
|
448
|
+
const def = defaultExpression(f);
|
|
449
|
+
const nowRequired = !f.optional && !f.list;
|
|
450
|
+
const wasRequired = p ? !p.optional && !p.list : false;
|
|
451
|
+
if (def && (!p || nowRequired && !wasRequired)) {
|
|
452
|
+
steps.push({
|
|
453
|
+
kind: "statement",
|
|
454
|
+
comment: `Backfill ${next.name}.${f.name} with its default on existing edges${def.note ? ` (${def.note})` : ""}.`,
|
|
455
|
+
cypher: `MATCH ()-[r:${q(next.relType)}]->() WHERE r.${q(f.name)} IS NULL SET r.${q(f.name)} = ${def.expr}`,
|
|
456
|
+
...def.params ? { params: def.params } : {}
|
|
457
|
+
});
|
|
458
|
+
} else if (nowRequired && !wasRequired) {
|
|
459
|
+
warnings.push(
|
|
460
|
+
`${next.name}.${f.name} is now required without a default; existing :${next.relType} edges may lack it.`
|
|
461
|
+
);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
function isEmptyPlan(plan) {
|
|
466
|
+
return plan.steps.length === 0;
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
// src/renderMigration.ts
|
|
470
|
+
function indentComment(text, indent) {
|
|
471
|
+
return text.split("\n").map((l) => `${indent}// ${l}`);
|
|
472
|
+
}
|
|
473
|
+
function call(cypher, params) {
|
|
474
|
+
const p = params && Object.keys(params).length ? `, ${JSON.stringify(params)}` : "";
|
|
475
|
+
return `await db.execute(${JSON.stringify(cypher)}${p});`;
|
|
476
|
+
}
|
|
477
|
+
function renderMigrationSource(plan, opts) {
|
|
478
|
+
const lines = [];
|
|
479
|
+
lines.push(
|
|
480
|
+
"// Generated by `cyphra migrate dev`. Review it before applying to shared databases."
|
|
481
|
+
);
|
|
482
|
+
if (plan.warnings.length) {
|
|
483
|
+
lines.push("//", "// REVIEW:");
|
|
484
|
+
for (const w of plan.warnings) lines.push(...indentComment(`- ${w}`, ""));
|
|
485
|
+
}
|
|
486
|
+
lines.push(
|
|
487
|
+
`import { defineMigration } from ${JSON.stringify(opts.runtimeImport ?? "cyphra")};`,
|
|
488
|
+
""
|
|
489
|
+
);
|
|
490
|
+
lines.push("export default defineMigration({");
|
|
491
|
+
lines.push(` name: ${JSON.stringify(opts.name)},`);
|
|
492
|
+
lines.push(" async up({ db }) {");
|
|
493
|
+
if (plan.steps.length === 0) {
|
|
494
|
+
lines.push(" // Nothing to do: write your own steps here.");
|
|
495
|
+
}
|
|
496
|
+
plan.steps.forEach((step, i) => {
|
|
497
|
+
if (i > 0) lines.push("");
|
|
498
|
+
lines.push(...indentComment(step.comment, " "));
|
|
499
|
+
if (step.kind === "statement") {
|
|
500
|
+
lines.push(` ${call(step.cypher, step.params)}`);
|
|
501
|
+
} else if (step.kind === "guard") {
|
|
502
|
+
lines.push(" {");
|
|
503
|
+
lines.push(` const [row] = await db.execute(${JSON.stringify(step.countCypher)});`);
|
|
504
|
+
lines.push(" if (row && Number(row.count) > 0) {");
|
|
505
|
+
lines.push(
|
|
506
|
+
` throw new Error(${JSON.stringify(step.message)} + \` (\${row.count} nodes)\`);`
|
|
507
|
+
);
|
|
508
|
+
lines.push(" }");
|
|
509
|
+
lines.push(" }");
|
|
510
|
+
} else {
|
|
511
|
+
lines.push(" // DESTRUCTIVE: uncomment to apply.");
|
|
512
|
+
lines.push(` // ${call(step.cypher)}`);
|
|
513
|
+
}
|
|
514
|
+
});
|
|
515
|
+
lines.push(" },");
|
|
516
|
+
lines.push("});", "");
|
|
517
|
+
return lines.join("\n");
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
// src/introspect.ts
|
|
521
|
+
import neo4j from "neo4j-driver";
|
|
522
|
+
import { toNative as toNative2 } from "@cyphra/runtime";
|
|
523
|
+
var ENDPOINT_SAMPLE_SIZE = 1e4;
|
|
524
|
+
function stripRelType(raw) {
|
|
525
|
+
const t = raw.startsWith(":") ? raw.slice(1) : raw;
|
|
526
|
+
return t.startsWith("`") && t.endsWith("`") ? t.slice(1, -1).replace(/``/g, "`") : t;
|
|
527
|
+
}
|
|
528
|
+
async function introspectDatabase(client) {
|
|
529
|
+
return client.withSession(async (session) => {
|
|
530
|
+
const rows = async (text, params = {}) => (await session.run(text, params)).records.map(
|
|
531
|
+
(r) => toNative2(r.toObject())
|
|
532
|
+
);
|
|
533
|
+
const nodeRows = await rows(
|
|
534
|
+
"CALL db.schema.nodeTypeProperties() YIELD nodeLabels, propertyName, propertyTypes, mandatory RETURN *"
|
|
535
|
+
);
|
|
536
|
+
const byCombo = /* @__PURE__ */ new Map();
|
|
537
|
+
for (const r of nodeRows) {
|
|
538
|
+
const labels = [...r.nodeLabels].sort();
|
|
539
|
+
const key = JSON.stringify(labels);
|
|
540
|
+
const entry = byCombo.get(key) ?? { labels, properties: [] };
|
|
541
|
+
byCombo.set(key, entry);
|
|
542
|
+
if (r.propertyName) {
|
|
543
|
+
entry.properties.push({
|
|
544
|
+
propertyName: r.propertyName,
|
|
545
|
+
propertyTypes: r.propertyTypes ?? [],
|
|
546
|
+
mandatory: Boolean(r.mandatory)
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
const relRows = await rows(
|
|
551
|
+
"CALL db.schema.relTypeProperties() YIELD relType, propertyName, propertyTypes, mandatory RETURN *"
|
|
552
|
+
);
|
|
553
|
+
const byType = /* @__PURE__ */ new Map();
|
|
554
|
+
for (const r of relRows) {
|
|
555
|
+
const type = stripRelType(r.relType);
|
|
556
|
+
const props = byType.get(type) ?? [];
|
|
557
|
+
byType.set(type, props);
|
|
558
|
+
if (r.propertyName) {
|
|
559
|
+
props.push({
|
|
560
|
+
propertyName: r.propertyName,
|
|
561
|
+
propertyTypes: r.propertyTypes ?? [],
|
|
562
|
+
mandatory: Boolean(r.mandatory)
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
const relTypes = [];
|
|
567
|
+
for (const [type, properties] of byType) {
|
|
568
|
+
const ends = await rows(
|
|
569
|
+
`MATCH ()-[r:\`${type.replace(/`/g, "``")}\`]->() WITH r LIMIT $limit
|
|
570
|
+
RETURN DISTINCT labels(startNode(r)) AS from, labels(endNode(r)) AS to`,
|
|
571
|
+
{ limit: neo4jInt(ENDPOINT_SAMPLE_SIZE) }
|
|
572
|
+
);
|
|
573
|
+
relTypes.push({
|
|
574
|
+
type,
|
|
575
|
+
properties,
|
|
576
|
+
endpoints: ends.map((e) => ({ from: e.from, to: e.to }))
|
|
577
|
+
});
|
|
578
|
+
}
|
|
579
|
+
const constraints = (await rows(
|
|
580
|
+
"SHOW CONSTRAINTS YIELD name, type, entityType, labelsOrTypes, properties RETURN *"
|
|
581
|
+
)).map((c) => ({
|
|
582
|
+
name: c.name,
|
|
583
|
+
type: c.type,
|
|
584
|
+
entityType: c.entityType,
|
|
585
|
+
labelsOrTypes: c.labelsOrTypes ?? [],
|
|
586
|
+
properties: c.properties ?? []
|
|
587
|
+
}));
|
|
588
|
+
const indexes = (await rows(
|
|
589
|
+
"SHOW INDEXES YIELD name, type, entityType, labelsOrTypes, properties, owningConstraint RETURN *"
|
|
590
|
+
)).map((i) => ({
|
|
591
|
+
name: i.name,
|
|
592
|
+
type: i.type,
|
|
593
|
+
entityType: i.entityType,
|
|
594
|
+
labelsOrTypes: i.labelsOrTypes ?? [],
|
|
595
|
+
properties: i.properties ?? [],
|
|
596
|
+
owningConstraint: i.owningConstraint ?? null
|
|
597
|
+
}));
|
|
598
|
+
return { nodeTypes: [...byCombo.values()], relTypes, constraints, indexes };
|
|
599
|
+
});
|
|
600
|
+
}
|
|
601
|
+
function neo4jInt(n) {
|
|
602
|
+
return neo4j.int(n);
|
|
603
|
+
}
|
|
604
|
+
var IDENT2 = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
605
|
+
var TYPE_MAP = {
|
|
606
|
+
String: "String",
|
|
607
|
+
Long: "Int",
|
|
608
|
+
Integer: "Int",
|
|
609
|
+
Double: "Float",
|
|
610
|
+
Float: "Float",
|
|
611
|
+
Boolean: "Boolean",
|
|
612
|
+
DateTime: "DateTime",
|
|
613
|
+
ZonedDateTime: "DateTime",
|
|
614
|
+
LocalDateTime: "DateTime",
|
|
615
|
+
Date: "Date"
|
|
616
|
+
};
|
|
617
|
+
function mapType(types) {
|
|
618
|
+
const mapped = /* @__PURE__ */ new Set();
|
|
619
|
+
let list;
|
|
620
|
+
for (const raw of types) {
|
|
621
|
+
const isList = raw.endsWith("Array") || raw.startsWith("List");
|
|
622
|
+
const base = raw.replace(/Array$/, "").replace(/^List<(.*)>$/, "$1");
|
|
623
|
+
const t = TYPE_MAP[base];
|
|
624
|
+
if (!t) return null;
|
|
625
|
+
if (list !== void 0 && list !== isList) return null;
|
|
626
|
+
list = isList;
|
|
627
|
+
mapped.add(t);
|
|
628
|
+
}
|
|
629
|
+
if (mapped.size === 0) return null;
|
|
630
|
+
if (mapped.size === 1) return { name: [...mapped][0], list: Boolean(list) };
|
|
631
|
+
if ([...mapped].every((t) => t === "Int" || t === "Float"))
|
|
632
|
+
return { name: "Float", list: Boolean(list) };
|
|
633
|
+
return null;
|
|
634
|
+
}
|
|
635
|
+
function camel(type) {
|
|
636
|
+
const parts = type.split(/[^A-Za-z0-9]+/).filter(Boolean);
|
|
637
|
+
const s = parts.map(
|
|
638
|
+
(p, i) => i === 0 ? p.toLowerCase() : p.charAt(0).toUpperCase() + p.slice(1).toLowerCase()
|
|
639
|
+
).join("");
|
|
640
|
+
return /^[A-Za-z_]/.test(s) ? s : `rel${s}`;
|
|
641
|
+
}
|
|
642
|
+
function pascal(type) {
|
|
643
|
+
const c = camel(type);
|
|
644
|
+
return c.charAt(0).toUpperCase() + c.slice(1);
|
|
645
|
+
}
|
|
646
|
+
function uniqueName(base, taken) {
|
|
647
|
+
let name = base;
|
|
648
|
+
let i = 2;
|
|
649
|
+
while (taken.has(name)) name = `${base}${i++}`;
|
|
650
|
+
taken.add(name);
|
|
651
|
+
return name;
|
|
652
|
+
}
|
|
653
|
+
var dec = (name) => ({ name, args: [] });
|
|
654
|
+
function schemaFromIntrospection(input) {
|
|
655
|
+
const warnings = [];
|
|
656
|
+
const labels = /* @__PURE__ */ new Map();
|
|
657
|
+
const ensureLabel = (l) => {
|
|
658
|
+
let e = labels.get(l);
|
|
659
|
+
if (!e) {
|
|
660
|
+
e = { combos: 0, props: /* @__PURE__ */ new Map() };
|
|
661
|
+
labels.set(l, e);
|
|
662
|
+
}
|
|
663
|
+
return e;
|
|
664
|
+
};
|
|
665
|
+
const skipLabel = (l) => l === CYPHRA_MIGRATION_LABEL || !IDENT2.test(l);
|
|
666
|
+
for (const nt of input.nodeTypes) {
|
|
667
|
+
for (const l of nt.labels) {
|
|
668
|
+
if (skipLabel(l)) {
|
|
669
|
+
if (l !== CYPHRA_MIGRATION_LABEL)
|
|
670
|
+
warnings.push(`Skipped label "${l}": not a valid identifier.`);
|
|
671
|
+
continue;
|
|
672
|
+
}
|
|
673
|
+
const e = ensureLabel(l);
|
|
674
|
+
e.combos += 1;
|
|
675
|
+
for (const p of nt.properties) {
|
|
676
|
+
const acc = e.props.get(p.propertyName) ?? {
|
|
677
|
+
types: /* @__PURE__ */ new Set(),
|
|
678
|
+
mandatoryIn: 0,
|
|
679
|
+
presentIn: 0
|
|
680
|
+
};
|
|
681
|
+
e.props.set(p.propertyName, acc);
|
|
682
|
+
p.propertyTypes.forEach((t) => acc.types.add(t));
|
|
683
|
+
acc.presentIn += 1;
|
|
684
|
+
if (p.mandatory) acc.mandatoryIn += 1;
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
for (const rt of input.relTypes) {
|
|
689
|
+
for (const ep of rt.endpoints) {
|
|
690
|
+
for (const l of [...ep.from, ...ep.to]) if (!skipLabel(l)) ensureLabel(l);
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
const uniqueOn = /* @__PURE__ */ new Map();
|
|
694
|
+
const relUnique = /* @__PURE__ */ new Set();
|
|
695
|
+
const indexOn = /* @__PURE__ */ new Set();
|
|
696
|
+
for (const c of input.constraints) {
|
|
697
|
+
if (c.properties.length !== 1 || c.labelsOrTypes.length !== 1) continue;
|
|
698
|
+
const key = c.labelsOrTypes[0];
|
|
699
|
+
if (c.type === "UNIQUENESS" || c.type.includes("UNIQUE") && c.entityType === "NODE") {
|
|
700
|
+
const list = uniqueOn.get(key) ?? [];
|
|
701
|
+
list.push({ prop: c.properties[0], name: c.name });
|
|
702
|
+
uniqueOn.set(key, list);
|
|
703
|
+
} else if (c.entityType === "RELATIONSHIP" && c.type.includes("UNIQUE")) {
|
|
704
|
+
relUnique.add(`${key}.${c.properties[0]}`);
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
for (const i of input.indexes) {
|
|
708
|
+
if (i.type !== "RANGE" || i.owningConstraint || i.properties.length !== 1 || i.labelsOrTypes.length !== 1) {
|
|
709
|
+
continue;
|
|
710
|
+
}
|
|
711
|
+
indexOn.add(`${i.entityType}:${i.labelsOrTypes[0]}.${i.properties[0]}`);
|
|
712
|
+
}
|
|
713
|
+
const nodeFields = /* @__PURE__ */ new Map();
|
|
714
|
+
const taken = /* @__PURE__ */ new Map();
|
|
715
|
+
for (const [label, e] of [...labels].sort(([a], [b]) => a.localeCompare(b))) {
|
|
716
|
+
const uniques = uniqueOn.get(label) ?? [];
|
|
717
|
+
const idProp = uniques.find((u) => u.prop === "id")?.prop ?? uniques.find((u) => /_id$/.test(u.name))?.prop;
|
|
718
|
+
const fields = [];
|
|
719
|
+
const ordered = [...e.props].sort(
|
|
720
|
+
([a], [b]) => a === idProp ? -1 : b === idProp ? 1 : a.localeCompare(b)
|
|
721
|
+
);
|
|
722
|
+
for (const [prop, acc] of ordered) {
|
|
723
|
+
if (!IDENT2.test(prop)) {
|
|
724
|
+
warnings.push(`Skipped ${label}.${prop}: not a valid identifier.`);
|
|
725
|
+
continue;
|
|
726
|
+
}
|
|
727
|
+
const t = mapType([...acc.types]);
|
|
728
|
+
if (!t) {
|
|
729
|
+
warnings.push(
|
|
730
|
+
`Skipped ${label}.${prop}: unsupported or mixed types (${[...acc.types].join(", ")}).`
|
|
731
|
+
);
|
|
732
|
+
continue;
|
|
733
|
+
}
|
|
734
|
+
const required = !t.list && acc.mandatoryIn === e.combos;
|
|
735
|
+
const decorators = [];
|
|
736
|
+
if (prop === idProp && required) decorators.push(dec("id"));
|
|
737
|
+
else if (uniques.some((u) => u.prop === prop)) decorators.push(dec("unique"));
|
|
738
|
+
else if (indexOn.has(`NODE:${label}.${prop}`)) decorators.push(dec("index"));
|
|
739
|
+
fields.push({
|
|
740
|
+
kind: "Scalar",
|
|
741
|
+
name: prop,
|
|
742
|
+
type: { name: t.name, optional: !required && !t.list, ...t.list ? { list: true } : {} },
|
|
743
|
+
decorators
|
|
744
|
+
});
|
|
745
|
+
}
|
|
746
|
+
nodeFields.set(label, fields);
|
|
747
|
+
taken.set(label, new Set(fields.map((f) => f.name)));
|
|
748
|
+
}
|
|
749
|
+
const relationships = [];
|
|
750
|
+
const declNames = new Set(labels.keys());
|
|
751
|
+
for (const rt of [...input.relTypes].sort((a, b) => a.type.localeCompare(b.type))) {
|
|
752
|
+
const pairs = [];
|
|
753
|
+
for (const ep of rt.endpoints) {
|
|
754
|
+
for (const from of ep.from) {
|
|
755
|
+
for (const to of ep.to) {
|
|
756
|
+
if (skipLabel(from) || skipLabel(to)) continue;
|
|
757
|
+
if (!pairs.some((p) => p.from === from && p.to === to)) pairs.push({ from, to });
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
if (pairs.length === 0) {
|
|
762
|
+
warnings.push(
|
|
763
|
+
`Relationship type :${rt.type} has no usable endpoints in the sample; skipped.`
|
|
764
|
+
);
|
|
765
|
+
continue;
|
|
766
|
+
}
|
|
767
|
+
const outTargets = (from) => pairs.filter((p) => p.from === from).length;
|
|
768
|
+
const inSources = (to) => pairs.filter((p) => p.to === to).length;
|
|
769
|
+
const relDecorator = (direction) => ({
|
|
770
|
+
name: "relationship",
|
|
771
|
+
args: [
|
|
772
|
+
{ key: "type", value: { kind: "string", value: rt.type } },
|
|
773
|
+
{ key: "direction", value: { kind: "identifier", value: direction } }
|
|
774
|
+
]
|
|
775
|
+
});
|
|
776
|
+
for (const { from, to } of pairs) {
|
|
777
|
+
const outName = uniqueName(
|
|
778
|
+
camel(rt.type) + (outTargets(from) > 1 ? to : ""),
|
|
779
|
+
taken.get(from)
|
|
780
|
+
);
|
|
781
|
+
nodeFields.get(from).push({
|
|
782
|
+
kind: "Relational",
|
|
783
|
+
name: outName,
|
|
784
|
+
target: to,
|
|
785
|
+
cardinality: "many",
|
|
786
|
+
optional: false,
|
|
787
|
+
decorators: [relDecorator("OUT")]
|
|
788
|
+
});
|
|
789
|
+
const inName = uniqueName(
|
|
790
|
+
`${camel(rt.type)}By${inSources(to) > 1 ? from : ""}`,
|
|
791
|
+
taken.get(to)
|
|
792
|
+
);
|
|
793
|
+
nodeFields.get(to).push({
|
|
794
|
+
kind: "Relational",
|
|
795
|
+
name: inName,
|
|
796
|
+
target: from,
|
|
797
|
+
cardinality: "many",
|
|
798
|
+
optional: false,
|
|
799
|
+
decorators: [relDecorator("IN")]
|
|
800
|
+
});
|
|
801
|
+
}
|
|
802
|
+
if (rt.properties.length === 0) continue;
|
|
803
|
+
const props = [];
|
|
804
|
+
for (const p of [...rt.properties].sort(
|
|
805
|
+
(a, b) => a.propertyName.localeCompare(b.propertyName)
|
|
806
|
+
)) {
|
|
807
|
+
const t = mapType(p.propertyTypes);
|
|
808
|
+
if (!t || !IDENT2.test(p.propertyName)) {
|
|
809
|
+
warnings.push(`Skipped :${rt.type}.${p.propertyName}: unsupported type or name.`);
|
|
810
|
+
continue;
|
|
811
|
+
}
|
|
812
|
+
const decorators = [];
|
|
813
|
+
if (relUnique.has(`${rt.type}.${p.propertyName}`)) decorators.push(dec("unique"));
|
|
814
|
+
else if (indexOn.has(`RELATIONSHIP:${rt.type}.${p.propertyName}`))
|
|
815
|
+
decorators.push(dec("index"));
|
|
816
|
+
props.push({
|
|
817
|
+
kind: "Scalar",
|
|
818
|
+
name: p.propertyName,
|
|
819
|
+
type: {
|
|
820
|
+
name: t.name,
|
|
821
|
+
optional: !p.mandatory && !t.list,
|
|
822
|
+
...t.list ? { list: true } : {}
|
|
823
|
+
},
|
|
824
|
+
decorators
|
|
825
|
+
});
|
|
826
|
+
}
|
|
827
|
+
for (const { from, to } of pairs) {
|
|
828
|
+
let base = pascal(rt.type) + (pairs.length > 1 ? `${from}${to}` : "");
|
|
829
|
+
if (declNames.has(base)) base += "Rel";
|
|
830
|
+
relationships.push({
|
|
831
|
+
kind: "Relationship",
|
|
832
|
+
name: uniqueName(base, declNames),
|
|
833
|
+
relType: rt.type,
|
|
834
|
+
from,
|
|
835
|
+
to,
|
|
836
|
+
fields: props
|
|
837
|
+
});
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
const nodes = [...nodeFields].map(([name, fields]) => ({
|
|
841
|
+
kind: "Node",
|
|
842
|
+
name,
|
|
843
|
+
fields
|
|
844
|
+
}));
|
|
845
|
+
for (const n of nodes) {
|
|
846
|
+
if (!n.fields.some((f) => f.kind === "Scalar")) {
|
|
847
|
+
warnings.push(`Node ${n.name} has no properties in the database.`);
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
return { doc: { kind: "Document", declarations: [...nodes, ...relationships] }, warnings };
|
|
851
|
+
}
|
|
231
852
|
export {
|
|
232
853
|
CYPHRA_MIGRATION_LABEL,
|
|
854
|
+
EMPTY_SCHEMA_MODEL,
|
|
855
|
+
ENDPOINT_SAMPLE_SIZE,
|
|
233
856
|
applyConstraintStatements,
|
|
234
857
|
compileRenameLabel,
|
|
235
858
|
compileRenameProperty,
|
|
236
859
|
constraintStatementsFromSchema,
|
|
237
860
|
createMigrationDb,
|
|
861
|
+
ddlObjectsFromModel,
|
|
238
862
|
defineMigration,
|
|
863
|
+
diffSchemaModels,
|
|
239
864
|
ensureMigrationInfrastructure,
|
|
240
865
|
indexStatementsFromSchema,
|
|
866
|
+
introspectDatabase,
|
|
867
|
+
isEmptyPlan,
|
|
241
868
|
isMigrationApplied,
|
|
869
|
+
listAppliedMigrations,
|
|
242
870
|
recordMigration,
|
|
871
|
+
renderMigrationSource,
|
|
243
872
|
runPendingMigrations,
|
|
873
|
+
schemaFromIntrospection,
|
|
244
874
|
schemaIntegrationHints,
|
|
245
875
|
wrapInTransactions
|
|
246
876
|
};
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/batch.ts","../src/defineMigration.ts","../src/rename.ts","../src/migrationDb.ts","../src/push.ts","../src/tracker.ts","../src/runner.ts","../src/schemaHints.ts"],"sourcesContent":["/**\n * Neo4j 5+ batching: wrap `inner` in `CALL { … } IN TRANSACTIONS OF n ROWS`.\n *\n * @param innerCypher - Subquery body (without `CALL {` / `}` wrapper).\n * @param batchSize - Rows per transaction.\n * @returns Full Cypher string to pass to `session.run`.\n *\n * @example\n * ```ts\n * const cypher = wrapInTransactions(\n * \"MATCH (u:User) WITH u LIMIT $batchSize SET u.processed = true\",\n * 1000,\n * );\n * ```\n */\nexport function wrapInTransactions(innerCypher: string, batchSize: number): string {\n if (!Number.isInteger(batchSize) || batchSize < 1) {\n throw new Error(`batchSize must be a positive integer, got ${batchSize}`);\n }\n return `CALL {\\n${innerCypher.trim()}\\n} IN TRANSACTIONS OF ${batchSize} ROWS`;\n}\n","import type { MigrationDb } from \"./migrationDb.js\";\n\n/**\n * Versioned migration: `name` is stable; `up` runs once per database.\n */\nexport type MigrationDefinition = {\n readonly name: string;\n readonly up: (ctx: { db: MigrationDb }) => Promise<void>;\n};\n\n/**\n * Define a migration module default export.\n *\n * @param def - Migration name and `up` handler.\n *\n * @example\n * ```ts\n * export default defineMigration({\n * name: \"001_init\",\n * async up({ db }) {\n * await db.run`MERGE (n:Example { id: ${\"seed-1\"} })`;\n * },\n * });\n * ```\n */\nexport function defineMigration(def: MigrationDefinition): MigrationDefinition {\n return def;\n}\n","import type { CompiledCypher } from \"@cyphra/query\";\n\nconst IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\nfunction assertIdent(name: string, label: string): void {\n if (!IDENT.test(name)) {\n throw new Error(`Invalid Neo4j ${label} identifier: ${JSON.stringify(name)}`);\n }\n}\n\n/**\n * Build Cypher to rename a node label (validated identifiers only — not user-controlled strings).\n *\n * @param fromLabel - Current label.\n * @param toLabel - Target label.\n */\nexport function compileRenameLabel(fromLabel: string, toLabel: string): CompiledCypher {\n assertIdent(fromLabel, \"label\");\n assertIdent(toLabel, \"label\");\n return {\n text: `MATCH (n:\\`${fromLabel}\\`) SET n:\\`${toLabel}\\` REMOVE n:\\`${fromLabel}\\``,\n params: {},\n };\n}\n\n/**\n * Build Cypher to rename a property on nodes with a given label.\n *\n * @param label - Node label.\n * @param fromProp - Existing property key.\n * @param toProp - New property key.\n */\nexport function compileRenameProperty(\n label: string,\n fromProp: string,\n toProp: string,\n): CompiledCypher {\n assertIdent(label, \"label\");\n assertIdent(fromProp, \"property\");\n assertIdent(toProp, \"property\");\n return {\n text: `MATCH (n:\\`${label}\\`) WHERE n.\\`${fromProp}\\` IS NOT NULL SET n.\\`${toProp}\\` = n.\\`${fromProp}\\` REMOVE n.\\`${fromProp}\\``,\n params: {},\n };\n}\n","import type { Session } from \"neo4j-driver\";\nimport type { CyphraClient } from \"@cyphra/runtime\";\nimport { wrapInTransactions } from \"./batch.js\";\nimport { compileRenameLabel, compileRenameProperty } from \"./rename.js\";\n\n/**\n * Database handle passed to `up()` in {@link defineMigration}.\n */\nexport type MigrationDb = {\n /**\n * Execute parameterized Cypher (tagged template); values are never concatenated as raw Cypher.\n */\n run(strings: TemplateStringsArray, ...values: unknown[]): Promise<void>;\n /**\n * Run a subquery inside `CALL { … } IN TRANSACTIONS OF n ROWS` (Neo4j 5+).\n * `inner` is the body only (no `CALL` wrapper); it should typically batch work with `LIMIT`/`WITH`.\n *\n * @param opts.inner - Cypher inside the implicit subquery.\n * @param opts.batchSize - Rows per transaction (must be ≥ 1).\n * @param opts.params - Optional parameters for the outer `run`.\n */\n runInTransactionBatches(opts: {\n inner: string;\n batchSize: number;\n params?: Record<string, unknown>;\n }): Promise<void>;\n /** Structural / data helpers (validated identifiers only). */\n readonly migrate: MigrationMigrateHelpers;\n};\n\nexport type MigrationMigrateHelpers = {\n renameLabel(opts: { from: string; to: string }): Promise<void>;\n renameProperty(opts: { label: string; from: string; to: string }): Promise<void>;\n};\n\n/**\n * Build a {@link MigrationDb} bound to one open session (one migration transaction policy).\n *\n * @param client - Cyphra runtime client.\n * @param session - Neo4j session (caller manages lifecycle).\n */\nexport function createMigrationDb(client: CyphraClient, session: Session): MigrationDb {\n const run = async (strings: TemplateStringsArray, ...values: unknown[]): Promise<void> => {\n const result = await client.runCypher(session, strings, ...values);\n await result;\n };\n\n const runInTransactionBatches = async (opts: {\n inner: string;\n batchSize: number;\n params?: Record<string, unknown>;\n }): Promise<void> => {\n const text = wrapInTransactions(opts.inner, opts.batchSize);\n const result = await session.run(text, opts.params ?? {});\n await result;\n };\n\n const migrate: MigrationMigrateHelpers = {\n async renameLabel(opts) {\n const { text, params } = compileRenameLabel(opts.from, opts.to);\n await session.run(text, params);\n },\n async renameProperty(opts) {\n const { text, params } = compileRenameProperty(opts.label, opts.from, opts.to);\n await session.run(text, params);\n },\n };\n\n return { run, runInTransactionBatches, migrate };\n}\n","import type { NodeDeclaration, ScalarNodeField, SchemaDocument } from \"@cyphra/schema\";\n\nfunction isScalarWithDecorator(\n field: { readonly kind: string; readonly decorators: readonly { readonly name: string }[] },\n dec: string,\n): field is ScalarNodeField {\n return field.kind === \"Scalar\" && field.decorators.some((d) => d.name === dec);\n}\n\n/** Decorator presence without a type predicate (avoids `never` when chaining multiple `@…` checks). */\nfunction hasDecoratorName(\n field: { readonly decorators: readonly { readonly name: string }[] },\n name: string,\n): boolean {\n return field.decorators.some((d) => d.name === name);\n}\n\n/** Cypher relationship type token for patterns (`:KNOWS` or :`a-b`). */\nfunction cypherRelTypeToken(relType: string): string {\n if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(relType)) {\n return relType;\n }\n return `\\`${relType.replace(/`/g, \"``\")}\\``;\n}\n\nfunction idPropertyName(node: NodeDeclaration): string | undefined {\n for (const f of node.fields) {\n if (isScalarWithDecorator(f, \"id\")) {\n return f.name;\n }\n }\n return undefined;\n}\n\n/**\n * Generate `CREATE CONSTRAINT … IF NOT EXISTS` statements for node `@id` / `@unique` and relationship `@unique`.\n *\n * Relationship property uniqueness uses Neo4j 5.7+ syntax (`FOR ()-[r:TYPE]-() REQUIRE r.prop IS UNIQUE`).\n *\n * @param doc - Parsed schema AST.\n * @returns Cypher DDL strings (Neo4j 5 syntax).\n */\nexport function constraintStatementsFromSchema(doc: SchemaDocument): string[] {\n const statements: string[] = [];\n for (const decl of doc.declarations) {\n if (decl.kind === \"Node\") {\n const label = decl.name;\n const idProp = idPropertyName(decl);\n if (idProp) {\n statements.push(\n `CREATE CONSTRAINT ${escapeConstraintName(`${label}_${idProp}_id`)} IF NOT EXISTS FOR (n:\\`${label}\\`) REQUIRE n.\\`${idProp}\\` IS UNIQUE`,\n );\n }\n for (const f of decl.fields) {\n if (!isScalarWithDecorator(f, \"unique\")) {\n continue;\n }\n if (f.name === idProp) {\n continue;\n }\n statements.push(\n `CREATE CONSTRAINT ${escapeConstraintName(`${label}_${f.name}_unique`)} IF NOT EXISTS FOR (n:\\`${label}\\`) REQUIRE n.\\`${f.name}\\` IS UNIQUE`,\n );\n }\n continue;\n }\n\n const typeTok = cypherRelTypeToken(decl.relType);\n for (const f of decl.fields) {\n if (!isScalarWithDecorator(f, \"unique\")) {\n continue;\n }\n statements.push(\n `CREATE CONSTRAINT ${escapeConstraintName(`${decl.name}_${f.name}_rel_unique`)} IF NOT EXISTS FOR ()-[r:${typeTok}]-() REQUIRE r.\\`${f.name}\\` IS UNIQUE`,\n );\n }\n }\n return statements;\n}\n\n/**\n * Generate `CREATE RANGE INDEX … IF NOT EXISTS` for `@index` on **node** scalars and on **relationship** model scalars.\n * Node indexes use `(n:Label)`; relationship indexes use `()-[r:TYPE]-()` with the Neo4j type from `type \"…\"`.\n *\n * @param doc - Parsed schema AST.\n * @returns Cypher DDL strings (Neo4j 5+ range index syntax).\n */\nexport function indexStatementsFromSchema(doc: SchemaDocument): string[] {\n const statements: string[] = [];\n for (const decl of doc.declarations) {\n if (decl.kind === \"Node\") {\n const label = decl.name;\n for (const f of decl.fields) {\n if (f.kind !== \"Scalar\") {\n continue;\n }\n if (!isScalarWithDecorator(f, \"index\")) {\n continue;\n }\n if (hasDecoratorName(f, \"unique\")) {\n continue;\n }\n statements.push(\n `CREATE RANGE INDEX ${escapeConstraintName(`${label}_${f.name}_idx`)} IF NOT EXISTS FOR (n:\\`${label}\\`) ON (n.\\`${f.name}\\`)`,\n );\n }\n continue;\n }\n\n const typeTok = cypherRelTypeToken(decl.relType);\n for (const f of decl.fields) {\n if (!isScalarWithDecorator(f, \"index\")) {\n continue;\n }\n if (hasDecoratorName(f, \"unique\")) {\n continue;\n }\n statements.push(\n `CREATE RANGE INDEX ${escapeConstraintName(`${decl.name}_${f.name}_rel_idx`)} IF NOT EXISTS FOR ()-[r:${typeTok}]-() ON (r.\\`${f.name}\\`)`,\n );\n }\n }\n return statements;\n}\n\nfunction escapeConstraintName(name: string): string {\n return name.replace(/[^A-Za-z0-9_]/g, \"_\");\n}\n","import type { Session } from \"neo4j-driver\";\n\n/** Neo4j label used to record applied migrations. */\nexport const CYPHRA_MIGRATION_LABEL = \"__CyphraMigration\";\n\n/**\n * Ensure uniqueness on migration name (idempotent).\n *\n * @param session - Open session.\n */\nexport async function ensureMigrationInfrastructure(session: Session): Promise<void> {\n const r = await session.run(`\n CREATE CONSTRAINT cyphra_migration_name_unique IF NOT EXISTS\n FOR (m:__CyphraMigration) REQUIRE m.name IS UNIQUE\n `);\n await r;\n}\n\n/**\n * @param session - Open session.\n * @param name - Migration name (e.g. file stem).\n */\nexport async function isMigrationApplied(session: Session, name: string): Promise<boolean> {\n const result = await session.run(\n `MATCH (m:__CyphraMigration { name: $name }) RETURN m AS m LIMIT 1`,\n { name },\n );\n const q = await result;\n return q.records.length > 0;\n}\n\n/**\n * Persist a successful migration.\n *\n * @param session - Open session.\n * @param name - Migration name.\n * @param checksum - Content checksum (e.g. SHA-256 hex).\n */\nexport async function recordMigration(\n session: Session,\n name: string,\n checksum: string,\n): Promise<void> {\n const r = await session.run(\n `\n CREATE (m:__CyphraMigration {\n name: $name,\n appliedAt: datetime(),\n checksum: $checksum\n })\n `,\n { name, checksum },\n );\n await r;\n}\n","import type { CyphraClient } from \"@cyphra/runtime\";\nimport { createMigrationDb } from \"./migrationDb.js\";\nimport type { MigrationDefinition } from \"./defineMigration.js\";\nimport * as tracker from \"./tracker.js\";\n\n/** Migration with precomputed checksum (e.g. SHA-256 of source file). */\nexport type LoadedMigration = {\n readonly name: string;\n readonly checksum: string;\n readonly definition: MigrationDefinition;\n};\n\n/**\n * Apply migrations in order, skipping those already recorded on `__CyphraMigration`.\n *\n * @param client - Cyphra client.\n * @param ordered - Migrations sorted lexicographically by `name` (caller responsibility).\n * @returns Names that were applied in this run.\n */\nexport async function runPendingMigrations(\n client: CyphraClient,\n ordered: readonly LoadedMigration[],\n): Promise<readonly string[]> {\n const applied: string[] = [];\n await client.withSession(async (session) => {\n await tracker.ensureMigrationInfrastructure(session);\n for (const m of ordered) {\n if (await tracker.isMigrationApplied(session, m.name)) {\n continue;\n }\n const db = createMigrationDb(client, session);\n await m.definition.up({ db });\n await tracker.recordMigration(session, m.name, m.checksum);\n applied.push(m.name);\n }\n });\n return applied;\n}\n\n/**\n * Execute DDL statements (e.g. from {@link constraintStatementsFromSchema}).\n *\n * @param client - Cyphra client.\n * @param statements - Cypher DDL, one statement per string.\n */\nexport async function applyConstraintStatements(\n client: CyphraClient,\n statements: readonly string[],\n): Promise<void> {\n await client.withSession(async (session) => {\n for (const statement of statements) {\n const r = await session.run(statement);\n await r;\n }\n });\n}\n","import type { SchemaDocument } from \"@cyphra/schema\";\n\n/**\n * Static hints for operating a database alongside the schema (no live DB inspection in V1).\n *\n * @param doc - Parsed schema document.\n * @returns Human-readable lines suitable for logs or docs.\n */\nexport function schemaIntegrationHints(doc: SchemaDocument): string[] {\n const hints: string[] = [];\n for (const d of doc.declarations) {\n if (d.kind === \"Relationship\") {\n hints.push(\n `Relationship model \"${d.name}\" maps to Neo4j type \\`${d.relType}\\` (:${d.from} → :${d.to}).`,\n );\n }\n }\n return hints;\n}\n"],"mappings":";AAeO,SAAS,mBAAmB,aAAqB,WAA2B;AACjF,MAAI,CAAC,OAAO,UAAU,SAAS,KAAK,YAAY,GAAG;AACjD,UAAM,IAAI,MAAM,6CAA6C,SAAS,EAAE;AAAA,EAC1E;AACA,SAAO;AAAA,EAAW,YAAY,KAAK,CAAC;AAAA,uBAA0B,SAAS;AACzE;;;ACKO,SAAS,gBAAgB,KAA+C;AAC7E,SAAO;AACT;;;ACzBA,IAAM,QAAQ;AAEd,SAAS,YAAY,MAAc,OAAqB;AACtD,MAAI,CAAC,MAAM,KAAK,IAAI,GAAG;AACrB,UAAM,IAAI,MAAM,iBAAiB,KAAK,gBAAgB,KAAK,UAAU,IAAI,CAAC,EAAE;AAAA,EAC9E;AACF;AAQO,SAAS,mBAA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ration.ts","../src/migrationDb.ts","../src/rename.ts","../src/push.ts","../src/tracker.ts","../src/runner.ts","../src/schemaHints.ts","../src/diff.ts","../src/renderMigration.ts","../src/introspect.ts"],"sourcesContent":["/**\n * Neo4j 5+ batching: wrap `inner` in `CALL { … } IN TRANSACTIONS OF n ROWS`.\n *\n * @param innerCypher - Subquery body (without `CALL {` / `}` wrapper).\n * @param batchSize - Rows per transaction.\n * @returns Full Cypher string to pass to `session.run`.\n *\n * @example\n * ```ts\n * const cypher = wrapInTransactions(\n * \"MATCH (u:User) WITH u LIMIT $batchSize SET u.processed = true\",\n * 1000,\n * );\n * ```\n */\nexport function wrapInTransactions(innerCypher: string, batchSize: number): string {\n if (!Number.isInteger(batchSize) || batchSize < 1) {\n throw new Error(`batchSize must be a positive integer, got ${batchSize}`);\n }\n return `CALL {\\n${innerCypher.trim()}\\n} IN TRANSACTIONS OF ${batchSize} ROWS`;\n}\n","import type { MigrationDb } from \"./migrationDb.js\";\n\n/**\n * Versioned migration: `name` is stable; `up` runs once per database.\n */\nexport type MigrationDefinition = {\n readonly name: string;\n readonly up: (ctx: { db: MigrationDb }) => Promise<void>;\n};\n\n/**\n * Define a migration module default export.\n *\n * @param def - Migration name and `up` handler.\n *\n * @example\n * ```ts\n * export default defineMigration({\n * name: \"001_init\",\n * async up({ db }) {\n * await db.run`MERGE (n:Example { id: ${\"seed-1\"} })`;\n * },\n * });\n * ```\n */\nexport function defineMigration(def: MigrationDefinition): MigrationDefinition {\n return def;\n}\n","import type { Session } from \"neo4j-driver\";\nimport { toNative, type CyphraClient } from \"@cyphra/runtime\";\nimport { wrapInTransactions } from \"./batch.js\";\nimport { compileRenameLabel, compileRenameProperty } from \"./rename.js\";\n\n/**\n * Database handle passed to `up()` in {@link defineMigration}.\n */\nexport type MigrationDb = {\n /**\n * Execute parameterized Cypher (tagged template); values are never concatenated as raw Cypher.\n */\n run(strings: TemplateStringsArray, ...values: unknown[]): Promise<void>;\n /**\n * Run a subquery inside `CALL { … } IN TRANSACTIONS OF n ROWS` (Neo4j 5+).\n * `inner` is the body only (no `CALL` wrapper); it should typically batch work with `LIMIT`/`WITH`.\n *\n * @param opts.inner - Cypher inside the implicit subquery.\n * @param opts.batchSize - Rows per transaction (must be ≥ 1).\n * @param opts.params - Optional parameters for the outer `run`.\n */\n runInTransactionBatches(opts: {\n inner: string;\n batchSize: number;\n params?: Record<string, unknown>;\n }): Promise<void>;\n /**\n * Execute a Cypher statement given as **trusted text** (used by generated migrations for DDL, which\n * cannot be parameterized). Pass values through `params`, never by string concatenation.\n *\n * @returns Rows as plain JS objects (integers → number, temporals → Date).\n */\n execute(text: string, params?: Record<string, unknown>): Promise<Record<string, unknown>[]>;\n /** Structural / data helpers (validated identifiers only). */\n readonly migrate: MigrationMigrateHelpers;\n};\n\nexport type MigrationMigrateHelpers = {\n renameLabel(opts: { from: string; to: string }): Promise<void>;\n renameProperty(opts: { label: string; from: string; to: string }): Promise<void>;\n};\n\n/**\n * Build a {@link MigrationDb} bound to one open session (one migration transaction policy).\n *\n * @param client - Cyphra runtime client.\n * @param session - Neo4j session (caller manages lifecycle).\n */\nexport function createMigrationDb(client: CyphraClient, session: Session): MigrationDb {\n const run = async (strings: TemplateStringsArray, ...values: unknown[]): Promise<void> => {\n const result = await client.runCypher(session, strings, ...values);\n await result;\n };\n\n const runInTransactionBatches = async (opts: {\n inner: string;\n batchSize: number;\n params?: Record<string, unknown>;\n }): Promise<void> => {\n const text = wrapInTransactions(opts.inner, opts.batchSize);\n const result = await session.run(text, opts.params ?? {});\n await result;\n };\n\n const migrate: MigrationMigrateHelpers = {\n async renameLabel(opts) {\n const { text, params } = compileRenameLabel(opts.from, opts.to);\n await session.run(text, params);\n },\n async renameProperty(opts) {\n const { text, params } = compileRenameProperty(opts.label, opts.from, opts.to);\n await session.run(text, params);\n },\n };\n\n const execute = async (\n text: string,\n params: Record<string, unknown> = {},\n ): Promise<Record<string, unknown>[]> => {\n const result = await session.run(text, params);\n return result.records.map((r) => toNative(r.toObject()) as Record<string, unknown>);\n };\n\n return { run, runInTransactionBatches, execute, migrate };\n}\n","import type { CompiledCypher } from \"@cyphra/query\";\n\nconst IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\nfunction assertIdent(name: string, label: string): void {\n if (!IDENT.test(name)) {\n throw new Error(`Invalid Neo4j ${label} identifier: ${JSON.stringify(name)}`);\n }\n}\n\n/**\n * Build Cypher to rename a node label (validated identifiers only — not user-controlled strings).\n *\n * @param fromLabel - Current label.\n * @param toLabel - Target label.\n */\nexport function compileRenameLabel(fromLabel: string, toLabel: string): CompiledCypher {\n assertIdent(fromLabel, \"label\");\n assertIdent(toLabel, \"label\");\n return {\n text: `MATCH (n:\\`${fromLabel}\\`) SET n:\\`${toLabel}\\` REMOVE n:\\`${fromLabel}\\``,\n params: {},\n };\n}\n\n/**\n * Build Cypher to rename a property on nodes with a given label.\n *\n * @param label - Node label.\n * @param fromProp - Existing property key.\n * @param toProp - New property key.\n */\nexport function compileRenameProperty(\n label: string,\n fromProp: string,\n toProp: string,\n): CompiledCypher {\n assertIdent(label, \"label\");\n assertIdent(fromProp, \"property\");\n assertIdent(toProp, \"property\");\n return {\n text: `MATCH (n:\\`${label}\\`) WHERE n.\\`${fromProp}\\` IS NOT NULL SET n.\\`${toProp}\\` = n.\\`${fromProp}\\` REMOVE n.\\`${fromProp}\\``,\n params: {},\n };\n}\n","import type { NodeDeclaration, ScalarNodeField, SchemaDocument } from \"@cyphra/schema\";\n\nfunction isScalarWithDecorator(\n field: { readonly kind: string; readonly decorators: readonly { readonly name: string }[] },\n dec: string,\n): field is ScalarNodeField {\n return field.kind === \"Scalar\" && field.decorators.some((d) => d.name === dec);\n}\n\n/** Decorator presence without a type predicate (avoids `never` when chaining multiple `@…` checks). */\nfunction hasDecoratorName(\n field: { readonly decorators: readonly { readonly name: string }[] },\n name: string,\n): boolean {\n return field.decorators.some((d) => d.name === name);\n}\n\n/** Cypher relationship type token for patterns (`:KNOWS` or :`a-b`). */\nfunction cypherRelTypeToken(relType: string): string {\n if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(relType)) {\n return relType;\n }\n return `\\`${relType.replace(/`/g, \"``\")}\\``;\n}\n\nfunction idPropertyName(node: NodeDeclaration): string | undefined {\n for (const f of node.fields) {\n if (isScalarWithDecorator(f, \"id\")) {\n return f.name;\n }\n }\n return undefined;\n}\n\n/**\n * Generate `CREATE CONSTRAINT … IF NOT EXISTS` statements for node `@id` / `@unique` and relationship `@unique`.\n *\n * Relationship property uniqueness uses Neo4j 5.7+ syntax (`FOR ()-[r:TYPE]-() REQUIRE r.prop IS UNIQUE`).\n *\n * @param doc - Parsed schema AST.\n * @returns Cypher DDL strings (Neo4j 5 syntax).\n */\nexport function constraintStatementsFromSchema(doc: SchemaDocument): string[] {\n const statements: string[] = [];\n for (const decl of doc.declarations) {\n if (decl.kind === \"Node\") {\n const label = decl.name;\n const idProp = idPropertyName(decl);\n if (idProp) {\n statements.push(\n `CREATE CONSTRAINT ${escapeConstraintName(`${label}_${idProp}_id`)} IF NOT EXISTS FOR (n:\\`${label}\\`) REQUIRE n.\\`${idProp}\\` IS UNIQUE`,\n );\n }\n for (const f of decl.fields) {\n if (!isScalarWithDecorator(f, \"unique\")) {\n continue;\n }\n if (f.name === idProp) {\n continue;\n }\n statements.push(\n `CREATE CONSTRAINT ${escapeConstraintName(`${label}_${f.name}_unique`)} IF NOT EXISTS FOR (n:\\`${label}\\`) REQUIRE n.\\`${f.name}\\` IS UNIQUE`,\n );\n }\n continue;\n }\n\n const typeTok = cypherRelTypeToken(decl.relType);\n for (const f of decl.fields) {\n if (!isScalarWithDecorator(f, \"unique\")) {\n continue;\n }\n statements.push(\n `CREATE CONSTRAINT ${escapeConstraintName(`${decl.name}_${f.name}_rel_unique`)} IF NOT EXISTS FOR ()-[r:${typeTok}]-() REQUIRE r.\\`${f.name}\\` IS UNIQUE`,\n );\n }\n }\n return statements;\n}\n\n/**\n * Generate `CREATE RANGE INDEX … IF NOT EXISTS` for `@index` on **node** scalars and on **relationship** model scalars.\n * Node indexes use `(n:Label)`; relationship indexes use `()-[r:TYPE]-()` with the Neo4j type from `type \"…\"`.\n *\n * @param doc - Parsed schema AST.\n * @returns Cypher DDL strings (Neo4j 5+ range index syntax).\n */\nexport function indexStatementsFromSchema(doc: SchemaDocument): string[] {\n const statements: string[] = [];\n for (const decl of doc.declarations) {\n if (decl.kind === \"Node\") {\n const label = decl.name;\n for (const f of decl.fields) {\n if (f.kind !== \"Scalar\") {\n continue;\n }\n if (!isScalarWithDecorator(f, \"index\")) {\n continue;\n }\n if (hasDecoratorName(f, \"unique\")) {\n continue;\n }\n statements.push(\n `CREATE RANGE INDEX ${escapeConstraintName(`${label}_${f.name}_idx`)} IF NOT EXISTS FOR (n:\\`${label}\\`) ON (n.\\`${f.name}\\`)`,\n );\n }\n continue;\n }\n\n const typeTok = cypherRelTypeToken(decl.relType);\n for (const f of decl.fields) {\n if (!isScalarWithDecorator(f, \"index\")) {\n continue;\n }\n if (hasDecoratorName(f, \"unique\")) {\n continue;\n }\n statements.push(\n `CREATE RANGE INDEX ${escapeConstraintName(`${decl.name}_${f.name}_rel_idx`)} IF NOT EXISTS FOR ()-[r:${typeTok}]-() ON (r.\\`${f.name}\\`)`,\n );\n }\n }\n return statements;\n}\n\nfunction escapeConstraintName(name: string): string {\n return name.replace(/[^A-Za-z0-9_]/g, \"_\");\n}\n","import type { Session } from \"neo4j-driver\";\n\n/** Neo4j label used to record applied migrations. */\nexport const CYPHRA_MIGRATION_LABEL = \"__CyphraMigration\";\n\n/**\n * Ensure uniqueness on migration name (idempotent).\n *\n * @param session - Open session.\n */\nexport async function ensureMigrationInfrastructure(session: Session): Promise<void> {\n const r = await session.run(`\n CREATE CONSTRAINT cyphra_migration_name_unique IF NOT EXISTS\n FOR (m:__CyphraMigration) REQUIRE m.name IS UNIQUE\n `);\n await r;\n}\n\n/**\n * @param session - Open session.\n * @param name - Migration name (e.g. file stem).\n */\nexport async function isMigrationApplied(session: Session, name: string): Promise<boolean> {\n const result = await session.run(\n `MATCH (m:__CyphraMigration { name: $name }) RETURN m AS m LIMIT 1`,\n { name },\n );\n const q = await result;\n return q.records.length > 0;\n}\n\n/**\n * Persist a successful migration.\n *\n * @param session - Open session.\n * @param name - Migration name.\n * @param checksum - Content checksum (e.g. SHA-256 hex).\n */\nexport async function recordMigration(\n session: Session,\n name: string,\n checksum: string,\n): Promise<void> {\n const r = await session.run(\n `\n CREATE (m:__CyphraMigration {\n name: $name,\n appliedAt: datetime(),\n checksum: $checksum\n })\n `,\n { name, checksum },\n );\n await r;\n}\n\nexport type AppliedMigration = {\n readonly name: string;\n readonly checksum: string | null;\n readonly appliedAt: Date | null;\n};\n\n/**\n * List applied migrations, oldest first.\n *\n * @param session - Open session.\n */\nexport async function listAppliedMigrations(session: Session): Promise<AppliedMigration[]> {\n const result = await session.run(\n `MATCH (m:__CyphraMigration) RETURN m.name AS name, m.checksum AS checksum, m.appliedAt AS appliedAt ORDER BY m.appliedAt, m.name`,\n );\n return result.records.map((r) => {\n const at = r.get(\"appliedAt\") as { toStandardDate?: () => Date } | null;\n return {\n name: r.get(\"name\") as string,\n checksum: (r.get(\"checksum\") as string | null) ?? null,\n appliedAt: at?.toStandardDate ? at.toStandardDate() : null,\n };\n });\n}\n","import type { CyphraClient } from \"@cyphra/runtime\";\nimport { createMigrationDb } from \"./migrationDb.js\";\nimport type { MigrationDefinition } from \"./defineMigration.js\";\nimport * as tracker from \"./tracker.js\";\n\n/** Migration with precomputed checksum (e.g. SHA-256 of source file). */\nexport type LoadedMigration = {\n readonly name: string;\n readonly checksum: string;\n readonly definition: MigrationDefinition;\n};\n\n/**\n * Apply migrations in order, skipping those already recorded on `__CyphraMigration`.\n *\n * @param client - Cyphra client.\n * @param ordered - Migrations sorted lexicographically by `name` (caller responsibility).\n * @returns Names that were applied in this run.\n */\nexport async function runPendingMigrations(\n client: CyphraClient,\n ordered: readonly LoadedMigration[],\n): Promise<readonly string[]> {\n const applied: string[] = [];\n await client.withSession(async (session) => {\n await tracker.ensureMigrationInfrastructure(session);\n for (const m of ordered) {\n if (await tracker.isMigrationApplied(session, m.name)) {\n continue;\n }\n const db = createMigrationDb(client, session);\n await m.definition.up({ db });\n await tracker.recordMigration(session, m.name, m.checksum);\n applied.push(m.name);\n }\n });\n return applied;\n}\n\n/**\n * Execute DDL statements (e.g. from {@link constraintStatementsFromSchema}).\n *\n * @param client - Cyphra client.\n * @param statements - Cypher DDL, one statement per string.\n */\nexport async function applyConstraintStatements(\n client: CyphraClient,\n statements: readonly string[],\n): Promise<void> {\n await client.withSession(async (session) => {\n for (const statement of statements) {\n const r = await session.run(statement);\n await r;\n }\n });\n}\n","import type { SchemaDocument } from \"@cyphra/schema\";\n\n/**\n * Static hints for operating a database alongside the schema (no live DB inspection in V1).\n *\n * @param doc - Parsed schema document.\n * @returns Human-readable lines suitable for logs or docs.\n */\nexport function schemaIntegrationHints(doc: SchemaDocument): string[] {\n const hints: string[] = [];\n for (const d of doc.declarations) {\n if (d.kind === \"Relationship\") {\n hints.push(\n `Relationship model \"${d.name}\" maps to Neo4j type \\`${d.relType}\\` (:${d.from} → :${d.to}).`,\n );\n }\n }\n return hints;\n}\n","/**\n * Schema diffing: compare two {@link SchemaModel}s (the snapshot taken at the last migration and the\n * current schema) and plan the migration that takes a database from one to the other.\n *\n * Neo4j is schemaless, so the plan has two parts:\n * - **DDL**: uniqueness constraints and range indexes, named exactly like `cyphra push` names them.\n * - **Data steps**: backfills for new defaults, guards for newly required fields, and\n * (commented-out) destructive cleanups for removed fields and models.\n *\n * @packageDocumentation\n */\n\nimport type {\n ResolvedNodeModel,\n ResolvedRelationshipModel,\n ResolvedScalarField,\n SchemaModel,\n} from \"@cyphra/schema\";\n\nfunction q(id: string): string {\n return \"`\" + id.replace(/`/g, \"``\") + \"`\";\n}\n\nfunction constraintName(name: string): string {\n return name.replace(/[^A-Za-z0-9_]/g, \"_\");\n}\n\n/** One named schema object (constraint or index) and the statement that creates it. */\nexport type DdlObject = {\n readonly name: string;\n readonly kind: \"constraint\" | \"index\";\n readonly create: string;\n};\n\n/**\n * Constraints and range indexes implied by a schema model. Names match\n * {@link import(\"./push.js\").constraintStatementsFromSchema} so `push` and migrations interoperate.\n */\nexport function ddlObjectsFromModel(model: SchemaModel): DdlObject[] {\n const out: DdlObject[] = [];\n for (const n of model.nodes) {\n const scalars = n.fields.filter((f): f is ResolvedScalarField => f.kind === \"scalar\");\n for (const f of scalars) {\n const target = `FOR (n:${q(n.label)})`;\n if (f.id) {\n const name = constraintName(`${n.label}_${f.name}_id`);\n out.push({\n name,\n kind: \"constraint\",\n create: `CREATE CONSTRAINT ${name} IF NOT EXISTS ${target} REQUIRE n.${q(f.name)} IS UNIQUE`,\n });\n } else if (f.unique) {\n const name = constraintName(`${n.label}_${f.name}_unique`);\n out.push({\n name,\n kind: \"constraint\",\n create: `CREATE CONSTRAINT ${name} IF NOT EXISTS ${target} REQUIRE n.${q(f.name)} IS UNIQUE`,\n });\n } else if (f.index) {\n const name = constraintName(`${n.label}_${f.name}_idx`);\n out.push({\n name,\n kind: \"index\",\n create: `CREATE RANGE INDEX ${name} IF NOT EXISTS ${target} ON (n.${q(f.name)})`,\n });\n }\n }\n }\n for (const r of model.relationships) {\n const target = `FOR ()-[r:${q(r.relType)}]-()`;\n for (const f of r.properties) {\n if (f.unique) {\n const name = constraintName(`${r.name}_${f.name}_rel_unique`);\n out.push({\n name,\n kind: \"constraint\",\n create: `CREATE CONSTRAINT ${name} IF NOT EXISTS ${target} REQUIRE r.${q(f.name)} IS UNIQUE`,\n });\n } else if (f.index) {\n const name = constraintName(`${r.name}_${f.name}_rel_idx`);\n out.push({\n name,\n kind: \"index\",\n create: `CREATE RANGE INDEX ${name} IF NOT EXISTS ${target} ON (r.${q(f.name)})`,\n });\n }\n }\n }\n return out;\n}\n\n/** A step of the planned migration. */\nexport type MigrationStep =\n | {\n /** Statement executed as-is. */\n readonly kind: \"statement\";\n readonly comment: string;\n readonly cypher: string;\n readonly params?: Readonly<Record<string, unknown>>;\n }\n | {\n /** Fails the migration if the query returns a non-zero `count`. */\n readonly kind: \"guard\";\n readonly comment: string;\n readonly countCypher: string;\n readonly message: string;\n }\n | {\n /** Destructive statement emitted commented-out: the author must opt in. */\n readonly kind: \"destructive\";\n readonly comment: string;\n readonly cypher: string;\n };\n\nexport type MigrationPlan = {\n readonly steps: readonly MigrationStep[];\n /** Things a human should review (type changes, likely renames, …). */\n readonly warnings: readonly string[];\n};\n\n/** An empty schema, used as the \"previous\" side for a project's first migration. */\nexport const EMPTY_SCHEMA_MODEL: SchemaModel = { version: 1, nodes: [], relationships: [] };\n\nfunction scalarsOf(n: ResolvedNodeModel): Map<string, ResolvedScalarField> {\n return new Map(\n n.fields.filter((f): f is ResolvedScalarField => f.kind === \"scalar\").map((f) => [f.name, f]),\n );\n}\n\nfunction typeLabel(f: ResolvedScalarField): string {\n return f.list ? `${f.type}[]` : f.optional ? `${f.type}?` : f.type;\n}\n\n/** Cypher expression that produces the default of `f`, plus params, or `null` if not expressible. */\nfunction defaultExpression(\n f: ResolvedScalarField,\n): { expr: string; params?: Record<string, unknown>; note?: string } | null {\n const d = f.default;\n if (!d) return null;\n if (d.kind === \"literal\") {\n if (f.type === \"Int\") return { expr: `toInteger($value)`, params: { value: d.value } };\n return { expr: \"$value\", params: { value: d.value } };\n }\n if (d.fn === \"now\") return { expr: f.type === \"Date\" ? \"date()\" : \"datetime()\" };\n if (d.fn === \"uuid\") return { expr: \"randomUUID()\" };\n return {\n expr: \"randomUUID()\",\n note: \"cuid() cannot be generated in Cypher; existing nodes get a UUID instead\",\n };\n}\n\nfunction nodeDataSteps(\n label: string,\n model: string,\n name: string,\n before: ResolvedScalarField | undefined,\n after: ResolvedScalarField,\n steps: MigrationStep[],\n warnings: string[],\n): void {\n const ref = `n.${q(name)}`;\n const match = `MATCH (n:${q(label)}) WHERE ${ref} IS NULL`;\n const nowRequired = !after.optional && !after.list;\n const wasRequired = before ? !before.optional && !before.list : false;\n\n if (before && before.type !== after.type) {\n warnings.push(\n `${model}.${name} changed type ${typeLabel(before)} → ${typeLabel(after)}; existing values are not converted. Add a conversion step (e.g. SET ${ref} = toInteger(${ref})) if needed.`,\n );\n }\n if (before && before.list !== after.list) {\n warnings.push(\n `${model}.${name} changed between list and single value; convert existing data manually.`,\n );\n }\n\n const def = defaultExpression(after);\n if (def && (!before || (nowRequired && !wasRequired))) {\n steps.push({\n kind: \"statement\",\n comment: `Backfill ${model}.${name} with its default on existing nodes${def.note ? ` (${def.note})` : \"\"}.`,\n cypher: `${match} SET ${ref} = ${def.expr}`,\n ...(def.params ? { params: def.params } : {}),\n });\n return;\n }\n if (nowRequired && !wasRequired) {\n steps.push({\n kind: \"guard\",\n comment: `${model}.${name} is now required and has no default: make sure no existing node lacks it.`,\n countCypher: `${match} RETURN count(n) AS count`,\n message: `${model}.${name} is required but some existing ${label} nodes do not have it. Backfill them in this migration before the guard (or add a @default).`,\n });\n }\n}\n\n/**\n * Plan the migration from `prev` to `next`.\n *\n * @param prev - Schema at the last migration ({@link EMPTY_SCHEMA_MODEL} for the first one).\n * @param next - Current schema.\n */\nexport function diffSchemaModels(prev: SchemaModel, next: SchemaModel): MigrationPlan {\n // Order: drop obsolete DDL → fix up data (backfills, guards) → create new DDL, so that e.g. a\n // backfilled @id gets its values before the uniqueness constraint is created.\n const drops: MigrationStep[] = [];\n const creates: MigrationStep[] = [];\n const steps: MigrationStep[] = [];\n const warnings: string[] = [];\n\n // --- DDL -----------------------------------------------------------------\n const before = new Map(ddlObjectsFromModel(prev).map((o) => [o.name, o]));\n const after = new Map(ddlObjectsFromModel(next).map((o) => [o.name, o]));\n for (const [name, o] of before) {\n const n = after.get(name);\n if (!n || n.create !== o.create) {\n drops.push({\n kind: \"statement\",\n comment: `Drop ${o.kind} ${name}.`,\n cypher: `DROP ${o.kind === \"constraint\" ? \"CONSTRAINT\" : \"INDEX\"} ${name} IF EXISTS`,\n });\n }\n }\n for (const [name, o] of after) {\n const p = before.get(name);\n if (!p || p.create !== o.create) {\n creates.push({ kind: \"statement\", comment: `Create ${o.kind} ${name}.`, cypher: o.create });\n }\n }\n\n // --- Node data -----------------------------------------------------------\n const prevNodes = new Map(prev.nodes.map((n) => [n.name, n]));\n const nextNodes = new Map(next.nodes.map((n) => [n.name, n]));\n\n const removedNodes = prev.nodes.filter((n) => !nextNodes.has(n.name));\n const addedNodes = next.nodes.filter((n) => !prevNodes.has(n.name));\n for (const r of removedNodes) {\n steps.push({\n kind: \"destructive\",\n comment: `Model ${r.name} was removed. Uncomment to delete its nodes (or rename the label instead: db.migrate.renameLabel).`,\n cypher: `MATCH (n:${q(r.label)}) DETACH DELETE n`,\n });\n }\n if (removedNodes.length && addedNodes.length) {\n warnings.push(\n `Models removed (${removedNodes.map((n) => n.name).join(\", \")}) and added (${addedNodes.map((n) => n.name).join(\", \")}): if this is a rename, replace the generated steps with db.migrate.renameLabel({ from, to }).`,\n );\n }\n\n for (const n of next.nodes) {\n const p = prevNodes.get(n.name);\n if (!p) continue; // new model: no existing nodes to fix up\n const ps = scalarsOf(p);\n const ns = scalarsOf(n);\n const removed = [...ps.keys()].filter((k) => !ns.has(k));\n const added = [...ns.keys()].filter((k) => !ps.has(k));\n for (const [name, f] of ns) {\n nodeDataSteps(n.label, n.name, name, ps.get(name), f, steps, warnings);\n }\n for (const name of removed) {\n steps.push({\n kind: \"destructive\",\n comment: `${n.name}.${name} was removed. Uncomment to delete the property from existing nodes.`,\n cypher: `MATCH (n:${q(n.label)}) WHERE n.${q(name)} IS NOT NULL REMOVE n.${q(name)}`,\n });\n }\n if (removed.length && added.length) {\n warnings.push(\n `${n.name}: fields removed (${removed.join(\", \")}) and added (${added.join(\", \")}). If this is a rename, use db.migrate.renameProperty({ label: ${JSON.stringify(n.label)}, from, to }) instead of the generated steps.`,\n );\n }\n }\n\n // --- Relationship models ---------------------------------------------------\n const prevRels = new Map(prev.relationships.map((r) => [r.name, r]));\n for (const r of next.relationships) {\n const p = prevRels.get(r.name);\n if (!p) continue;\n relationshipDataSteps(p, r, steps, warnings);\n }\n\n return { steps: [...drops, ...steps, ...creates], warnings };\n}\n\nfunction relationshipDataSteps(\n prev: ResolvedRelationshipModel,\n next: ResolvedRelationshipModel,\n steps: MigrationStep[],\n warnings: string[],\n): void {\n if (prev.relType !== next.relType) {\n warnings.push(\n `Relationship ${next.name} changed type :${prev.relType} → :${next.relType}; existing edges are not retyped.`,\n );\n return;\n }\n const ps = new Map(prev.properties.map((f) => [f.name, f]));\n for (const f of next.properties) {\n const p = ps.get(f.name);\n const def = defaultExpression(f);\n const nowRequired = !f.optional && !f.list;\n const wasRequired = p ? !p.optional && !p.list : false;\n if (def && (!p || (nowRequired && !wasRequired))) {\n steps.push({\n kind: \"statement\",\n comment: `Backfill ${next.name}.${f.name} with its default on existing edges${def.note ? ` (${def.note})` : \"\"}.`,\n cypher: `MATCH ()-[r:${q(next.relType)}]->() WHERE r.${q(f.name)} IS NULL SET r.${q(f.name)} = ${def.expr}`,\n ...(def.params ? { params: def.params } : {}),\n });\n } else if (nowRequired && !wasRequired) {\n warnings.push(\n `${next.name}.${f.name} is now required without a default; existing :${next.relType} edges may lack it.`,\n );\n }\n }\n}\n\n/** `true` when the plan has nothing to do. */\nexport function isEmptyPlan(plan: MigrationPlan): boolean {\n return plan.steps.length === 0;\n}\n","import type { MigrationPlan } from \"./diff.js\";\n\n/** Options for {@link renderMigrationSource}. */\nexport type RenderMigrationOptions = {\n /** Migration name (also the file stem). */\n readonly name: string;\n /** Module to import `defineMigration` from (default `\"cyphra\"`). */\n readonly runtimeImport?: string;\n};\n\nfunction indentComment(text: string, indent: string): string[] {\n return text.split(\"\\n\").map((l) => `${indent}// ${l}`);\n}\n\nfunction call(cypher: string, params?: Readonly<Record<string, unknown>>): string {\n const p = params && Object.keys(params).length ? `, ${JSON.stringify(params)}` : \"\";\n return `await db.execute(${JSON.stringify(cypher)}${p});`;\n}\n\n/**\n * Render a migration module (`.mjs`) for a {@link MigrationPlan}.\n * Destructive steps are emitted commented-out; warnings become a review note at the top.\n */\nexport function renderMigrationSource(plan: MigrationPlan, opts: RenderMigrationOptions): string {\n const lines: string[] = [];\n lines.push(\n \"// Generated by `cyphra migrate dev`. Review it before applying to shared databases.\",\n );\n if (plan.warnings.length) {\n lines.push(\"//\", \"// REVIEW:\");\n for (const w of plan.warnings) lines.push(...indentComment(`- ${w}`, \"\"));\n }\n lines.push(\n `import { defineMigration } from ${JSON.stringify(opts.runtimeImport ?? \"cyphra\")};`,\n \"\",\n );\n lines.push(\"export default defineMigration({\");\n lines.push(` name: ${JSON.stringify(opts.name)},`);\n lines.push(\" async up({ db }) {\");\n if (plan.steps.length === 0) {\n lines.push(\" // Nothing to do: write your own steps here.\");\n }\n plan.steps.forEach((step, i) => {\n if (i > 0) lines.push(\"\");\n lines.push(...indentComment(step.comment, \" \"));\n if (step.kind === \"statement\") {\n lines.push(` ${call(step.cypher, step.params)}`);\n } else if (step.kind === \"guard\") {\n lines.push(\" {\");\n lines.push(` const [row] = await db.execute(${JSON.stringify(step.countCypher)});`);\n lines.push(\" if (row && Number(row.count) > 0) {\");\n lines.push(\n ` throw new Error(${JSON.stringify(step.message)} + \\` (\\${row.count} nodes)\\`);`,\n );\n lines.push(\" }\");\n lines.push(\" }\");\n } else {\n lines.push(\" // DESTRUCTIVE: uncomment to apply.\");\n lines.push(` // ${call(step.cypher)}`);\n }\n });\n lines.push(\" },\");\n lines.push(\"});\", \"\");\n return lines.join(\"\\n\");\n}\n","/**\n * Database introspection for `cyphra pull`: read labels, relationship types, property types,\n * constraints and indexes from a live Neo4j database and turn them into a `.cyphra` schema.\n *\n * Split in two so the conversion is testable without a database:\n * {@link introspectDatabase} (queries) → {@link schemaFromIntrospection} (pure).\n *\n * @packageDocumentation\n */\n\nimport type {\n Decorator,\n NodeDeclaration,\n RelationalNodeField,\n RelationshipDeclaration,\n ScalarNodeField,\n ScalarTypeName,\n SchemaDocument,\n} from \"@cyphra/schema\";\nimport neo4j from \"neo4j-driver\";\nimport { toNative, type CyphraClient } from \"@cyphra/runtime\";\nimport { CYPHRA_MIGRATION_LABEL } from \"./tracker.js\";\n\nexport type IntrospectedProperty = {\n readonly propertyName: string;\n readonly propertyTypes: readonly string[];\n readonly mandatory: boolean;\n};\n\nexport type IntrospectionResult = {\n /** One entry per label combination (`db.schema.nodeTypeProperties`). */\n readonly nodeTypes: readonly {\n readonly labels: readonly string[];\n readonly properties: readonly IntrospectedProperty[];\n }[];\n /** One entry per relationship type (`db.schema.relTypeProperties`). */\n readonly relTypes: readonly {\n readonly type: string;\n readonly properties: readonly IntrospectedProperty[];\n /** Sampled (start labels, end labels) combinations. */\n readonly endpoints: readonly {\n readonly from: readonly string[];\n readonly to: readonly string[];\n }[];\n }[];\n readonly constraints: readonly {\n readonly name: string;\n readonly type: string;\n readonly entityType: string;\n readonly labelsOrTypes: readonly string[];\n readonly properties: readonly string[];\n }[];\n readonly indexes: readonly {\n readonly name: string;\n readonly type: string;\n readonly entityType: string;\n readonly labelsOrTypes: readonly string[];\n readonly properties: readonly string[];\n readonly owningConstraint: string | null;\n }[];\n};\n\n/** Edges sampled per relationship type to discover its endpoint labels. */\nexport const ENDPOINT_SAMPLE_SIZE = 10_000;\n\nfunction stripRelType(raw: string): string {\n // db.schema.relTypeProperties returns \":`TYPE`\".\n const t = raw.startsWith(\":\") ? raw.slice(1) : raw;\n return t.startsWith(\"`\") && t.endsWith(\"`\") ? t.slice(1, -1).replace(/``/g, \"`\") : t;\n}\n\n/**\n * Read the database's implicit schema. Read-only; samples at most {@link ENDPOINT_SAMPLE_SIZE}\n * edges per relationship type.\n */\nexport async function introspectDatabase(client: CyphraClient): Promise<IntrospectionResult> {\n return client.withSession(async (session) => {\n const rows = async (text: string, params: Record<string, unknown> = {}) =>\n (await session.run(text, params)).records.map(\n (r) => toNative(r.toObject()) as Record<string, unknown>,\n );\n\n const nodeRows = await rows(\n \"CALL db.schema.nodeTypeProperties() YIELD nodeLabels, propertyName, propertyTypes, mandatory RETURN *\",\n );\n const byCombo = new Map<string, { labels: string[]; properties: IntrospectedProperty[] }>();\n for (const r of nodeRows) {\n const labels = [...(r.nodeLabels as string[])].sort();\n const key = JSON.stringify(labels);\n const entry = byCombo.get(key) ?? { labels, properties: [] };\n byCombo.set(key, entry);\n if (r.propertyName) {\n entry.properties.push({\n propertyName: r.propertyName as string,\n propertyTypes: (r.propertyTypes as string[] | null) ?? [],\n mandatory: Boolean(r.mandatory),\n });\n }\n }\n\n const relRows = await rows(\n \"CALL db.schema.relTypeProperties() YIELD relType, propertyName, propertyTypes, mandatory RETURN *\",\n );\n const byType = new Map<string, IntrospectedProperty[]>();\n for (const r of relRows) {\n const type = stripRelType(r.relType as string);\n const props = byType.get(type) ?? [];\n byType.set(type, props);\n if (r.propertyName) {\n props.push({\n propertyName: r.propertyName as string,\n propertyTypes: (r.propertyTypes as string[] | null) ?? [],\n mandatory: Boolean(r.mandatory),\n });\n }\n }\n\n const relTypes: IntrospectionResult[\"relTypes\"][number][] = [];\n for (const [type, properties] of byType) {\n const ends = await rows(\n `MATCH ()-[r:\\`${type.replace(/`/g, \"``\")}\\`]->() WITH r LIMIT $limit\n RETURN DISTINCT labels(startNode(r)) AS from, labels(endNode(r)) AS to`,\n { limit: neo4jInt(ENDPOINT_SAMPLE_SIZE) },\n );\n relTypes.push({\n type,\n properties,\n endpoints: ends.map((e) => ({ from: e.from as string[], to: e.to as string[] })),\n });\n }\n\n const constraints = (\n await rows(\n \"SHOW CONSTRAINTS YIELD name, type, entityType, labelsOrTypes, properties RETURN *\",\n )\n ).map((c) => ({\n name: c.name as string,\n type: c.type as string,\n entityType: c.entityType as string,\n labelsOrTypes: (c.labelsOrTypes as string[] | null) ?? [],\n properties: (c.properties as string[] | null) ?? [],\n }));\n\n const indexes = (\n await rows(\n \"SHOW INDEXES YIELD name, type, entityType, labelsOrTypes, properties, owningConstraint RETURN *\",\n )\n ).map((i) => ({\n name: i.name as string,\n type: i.type as string,\n entityType: i.entityType as string,\n labelsOrTypes: (i.labelsOrTypes as string[] | null) ?? [],\n properties: (i.properties as string[] | null) ?? [],\n owningConstraint: (i.owningConstraint as string | null) ?? null,\n }));\n\n return { nodeTypes: [...byCombo.values()], relTypes, constraints, indexes };\n });\n}\n\nfunction neo4jInt(n: number): unknown {\n return neo4j.int(n);\n}\n\n// ---------------------------------------------------------------------------\n// Pure conversion\n// ---------------------------------------------------------------------------\n\nconst IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\nconst TYPE_MAP: Record<string, ScalarTypeName> = {\n String: \"String\",\n Long: \"Int\",\n Integer: \"Int\",\n Double: \"Float\",\n Float: \"Float\",\n Boolean: \"Boolean\",\n DateTime: \"DateTime\",\n ZonedDateTime: \"DateTime\",\n LocalDateTime: \"DateTime\",\n Date: \"Date\",\n};\n\nfunction mapType(types: readonly string[]): { name: ScalarTypeName; list: boolean } | null {\n const mapped = new Set<string>();\n let list: boolean | undefined;\n for (const raw of types) {\n const isList = raw.endsWith(\"Array\") || raw.startsWith(\"List\");\n const base = raw.replace(/Array$/, \"\").replace(/^List<(.*)>$/, \"$1\");\n const t = TYPE_MAP[base];\n if (!t) return null;\n if (list !== undefined && list !== isList) return null;\n list = isList;\n mapped.add(t);\n }\n if (mapped.size === 0) return null;\n if (mapped.size === 1) return { name: [...mapped][0] as ScalarTypeName, list: Boolean(list) };\n if ([...mapped].every((t) => t === \"Int\" || t === \"Float\"))\n return { name: \"Float\", list: Boolean(list) };\n return null;\n}\n\nfunction camel(type: string): string {\n const parts = type.split(/[^A-Za-z0-9]+/).filter(Boolean);\n const s = parts\n .map((p, i) =>\n i === 0 ? p.toLowerCase() : p.charAt(0).toUpperCase() + p.slice(1).toLowerCase(),\n )\n .join(\"\");\n return /^[A-Za-z_]/.test(s) ? s : `rel${s}`;\n}\n\nfunction pascal(type: string): string {\n const c = camel(type);\n return c.charAt(0).toUpperCase() + c.slice(1);\n}\n\nfunction uniqueName(base: string, taken: Set<string>): string {\n let name = base;\n let i = 2;\n while (taken.has(name)) name = `${base}${i++}`;\n taken.add(name);\n return name;\n}\n\nconst dec = (name: string): Decorator => ({ name, args: [] });\n\n/**\n * Convert introspection results into a `.cyphra` {@link SchemaDocument}.\n *\n * - Properties: required when present on every node of the label; types mapped from Neo4j's.\n * - Single-property uniqueness constraints become `@id` (property `id` or constraint `…_id`) / `@unique`;\n * single-property range indexes become `@index`.\n * - Every sampled `(start)-[:TYPE]->(end)` pair becomes an `OUT` field on the start node and an `IN`\n * field (`…By`) on the end node, both to-many. Relationship types with properties also get a\n * `relationship { … }` model.\n */\nexport function schemaFromIntrospection(input: IntrospectionResult): {\n doc: SchemaDocument;\n warnings: string[];\n} {\n const warnings: string[] = [];\n\n // --- labels and their properties ------------------------------------------------\n type PropAcc = { types: Set<string>; mandatoryIn: number; presentIn: number };\n const labels = new Map<string, { combos: number; props: Map<string, PropAcc> }>();\n const ensureLabel = (l: string) => {\n let e = labels.get(l);\n if (!e) {\n e = { combos: 0, props: new Map() };\n labels.set(l, e);\n }\n return e;\n };\n const skipLabel = (l: string) => l === CYPHRA_MIGRATION_LABEL || !IDENT.test(l);\n\n for (const nt of input.nodeTypes) {\n for (const l of nt.labels) {\n if (skipLabel(l)) {\n if (l !== CYPHRA_MIGRATION_LABEL)\n warnings.push(`Skipped label \"${l}\": not a valid identifier.`);\n continue;\n }\n const e = ensureLabel(l);\n e.combos += 1;\n for (const p of nt.properties) {\n const acc = e.props.get(p.propertyName) ?? {\n types: new Set(),\n mandatoryIn: 0,\n presentIn: 0,\n };\n e.props.set(p.propertyName, acc);\n p.propertyTypes.forEach((t) => acc.types.add(t));\n acc.presentIn += 1;\n if (p.mandatory) acc.mandatoryIn += 1;\n }\n }\n }\n for (const rt of input.relTypes) {\n for (const ep of rt.endpoints) {\n for (const l of [...ep.from, ...ep.to]) if (!skipLabel(l)) ensureLabel(l);\n }\n }\n\n // --- constraints / indexes ----------------------------------------------------\n const uniqueOn = new Map<string, { prop: string; name: string }[]>();\n const relUnique = new Set<string>();\n const indexOn = new Set<string>();\n for (const c of input.constraints) {\n if (c.properties.length !== 1 || c.labelsOrTypes.length !== 1) continue;\n const key = c.labelsOrTypes[0]!;\n if (c.type === \"UNIQUENESS\" || (c.type.includes(\"UNIQUE\") && c.entityType === \"NODE\")) {\n const list = uniqueOn.get(key) ?? [];\n list.push({ prop: c.properties[0]!, name: c.name });\n uniqueOn.set(key, list);\n } else if (c.entityType === \"RELATIONSHIP\" && c.type.includes(\"UNIQUE\")) {\n relUnique.add(`${key}.${c.properties[0]}`);\n }\n }\n for (const i of input.indexes) {\n if (\n i.type !== \"RANGE\" ||\n i.owningConstraint ||\n i.properties.length !== 1 ||\n i.labelsOrTypes.length !== 1\n ) {\n continue;\n }\n indexOn.add(`${i.entityType}:${i.labelsOrTypes[0]}.${i.properties[0]}`);\n }\n\n // --- node declarations ---------------------------------------------------------\n const nodeFields = new Map<string, (ScalarNodeField | RelationalNodeField)[]>();\n const taken = new Map<string, Set<string>>();\n for (const [label, e] of [...labels].sort(([a], [b]) => a.localeCompare(b))) {\n const uniques = uniqueOn.get(label) ?? [];\n const idProp =\n uniques.find((u) => u.prop === \"id\")?.prop ?? uniques.find((u) => /_id$/.test(u.name))?.prop;\n const fields: ScalarNodeField[] = [];\n const ordered = [...e.props].sort(([a], [b]) =>\n a === idProp ? -1 : b === idProp ? 1 : a.localeCompare(b),\n );\n for (const [prop, acc] of ordered) {\n if (!IDENT.test(prop)) {\n warnings.push(`Skipped ${label}.${prop}: not a valid identifier.`);\n continue;\n }\n const t = mapType([...acc.types]);\n if (!t) {\n warnings.push(\n `Skipped ${label}.${prop}: unsupported or mixed types (${[...acc.types].join(\", \")}).`,\n );\n continue;\n }\n const required = !t.list && acc.mandatoryIn === e.combos;\n const decorators: Decorator[] = [];\n if (prop === idProp && required) decorators.push(dec(\"id\"));\n else if (uniques.some((u) => u.prop === prop)) decorators.push(dec(\"unique\"));\n else if (indexOn.has(`NODE:${label}.${prop}`)) decorators.push(dec(\"index\"));\n fields.push({\n kind: \"Scalar\",\n name: prop,\n type: { name: t.name, optional: !required && !t.list, ...(t.list ? { list: true } : {}) },\n decorators,\n });\n }\n nodeFields.set(label, fields);\n taken.set(label, new Set(fields.map((f) => f.name)));\n }\n\n // --- relations ------------------------------------------------------------------\n const relationships: RelationshipDeclaration[] = [];\n const declNames = new Set(labels.keys());\n for (const rt of [...input.relTypes].sort((a, b) => a.type.localeCompare(b.type))) {\n const pairs: { from: string; to: string }[] = [];\n for (const ep of rt.endpoints) {\n for (const from of ep.from) {\n for (const to of ep.to) {\n if (skipLabel(from) || skipLabel(to)) continue;\n if (!pairs.some((p) => p.from === from && p.to === to)) pairs.push({ from, to });\n }\n }\n }\n if (pairs.length === 0) {\n warnings.push(\n `Relationship type :${rt.type} has no usable endpoints in the sample; skipped.`,\n );\n continue;\n }\n const outTargets = (from: string) => pairs.filter((p) => p.from === from).length;\n const inSources = (to: string) => pairs.filter((p) => p.to === to).length;\n const relDecorator = (direction: \"OUT\" | \"IN\"): Decorator => ({\n name: \"relationship\",\n args: [\n { key: \"type\", value: { kind: \"string\", value: rt.type } },\n { key: \"direction\", value: { kind: \"identifier\", value: direction } },\n ],\n });\n for (const { from, to } of pairs) {\n const outName = uniqueName(\n camel(rt.type) + (outTargets(from) > 1 ? to : \"\"),\n taken.get(from)!,\n );\n nodeFields.get(from)!.push({\n kind: \"Relational\",\n name: outName,\n target: to,\n cardinality: \"many\",\n optional: false,\n decorators: [relDecorator(\"OUT\")],\n });\n const inName = uniqueName(\n `${camel(rt.type)}By${inSources(to) > 1 ? from : \"\"}`,\n taken.get(to)!,\n );\n nodeFields.get(to)!.push({\n kind: \"Relational\",\n name: inName,\n target: from,\n cardinality: \"many\",\n optional: false,\n decorators: [relDecorator(\"IN\")],\n });\n }\n\n if (rt.properties.length === 0) continue;\n const props: ScalarNodeField[] = [];\n for (const p of [...rt.properties].sort((a, b) =>\n a.propertyName.localeCompare(b.propertyName),\n )) {\n const t = mapType(p.propertyTypes);\n if (!t || !IDENT.test(p.propertyName)) {\n warnings.push(`Skipped :${rt.type}.${p.propertyName}: unsupported type or name.`);\n continue;\n }\n const decorators: Decorator[] = [];\n if (relUnique.has(`${rt.type}.${p.propertyName}`)) decorators.push(dec(\"unique\"));\n else if (indexOn.has(`RELATIONSHIP:${rt.type}.${p.propertyName}`))\n decorators.push(dec(\"index\"));\n props.push({\n kind: \"Scalar\",\n name: p.propertyName,\n type: {\n name: t.name,\n optional: !p.mandatory && !t.list,\n ...(t.list ? { list: true } : {}),\n },\n decorators,\n });\n }\n for (const { from, to } of pairs) {\n let base = pascal(rt.type) + (pairs.length > 1 ? `${from}${to}` : \"\");\n if (declNames.has(base)) base += \"Rel\";\n relationships.push({\n kind: \"Relationship\",\n name: uniqueName(base, declNames),\n relType: rt.type,\n from,\n to,\n fields: props,\n });\n }\n }\n\n const nodes: NodeDeclaration[] = [...nodeFields].map(([name, fields]) => ({\n kind: \"Node\",\n name,\n fields,\n }));\n for (const n of nodes) {\n if (!n.fields.some((f) => f.kind === \"Scalar\")) {\n warnings.push(`Node ${n.name} has no properties in the database.`);\n }\n }\n return { doc: { kind: \"Document\", declarations: [...nodes, ...relationships] }, warnings };\n}\n"],"mappings":";AAeO,SAAS,mBAAmB,aAAqB,WAA2B;AACjF,MAAI,CAAC,OAAO,UAAU,SAAS,KAAK,YAAY,GAAG;AACjD,UAAM,IAAI,MAAM,6CAA6C,SAAS,EAAE;AAAA,EAC1E;AACA,SAAO;AAAA,EAAW,YAAY,KAAK,CAAC;AAAA,uBAA0B,SAAS;AACzE;;;ACKO,SAAS,gBAAgB,KAA+C;AAC7E,SAAO;AACT;;;AC1BA,SAAS,gBAAmC;;;ACC5C,IAAM,QAAQ;AAEd,SAAS,YAAY,MAAc,OAAqB;AACtD,MAAI,CAAC,MAAM,KAAK,IAAI,GAAG;AACrB,UAAM,IAAI,MAAM,iBAAiB,KAAK,gBAAgB,KAAK,UAAU,IAAI,CAAC,EAAE;AAAA,EAC9E;AACF;AAQO,SAAS,mBAAmB,WAAmB,SAAiC;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
|
|
2
2
|
"name": "@cyphra/migrator",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Versioned migrations
|
|
3
|
+
"version": "0.2.2",
|
|
4
|
+
"description": "Versioned schema migrations for Neo4j: constraints, indexes and data migrations (Cyphra)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
7
7
|
"publishConfig": {
|
|
@@ -20,17 +20,38 @@
|
|
|
20
20
|
}
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
|
-
"neo4j-driver": "^5.
|
|
24
|
-
"@cyphra/query": "0.
|
|
25
|
-
"@cyphra/runtime": "0.
|
|
26
|
-
"@cyphra/schema": "0.
|
|
23
|
+
"neo4j-driver": "^5.28.3",
|
|
24
|
+
"@cyphra/query": "0.2.2",
|
|
25
|
+
"@cyphra/runtime": "0.2.2",
|
|
26
|
+
"@cyphra/schema": "0.2.2"
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
|
-
"@types/node": "^22.
|
|
30
|
-
"tsup": "^8.
|
|
31
|
-
"typescript": "^5.
|
|
32
|
-
"vitest": "^
|
|
29
|
+
"@types/node": "^22.20.5",
|
|
30
|
+
"tsup": "^8.5.1",
|
|
31
|
+
"typescript": "^5.9.3",
|
|
32
|
+
"vitest": "^4.1.12"
|
|
33
33
|
},
|
|
34
|
+
"license": "MIT",
|
|
35
|
+
"repository": {
|
|
36
|
+
"type": "git",
|
|
37
|
+
"url": "git+https://github.com/Cyphra-dev/cyphra.git",
|
|
38
|
+
"directory": "packages/migrator"
|
|
39
|
+
},
|
|
40
|
+
"homepage": "https://www.cyphra.dev/migrations",
|
|
41
|
+
"bugs": {
|
|
42
|
+
"url": "https://github.com/Cyphra-dev/cyphra/issues"
|
|
43
|
+
},
|
|
44
|
+
"keywords": [
|
|
45
|
+
"neo4j",
|
|
46
|
+
"neo4j-orm",
|
|
47
|
+
"orm",
|
|
48
|
+
"typescript",
|
|
49
|
+
"cypher",
|
|
50
|
+
"graph-database",
|
|
51
|
+
"cyphra",
|
|
52
|
+
"migrations",
|
|
53
|
+
"schema-migrations"
|
|
54
|
+
],
|
|
34
55
|
"scripts": {
|
|
35
56
|
"build": "tsup",
|
|
36
57
|
"typecheck": "tsc --noEmit",
|