@cyphra/migrator 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Session } from 'neo4j-driver';
2
2
  import { CyphraClient } from '@cyphra/runtime';
3
- import { SchemaDocument, SchemaModel } from '@cyphra/schema';
3
+ import { SchemaDocument, SchemaModel, ResolvedFulltextIndex, ResolvedScalarField } from '@cyphra/schema';
4
4
  import { CompiledCypher } from '@cyphra/query';
5
5
 
6
6
  /**
@@ -113,6 +113,22 @@ declare function constraintStatementsFromSchema(doc: SchemaDocument): string[];
113
113
  * @returns Cypher DDL strings (Neo4j 5+ range index syntax).
114
114
  */
115
115
  declare function indexStatementsFromSchema(doc: SchemaDocument): string[];
116
+ /**
117
+ * Generate `CREATE VECTOR INDEX … IF NOT EXISTS` for every `Vector(N) @vectorIndex(...)` node field,
118
+ * with `vector.dimensions` and `vector.similarity_function` in `OPTIONS` (Neo4j 5.15+).
119
+ *
120
+ * @param doc - Parsed schema AST.
121
+ * @returns Cypher DDL strings, named like migrations name them.
122
+ */
123
+ declare function vectorIndexStatementsFromSchema(doc: SchemaDocument): string[];
124
+ /**
125
+ * Generate `CREATE FULLTEXT INDEX … IF NOT EXISTS` for every `@@fulltext([...])` node attribute,
126
+ * with `fulltext.analyzer` / `fulltext.eventually_consistent` in `OPTIONS` when set.
127
+ *
128
+ * @param doc - Parsed schema AST.
129
+ * @returns Cypher DDL strings, named like migrations name them.
130
+ */
131
+ declare function fulltextIndexStatementsFromSchema(doc: SchemaDocument): string[];
116
132
 
117
133
  /**
118
134
  * Build Cypher to rename a node label (validated identifiers only — not user-controlled strings).
@@ -165,13 +181,26 @@ declare function schemaIntegrationHints(doc: SchemaDocument): string[];
165
181
  * current schema) and plan the migration that takes a database from one to the other.
166
182
  *
167
183
  * Neo4j is schemaless, so the plan has two parts:
168
- * - **DDL**: uniqueness constraints and range indexes, named exactly like `cyphra push` names them.
184
+ * - **DDL**: uniqueness constraints and range, vector and full-text indexes, named exactly like
185
+ * `cyphra push` names them.
169
186
  * - **Data steps**: backfills for new defaults, guards for newly required fields, and
170
187
  * (commented-out) destructive cleanups for removed fields and models.
171
188
  *
172
189
  * @packageDocumentation
173
190
  */
174
191
 
192
+ /**
193
+ * `CREATE VECTOR INDEX … IF NOT EXISTS` for a `Vector(N) @vectorIndex(...)` field (Neo4j 5.15+).
194
+ * Dimensions and similarity are part of the statement, so changing either one makes the diff drop
195
+ * and recreate the index.
196
+ */
197
+ declare function vectorIndexStatement(label: string, f: ResolvedScalarField): string | null;
198
+ /**
199
+ * `CREATE FULLTEXT INDEX … IF NOT EXISTS` for a `@@fulltext([...])` model attribute. Fields,
200
+ * analyzer and consistency are part of the statement, so changing any of them makes the diff drop
201
+ * and recreate the index.
202
+ */
203
+ declare function fulltextIndexStatement(label: string, index: ResolvedFulltextIndex): string;
175
204
  /** One named schema object (constraint or index) and the statement that creates it. */
176
205
  type DdlObject = {
177
206
  readonly name: string;
@@ -277,6 +306,8 @@ type IntrospectionResult = {
277
306
  readonly labelsOrTypes: readonly string[];
278
307
  readonly properties: readonly string[];
279
308
  readonly owningConstraint: string | null;
309
+ /** `OPTIONS` of the index (`indexConfig` holds a vector index's dimensions and similarity). */
310
+ readonly options?: Readonly<Record<string, unknown>> | null;
280
311
  }[];
281
312
  };
282
313
  /** Edges sampled per relationship type to discover its endpoint labels. */
@@ -334,4 +365,4 @@ type AppliedMigration = {
334
365
  */
335
366
  declare function listAppliedMigrations(session: Session): Promise<AppliedMigration[]>;
336
367
 
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 };
368
+ 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, fulltextIndexStatement, fulltextIndexStatementsFromSchema, indexStatementsFromSchema, introspectDatabase, isEmptyPlan, isMigrationApplied, listAppliedMigrations, recordMigration, renderMigrationSource, runPendingMigrations, schemaFromIntrospection, schemaIntegrationHints, vectorIndexStatement, vectorIndexStatementsFromSchema, wrapInTransactions };
package/dist/index.js CHANGED
@@ -70,184 +70,9 @@ function createMigrationDb(client, session) {
70
70
  }
71
71
 
72
72
  // src/push.ts
73
- function isScalarWithDecorator(field, dec2) {
74
- return field.kind === "Scalar" && field.decorators.some((d) => d.name === dec2);
75
- }
76
- function hasDecoratorName(field, name) {
77
- return field.decorators.some((d) => d.name === name);
78
- }
79
- function cypherRelTypeToken(relType) {
80
- if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(relType)) {
81
- return relType;
82
- }
83
- return `\`${relType.replace(/`/g, "``")}\``;
84
- }
85
- function idPropertyName(node) {
86
- for (const f of node.fields) {
87
- if (isScalarWithDecorator(f, "id")) {
88
- return f.name;
89
- }
90
- }
91
- return void 0;
92
- }
93
- function constraintStatementsFromSchema(doc) {
94
- const statements = [];
95
- for (const decl of doc.declarations) {
96
- if (decl.kind === "Node") {
97
- const label = decl.name;
98
- const idProp = idPropertyName(decl);
99
- if (idProp) {
100
- statements.push(
101
- `CREATE CONSTRAINT ${escapeConstraintName(`${label}_${idProp}_id`)} IF NOT EXISTS FOR (n:\`${label}\`) REQUIRE n.\`${idProp}\` IS UNIQUE`
102
- );
103
- }
104
- for (const f of decl.fields) {
105
- if (!isScalarWithDecorator(f, "unique")) {
106
- continue;
107
- }
108
- if (f.name === idProp) {
109
- continue;
110
- }
111
- statements.push(
112
- `CREATE CONSTRAINT ${escapeConstraintName(`${label}_${f.name}_unique`)} IF NOT EXISTS FOR (n:\`${label}\`) REQUIRE n.\`${f.name}\` IS UNIQUE`
113
- );
114
- }
115
- continue;
116
- }
117
- const typeTok = cypherRelTypeToken(decl.relType);
118
- for (const f of decl.fields) {
119
- if (!isScalarWithDecorator(f, "unique")) {
120
- continue;
121
- }
122
- statements.push(
123
- `CREATE CONSTRAINT ${escapeConstraintName(`${decl.name}_${f.name}_rel_unique`)} IF NOT EXISTS FOR ()-[r:${typeTok}]-() REQUIRE r.\`${f.name}\` IS UNIQUE`
124
- );
125
- }
126
- }
127
- return statements;
128
- }
129
- function indexStatementsFromSchema(doc) {
130
- const statements = [];
131
- for (const decl of doc.declarations) {
132
- if (decl.kind === "Node") {
133
- const label = decl.name;
134
- for (const f of decl.fields) {
135
- if (f.kind !== "Scalar") {
136
- continue;
137
- }
138
- if (!isScalarWithDecorator(f, "index")) {
139
- continue;
140
- }
141
- if (hasDecoratorName(f, "unique")) {
142
- continue;
143
- }
144
- statements.push(
145
- `CREATE RANGE INDEX ${escapeConstraintName(`${label}_${f.name}_idx`)} IF NOT EXISTS FOR (n:\`${label}\`) ON (n.\`${f.name}\`)`
146
- );
147
- }
148
- continue;
149
- }
150
- const typeTok = cypherRelTypeToken(decl.relType);
151
- for (const f of decl.fields) {
152
- if (!isScalarWithDecorator(f, "index")) {
153
- continue;
154
- }
155
- if (hasDecoratorName(f, "unique")) {
156
- continue;
157
- }
158
- statements.push(
159
- `CREATE RANGE INDEX ${escapeConstraintName(`${decl.name}_${f.name}_rel_idx`)} IF NOT EXISTS FOR ()-[r:${typeTok}]-() ON (r.\`${f.name}\`)`
160
- );
161
- }
162
- }
163
- return statements;
164
- }
165
- function escapeConstraintName(name) {
166
- return name.replace(/[^A-Za-z0-9_]/g, "_");
167
- }
168
-
169
- // src/tracker.ts
170
- var CYPHRA_MIGRATION_LABEL = "__CyphraMigration";
171
- async function ensureMigrationInfrastructure(session) {
172
- const r = await session.run(`
173
- CREATE CONSTRAINT cyphra_migration_name_unique IF NOT EXISTS
174
- FOR (m:__CyphraMigration) REQUIRE m.name IS UNIQUE
175
- `);
176
- await r;
177
- }
178
- async function isMigrationApplied(session, name) {
179
- const result = await session.run(
180
- `MATCH (m:__CyphraMigration { name: $name }) RETURN m AS m LIMIT 1`,
181
- { name }
182
- );
183
- const q2 = await result;
184
- return q2.records.length > 0;
185
- }
186
- async function recordMigration(session, name, checksum) {
187
- const r = await session.run(
188
- `
189
- CREATE (m:__CyphraMigration {
190
- name: $name,
191
- appliedAt: datetime(),
192
- checksum: $checksum
193
- })
194
- `,
195
- { name, checksum }
196
- );
197
- await r;
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
- }
212
-
213
- // src/runner.ts
214
- async function runPendingMigrations(client, ordered) {
215
- const applied = [];
216
- await client.withSession(async (session) => {
217
- await ensureMigrationInfrastructure(session);
218
- for (const m of ordered) {
219
- if (await isMigrationApplied(session, m.name)) {
220
- continue;
221
- }
222
- const db = createMigrationDb(client, session);
223
- await m.definition.up({ db });
224
- await recordMigration(session, m.name, m.checksum);
225
- applied.push(m.name);
226
- }
227
- });
228
- return applied;
229
- }
230
- async function applyConstraintStatements(client, statements) {
231
- await client.withSession(async (session) => {
232
- for (const statement of statements) {
233
- const r = await session.run(statement);
234
- await r;
235
- }
236
- });
237
- }
238
-
239
- // src/schemaHints.ts
240
- function schemaIntegrationHints(doc) {
241
- const hints = [];
242
- for (const d of doc.declarations) {
243
- if (d.kind === "Relationship") {
244
- hints.push(
245
- `Relationship model "${d.name}" maps to Neo4j type \`${d.relType}\` (:${d.from} \u2192 :${d.to}).`
246
- );
247
- }
248
- }
249
- return hints;
250
- }
73
+ import {
74
+ resolveSchema
75
+ } from "@cyphra/schema";
251
76
 
252
77
  // src/diff.ts
253
78
  function q(id) {
@@ -256,12 +81,41 @@ function q(id) {
256
81
  function constraintName(name) {
257
82
  return name.replace(/[^A-Za-z0-9_]/g, "_");
258
83
  }
84
+ function vectorIndexStatement(label, f) {
85
+ if (f.type !== "Vector" || !f.vectorIndex || f.dimensions === void 0) return null;
86
+ const entries = [
87
+ `\`vector.dimensions\`: ${f.dimensions}`,
88
+ `\`vector.similarity_function\`: '${f.vectorIndex.similarity}'`
89
+ ];
90
+ if (f.vectorIndex.quantization !== void 0) {
91
+ entries.push(`\`vector.quantization.enabled\`: ${f.vectorIndex.quantization}`);
92
+ }
93
+ const config = `{${entries.join(", ")}}`;
94
+ return `CREATE VECTOR INDEX ${f.vectorIndex.name} IF NOT EXISTS FOR (n:${q(label)}) ON n.${q(f.name)} OPTIONS {indexConfig: ${config}}`;
95
+ }
96
+ function fulltextIndexStatement(label, index) {
97
+ const props = index.fields.map((f) => `n.${q(f)}`).join(", ");
98
+ const entries = [];
99
+ if (index.analyzer !== void 0) {
100
+ entries.push(`\`fulltext.analyzer\`: '${index.analyzer}'`);
101
+ }
102
+ if (index.eventuallyConsistent !== void 0) {
103
+ entries.push(`\`fulltext.eventually_consistent\`: ${index.eventuallyConsistent}`);
104
+ }
105
+ const options = entries.length ? ` OPTIONS {indexConfig: {${entries.join(", ")}}}` : "";
106
+ return `CREATE FULLTEXT INDEX ${index.name} IF NOT EXISTS FOR (n:${q(label)}) ON EACH [${props}]${options}`;
107
+ }
259
108
  function ddlObjectsFromModel(model) {
260
109
  const out = [];
261
110
  for (const n of model.nodes) {
262
111
  const scalars = n.fields.filter((f) => f.kind === "scalar");
263
112
  for (const f of scalars) {
264
113
  const target = `FOR (n:${q(n.label)})`;
114
+ const vector = vectorIndexStatement(n.label, f);
115
+ if (vector) {
116
+ out.push({ name: f.vectorIndex.name, kind: "index", create: vector });
117
+ continue;
118
+ }
265
119
  if (f.id) {
266
120
  const name = constraintName(`${n.label}_${f.name}_id`);
267
121
  out.push({
@@ -286,6 +140,11 @@ function ddlObjectsFromModel(model) {
286
140
  }
287
141
  }
288
142
  }
143
+ for (const n of model.nodes) {
144
+ for (const index of n.fulltextIndexes ?? []) {
145
+ out.push({ name: index.name, kind: "index", create: fulltextIndexStatement(n.label, index) });
146
+ }
147
+ }
289
148
  for (const r of model.relationships) {
290
149
  const target = `FOR ()-[r:${q(r.relType)}]-()`;
291
150
  for (const f of r.properties) {
@@ -315,6 +174,7 @@ function scalarsOf(n) {
315
174
  );
316
175
  }
317
176
  function typeLabel(f) {
177
+ if (f.type === "Vector") return `Vector(${f.dimensions})${f.optional ? "?" : ""}`;
318
178
  return f.list ? `${f.type}[]` : f.optional ? `${f.type}?` : f.type;
319
179
  }
320
180
  function defaultExpression(f) {
@@ -336,7 +196,13 @@ function nodeDataSteps(label, model, name, before, after, steps, warnings) {
336
196
  const match = `MATCH (n:${q(label)}) WHERE ${ref} IS NULL`;
337
197
  const nowRequired = !after.optional && !after.list;
338
198
  const wasRequired = before ? !before.optional && !before.list : false;
339
- if (before && before.type !== after.type) {
199
+ if (before && after.type === "Vector" && before.type === "Vector") {
200
+ if (before.dimensions !== after.dimensions) {
201
+ warnings.push(
202
+ `${model}.${name} changed dimensions ${before.dimensions} \u2192 ${after.dimensions}; existing embeddings keep their old length and are not indexed (or returned by findSimilar) until re-embedded.`
203
+ );
204
+ }
205
+ } else if (before && before.type !== after.type) {
340
206
  warnings.push(
341
207
  `${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
208
  );
@@ -466,6 +332,205 @@ function isEmptyPlan(plan) {
466
332
  return plan.steps.length === 0;
467
333
  }
468
334
 
335
+ // src/push.ts
336
+ function isScalarWithDecorator(field, dec2) {
337
+ return field.kind === "Scalar" && field.decorators.some((d) => d.name === dec2);
338
+ }
339
+ function hasDecoratorName(field, name) {
340
+ return field.decorators.some((d) => d.name === name);
341
+ }
342
+ function cypherRelTypeToken(relType) {
343
+ if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(relType)) {
344
+ return relType;
345
+ }
346
+ return `\`${relType.replace(/`/g, "``")}\``;
347
+ }
348
+ function idPropertyName(node) {
349
+ for (const f of node.fields) {
350
+ if (isScalarWithDecorator(f, "id")) {
351
+ return f.name;
352
+ }
353
+ }
354
+ return void 0;
355
+ }
356
+ function constraintStatementsFromSchema(doc) {
357
+ const statements = [];
358
+ for (const decl of doc.declarations) {
359
+ if (decl.kind === "Node") {
360
+ const label = decl.name;
361
+ const idProp = idPropertyName(decl);
362
+ if (idProp) {
363
+ statements.push(
364
+ `CREATE CONSTRAINT ${escapeConstraintName(`${label}_${idProp}_id`)} IF NOT EXISTS FOR (n:\`${label}\`) REQUIRE n.\`${idProp}\` IS UNIQUE`
365
+ );
366
+ }
367
+ for (const f of decl.fields) {
368
+ if (!isScalarWithDecorator(f, "unique")) {
369
+ continue;
370
+ }
371
+ if (f.name === idProp) {
372
+ continue;
373
+ }
374
+ statements.push(
375
+ `CREATE CONSTRAINT ${escapeConstraintName(`${label}_${f.name}_unique`)} IF NOT EXISTS FOR (n:\`${label}\`) REQUIRE n.\`${f.name}\` IS UNIQUE`
376
+ );
377
+ }
378
+ continue;
379
+ }
380
+ const typeTok = cypherRelTypeToken(decl.relType);
381
+ for (const f of decl.fields) {
382
+ if (!isScalarWithDecorator(f, "unique")) {
383
+ continue;
384
+ }
385
+ statements.push(
386
+ `CREATE CONSTRAINT ${escapeConstraintName(`${decl.name}_${f.name}_rel_unique`)} IF NOT EXISTS FOR ()-[r:${typeTok}]-() REQUIRE r.\`${f.name}\` IS UNIQUE`
387
+ );
388
+ }
389
+ }
390
+ return statements;
391
+ }
392
+ function indexStatementsFromSchema(doc) {
393
+ const statements = [];
394
+ for (const decl of doc.declarations) {
395
+ if (decl.kind === "Node") {
396
+ const label = decl.name;
397
+ for (const f of decl.fields) {
398
+ if (f.kind !== "Scalar") {
399
+ continue;
400
+ }
401
+ if (!isScalarWithDecorator(f, "index")) {
402
+ continue;
403
+ }
404
+ if (hasDecoratorName(f, "unique")) {
405
+ continue;
406
+ }
407
+ statements.push(
408
+ `CREATE RANGE INDEX ${escapeConstraintName(`${label}_${f.name}_idx`)} IF NOT EXISTS FOR (n:\`${label}\`) ON (n.\`${f.name}\`)`
409
+ );
410
+ }
411
+ continue;
412
+ }
413
+ const typeTok = cypherRelTypeToken(decl.relType);
414
+ for (const f of decl.fields) {
415
+ if (!isScalarWithDecorator(f, "index")) {
416
+ continue;
417
+ }
418
+ if (hasDecoratorName(f, "unique")) {
419
+ continue;
420
+ }
421
+ statements.push(
422
+ `CREATE RANGE INDEX ${escapeConstraintName(`${decl.name}_${f.name}_rel_idx`)} IF NOT EXISTS FOR ()-[r:${typeTok}]-() ON (r.\`${f.name}\`)`
423
+ );
424
+ }
425
+ }
426
+ return statements;
427
+ }
428
+ function vectorIndexStatementsFromSchema(doc) {
429
+ const statements = [];
430
+ for (const n of resolveSchema(doc).nodes) {
431
+ for (const f of n.fields) {
432
+ const stmt = f.kind === "scalar" ? vectorIndexStatement(n.label, f) : null;
433
+ if (stmt) statements.push(stmt);
434
+ }
435
+ }
436
+ return statements;
437
+ }
438
+ function fulltextIndexStatementsFromSchema(doc) {
439
+ const statements = [];
440
+ for (const n of resolveSchema(doc).nodes) {
441
+ for (const index of n.fulltextIndexes ?? []) {
442
+ statements.push(fulltextIndexStatement(n.label, index));
443
+ }
444
+ }
445
+ return statements;
446
+ }
447
+ function escapeConstraintName(name) {
448
+ return name.replace(/[^A-Za-z0-9_]/g, "_");
449
+ }
450
+
451
+ // src/tracker.ts
452
+ var CYPHRA_MIGRATION_LABEL = "__CyphraMigration";
453
+ async function ensureMigrationInfrastructure(session) {
454
+ const r = await session.run(`
455
+ CREATE CONSTRAINT cyphra_migration_name_unique IF NOT EXISTS
456
+ FOR (m:__CyphraMigration) REQUIRE m.name IS UNIQUE
457
+ `);
458
+ await r;
459
+ }
460
+ async function isMigrationApplied(session, name) {
461
+ const result = await session.run(
462
+ `MATCH (m:__CyphraMigration { name: $name }) RETURN m AS m LIMIT 1`,
463
+ { name }
464
+ );
465
+ const q2 = await result;
466
+ return q2.records.length > 0;
467
+ }
468
+ async function recordMigration(session, name, checksum) {
469
+ const r = await session.run(
470
+ `
471
+ CREATE (m:__CyphraMigration {
472
+ name: $name,
473
+ appliedAt: datetime(),
474
+ checksum: $checksum
475
+ })
476
+ `,
477
+ { name, checksum }
478
+ );
479
+ await r;
480
+ }
481
+ async function listAppliedMigrations(session) {
482
+ const result = await session.run(
483
+ `MATCH (m:__CyphraMigration) RETURN m.name AS name, m.checksum AS checksum, m.appliedAt AS appliedAt ORDER BY m.appliedAt, m.name`
484
+ );
485
+ return result.records.map((r) => {
486
+ const at = r.get("appliedAt");
487
+ return {
488
+ name: r.get("name"),
489
+ checksum: r.get("checksum") ?? null,
490
+ appliedAt: at?.toStandardDate ? at.toStandardDate() : null
491
+ };
492
+ });
493
+ }
494
+
495
+ // src/runner.ts
496
+ async function runPendingMigrations(client, ordered) {
497
+ const applied = [];
498
+ await client.withSession(async (session) => {
499
+ await ensureMigrationInfrastructure(session);
500
+ for (const m of ordered) {
501
+ if (await isMigrationApplied(session, m.name)) {
502
+ continue;
503
+ }
504
+ const db = createMigrationDb(client, session);
505
+ await m.definition.up({ db });
506
+ await recordMigration(session, m.name, m.checksum);
507
+ applied.push(m.name);
508
+ }
509
+ });
510
+ return applied;
511
+ }
512
+ async function applyConstraintStatements(client, statements) {
513
+ await client.withSession(async (session) => {
514
+ for (const statement of statements) {
515
+ const r = await session.run(statement);
516
+ await r;
517
+ }
518
+ });
519
+ }
520
+
521
+ // src/schemaHints.ts
522
+ function schemaIntegrationHints(doc) {
523
+ const hints = [];
524
+ for (const d of doc.declarations) {
525
+ if (d.kind === "Relationship") {
526
+ hints.push(
527
+ `Relationship model "${d.name}" maps to Neo4j type \`${d.relType}\` (:${d.from} \u2192 :${d.to}).`
528
+ );
529
+ }
530
+ }
531
+ return hints;
532
+ }
533
+
469
534
  // src/renderMigration.ts
470
535
  function indentComment(text, indent) {
471
536
  return text.split("\n").map((l) => `${indent}// ${l}`);
@@ -518,6 +583,12 @@ function renderMigrationSource(plan, opts) {
518
583
  }
519
584
 
520
585
  // src/introspect.ts
586
+ import {
587
+ DEFAULT_FULLTEXT_ANALYZER,
588
+ FULLTEXT_ANALYZERS,
589
+ MAX_VECTOR_DIMENSIONS,
590
+ VECTOR_SIMILARITIES
591
+ } from "@cyphra/schema";
521
592
  import neo4j from "neo4j-driver";
522
593
  import { toNative as toNative2 } from "@cyphra/runtime";
523
594
  var ENDPOINT_SAMPLE_SIZE = 1e4;
@@ -586,14 +657,15 @@ async function introspectDatabase(client) {
586
657
  properties: c.properties ?? []
587
658
  }));
588
659
  const indexes = (await rows(
589
- "SHOW INDEXES YIELD name, type, entityType, labelsOrTypes, properties, owningConstraint RETURN *"
660
+ "SHOW INDEXES YIELD name, type, entityType, labelsOrTypes, properties, owningConstraint, options RETURN *"
590
661
  )).map((i) => ({
591
662
  name: i.name,
592
663
  type: i.type,
593
664
  entityType: i.entityType,
594
665
  labelsOrTypes: i.labelsOrTypes ?? [],
595
666
  properties: i.properties ?? [],
596
- owningConstraint: i.owningConstraint ?? null
667
+ owningConstraint: i.owningConstraint ?? null,
668
+ options: i.options ?? null
597
669
  }));
598
670
  return { nodeTypes: [...byCombo.values()], relTypes, constraints, indexes };
599
671
  });
@@ -704,7 +776,55 @@ function schemaFromIntrospection(input) {
704
776
  relUnique.add(`${key}.${c.properties[0]}`);
705
777
  }
706
778
  }
779
+ const vectorOn = /* @__PURE__ */ new Map();
780
+ const fulltext = [];
707
781
  for (const i of input.indexes) {
782
+ if (i.type === "FULLTEXT") {
783
+ const where = `full-text index ${i.name}`;
784
+ if (i.entityType !== "NODE") {
785
+ warnings.push(`Skipped ${where}: relationship full-text indexes are not supported.`);
786
+ } else if (i.labelsOrTypes.length !== 1) {
787
+ warnings.push(`Skipped ${where}: only single-label full-text indexes are supported.`);
788
+ } else if (!IDENT2.test(i.name)) {
789
+ warnings.push(`Skipped ${where}: its name is not a valid identifier.`);
790
+ } else {
791
+ fulltext.push({
792
+ name: i.name,
793
+ label: i.labelsOrTypes[0],
794
+ properties: i.properties,
795
+ config: (i.options ?? {}).indexConfig ?? {}
796
+ });
797
+ }
798
+ continue;
799
+ }
800
+ if (i.type === "VECTOR" && i.entityType === "NODE") {
801
+ const where = `vector index ${i.name}`;
802
+ if (i.properties.length !== 1 || i.labelsOrTypes.length !== 1) {
803
+ warnings.push(
804
+ `Skipped ${where}: only single-label, single-property indexes are supported.`
805
+ );
806
+ continue;
807
+ }
808
+ const config = (i.options ?? {}).indexConfig;
809
+ const dims = Number(config?.["vector.dimensions"]);
810
+ const similarity = String(config?.["vector.similarity_function"] ?? "").toLowerCase();
811
+ if (!Number.isInteger(dims) || dims < 1 || dims > MAX_VECTOR_DIMENSIONS) {
812
+ warnings.push(`Skipped ${where}: no supported vector.dimensions in its options.`);
813
+ continue;
814
+ }
815
+ if (!VECTOR_SIMILARITIES.includes(similarity)) {
816
+ warnings.push(`Skipped ${where}: unsupported similarity function "${similarity}".`);
817
+ continue;
818
+ }
819
+ vectorOn.set(`${i.labelsOrTypes[0]}.${i.properties[0]}`, {
820
+ name: i.name,
821
+ dimensions: dims,
822
+ similarity,
823
+ // Neo4j turns quantization on by default (5.23+): only an explicit "off" is worth keeping.
824
+ quantization: config?.["vector.quantization.enabled"] === false ? false : void 0
825
+ });
826
+ continue;
827
+ }
708
828
  if (i.type !== "RANGE" || i.owningConstraint || i.properties.length !== 1 || i.labelsOrTypes.length !== 1) {
709
829
  continue;
710
830
  }
@@ -724,6 +844,29 @@ function schemaFromIntrospection(input) {
724
844
  warnings.push(`Skipped ${label}.${prop}: not a valid identifier.`);
725
845
  continue;
726
846
  }
847
+ const vector = vectorOn.get(`${label}.${prop}`);
848
+ if (vector) {
849
+ const args = [
850
+ { key: "similarity", value: { kind: "identifier", value: vector.similarity } }
851
+ ];
852
+ if (vector.name !== `${label}_${prop}_vector`) {
853
+ args.push({ key: "name", value: { kind: "string", value: vector.name } });
854
+ }
855
+ if (vector.quantization === false) {
856
+ args.push({ key: "quantization", value: { kind: "boolean", value: false } });
857
+ }
858
+ fields.push({
859
+ kind: "Scalar",
860
+ name: prop,
861
+ type: {
862
+ name: "Vector",
863
+ optional: acc.mandatoryIn !== e.combos,
864
+ dimensions: vector.dimensions
865
+ },
866
+ decorators: [{ name: "vectorIndex", args }]
867
+ });
868
+ continue;
869
+ }
727
870
  const t = mapType([...acc.types]);
728
871
  if (!t) {
729
872
  warnings.push(
@@ -837,11 +980,46 @@ function schemaFromIntrospection(input) {
837
980
  });
838
981
  }
839
982
  }
840
- const nodes = [...nodeFields].map(([name, fields]) => ({
841
- kind: "Node",
842
- name,
843
- fields
844
- }));
983
+ const attributesOf = /* @__PURE__ */ new Map();
984
+ for (const ft of fulltext) {
985
+ const where = `full-text index ${ft.name}`;
986
+ const fields = nodeFields.get(ft.label);
987
+ if (!fields) {
988
+ warnings.push(`Skipped ${where}: label ${ft.label} has no nodes in the database.`);
989
+ continue;
990
+ }
991
+ const missing = ft.properties.filter(
992
+ (p) => !fields.some((f) => f.kind === "Scalar" && f.name === p && f.type.name === "String")
993
+ );
994
+ if (missing.length) {
995
+ warnings.push(
996
+ `Skipped ${where}: ${missing.map((p) => `${ft.label}.${p}`).join(", ")} not found as String / String[] properties.`
997
+ );
998
+ continue;
999
+ }
1000
+ const args = [];
1001
+ if (ft.name !== `${ft.label}_${ft.properties.join("_")}_fulltext`) {
1002
+ args.push({ key: "name", value: { kind: "string", value: ft.name } });
1003
+ }
1004
+ const analyzer = String(ft.config["fulltext.analyzer"] ?? DEFAULT_FULLTEXT_ANALYZER);
1005
+ if (analyzer !== DEFAULT_FULLTEXT_ANALYZER) {
1006
+ if (!FULLTEXT_ANALYZERS.includes(analyzer)) {
1007
+ warnings.push(`Skipped ${where}: unsupported analyzer "${analyzer}".`);
1008
+ continue;
1009
+ }
1010
+ args.push({ key: "analyzer", value: { kind: "string", value: analyzer } });
1011
+ }
1012
+ if (ft.config["fulltext.eventually_consistent"] === true) {
1013
+ args.push({ key: "eventuallyConsistent", value: { kind: "boolean", value: true } });
1014
+ }
1015
+ const list = attributesOf.get(ft.label) ?? [];
1016
+ list.push({ kind: "ModelAttribute", name: "fulltext", fields: [...ft.properties], args });
1017
+ attributesOf.set(ft.label, list);
1018
+ }
1019
+ const nodes = [...nodeFields].map(([name, fields]) => {
1020
+ const attributes = attributesOf.get(name);
1021
+ return attributes ? { kind: "Node", name, fields, attributes } : { kind: "Node", name, fields };
1022
+ });
845
1023
  for (const n of nodes) {
846
1024
  if (!n.fields.some((f) => f.kind === "Scalar")) {
847
1025
  warnings.push(`Node ${n.name} has no properties in the database.`);
@@ -862,6 +1040,8 @@ export {
862
1040
  defineMigration,
863
1041
  diffSchemaModels,
864
1042
  ensureMigrationInfrastructure,
1043
+ fulltextIndexStatement,
1044
+ fulltextIndexStatementsFromSchema,
865
1045
  indexStatementsFromSchema,
866
1046
  introspectDatabase,
867
1047
  isEmptyPlan,
@@ -872,6 +1052,8 @@ export {
872
1052
  runPendingMigrations,
873
1053
  schemaFromIntrospection,
874
1054
  schemaIntegrationHints,
1055
+ vectorIndexStatement,
1056
+ vectorIndexStatementsFromSchema,
875
1057
  wrapInTransactions
876
1058
  };
877
1059
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/batch.ts","../src/defineMigration.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,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a,EAAE,GAAG,SAAS;AAC3F;","names":["dec","q","toNative","toNative","IDENT"]}
1
+ {"version":3,"sources":["../src/batch.ts","../src/defineMigration.ts","../src/migrationDb.ts","../src/rename.ts","../src/push.ts","../src/diff.ts","../src/tracker.ts","../src/runner.ts","../src/schemaHints.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 {\n resolveSchema,\n type NodeDeclaration,\n type ScalarNodeField,\n type SchemaDocument,\n} from \"@cyphra/schema\";\nimport { fulltextIndexStatement, vectorIndexStatement } from \"./diff.js\";\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\n/**\n * Generate `CREATE VECTOR INDEX … IF NOT EXISTS` for every `Vector(N) @vectorIndex(...)` node field,\n * with `vector.dimensions` and `vector.similarity_function` in `OPTIONS` (Neo4j 5.15+).\n *\n * @param doc - Parsed schema AST.\n * @returns Cypher DDL strings, named like migrations name them.\n */\nexport function vectorIndexStatementsFromSchema(doc: SchemaDocument): string[] {\n const statements: string[] = [];\n for (const n of resolveSchema(doc).nodes) {\n for (const f of n.fields) {\n const stmt = f.kind === \"scalar\" ? vectorIndexStatement(n.label, f) : null;\n if (stmt) statements.push(stmt);\n }\n }\n return statements;\n}\n\n/**\n * Generate `CREATE FULLTEXT INDEX … IF NOT EXISTS` for every `@@fulltext([...])` node attribute,\n * with `fulltext.analyzer` / `fulltext.eventually_consistent` in `OPTIONS` when set.\n *\n * @param doc - Parsed schema AST.\n * @returns Cypher DDL strings, named like migrations name them.\n */\nexport function fulltextIndexStatementsFromSchema(doc: SchemaDocument): string[] {\n const statements: string[] = [];\n for (const n of resolveSchema(doc).nodes) {\n for (const index of n.fulltextIndexes ?? []) {\n statements.push(fulltextIndexStatement(n.label, index));\n }\n }\n return statements;\n}\n\nfunction escapeConstraintName(name: string): string {\n return name.replace(/[^A-Za-z0-9_]/g, \"_\");\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, vector and full-text indexes, named exactly like\n * `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 ResolvedFulltextIndex,\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/**\n * `CREATE VECTOR INDEX … IF NOT EXISTS` for a `Vector(N) @vectorIndex(...)` field (Neo4j 5.15+).\n * Dimensions and similarity are part of the statement, so changing either one makes the diff drop\n * and recreate the index.\n */\nexport function vectorIndexStatement(label: string, f: ResolvedScalarField): string | null {\n if (f.type !== \"Vector\" || !f.vectorIndex || f.dimensions === undefined) return null;\n const entries = [\n `\\`vector.dimensions\\`: ${f.dimensions}`,\n `\\`vector.similarity_function\\`: '${f.vectorIndex.similarity}'`,\n ];\n if (f.vectorIndex.quantization !== undefined) {\n entries.push(`\\`vector.quantization.enabled\\`: ${f.vectorIndex.quantization}`);\n }\n const config = `{${entries.join(\", \")}}`;\n return `CREATE VECTOR INDEX ${f.vectorIndex.name} IF NOT EXISTS FOR (n:${q(label)}) ON n.${q(f.name)} OPTIONS {indexConfig: ${config}}`;\n}\n\n/**\n * `CREATE FULLTEXT INDEX … IF NOT EXISTS` for a `@@fulltext([...])` model attribute. Fields,\n * analyzer and consistency are part of the statement, so changing any of them makes the diff drop\n * and recreate the index.\n */\nexport function fulltextIndexStatement(label: string, index: ResolvedFulltextIndex): string {\n const props = index.fields.map((f) => `n.${q(f)}`).join(\", \");\n const entries: string[] = [];\n if (index.analyzer !== undefined) {\n entries.push(`\\`fulltext.analyzer\\`: '${index.analyzer}'`);\n }\n if (index.eventuallyConsistent !== undefined) {\n entries.push(`\\`fulltext.eventually_consistent\\`: ${index.eventuallyConsistent}`);\n }\n const options = entries.length ? ` OPTIONS {indexConfig: {${entries.join(\", \")}}}` : \"\";\n return `CREATE FULLTEXT INDEX ${index.name} IF NOT EXISTS FOR (n:${q(label)}) ON EACH [${props}]${options}`;\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 const vector = vectorIndexStatement(n.label, f);\n if (vector) {\n out.push({ name: f.vectorIndex!.name, kind: \"index\", create: vector });\n continue;\n }\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 n of model.nodes) {\n for (const index of n.fulltextIndexes ?? []) {\n out.push({ name: index.name, kind: \"index\", create: fulltextIndexStatement(n.label, index) });\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 if (f.type === \"Vector\") return `Vector(${f.dimensions})${f.optional ? \"?\" : \"\"}`;\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 && after.type === \"Vector\" && before.type === \"Vector\") {\n if (before.dimensions !== after.dimensions) {\n warnings.push(\n `${model}.${name} changed dimensions ${before.dimensions} → ${after.dimensions}; existing embeddings keep their old length and are not indexed (or returned by findSimilar) until re-embedded.`,\n );\n }\n } else 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 { 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","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 {\n DEFAULT_FULLTEXT_ANALYZER,\n FULLTEXT_ANALYZERS,\n MAX_VECTOR_DIMENSIONS,\n VECTOR_SIMILARITIES,\n type Decorator,\n type DecoratorArg,\n type ModelAttribute,\n type NodeDeclaration,\n type RelationalNodeField,\n type RelationshipDeclaration,\n type ScalarNodeField,\n type ScalarTypeName,\n type 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 /** `OPTIONS` of the index (`indexConfig` holds a vector index's dimensions and similarity). */\n readonly options?: Readonly<Record<string, unknown>> | 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, options 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 options: (i.options as Record<string, unknown> | 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 const vectorOn = new Map<\n string,\n { name: string; dimensions: number; similarity: string; quantization: false | undefined }\n >();\n const fulltext: {\n name: string;\n label: string;\n properties: readonly string[];\n config: Record<string, unknown>;\n }[] = [];\n for (const i of input.indexes) {\n if (i.type === \"FULLTEXT\") {\n const where = `full-text index ${i.name}`;\n if (i.entityType !== \"NODE\") {\n warnings.push(`Skipped ${where}: relationship full-text indexes are not supported.`);\n } else if (i.labelsOrTypes.length !== 1) {\n warnings.push(`Skipped ${where}: only single-label full-text indexes are supported.`);\n } else if (!IDENT.test(i.name)) {\n warnings.push(`Skipped ${where}: its name is not a valid identifier.`);\n } else {\n fulltext.push({\n name: i.name,\n label: i.labelsOrTypes[0]!,\n properties: i.properties,\n config:\n ((i.options ?? {}) as { indexConfig?: Record<string, unknown> }).indexConfig ?? {},\n });\n }\n continue;\n }\n if (i.type === \"VECTOR\" && i.entityType === \"NODE\") {\n const where = `vector index ${i.name}`;\n if (i.properties.length !== 1 || i.labelsOrTypes.length !== 1) {\n warnings.push(\n `Skipped ${where}: only single-label, single-property indexes are supported.`,\n );\n continue;\n }\n const config = ((i.options ?? {}) as { indexConfig?: Record<string, unknown> }).indexConfig;\n const dims = Number(config?.[\"vector.dimensions\"]);\n const similarity = String(config?.[\"vector.similarity_function\"] ?? \"\").toLowerCase();\n if (!Number.isInteger(dims) || dims < 1 || dims > MAX_VECTOR_DIMENSIONS) {\n warnings.push(`Skipped ${where}: no supported vector.dimensions in its options.`);\n continue;\n }\n if (!(VECTOR_SIMILARITIES as readonly string[]).includes(similarity)) {\n warnings.push(`Skipped ${where}: unsupported similarity function \"${similarity}\".`);\n continue;\n }\n vectorOn.set(`${i.labelsOrTypes[0]}.${i.properties[0]}`, {\n name: i.name,\n dimensions: dims,\n similarity,\n // Neo4j turns quantization on by default (5.23+): only an explicit \"off\" is worth keeping.\n quantization: config?.[\"vector.quantization.enabled\"] === false ? false : undefined,\n });\n continue;\n }\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 vector = vectorOn.get(`${label}.${prop}`);\n if (vector) {\n const args: DecoratorArg[] = [\n { key: \"similarity\", value: { kind: \"identifier\", value: vector.similarity } },\n ];\n if (vector.name !== `${label}_${prop}_vector`) {\n args.push({ key: \"name\", value: { kind: \"string\", value: vector.name } });\n }\n if (vector.quantization === false) {\n args.push({ key: \"quantization\", value: { kind: \"boolean\", value: false } });\n }\n fields.push({\n kind: \"Scalar\",\n name: prop,\n type: {\n name: \"Vector\",\n optional: acc.mandatoryIn !== e.combos,\n dimensions: vector.dimensions,\n },\n decorators: [{ name: \"vectorIndex\", args }],\n });\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 // --- full-text indexes → @@fulltext ----------------------------------------------\n const attributesOf = new Map<string, ModelAttribute[]>();\n for (const ft of fulltext) {\n const where = `full-text index ${ft.name}`;\n const fields = nodeFields.get(ft.label);\n if (!fields) {\n warnings.push(`Skipped ${where}: label ${ft.label} has no nodes in the database.`);\n continue;\n }\n const missing = ft.properties.filter(\n (p) => !fields.some((f) => f.kind === \"Scalar\" && f.name === p && f.type.name === \"String\"),\n );\n if (missing.length) {\n warnings.push(\n `Skipped ${where}: ${missing.map((p) => `${ft.label}.${p}`).join(\", \")} not found as String / String[] properties.`,\n );\n continue;\n }\n const args: DecoratorArg[] = [];\n if (ft.name !== `${ft.label}_${ft.properties.join(\"_\")}_fulltext`) {\n args.push({ key: \"name\", value: { kind: \"string\", value: ft.name } });\n }\n const analyzer = String(ft.config[\"fulltext.analyzer\"] ?? DEFAULT_FULLTEXT_ANALYZER);\n if (analyzer !== DEFAULT_FULLTEXT_ANALYZER) {\n if (!(FULLTEXT_ANALYZERS as readonly string[]).includes(analyzer)) {\n warnings.push(`Skipped ${where}: unsupported analyzer \"${analyzer}\".`);\n continue;\n }\n args.push({ key: \"analyzer\", value: { kind: \"string\", value: analyzer } });\n }\n // Neo4j's default is false: only an explicit \"on\" is worth keeping.\n if (ft.config[\"fulltext.eventually_consistent\"] === true) {\n args.push({ key: \"eventuallyConsistent\", value: { kind: \"boolean\", value: true } });\n }\n const list = attributesOf.get(ft.label) ?? [];\n list.push({ kind: \"ModelAttribute\", name: \"fulltext\", fields: [...ft.properties], args });\n attributesOf.set(ft.label, list);\n }\n\n const nodes: NodeDeclaration[] = [...nodeFields].map(([name, fields]) => {\n const attributes = attributesOf.get(name);\n return attributes ? { kind: \"Node\", name, fields, attributes } : { kind: \"Node\", name, 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,g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rator",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "Versioned schema migrations for Neo4j: constraints, indexes and data migrations (Cyphra)",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -20,9 +20,9 @@
20
20
  }
21
21
  },
22
22
  "dependencies": {
23
- "@cyphra/query": "0.6.0",
24
- "@cyphra/runtime": "0.6.0",
25
- "@cyphra/schema": "0.6.0"
23
+ "@cyphra/query": "0.7.0",
24
+ "@cyphra/runtime": "0.7.0",
25
+ "@cyphra/schema": "0.7.0"
26
26
  },
27
27
  "peerDependencies": {
28
28
  "neo4j-driver": "^5.28.3 || ^6.0.0"