@cyphra/migrator 0.1.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/README.md ADDED
@@ -0,0 +1,17 @@
1
+ # @cyphra/migrator
2
+
3
+ Versioned Neo4j migrations and schema push for Cyphra.
4
+
5
+ ```ts
6
+ import { defineMigration, runPendingMigrations } from "@cyphra/migrator";
7
+ import { CyphraClient } from "@cyphra/runtime";
8
+
9
+ export default defineMigration({
10
+ name: "001_example",
11
+ async up({ db }) {
12
+ await db.run`RETURN 1`;
13
+ },
14
+ });
15
+ ```
16
+
17
+ Tracking node: `(:__CyphraMigration { name, appliedAt, checksum })`.
@@ -0,0 +1,178 @@
1
+ import { Session } from 'neo4j-driver';
2
+ import { CyphraClient } from '@cyphra/runtime';
3
+ import { SchemaDocument } from '@cyphra/schema';
4
+ import { CompiledCypher } from '@cyphra/query';
5
+
6
+ /**
7
+ * Neo4j 5+ batching: wrap `inner` in `CALL { … } IN TRANSACTIONS OF n ROWS`.
8
+ *
9
+ * @param innerCypher - Subquery body (without `CALL {` / `}` wrapper).
10
+ * @param batchSize - Rows per transaction.
11
+ * @returns Full Cypher string to pass to `session.run`.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * const cypher = wrapInTransactions(
16
+ * "MATCH (u:User) WITH u LIMIT $batchSize SET u.processed = true",
17
+ * 1000,
18
+ * );
19
+ * ```
20
+ */
21
+ declare function wrapInTransactions(innerCypher: string, batchSize: number): string;
22
+
23
+ /**
24
+ * Database handle passed to `up()` in {@link defineMigration}.
25
+ */
26
+ type MigrationDb = {
27
+ /**
28
+ * Execute parameterized Cypher (tagged template); values are never concatenated as raw Cypher.
29
+ */
30
+ run(strings: TemplateStringsArray, ...values: unknown[]): Promise<void>;
31
+ /**
32
+ * Run a subquery inside `CALL { … } IN TRANSACTIONS OF n ROWS` (Neo4j 5+).
33
+ * `inner` is the body only (no `CALL` wrapper); it should typically batch work with `LIMIT`/`WITH`.
34
+ *
35
+ * @param opts.inner - Cypher inside the implicit subquery.
36
+ * @param opts.batchSize - Rows per transaction (must be ≥ 1).
37
+ * @param opts.params - Optional parameters for the outer `run`.
38
+ */
39
+ runInTransactionBatches(opts: {
40
+ inner: string;
41
+ batchSize: number;
42
+ params?: Record<string, unknown>;
43
+ }): Promise<void>;
44
+ /** Structural / data helpers (validated identifiers only). */
45
+ readonly migrate: MigrationMigrateHelpers;
46
+ };
47
+ type MigrationMigrateHelpers = {
48
+ renameLabel(opts: {
49
+ from: string;
50
+ to: string;
51
+ }): Promise<void>;
52
+ renameProperty(opts: {
53
+ label: string;
54
+ from: string;
55
+ to: string;
56
+ }): Promise<void>;
57
+ };
58
+ /**
59
+ * Build a {@link MigrationDb} bound to one open session (one migration transaction policy).
60
+ *
61
+ * @param client - Cyphra runtime client.
62
+ * @param session - Neo4j session (caller manages lifecycle).
63
+ */
64
+ declare function createMigrationDb(client: CyphraClient, session: Session): MigrationDb;
65
+
66
+ /**
67
+ * Versioned migration: `name` is stable; `up` runs once per database.
68
+ */
69
+ type MigrationDefinition = {
70
+ readonly name: string;
71
+ readonly up: (ctx: {
72
+ db: MigrationDb;
73
+ }) => Promise<void>;
74
+ };
75
+ /**
76
+ * Define a migration module default export.
77
+ *
78
+ * @param def - Migration name and `up` handler.
79
+ *
80
+ * @example
81
+ * ```ts
82
+ * export default defineMigration({
83
+ * name: "001_init",
84
+ * async up({ db }) {
85
+ * await db.run`MERGE (n:Example { id: ${"seed-1"} })`;
86
+ * },
87
+ * });
88
+ * ```
89
+ */
90
+ declare function defineMigration(def: MigrationDefinition): MigrationDefinition;
91
+
92
+ /**
93
+ * Generate `CREATE CONSTRAINT … IF NOT EXISTS` statements for node `@id` / `@unique` and relationship `@unique`.
94
+ *
95
+ * Relationship property uniqueness uses Neo4j 5.7+ syntax (`FOR ()-[r:TYPE]-() REQUIRE r.prop IS UNIQUE`).
96
+ *
97
+ * @param doc - Parsed schema AST.
98
+ * @returns Cypher DDL strings (Neo4j 5 syntax).
99
+ */
100
+ declare function constraintStatementsFromSchema(doc: SchemaDocument): string[];
101
+ /**
102
+ * Generate `CREATE RANGE INDEX … IF NOT EXISTS` for `@index` on **node** scalars and on **relationship** model scalars.
103
+ * Node indexes use `(n:Label)`; relationship indexes use `()-[r:TYPE]-()` with the Neo4j type from `type "…"`.
104
+ *
105
+ * @param doc - Parsed schema AST.
106
+ * @returns Cypher DDL strings (Neo4j 5+ range index syntax).
107
+ */
108
+ declare function indexStatementsFromSchema(doc: SchemaDocument): string[];
109
+
110
+ /**
111
+ * Build Cypher to rename a node label (validated identifiers only — not user-controlled strings).
112
+ *
113
+ * @param fromLabel - Current label.
114
+ * @param toLabel - Target label.
115
+ */
116
+ declare function compileRenameLabel(fromLabel: string, toLabel: string): CompiledCypher;
117
+ /**
118
+ * Build Cypher to rename a property on nodes with a given label.
119
+ *
120
+ * @param label - Node label.
121
+ * @param fromProp - Existing property key.
122
+ * @param toProp - New property key.
123
+ */
124
+ declare function compileRenameProperty(label: string, fromProp: string, toProp: string): CompiledCypher;
125
+
126
+ /** Migration with precomputed checksum (e.g. SHA-256 of source file). */
127
+ type LoadedMigration = {
128
+ readonly name: string;
129
+ readonly checksum: string;
130
+ readonly definition: MigrationDefinition;
131
+ };
132
+ /**
133
+ * Apply migrations in order, skipping those already recorded on `__CyphraMigration`.
134
+ *
135
+ * @param client - Cyphra client.
136
+ * @param ordered - Migrations sorted lexicographically by `name` (caller responsibility).
137
+ * @returns Names that were applied in this run.
138
+ */
139
+ declare function runPendingMigrations(client: CyphraClient, ordered: readonly LoadedMigration[]): Promise<readonly string[]>;
140
+ /**
141
+ * Execute DDL statements (e.g. from {@link constraintStatementsFromSchema}).
142
+ *
143
+ * @param client - Cyphra client.
144
+ * @param statements - Cypher DDL, one statement per string.
145
+ */
146
+ declare function applyConstraintStatements(client: CyphraClient, statements: readonly string[]): Promise<void>;
147
+
148
+ /**
149
+ * Static hints for operating a database alongside the schema (no live DB inspection in V1).
150
+ *
151
+ * @param doc - Parsed schema document.
152
+ * @returns Human-readable lines suitable for logs or docs.
153
+ */
154
+ declare function schemaIntegrationHints(doc: SchemaDocument): string[];
155
+
156
+ /** Neo4j label used to record applied migrations. */
157
+ declare const CYPHRA_MIGRATION_LABEL = "__CyphraMigration";
158
+ /**
159
+ * Ensure uniqueness on migration name (idempotent).
160
+ *
161
+ * @param session - Open session.
162
+ */
163
+ declare function ensureMigrationInfrastructure(session: Session): Promise<void>;
164
+ /**
165
+ * @param session - Open session.
166
+ * @param name - Migration name (e.g. file stem).
167
+ */
168
+ declare function isMigrationApplied(session: Session, name: string): Promise<boolean>;
169
+ /**
170
+ * Persist a successful migration.
171
+ *
172
+ * @param session - Open session.
173
+ * @param name - Migration name.
174
+ * @param checksum - Content checksum (e.g. SHA-256 hex).
175
+ */
176
+ declare function recordMigration(session: Session, name: string, checksum: string): Promise<void>;
177
+
178
+ export { CYPHRA_MIGRATION_LABEL, type LoadedMigration, type MigrationDb, type MigrationDefinition, type MigrationMigrateHelpers, applyConstraintStatements, compileRenameLabel, compileRenameProperty, constraintStatementsFromSchema, createMigrationDb, defineMigration, ensureMigrationInfrastructure, indexStatementsFromSchema, isMigrationApplied, recordMigration, runPendingMigrations, schemaIntegrationHints, wrapInTransactions };
package/dist/index.js ADDED
@@ -0,0 +1,247 @@
1
+ // src/batch.ts
2
+ function wrapInTransactions(innerCypher, batchSize) {
3
+ if (!Number.isInteger(batchSize) || batchSize < 1) {
4
+ throw new Error(`batchSize must be a positive integer, got ${batchSize}`);
5
+ }
6
+ return `CALL {
7
+ ${innerCypher.trim()}
8
+ } IN TRANSACTIONS OF ${batchSize} ROWS`;
9
+ }
10
+
11
+ // src/defineMigration.ts
12
+ function defineMigration(def) {
13
+ return def;
14
+ }
15
+
16
+ // src/rename.ts
17
+ var IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
18
+ function assertIdent(name, label) {
19
+ if (!IDENT.test(name)) {
20
+ throw new Error(`Invalid Neo4j ${label} identifier: ${JSON.stringify(name)}`);
21
+ }
22
+ }
23
+ function compileRenameLabel(fromLabel, toLabel) {
24
+ assertIdent(fromLabel, "label");
25
+ assertIdent(toLabel, "label");
26
+ return {
27
+ text: `MATCH (n:\`${fromLabel}\`) SET n:\`${toLabel}\` REMOVE n:\`${fromLabel}\``,
28
+ params: {}
29
+ };
30
+ }
31
+ function compileRenameProperty(label, fromProp, toProp) {
32
+ assertIdent(label, "label");
33
+ assertIdent(fromProp, "property");
34
+ assertIdent(toProp, "property");
35
+ return {
36
+ text: `MATCH (n:\`${label}\`) WHERE n.\`${fromProp}\` IS NOT NULL SET n.\`${toProp}\` = n.\`${fromProp}\` REMOVE n.\`${fromProp}\``,
37
+ params: {}
38
+ };
39
+ }
40
+
41
+ // src/migrationDb.ts
42
+ function createMigrationDb(client, session) {
43
+ const run = async (strings, ...values) => {
44
+ const result = await client.runCypher(session, strings, ...values);
45
+ await result;
46
+ };
47
+ const runInTransactionBatches = async (opts) => {
48
+ const text = wrapInTransactions(opts.inner, opts.batchSize);
49
+ const result = await session.run(text, opts.params ?? {});
50
+ await result;
51
+ };
52
+ const migrate = {
53
+ async renameLabel(opts) {
54
+ const { text, params } = compileRenameLabel(opts.from, opts.to);
55
+ await session.run(text, params);
56
+ },
57
+ async renameProperty(opts) {
58
+ const { text, params } = compileRenameProperty(opts.label, opts.from, opts.to);
59
+ await session.run(text, params);
60
+ }
61
+ };
62
+ return { run, runInTransactionBatches, migrate };
63
+ }
64
+
65
+ // src/push.ts
66
+ function isScalarWithDecorator(field, dec) {
67
+ return field.kind === "Scalar" && field.decorators.some((d) => d.name === dec);
68
+ }
69
+ function hasDecoratorName(field, name) {
70
+ return field.decorators.some((d) => d.name === name);
71
+ }
72
+ function cypherRelTypeToken(relType) {
73
+ if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(relType)) {
74
+ return relType;
75
+ }
76
+ return `\`${relType.replace(/`/g, "``")}\``;
77
+ }
78
+ function idPropertyName(node) {
79
+ for (const f of node.fields) {
80
+ if (isScalarWithDecorator(f, "id")) {
81
+ return f.name;
82
+ }
83
+ }
84
+ return void 0;
85
+ }
86
+ function constraintStatementsFromSchema(doc) {
87
+ const statements = [];
88
+ for (const decl of doc.declarations) {
89
+ if (decl.kind === "Node") {
90
+ const label = decl.name;
91
+ const idProp = idPropertyName(decl);
92
+ if (idProp) {
93
+ statements.push(
94
+ `CREATE CONSTRAINT ${escapeConstraintName(`${label}_${idProp}_id`)} IF NOT EXISTS FOR (n:\`${label}\`) REQUIRE n.\`${idProp}\` IS UNIQUE`
95
+ );
96
+ }
97
+ for (const f of decl.fields) {
98
+ if (!isScalarWithDecorator(f, "unique")) {
99
+ continue;
100
+ }
101
+ if (f.name === idProp) {
102
+ continue;
103
+ }
104
+ statements.push(
105
+ `CREATE CONSTRAINT ${escapeConstraintName(`${label}_${f.name}_unique`)} IF NOT EXISTS FOR (n:\`${label}\`) REQUIRE n.\`${f.name}\` IS UNIQUE`
106
+ );
107
+ }
108
+ continue;
109
+ }
110
+ const typeTok = cypherRelTypeToken(decl.relType);
111
+ for (const f of decl.fields) {
112
+ if (!isScalarWithDecorator(f, "unique")) {
113
+ continue;
114
+ }
115
+ statements.push(
116
+ `CREATE CONSTRAINT ${escapeConstraintName(`${decl.name}_${f.name}_rel_unique`)} IF NOT EXISTS FOR ()-[r:${typeTok}]-() REQUIRE r.\`${f.name}\` IS UNIQUE`
117
+ );
118
+ }
119
+ }
120
+ return statements;
121
+ }
122
+ function indexStatementsFromSchema(doc) {
123
+ const statements = [];
124
+ for (const decl of doc.declarations) {
125
+ if (decl.kind === "Node") {
126
+ const label = decl.name;
127
+ for (const f of decl.fields) {
128
+ if (f.kind !== "Scalar") {
129
+ continue;
130
+ }
131
+ if (!isScalarWithDecorator(f, "index")) {
132
+ continue;
133
+ }
134
+ if (hasDecoratorName(f, "unique")) {
135
+ continue;
136
+ }
137
+ statements.push(
138
+ `CREATE RANGE INDEX ${escapeConstraintName(`${label}_${f.name}_idx`)} IF NOT EXISTS FOR (n:\`${label}\`) ON (n.\`${f.name}\`)`
139
+ );
140
+ }
141
+ continue;
142
+ }
143
+ const typeTok = cypherRelTypeToken(decl.relType);
144
+ for (const f of decl.fields) {
145
+ if (!isScalarWithDecorator(f, "index")) {
146
+ continue;
147
+ }
148
+ if (hasDecoratorName(f, "unique")) {
149
+ continue;
150
+ }
151
+ statements.push(
152
+ `CREATE RANGE INDEX ${escapeConstraintName(`${decl.name}_${f.name}_rel_idx`)} IF NOT EXISTS FOR ()-[r:${typeTok}]-() ON (r.\`${f.name}\`)`
153
+ );
154
+ }
155
+ }
156
+ return statements;
157
+ }
158
+ function escapeConstraintName(name) {
159
+ return name.replace(/[^A-Za-z0-9_]/g, "_");
160
+ }
161
+
162
+ // src/tracker.ts
163
+ var CYPHRA_MIGRATION_LABEL = "__CyphraMigration";
164
+ async function ensureMigrationInfrastructure(session) {
165
+ const r = await session.run(`
166
+ CREATE CONSTRAINT cyphra_migration_name_unique IF NOT EXISTS
167
+ FOR (m:__CyphraMigration) REQUIRE m.name IS UNIQUE
168
+ `);
169
+ await r;
170
+ }
171
+ async function isMigrationApplied(session, name) {
172
+ const result = await session.run(
173
+ `MATCH (m:__CyphraMigration { name: $name }) RETURN m AS m LIMIT 1`,
174
+ { name }
175
+ );
176
+ const q = await result;
177
+ return q.records.length > 0;
178
+ }
179
+ async function recordMigration(session, name, checksum) {
180
+ const r = await session.run(
181
+ `
182
+ CREATE (m:__CyphraMigration {
183
+ name: $name,
184
+ appliedAt: datetime(),
185
+ checksum: $checksum
186
+ })
187
+ `,
188
+ { name, checksum }
189
+ );
190
+ await r;
191
+ }
192
+
193
+ // src/runner.ts
194
+ async function runPendingMigrations(client, ordered) {
195
+ const applied = [];
196
+ await client.withSession(async (session) => {
197
+ await ensureMigrationInfrastructure(session);
198
+ for (const m of ordered) {
199
+ if (await isMigrationApplied(session, m.name)) {
200
+ continue;
201
+ }
202
+ const db = createMigrationDb(client, session);
203
+ await m.definition.up({ db });
204
+ await recordMigration(session, m.name, m.checksum);
205
+ applied.push(m.name);
206
+ }
207
+ });
208
+ return applied;
209
+ }
210
+ async function applyConstraintStatements(client, statements) {
211
+ await client.withSession(async (session) => {
212
+ for (const statement of statements) {
213
+ const r = await session.run(statement);
214
+ await r;
215
+ }
216
+ });
217
+ }
218
+
219
+ // src/schemaHints.ts
220
+ function schemaIntegrationHints(doc) {
221
+ const hints = [];
222
+ for (const d of doc.declarations) {
223
+ if (d.kind === "Relationship") {
224
+ hints.push(
225
+ `Relationship model "${d.name}" maps to Neo4j type \`${d.relType}\` (:${d.from} \u2192 :${d.to}).`
226
+ );
227
+ }
228
+ }
229
+ return hints;
230
+ }
231
+ export {
232
+ CYPHRA_MIGRATION_LABEL,
233
+ applyConstraintStatements,
234
+ compileRenameLabel,
235
+ compileRenameProperty,
236
+ constraintStatementsFromSchema,
237
+ createMigrationDb,
238
+ defineMigration,
239
+ ensureMigrationInfrastructure,
240
+ indexStatementsFromSchema,
241
+ isMigrationApplied,
242
+ recordMigration,
243
+ runPendingMigrations,
244
+ schemaIntegrationHints,
245
+ wrapInTransactions
246
+ };
247
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/batch.ts","../src/defineMigration.ts","../src/rename.ts","../src/migrationDb.ts","../src/push.ts","../src/tracker.ts","../src/runner.ts","../src/schemaHints.ts"],"sourcesContent":["/**\n * Neo4j 5+ batching: wrap `inner` in `CALL { … } IN TRANSACTIONS OF n ROWS`.\n *\n * @param innerCypher - Subquery body (without `CALL {` / `}` wrapper).\n * @param batchSize - Rows per transaction.\n * @returns Full Cypher string to pass to `session.run`.\n *\n * @example\n * ```ts\n * const cypher = wrapInTransactions(\n * \"MATCH (u:User) WITH u LIMIT $batchSize SET u.processed = true\",\n * 1000,\n * );\n * ```\n */\nexport function wrapInTransactions(innerCypher: string, batchSize: number): string {\n if (!Number.isInteger(batchSize) || batchSize < 1) {\n throw new Error(`batchSize must be a positive integer, got ${batchSize}`);\n }\n return `CALL {\\n${innerCypher.trim()}\\n} IN TRANSACTIONS OF ${batchSize} ROWS`;\n}\n","import type { MigrationDb } from \"./migrationDb.js\";\n\n/**\n * Versioned migration: `name` is stable; `up` runs once per database.\n */\nexport type MigrationDefinition = {\n readonly name: string;\n readonly up: (ctx: { db: MigrationDb }) => Promise<void>;\n};\n\n/**\n * Define a migration module default export.\n *\n * @param def - Migration name and `up` handler.\n *\n * @example\n * ```ts\n * export default defineMigration({\n * name: \"001_init\",\n * async up({ db }) {\n * await db.run`MERGE (n:Example { id: ${\"seed-1\"} })`;\n * },\n * });\n * ```\n */\nexport function defineMigration(def: MigrationDefinition): MigrationDefinition {\n return def;\n}\n","import type { CompiledCypher } from \"@cyphra/query\";\n\nconst IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\nfunction assertIdent(name: string, label: string): void {\n if (!IDENT.test(name)) {\n throw new Error(`Invalid Neo4j ${label} identifier: ${JSON.stringify(name)}`);\n }\n}\n\n/**\n * Build Cypher to rename a node label (validated identifiers only — not user-controlled strings).\n *\n * @param fromLabel - Current label.\n * @param toLabel - Target label.\n */\nexport function compileRenameLabel(fromLabel: string, toLabel: string): CompiledCypher {\n assertIdent(fromLabel, \"label\");\n assertIdent(toLabel, \"label\");\n return {\n text: `MATCH (n:\\`${fromLabel}\\`) SET n:\\`${toLabel}\\` REMOVE n:\\`${fromLabel}\\``,\n params: {},\n };\n}\n\n/**\n * Build Cypher to rename a property on nodes with a given label.\n *\n * @param label - Node label.\n * @param fromProp - Existing property key.\n * @param toProp - New property key.\n */\nexport function compileRenameProperty(\n label: string,\n fromProp: string,\n toProp: string,\n): CompiledCypher {\n assertIdent(label, \"label\");\n assertIdent(fromProp, \"property\");\n assertIdent(toProp, \"property\");\n return {\n text: `MATCH (n:\\`${label}\\`) WHERE n.\\`${fromProp}\\` IS NOT NULL SET n.\\`${toProp}\\` = n.\\`${fromProp}\\` REMOVE n.\\`${fromProp}\\``,\n params: {},\n };\n}\n","import type { Session } from \"neo4j-driver\";\nimport type { CyphraClient } from \"@cyphra/runtime\";\nimport { wrapInTransactions } from \"./batch.js\";\nimport { compileRenameLabel, compileRenameProperty } from \"./rename.js\";\n\n/**\n * Database handle passed to `up()` in {@link defineMigration}.\n */\nexport type MigrationDb = {\n /**\n * Execute parameterized Cypher (tagged template); values are never concatenated as raw Cypher.\n */\n run(strings: TemplateStringsArray, ...values: unknown[]): Promise<void>;\n /**\n * Run a subquery inside `CALL { … } IN TRANSACTIONS OF n ROWS` (Neo4j 5+).\n * `inner` is the body only (no `CALL` wrapper); it should typically batch work with `LIMIT`/`WITH`.\n *\n * @param opts.inner - Cypher inside the implicit subquery.\n * @param opts.batchSize - Rows per transaction (must be ≥ 1).\n * @param opts.params - Optional parameters for the outer `run`.\n */\n runInTransactionBatches(opts: {\n inner: string;\n batchSize: number;\n params?: Record<string, unknown>;\n }): Promise<void>;\n /** Structural / data helpers (validated identifiers only). */\n readonly migrate: MigrationMigrateHelpers;\n};\n\nexport type MigrationMigrateHelpers = {\n renameLabel(opts: { from: string; to: string }): Promise<void>;\n renameProperty(opts: { label: string; from: string; to: string }): Promise<void>;\n};\n\n/**\n * Build a {@link MigrationDb} bound to one open session (one migration transaction policy).\n *\n * @param client - Cyphra runtime client.\n * @param session - Neo4j session (caller manages lifecycle).\n */\nexport function createMigrationDb(client: CyphraClient, session: Session): MigrationDb {\n const run = async (strings: TemplateStringsArray, ...values: unknown[]): Promise<void> => {\n const result = await client.runCypher(session, strings, ...values);\n await result;\n };\n\n const runInTransactionBatches = async (opts: {\n inner: string;\n batchSize: number;\n params?: Record<string, unknown>;\n }): Promise<void> => {\n const text = wrapInTransactions(opts.inner, opts.batchSize);\n const result = await session.run(text, opts.params ?? {});\n await result;\n };\n\n const migrate: MigrationMigrateHelpers = {\n async renameLabel(opts) {\n const { text, params } = compileRenameLabel(opts.from, opts.to);\n await session.run(text, params);\n },\n async renameProperty(opts) {\n const { text, params } = compileRenameProperty(opts.label, opts.from, opts.to);\n await session.run(text, params);\n },\n };\n\n return { run, runInTransactionBatches, migrate };\n}\n","import type { NodeDeclaration, ScalarNodeField, SchemaDocument } from \"@cyphra/schema\";\n\nfunction isScalarWithDecorator(\n field: { readonly kind: string; readonly decorators: readonly { readonly name: string }[] },\n dec: string,\n): field is ScalarNodeField {\n return field.kind === \"Scalar\" && field.decorators.some((d) => d.name === dec);\n}\n\n/** Decorator presence without a type predicate (avoids `never` when chaining multiple `@…` checks). */\nfunction hasDecoratorName(\n field: { readonly decorators: readonly { readonly name: string }[] },\n name: string,\n): boolean {\n return field.decorators.some((d) => d.name === name);\n}\n\n/** Cypher relationship type token for patterns (`:KNOWS` or :`a-b`). */\nfunction cypherRelTypeToken(relType: string): string {\n if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(relType)) {\n return relType;\n }\n return `\\`${relType.replace(/`/g, \"``\")}\\``;\n}\n\nfunction idPropertyName(node: NodeDeclaration): string | undefined {\n for (const f of node.fields) {\n if (isScalarWithDecorator(f, \"id\")) {\n return f.name;\n }\n }\n return undefined;\n}\n\n/**\n * Generate `CREATE CONSTRAINT … IF NOT EXISTS` statements for node `@id` / `@unique` and relationship `@unique`.\n *\n * Relationship property uniqueness uses Neo4j 5.7+ syntax (`FOR ()-[r:TYPE]-() REQUIRE r.prop IS UNIQUE`).\n *\n * @param doc - Parsed schema AST.\n * @returns Cypher DDL strings (Neo4j 5 syntax).\n */\nexport function constraintStatementsFromSchema(doc: SchemaDocument): string[] {\n const statements: string[] = [];\n for (const decl of doc.declarations) {\n if (decl.kind === \"Node\") {\n const label = decl.name;\n const idProp = idPropertyName(decl);\n if (idProp) {\n statements.push(\n `CREATE CONSTRAINT ${escapeConstraintName(`${label}_${idProp}_id`)} IF NOT EXISTS FOR (n:\\`${label}\\`) REQUIRE n.\\`${idProp}\\` IS UNIQUE`,\n );\n }\n for (const f of decl.fields) {\n if (!isScalarWithDecorator(f, \"unique\")) {\n continue;\n }\n if (f.name === idProp) {\n continue;\n }\n statements.push(\n `CREATE CONSTRAINT ${escapeConstraintName(`${label}_${f.name}_unique`)} IF NOT EXISTS FOR (n:\\`${label}\\`) REQUIRE n.\\`${f.name}\\` IS UNIQUE`,\n );\n }\n continue;\n }\n\n const typeTok = cypherRelTypeToken(decl.relType);\n for (const f of decl.fields) {\n if (!isScalarWithDecorator(f, \"unique\")) {\n continue;\n }\n statements.push(\n `CREATE CONSTRAINT ${escapeConstraintName(`${decl.name}_${f.name}_rel_unique`)} IF NOT EXISTS FOR ()-[r:${typeTok}]-() REQUIRE r.\\`${f.name}\\` IS UNIQUE`,\n );\n }\n }\n return statements;\n}\n\n/**\n * Generate `CREATE RANGE INDEX … IF NOT EXISTS` for `@index` on **node** scalars and on **relationship** model scalars.\n * Node indexes use `(n:Label)`; relationship indexes use `()-[r:TYPE]-()` with the Neo4j type from `type \"…\"`.\n *\n * @param doc - Parsed schema AST.\n * @returns Cypher DDL strings (Neo4j 5+ range index syntax).\n */\nexport function indexStatementsFromSchema(doc: SchemaDocument): string[] {\n const statements: string[] = [];\n for (const decl of doc.declarations) {\n if (decl.kind === \"Node\") {\n const label = decl.name;\n for (const f of decl.fields) {\n if (f.kind !== \"Scalar\") {\n continue;\n }\n if (!isScalarWithDecorator(f, \"index\")) {\n continue;\n }\n if (hasDecoratorName(f, \"unique\")) {\n continue;\n }\n statements.push(\n `CREATE RANGE INDEX ${escapeConstraintName(`${label}_${f.name}_idx`)} IF NOT EXISTS FOR (n:\\`${label}\\`) ON (n.\\`${f.name}\\`)`,\n );\n }\n continue;\n }\n\n const typeTok = cypherRelTypeToken(decl.relType);\n for (const f of decl.fields) {\n if (!isScalarWithDecorator(f, \"index\")) {\n continue;\n }\n if (hasDecoratorName(f, \"unique\")) {\n continue;\n }\n statements.push(\n `CREATE RANGE INDEX ${escapeConstraintName(`${decl.name}_${f.name}_rel_idx`)} IF NOT EXISTS FOR ()-[r:${typeTok}]-() ON (r.\\`${f.name}\\`)`,\n );\n }\n }\n return statements;\n}\n\nfunction escapeConstraintName(name: string): string {\n return name.replace(/[^A-Za-z0-9_]/g, \"_\");\n}\n","import type { Session } from \"neo4j-driver\";\n\n/** Neo4j label used to record applied migrations. */\nexport const CYPHRA_MIGRATION_LABEL = \"__CyphraMigration\";\n\n/**\n * Ensure uniqueness on migration name (idempotent).\n *\n * @param session - Open session.\n */\nexport async function ensureMigrationInfrastructure(session: Session): Promise<void> {\n const r = await session.run(`\n CREATE CONSTRAINT cyphra_migration_name_unique IF NOT EXISTS\n FOR (m:__CyphraMigration) REQUIRE m.name IS UNIQUE\n `);\n await r;\n}\n\n/**\n * @param session - Open session.\n * @param name - Migration name (e.g. file stem).\n */\nexport async function isMigrationApplied(session: Session, name: string): Promise<boolean> {\n const result = await session.run(\n `MATCH (m:__CyphraMigration { name: $name }) RETURN m AS m LIMIT 1`,\n { name },\n );\n const q = await result;\n return q.records.length > 0;\n}\n\n/**\n * Persist a successful migration.\n *\n * @param session - Open session.\n * @param name - Migration name.\n * @param checksum - Content checksum (e.g. SHA-256 hex).\n */\nexport async function recordMigration(\n session: Session,\n name: string,\n checksum: string,\n): Promise<void> {\n const r = await session.run(\n `\n CREATE (m:__CyphraMigration {\n name: $name,\n appliedAt: datetime(),\n checksum: $checksum\n })\n `,\n { name, checksum },\n );\n await r;\n}\n","import type { CyphraClient } from \"@cyphra/runtime\";\nimport { createMigrationDb } from \"./migrationDb.js\";\nimport type { MigrationDefinition } from \"./defineMigration.js\";\nimport * as tracker from \"./tracker.js\";\n\n/** Migration with precomputed checksum (e.g. SHA-256 of source file). */\nexport type LoadedMigration = {\n readonly name: string;\n readonly checksum: string;\n readonly definition: MigrationDefinition;\n};\n\n/**\n * Apply migrations in order, skipping those already recorded on `__CyphraMigration`.\n *\n * @param client - Cyphra client.\n * @param ordered - Migrations sorted lexicographically by `name` (caller responsibility).\n * @returns Names that were applied in this run.\n */\nexport async function runPendingMigrations(\n client: CyphraClient,\n ordered: readonly LoadedMigration[],\n): Promise<readonly string[]> {\n const applied: string[] = [];\n await client.withSession(async (session) => {\n await tracker.ensureMigrationInfrastructure(session);\n for (const m of ordered) {\n if (await tracker.isMigrationApplied(session, m.name)) {\n continue;\n }\n const db = createMigrationDb(client, session);\n await m.definition.up({ db });\n await tracker.recordMigration(session, m.name, m.checksum);\n applied.push(m.name);\n }\n });\n return applied;\n}\n\n/**\n * Execute DDL statements (e.g. from {@link constraintStatementsFromSchema}).\n *\n * @param client - Cyphra client.\n * @param statements - Cypher DDL, one statement per string.\n */\nexport async function applyConstraintStatements(\n client: CyphraClient,\n statements: readonly string[],\n): Promise<void> {\n await client.withSession(async (session) => {\n for (const statement of statements) {\n const r = await session.run(statement);\n await r;\n }\n });\n}\n","import type { SchemaDocument } from \"@cyphra/schema\";\n\n/**\n * Static hints for operating a database alongside the schema (no live DB inspection in V1).\n *\n * @param doc - Parsed schema document.\n * @returns Human-readable lines suitable for logs or docs.\n */\nexport function schemaIntegrationHints(doc: SchemaDocument): string[] {\n const hints: string[] = [];\n for (const d of doc.declarations) {\n if (d.kind === \"Relationship\") {\n hints.push(\n `Relationship model \"${d.name}\" maps to Neo4j type \\`${d.relType}\\` (:${d.from} → :${d.to}).`,\n );\n }\n }\n return hints;\n}\n"],"mappings":";AAeO,SAAS,mBAAmB,aAAqB,WAA2B;AACjF,MAAI,CAAC,OAAO,UAAU,SAAS,KAAK,YAAY,GAAG;AACjD,UAAM,IAAI,MAAM,6CAA6C,SAAS,EAAE;AAAA,EAC1E;AACA,SAAO;AAAA,EAAW,YAAY,KAAK,CAAC;AAAA,uBAA0B,SAAS;AACzE;;;ACKO,SAAS,gBAAgB,KAA+C;AAC7E,SAAO;AACT;;;ACzBA,IAAM,QAAQ;AAEd,SAAS,YAAY,MAAc,OAAqB;AACtD,MAAI,CAAC,MAAM,KAAK,IAAI,GAAG;AACrB,UAAM,IAAI,MAAM,iBAAiB,KAAK,gBAAgB,KAAK,UAAU,IAAI,CAAC,EAAE;AAAA,EAC9E;AACF;AAQO,SAAS,mBAAmB,WAAmB,SAAiC;AACrF,cAAY,WA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",
4
+ "description": "Versioned migrations, batch helpers, and schema push for Cyphra",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "README.md"
13
+ ],
14
+ "main": "./dist/index.js",
15
+ "types": "./dist/index.d.ts",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "import": "./dist/index.js"
20
+ }
21
+ },
22
+ "dependencies": {
23
+ "neo4j-driver": "^5.27.0",
24
+ "@cyphra/query": "0.1.0",
25
+ "@cyphra/runtime": "0.1.0",
26
+ "@cyphra/schema": "0.1.0"
27
+ },
28
+ "devDependencies": {
29
+ "@types/node": "^22.10.2",
30
+ "tsup": "^8.3.5",
31
+ "typescript": "^5.7.2",
32
+ "vitest": "^3.0.2"
33
+ },
34
+ "scripts": {
35
+ "build": "tsup",
36
+ "typecheck": "tsc --noEmit",
37
+ "test": "vitest run"
38
+ }
39
+ }