@autofleet/sadot 1.6.0-alpha.0 → 1.6.0-alpha.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/migrations/001-create-core-tables.cjs +1 -1
- package/dist/migrations/001-create-core-tables.cjs.map +1 -1
- package/dist/migrations/001-create-core-tables.js +1 -1
- package/dist/migrations/001-create-core-tables.js.map +1 -1
- package/dist/migrations/index.cjs +1 -1
- package/dist/migrations/index.cjs.map +1 -1
- package/dist/migrations/index.js +1 -1
- package/dist/migrations/index.js.map +1 -1
- package/dist/models/index.cjs +1 -1
- package/dist/models/index.cjs.map +1 -1
- package/dist/models/index.js +1 -1
- package/dist/models/index.js.map +1 -1
- package/package.json +3 -3
|
@@ -12,7 +12,7 @@ const e=async({context:e})=>{let{sequelize:t}=e;await t.query(`
|
|
|
12
12
|
"required" BOOLEAN DEFAULT false,
|
|
13
13
|
"disabled" BOOLEAN DEFAULT false,
|
|
14
14
|
"default_value" JSONB,
|
|
15
|
-
"
|
|
15
|
+
"block_editing_from_u_i" BOOLEAN NOT NULL DEFAULT false,
|
|
16
16
|
"created_at" TIMESTAMPTZ NOT NULL,
|
|
17
17
|
"updated_at" TIMESTAMPTZ,
|
|
18
18
|
"deleted_at" TIMESTAMPTZ,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"001-create-core-tables.cjs","names":["up: MigrationFn<QueryInterface>","down: MigrationFn<QueryInterface>"],"sources":["../../src/migrations/001-create-core-tables.ts"],"sourcesContent":["import type { MigrationFn } from 'umzug';\nimport type { QueryInterface } from 'sequelize';\n\nexport const up: MigrationFn<QueryInterface> = async ({ context: queryInterface }) => {\n const { sequelize } = queryInterface;\n\n await sequelize.query(`\n CREATE TABLE IF NOT EXISTS \"custom_field_definitions\" (\n \"id\" UUID NOT NULL DEFAULT gen_random_uuid(),\n \"name\" VARCHAR NOT NULL,\n \"display_name\" VARCHAR,\n \"field_type\" VARCHAR NOT NULL,\n \"validation\" JSONB,\n \"entity_id\" UUID NOT NULL,\n \"entity_type\" VARCHAR NOT NULL,\n \"model_type\" VARCHAR NOT NULL,\n \"description\" TEXT,\n \"required\" BOOLEAN DEFAULT false,\n \"disabled\" BOOLEAN DEFAULT false,\n \"default_value\" JSONB,\n \"
|
|
1
|
+
{"version":3,"file":"001-create-core-tables.cjs","names":["up: MigrationFn<QueryInterface>","down: MigrationFn<QueryInterface>"],"sources":["../../src/migrations/001-create-core-tables.ts"],"sourcesContent":["import type { MigrationFn } from 'umzug';\nimport type { QueryInterface } from 'sequelize';\n\nexport const up: MigrationFn<QueryInterface> = async ({ context: queryInterface }) => {\n const { sequelize } = queryInterface;\n\n await sequelize.query(`\n CREATE TABLE IF NOT EXISTS \"custom_field_definitions\" (\n \"id\" UUID NOT NULL DEFAULT gen_random_uuid(),\n \"name\" VARCHAR NOT NULL,\n \"display_name\" VARCHAR,\n \"field_type\" VARCHAR NOT NULL,\n \"validation\" JSONB,\n \"entity_id\" UUID NOT NULL,\n \"entity_type\" VARCHAR NOT NULL,\n \"model_type\" VARCHAR NOT NULL,\n \"description\" TEXT,\n \"required\" BOOLEAN DEFAULT false,\n \"disabled\" BOOLEAN DEFAULT false,\n \"default_value\" JSONB,\n \"block_editing_from_u_i\" BOOLEAN NOT NULL DEFAULT false,\n \"created_at\" TIMESTAMPTZ NOT NULL,\n \"updated_at\" TIMESTAMPTZ,\n \"deleted_at\" TIMESTAMPTZ,\n PRIMARY KEY (\"id\")\n )\n `);\n\n await sequelize.query(`\n CREATE UNIQUE INDEX IF NOT EXISTS \"unique_name_model_type\"\n ON \"custom_field_definitions\" (\"model_type\", \"entity_id\", \"name\")\n `);\n\n await sequelize.query(`\n CREATE TABLE IF NOT EXISTS \"custom_field_values\" (\n \"model_id\" UUID NOT NULL,\n \"custom_field_definition_id\" UUID NOT NULL\n REFERENCES \"custom_field_definitions\" (\"id\"),\n \"value\" JSONB,\n \"created_at\" TIMESTAMPTZ NOT NULL,\n \"updated_at\" TIMESTAMPTZ,\n \"deleted_at\" TIMESTAMPTZ,\n PRIMARY KEY (\"model_id\", \"custom_field_definition_id\")\n )\n `);\n\n await sequelize.query(`\n CREATE INDEX IF NOT EXISTS \"idx_custom_field_values_active_definition_id\"\n ON \"custom_field_values\" (\"custom_field_definition_id\")\n WHERE \"deleted_at\" IS NULL\n `);\n\n await sequelize.query(`\n CREATE TABLE IF NOT EXISTS \"custom_validators\" (\n \"id\" UUID NOT NULL DEFAULT gen_random_uuid(),\n \"entity_id\" UUID NOT NULL,\n \"entity_type\" VARCHAR NOT NULL,\n \"model_type\" VARCHAR NOT NULL,\n \"schema\" JSONB NOT NULL,\n \"disabled\" BOOLEAN NOT NULL DEFAULT false,\n \"created_at\" TIMESTAMPTZ NOT NULL,\n \"updated_at\" TIMESTAMPTZ,\n PRIMARY KEY (\"id\")\n )\n `);\n};\n\nexport const down: MigrationFn<QueryInterface> = async ({ context: queryInterface }) => {\n const { sequelize } = queryInterface;\n await sequelize.query('DROP TABLE IF EXISTS \"custom_field_values\"');\n await sequelize.query('DROP TABLE IF EXISTS \"custom_field_definitions\"');\n await sequelize.query('DROP TABLE IF EXISTS \"custom_validators\"');\n};\n"],"mappings":"AAGA,MAAaA,EAAkC,MAAO,CAAE,QAAS,KAAqB,CACpF,GAAM,CAAE,aAAc,EAEtB,MAAM,EAAU,MAAM;;;;;;;;;;;;;;;;;;;;IAoBpB,CAEF,MAAM,EAAU,MAAM;;;IAGpB,CAEF,MAAM,EAAU,MAAM;;;;;;;;;;;IAWpB,CAEF,MAAM,EAAU,MAAM;;;;IAIpB,CAEF,MAAM,EAAU,MAAM;;;;;;;;;;;;IAYpB,EAGSC,EAAoC,MAAO,CAAE,QAAS,KAAqB,CACtF,GAAM,CAAE,aAAc,EACtB,MAAM,EAAU,MAAM,6CAA6C,CACnE,MAAM,EAAU,MAAM,kDAAkD,CACxE,MAAM,EAAU,MAAM,2CAA2C"}
|
|
@@ -12,7 +12,7 @@ const e=async({context:e})=>{let{sequelize:t}=e;await t.query(`
|
|
|
12
12
|
"required" BOOLEAN DEFAULT false,
|
|
13
13
|
"disabled" BOOLEAN DEFAULT false,
|
|
14
14
|
"default_value" JSONB,
|
|
15
|
-
"
|
|
15
|
+
"block_editing_from_u_i" BOOLEAN NOT NULL DEFAULT false,
|
|
16
16
|
"created_at" TIMESTAMPTZ NOT NULL,
|
|
17
17
|
"updated_at" TIMESTAMPTZ,
|
|
18
18
|
"deleted_at" TIMESTAMPTZ,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"001-create-core-tables.js","names":["up: MigrationFn<QueryInterface>","down: MigrationFn<QueryInterface>"],"sources":["../../src/migrations/001-create-core-tables.ts"],"sourcesContent":["import type { MigrationFn } from 'umzug';\nimport type { QueryInterface } from 'sequelize';\n\nexport const up: MigrationFn<QueryInterface> = async ({ context: queryInterface }) => {\n const { sequelize } = queryInterface;\n\n await sequelize.query(`\n CREATE TABLE IF NOT EXISTS \"custom_field_definitions\" (\n \"id\" UUID NOT NULL DEFAULT gen_random_uuid(),\n \"name\" VARCHAR NOT NULL,\n \"display_name\" VARCHAR,\n \"field_type\" VARCHAR NOT NULL,\n \"validation\" JSONB,\n \"entity_id\" UUID NOT NULL,\n \"entity_type\" VARCHAR NOT NULL,\n \"model_type\" VARCHAR NOT NULL,\n \"description\" TEXT,\n \"required\" BOOLEAN DEFAULT false,\n \"disabled\" BOOLEAN DEFAULT false,\n \"default_value\" JSONB,\n \"
|
|
1
|
+
{"version":3,"file":"001-create-core-tables.js","names":["up: MigrationFn<QueryInterface>","down: MigrationFn<QueryInterface>"],"sources":["../../src/migrations/001-create-core-tables.ts"],"sourcesContent":["import type { MigrationFn } from 'umzug';\nimport type { QueryInterface } from 'sequelize';\n\nexport const up: MigrationFn<QueryInterface> = async ({ context: queryInterface }) => {\n const { sequelize } = queryInterface;\n\n await sequelize.query(`\n CREATE TABLE IF NOT EXISTS \"custom_field_definitions\" (\n \"id\" UUID NOT NULL DEFAULT gen_random_uuid(),\n \"name\" VARCHAR NOT NULL,\n \"display_name\" VARCHAR,\n \"field_type\" VARCHAR NOT NULL,\n \"validation\" JSONB,\n \"entity_id\" UUID NOT NULL,\n \"entity_type\" VARCHAR NOT NULL,\n \"model_type\" VARCHAR NOT NULL,\n \"description\" TEXT,\n \"required\" BOOLEAN DEFAULT false,\n \"disabled\" BOOLEAN DEFAULT false,\n \"default_value\" JSONB,\n \"block_editing_from_u_i\" BOOLEAN NOT NULL DEFAULT false,\n \"created_at\" TIMESTAMPTZ NOT NULL,\n \"updated_at\" TIMESTAMPTZ,\n \"deleted_at\" TIMESTAMPTZ,\n PRIMARY KEY (\"id\")\n )\n `);\n\n await sequelize.query(`\n CREATE UNIQUE INDEX IF NOT EXISTS \"unique_name_model_type\"\n ON \"custom_field_definitions\" (\"model_type\", \"entity_id\", \"name\")\n `);\n\n await sequelize.query(`\n CREATE TABLE IF NOT EXISTS \"custom_field_values\" (\n \"model_id\" UUID NOT NULL,\n \"custom_field_definition_id\" UUID NOT NULL\n REFERENCES \"custom_field_definitions\" (\"id\"),\n \"value\" JSONB,\n \"created_at\" TIMESTAMPTZ NOT NULL,\n \"updated_at\" TIMESTAMPTZ,\n \"deleted_at\" TIMESTAMPTZ,\n PRIMARY KEY (\"model_id\", \"custom_field_definition_id\")\n )\n `);\n\n await sequelize.query(`\n CREATE INDEX IF NOT EXISTS \"idx_custom_field_values_active_definition_id\"\n ON \"custom_field_values\" (\"custom_field_definition_id\")\n WHERE \"deleted_at\" IS NULL\n `);\n\n await sequelize.query(`\n CREATE TABLE IF NOT EXISTS \"custom_validators\" (\n \"id\" UUID NOT NULL DEFAULT gen_random_uuid(),\n \"entity_id\" UUID NOT NULL,\n \"entity_type\" VARCHAR NOT NULL,\n \"model_type\" VARCHAR NOT NULL,\n \"schema\" JSONB NOT NULL,\n \"disabled\" BOOLEAN NOT NULL DEFAULT false,\n \"created_at\" TIMESTAMPTZ NOT NULL,\n \"updated_at\" TIMESTAMPTZ,\n PRIMARY KEY (\"id\")\n )\n `);\n};\n\nexport const down: MigrationFn<QueryInterface> = async ({ context: queryInterface }) => {\n const { sequelize } = queryInterface;\n await sequelize.query('DROP TABLE IF EXISTS \"custom_field_values\"');\n await sequelize.query('DROP TABLE IF EXISTS \"custom_field_definitions\"');\n await sequelize.query('DROP TABLE IF EXISTS \"custom_validators\"');\n};\n"],"mappings":"AAGA,MAAaA,EAAkC,MAAO,CAAE,QAAS,KAAqB,CACpF,GAAM,CAAE,aAAc,EAEtB,MAAM,EAAU,MAAM;;;;;;;;;;;;;;;;;;;;IAoBpB,CAEF,MAAM,EAAU,MAAM;;;IAGpB,CAEF,MAAM,EAAU,MAAM;;;;;;;;;;;IAWpB,CAEF,MAAM,EAAU,MAAM;;;;IAIpB,CAEF,MAAM,EAAU,MAAM;;;;;;;;;;;;IAYpB,EAGSC,EAAoC,MAAO,CAAE,QAAS,KAAqB,CACtF,GAAM,CAAE,aAAc,EACtB,MAAM,EAAU,MAAM,6CAA6C,CACnE,MAAM,EAAU,MAAM,kDAAkD,CACxE,MAAM,EAAU,MAAM,2CAA2C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require(`../utils/logger/index.cjs`),t=require(`./001-create-core-tables.cjs`),n=require(`./002-create-custom-field-entries.cjs`),r=require(`./003-create-custom-field-model-type-map.cjs`),{Umzug:i,SequelizeStorage:a}=require(`umzug`),o=e=>{let{useCustomFieldsEntries:i=!1,useModelTypeMapping:a=!1}=e;return[{name:`001-create-core-tables`,up:t.up,down:t.down},...i?[{name:`002-create-custom-field-entries`,up:n.up,down:n.down}]:[],...a?[{name:`003-create-custom-field-model-type-map`,up:r.up,down:r.down}]:[]]},s=async(t,n={})=>{let r=t.getQueryInterface(),
|
|
1
|
+
const e=require(`../utils/logger/index.cjs`),t=require(`./001-create-core-tables.cjs`),n=require(`./002-create-custom-field-entries.cjs`),r=require(`./003-create-custom-field-model-type-map.cjs`),{Umzug:i,SequelizeStorage:a}=require(`umzug`),o=e=>{let{useCustomFieldsEntries:i=!1,useModelTypeMapping:a=!1}=e;return[{name:`001-create-core-tables`,up:t.up,down:t.down},...i?[{name:`002-create-custom-field-entries`,up:n.up,down:n.down}]:[],...a?[{name:`003-create-custom-field-model-type-map`,up:r.up,down:r.down}]:[]]},s=839274628,c=async(t,n={})=>{let r=t.getQueryInterface(),c=new a({sequelize:t,tableName:`sadot_migrations`}),l=new i({migrations:o(n),context:r,storage:c,logger:{info:t=>e.default.info(`[umzug] ${JSON.stringify(t)}`),warn:t=>e.default.warn(`[umzug] ${JSON.stringify(t)}`),error:t=>e.default.error(`[umzug] ${JSON.stringify(t)}`),debug:t=>e.default.debug(`[umzug] ${JSON.stringify(t)}`)}}),u=await l.pending();if(u.length===0){e.default.info(`[umzug] no pending migrations, skipping`);return}e.default.info(`[umzug] pending migrations detected, acquiring advisory lock`,{pending:u.map(e=>e.name)});let d=await t.transaction();try{await t.query(`SELECT pg_advisory_lock(${s})`,{transaction:d}),e.default.info(`[umzug] advisory lock acquired`),(await l.pending()).length>0?await l.up():e.default.info(`[umzug] migrations already applied by another instance, skipping`)}finally{await t.query(`SELECT pg_advisory_unlock(${s})`,{transaction:d}),await d.commit(),e.default.info(`[umzug] advisory lock released`)}};exports.runSadotMigrations=c;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["logger"],"sources":["../../src/migrations/index.ts"],"sourcesContent":["import type { InputMigrations } from 'umzug';\nimport type { QueryInterface } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport * as migration001 from './001-create-core-tables';\nimport * as migration002 from './002-create-custom-field-entries';\nimport * as migration003 from './003-create-custom-field-model-type-map';\n\n// umzug is CJS. Static ESM named imports break in vitest after vi.resetModules()\n// because Vite's SSR transform re-evaluates the module outside the inline bundle.\n// require() goes through Node's native CJS loader and is stable across resets.\n\n// eslint-disable-next-line import/no-commonjs, @typescript-eslint/no-require-imports\nconst { Umzug, SequelizeStorage } = require('umzug') as typeof import('umzug');\n\ninterface MigratorOptions {\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n}\n\nconst buildMigrationList = (options: MigratorOptions): InputMigrations<QueryInterface> => {\n const { useCustomFieldsEntries = false, useModelTypeMapping = false } = options;\n return [\n { name: '001-create-core-tables', up: migration001.up, down: migration001.down },\n ...(useCustomFieldsEntries ? [{ name: '002-create-custom-field-entries', up: migration002.up, down: migration002.down }] : []),\n ...(useModelTypeMapping ? [{ name: '003-create-custom-field-model-type-map', up: migration003.up, down: migration003.down }] : []),\n ];\n};\n\n/**\n * Runs sadot migrations via umzug. All migrations use IF NOT EXISTS / IF EXISTS,\n * so they are fully idempotent — safe to run against both fresh and existing\n * databases (including DBs previously managed by the legacy sync() path).\n */\nconst runSadotMigrations = async (sequelize: Sequelize, options: MigratorOptions = {}): Promise<void> => {\n const queryInterface = sequelize.getQueryInterface() as unknown as QueryInterface;\n const storage = new SequelizeStorage({ sequelize: sequelize as never, tableName: 'sadot_migrations' });\n\n const
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["logger"],"sources":["../../src/migrations/index.ts"],"sourcesContent":["import type { InputMigrations } from 'umzug';\nimport type { QueryInterface } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport * as migration001 from './001-create-core-tables';\nimport * as migration002 from './002-create-custom-field-entries';\nimport * as migration003 from './003-create-custom-field-model-type-map';\n\n// umzug is CJS. Static ESM named imports break in vitest after vi.resetModules()\n// because Vite's SSR transform re-evaluates the module outside the inline bundle.\n// require() goes through Node's native CJS loader and is stable across resets.\n\n// eslint-disable-next-line import/no-commonjs, @typescript-eslint/no-require-imports\nconst { Umzug, SequelizeStorage } = require('umzug') as typeof import('umzug');\n\ninterface MigratorOptions {\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n}\n\nconst buildMigrationList = (options: MigratorOptions): InputMigrations<QueryInterface> => {\n const { useCustomFieldsEntries = false, useModelTypeMapping = false } = options;\n return [\n { name: '001-create-core-tables', up: migration001.up, down: migration001.down },\n ...(useCustomFieldsEntries ? [{ name: '002-create-custom-field-entries', up: migration002.up, down: migration002.down }] : []),\n ...(useModelTypeMapping ? [{ name: '003-create-custom-field-model-type-map', up: migration003.up, down: migration003.down }] : []),\n ];\n};\n\n// Stable advisory-lock ID for sadot migrations. Chosen arbitrarily; must not\n// collide with other advisory locks in the same database.\nconst SADOT_MIGRATION_LOCK_ID = 839274628;\n\n/**\n * Runs sadot migrations via umzug. All migrations use IF NOT EXISTS / IF EXISTS,\n * so they are fully idempotent — safe to run against both fresh and existing\n * databases (including DBs previously managed by the legacy sync() path).\n *\n * A PostgreSQL advisory lock is acquired before running migrations so that when\n * multiple pods start concurrently only one of them executes the migrations.\n * The remaining pods block until the lock is released, then proceed — Umzug will\n * see the migrations have already been applied and skip them.\n */\nconst runSadotMigrations = async (sequelize: Sequelize, options: MigratorOptions = {}): Promise<void> => {\n const queryInterface = sequelize.getQueryInterface() as unknown as QueryInterface;\n const storage = new SequelizeStorage({ sequelize: sequelize as never, tableName: 'sadot_migrations' });\n\n const umzugLogger = {\n info: (msg: Record<string, unknown>) => logger.info(`[umzug] ${JSON.stringify(msg)}`),\n warn: (msg: Record<string, unknown>) => logger.warn(`[umzug] ${JSON.stringify(msg)}`),\n error: (msg: Record<string, unknown>) => logger.error(`[umzug] ${JSON.stringify(msg)}`),\n debug: (msg: Record<string, unknown>) => logger.debug(`[umzug] ${JSON.stringify(msg)}`),\n };\n\n const migrator = new Umzug<QueryInterface>({\n migrations: buildMigrationList(options),\n context: queryInterface,\n storage,\n logger: umzugLogger,\n });\n\n const pending = await migrator.pending();\n if (pending.length === 0) {\n logger.info('[umzug] no pending migrations, skipping');\n return;\n }\n\n logger.info('[umzug] pending migrations detected, acquiring advisory lock', { pending: pending.map(m => m.name) });\n\n // Use a transaction to pin lock/unlock to the same pool connection.\n // pg_advisory_lock (session-level) is used so the lock remains held while\n // migrator.up() runs its own queries on other pool connections.\n const transaction = await sequelize.transaction();\n try {\n await sequelize.query(`SELECT pg_advisory_lock(${SADOT_MIGRATION_LOCK_ID})`, { transaction });\n logger.info('[umzug] advisory lock acquired');\n\n // Re-check after acquiring the lock — another pod may have already\n // applied the migrations while we were waiting.\n const stillPending = await migrator.pending();\n if (stillPending.length > 0) {\n await migrator.up();\n } else {\n logger.info('[umzug] migrations already applied by another instance, skipping');\n }\n } finally {\n await sequelize.query(`SELECT pg_advisory_unlock(${SADOT_MIGRATION_LOCK_ID})`, { transaction });\n await transaction.commit();\n logger.info('[umzug] advisory lock released');\n }\n};\n\nexport { runSadotMigrations };\n"],"mappings":"oMAaM,CAAE,QAAO,oBAAqB,QAAQ,QAAQ,CAO9C,EAAsB,GAA8D,CACxF,GAAM,CAAE,yBAAyB,GAAO,sBAAsB,IAAU,EACxE,MAAO,CACL,CAAE,KAAM,yBAA0B,GAAA,EAAA,GAAqB,KAAA,EAAA,KAAyB,CAChF,GAAI,EAAyB,CAAC,CAAE,KAAM,kCAAmC,GAAA,EAAA,GAAqB,KAAA,EAAA,KAAyB,CAAC,CAAG,EAAE,CAC7H,GAAI,EAAsB,CAAC,CAAE,KAAM,yCAA0C,GAAA,EAAA,GAAqB,KAAA,EAAA,KAAyB,CAAC,CAAG,EAAE,CAClI,EAKG,EAA0B,UAY1B,EAAqB,MAAO,EAAsB,EAA2B,EAAE,GAAoB,CACvG,IAAM,EAAiB,EAAU,mBAAmB,CAC9C,EAAU,IAAI,EAAiB,CAAa,YAAoB,UAAW,mBAAoB,CAAC,CAShG,EAAW,IAAI,EAAsB,CACzC,WAAY,EAAmB,EAAQ,CACvC,QAAS,EACT,UACA,OAXkB,CAClB,KAAO,GAAiCA,EAAAA,QAAO,KAAK,WAAW,KAAK,UAAU,EAAI,GAAG,CACrF,KAAO,GAAiCA,EAAAA,QAAO,KAAK,WAAW,KAAK,UAAU,EAAI,GAAG,CACrF,MAAQ,GAAiCA,EAAAA,QAAO,MAAM,WAAW,KAAK,UAAU,EAAI,GAAG,CACvF,MAAQ,GAAiCA,EAAAA,QAAO,MAAM,WAAW,KAAK,UAAU,EAAI,GAAG,CACxF,CAOA,CAAC,CAEI,EAAU,MAAM,EAAS,SAAS,CACxC,GAAI,EAAQ,SAAW,EAAG,CACxB,EAAA,QAAO,KAAK,0CAA0C,CACtD,OAGF,EAAA,QAAO,KAAK,+DAAgE,CAAE,QAAS,EAAQ,IAAI,GAAK,EAAE,KAAK,CAAE,CAAC,CAKlH,IAAM,EAAc,MAAM,EAAU,aAAa,CACjD,GAAI,CACF,MAAM,EAAU,MAAM,2BAA2B,EAAwB,GAAI,CAAE,cAAa,CAAC,CAC7F,EAAA,QAAO,KAAK,iCAAiC,EAIxB,MAAM,EAAS,SAAS,EAC5B,OAAS,EACxB,MAAM,EAAS,IAAI,CAEnB,EAAA,QAAO,KAAK,mEAAmE,QAEzE,CACR,MAAM,EAAU,MAAM,6BAA6B,EAAwB,GAAI,CAAE,cAAa,CAAC,CAC/F,MAAM,EAAY,QAAQ,CAC1B,EAAA,QAAO,KAAK,iCAAiC"}
|
package/dist/migrations/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{__require as e}from"../_virtual/rolldown_runtime.js";import t from"../utils/logger/index.js";import{down as n,up as r}from"./001-create-core-tables.js";import{down as i,up as a}from"./002-create-custom-field-entries.js";import{down as o,up as s}from"./003-create-custom-field-model-type-map.js";const{Umzug:c,SequelizeStorage:l}=e(`umzug`),u=e=>{let{useCustomFieldsEntries:t=!1,useModelTypeMapping:c=!1}=e;return[{name:`001-create-core-tables`,up:r,down:n},...t?[{name:`002-create-custom-field-entries`,up:a,down:i}]:[],...c?[{name:`003-create-custom-field-model-type-map`,up:s,down:o}]:[]]},d=async(e,n={})=>{let r=e.getQueryInterface(),i=new l({sequelize:e,tableName:`sadot_migrations`})
|
|
1
|
+
import{__require as e}from"../_virtual/rolldown_runtime.js";import t from"../utils/logger/index.js";import{down as n,up as r}from"./001-create-core-tables.js";import{down as i,up as a}from"./002-create-custom-field-entries.js";import{down as o,up as s}from"./003-create-custom-field-model-type-map.js";const{Umzug:c,SequelizeStorage:l}=e(`umzug`),u=e=>{let{useCustomFieldsEntries:t=!1,useModelTypeMapping:c=!1}=e;return[{name:`001-create-core-tables`,up:r,down:n},...t?[{name:`002-create-custom-field-entries`,up:a,down:i}]:[],...c?[{name:`003-create-custom-field-model-type-map`,up:s,down:o}]:[]]},d=839274628,f=async(e,n={})=>{let r=e.getQueryInterface(),i=new l({sequelize:e,tableName:`sadot_migrations`}),a=new c({migrations:u(n),context:r,storage:i,logger:{info:e=>t.info(`[umzug] ${JSON.stringify(e)}`),warn:e=>t.warn(`[umzug] ${JSON.stringify(e)}`),error:e=>t.error(`[umzug] ${JSON.stringify(e)}`),debug:e=>t.debug(`[umzug] ${JSON.stringify(e)}`)}}),o=await a.pending();if(o.length===0){t.info(`[umzug] no pending migrations, skipping`);return}t.info(`[umzug] pending migrations detected, acquiring advisory lock`,{pending:o.map(e=>e.name)});let s=await e.transaction();try{await e.query(`SELECT pg_advisory_lock(${d})`,{transaction:s}),t.info(`[umzug] advisory lock acquired`),(await a.pending()).length>0?await a.up():t.info(`[umzug] migrations already applied by another instance, skipping`)}finally{await e.query(`SELECT pg_advisory_unlock(${d})`,{transaction:s}),await s.commit(),t.info(`[umzug] advisory lock released`)}};export{f as runSadotMigrations};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["migration001.up","migration001.down","migration002.up","migration002.down","migration003.up","migration003.down","logger"],"sources":["../../src/migrations/index.ts"],"sourcesContent":["import type { InputMigrations } from 'umzug';\nimport type { QueryInterface } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport * as migration001 from './001-create-core-tables';\nimport * as migration002 from './002-create-custom-field-entries';\nimport * as migration003 from './003-create-custom-field-model-type-map';\n\n// umzug is CJS. Static ESM named imports break in vitest after vi.resetModules()\n// because Vite's SSR transform re-evaluates the module outside the inline bundle.\n// require() goes through Node's native CJS loader and is stable across resets.\n\n// eslint-disable-next-line import/no-commonjs, @typescript-eslint/no-require-imports\nconst { Umzug, SequelizeStorage } = require('umzug') as typeof import('umzug');\n\ninterface MigratorOptions {\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n}\n\nconst buildMigrationList = (options: MigratorOptions): InputMigrations<QueryInterface> => {\n const { useCustomFieldsEntries = false, useModelTypeMapping = false } = options;\n return [\n { name: '001-create-core-tables', up: migration001.up, down: migration001.down },\n ...(useCustomFieldsEntries ? [{ name: '002-create-custom-field-entries', up: migration002.up, down: migration002.down }] : []),\n ...(useModelTypeMapping ? [{ name: '003-create-custom-field-model-type-map', up: migration003.up, down: migration003.down }] : []),\n ];\n};\n\n/**\n * Runs sadot migrations via umzug. All migrations use IF NOT EXISTS / IF EXISTS,\n * so they are fully idempotent — safe to run against both fresh and existing\n * databases (including DBs previously managed by the legacy sync() path).\n */\nconst runSadotMigrations = async (sequelize: Sequelize, options: MigratorOptions = {}): Promise<void> => {\n const queryInterface = sequelize.getQueryInterface() as unknown as QueryInterface;\n const storage = new SequelizeStorage({ sequelize: sequelize as never, tableName: 'sadot_migrations' });\n\n const
|
|
1
|
+
{"version":3,"file":"index.js","names":["migration001.up","migration001.down","migration002.up","migration002.down","migration003.up","migration003.down","logger"],"sources":["../../src/migrations/index.ts"],"sourcesContent":["import type { InputMigrations } from 'umzug';\nimport type { QueryInterface } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport * as migration001 from './001-create-core-tables';\nimport * as migration002 from './002-create-custom-field-entries';\nimport * as migration003 from './003-create-custom-field-model-type-map';\n\n// umzug is CJS. Static ESM named imports break in vitest after vi.resetModules()\n// because Vite's SSR transform re-evaluates the module outside the inline bundle.\n// require() goes through Node's native CJS loader and is stable across resets.\n\n// eslint-disable-next-line import/no-commonjs, @typescript-eslint/no-require-imports\nconst { Umzug, SequelizeStorage } = require('umzug') as typeof import('umzug');\n\ninterface MigratorOptions {\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n}\n\nconst buildMigrationList = (options: MigratorOptions): InputMigrations<QueryInterface> => {\n const { useCustomFieldsEntries = false, useModelTypeMapping = false } = options;\n return [\n { name: '001-create-core-tables', up: migration001.up, down: migration001.down },\n ...(useCustomFieldsEntries ? [{ name: '002-create-custom-field-entries', up: migration002.up, down: migration002.down }] : []),\n ...(useModelTypeMapping ? [{ name: '003-create-custom-field-model-type-map', up: migration003.up, down: migration003.down }] : []),\n ];\n};\n\n// Stable advisory-lock ID for sadot migrations. Chosen arbitrarily; must not\n// collide with other advisory locks in the same database.\nconst SADOT_MIGRATION_LOCK_ID = 839274628;\n\n/**\n * Runs sadot migrations via umzug. All migrations use IF NOT EXISTS / IF EXISTS,\n * so they are fully idempotent — safe to run against both fresh and existing\n * databases (including DBs previously managed by the legacy sync() path).\n *\n * A PostgreSQL advisory lock is acquired before running migrations so that when\n * multiple pods start concurrently only one of them executes the migrations.\n * The remaining pods block until the lock is released, then proceed — Umzug will\n * see the migrations have already been applied and skip them.\n */\nconst runSadotMigrations = async (sequelize: Sequelize, options: MigratorOptions = {}): Promise<void> => {\n const queryInterface = sequelize.getQueryInterface() as unknown as QueryInterface;\n const storage = new SequelizeStorage({ sequelize: sequelize as never, tableName: 'sadot_migrations' });\n\n const umzugLogger = {\n info: (msg: Record<string, unknown>) => logger.info(`[umzug] ${JSON.stringify(msg)}`),\n warn: (msg: Record<string, unknown>) => logger.warn(`[umzug] ${JSON.stringify(msg)}`),\n error: (msg: Record<string, unknown>) => logger.error(`[umzug] ${JSON.stringify(msg)}`),\n debug: (msg: Record<string, unknown>) => logger.debug(`[umzug] ${JSON.stringify(msg)}`),\n };\n\n const migrator = new Umzug<QueryInterface>({\n migrations: buildMigrationList(options),\n context: queryInterface,\n storage,\n logger: umzugLogger,\n });\n\n const pending = await migrator.pending();\n if (pending.length === 0) {\n logger.info('[umzug] no pending migrations, skipping');\n return;\n }\n\n logger.info('[umzug] pending migrations detected, acquiring advisory lock', { pending: pending.map(m => m.name) });\n\n // Use a transaction to pin lock/unlock to the same pool connection.\n // pg_advisory_lock (session-level) is used so the lock remains held while\n // migrator.up() runs its own queries on other pool connections.\n const transaction = await sequelize.transaction();\n try {\n await sequelize.query(`SELECT pg_advisory_lock(${SADOT_MIGRATION_LOCK_ID})`, { transaction });\n logger.info('[umzug] advisory lock acquired');\n\n // Re-check after acquiring the lock — another pod may have already\n // applied the migrations while we were waiting.\n const stillPending = await migrator.pending();\n if (stillPending.length > 0) {\n await migrator.up();\n } else {\n logger.info('[umzug] migrations already applied by another instance, skipping');\n }\n } finally {\n await sequelize.query(`SELECT pg_advisory_unlock(${SADOT_MIGRATION_LOCK_ID})`, { transaction });\n await transaction.commit();\n logger.info('[umzug] advisory lock released');\n }\n};\n\nexport { runSadotMigrations };\n"],"mappings":"8SAaA,KAAM,CAAE,QAAO,oBAAA,EAA6B,QAAQ,CAO9C,EAAsB,GAA8D,CACxF,GAAM,CAAE,yBAAyB,GAAO,sBAAsB,IAAU,EACxE,MAAO,CACL,CAAE,KAAM,yBAA8BA,KAAuBC,OAAmB,CAChF,GAAI,EAAyB,CAAC,CAAE,KAAM,kCAAmC,GAAIC,EAAiB,KAAMC,EAAmB,CAAC,CAAG,EAAE,CAC7H,GAAI,EAAsB,CAAC,CAAE,KAAM,yCAA0C,GAAIC,EAAiB,KAAMC,EAAmB,CAAC,CAAG,EAAE,CAClI,EAKG,EAA0B,UAY1B,EAAqB,MAAO,EAAsB,EAA2B,EAAE,GAAoB,CACvG,IAAM,EAAiB,EAAU,mBAAmB,CAC9C,EAAU,IAAI,EAAiB,CAAa,YAAoB,UAAW,mBAAoB,CAAC,CAShG,EAAW,IAAI,EAAsB,CACzC,WAAY,EAAmB,EAAQ,CACvC,QAAS,EACT,UACA,OAXkB,CAClB,KAAO,GAAiCC,EAAO,KAAK,WAAW,KAAK,UAAU,EAAI,GAAG,CACrF,KAAO,GAAiCA,EAAO,KAAK,WAAW,KAAK,UAAU,EAAI,GAAG,CACrF,MAAQ,GAAiCA,EAAO,MAAM,WAAW,KAAK,UAAU,EAAI,GAAG,CACvF,MAAQ,GAAiCA,EAAO,MAAM,WAAW,KAAK,UAAU,EAAI,GAAG,CACxF,CAOA,CAAC,CAEI,EAAU,MAAM,EAAS,SAAS,CACxC,GAAI,EAAQ,SAAW,EAAG,CACxB,EAAO,KAAK,0CAA0C,CACtD,OAGF,EAAO,KAAK,+DAAgE,CAAE,QAAS,EAAQ,IAAI,GAAK,EAAE,KAAK,CAAE,CAAC,CAKlH,IAAM,EAAc,MAAM,EAAU,aAAa,CACjD,GAAI,CACF,MAAM,EAAU,MAAM,2BAA2B,EAAwB,GAAI,CAAE,cAAa,CAAC,CAC7F,EAAO,KAAK,iCAAiC,EAIxB,MAAM,EAAS,SAAS,EAC5B,OAAS,EACxB,MAAM,EAAS,IAAI,CAEnB,EAAO,KAAK,mEAAmE,QAEzE,CACR,MAAM,EAAU,MAAM,6BAA6B,EAAwB,GAAI,CAAE,cAAa,CAAC,CAC/F,MAAM,EAAY,QAAQ,CAC1B,EAAO,KAAK,iCAAiC"}
|
package/dist/models/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`),n=require(`./CustomFieldValue.cjs`),r=require(`./CustomFieldDefinition.cjs`),i=require(`./tests/AssociatedTestModel.cjs`),a=require(`./tests/TestModel.cjs`),o=require(`./tests/contextAwareModels/ContextTestModel.cjs`),s=require(`./tests/contextAwareModels/ContextAwareTestModel.cjs`),c=require(`./CustomFieldEntries.cjs`),l=require(`./CustomValidator.cjs`),u=require(`./CustomFieldModelTypeMap.cjs`),d=require(`../migrations/index.cjs`);let f=require(`sequelize`);const p=[a.default,i.default,s.default,o.default],m=`sadot-migration`,h=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,g=async(e,
|
|
1
|
+
const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/logger/index.cjs`),n=require(`./CustomFieldValue.cjs`),r=require(`./CustomFieldDefinition.cjs`),i=require(`./tests/AssociatedTestModel.cjs`),a=require(`./tests/TestModel.cjs`),o=require(`./tests/contextAwareModels/ContextTestModel.cjs`),s=require(`./tests/contextAwareModels/ContextAwareTestModel.cjs`),c=require(`./CustomFieldEntries.cjs`),l=require(`./CustomValidator.cjs`),u=require(`./CustomFieldModelTypeMap.cjs`),d=require(`../migrations/index.cjs`);let f=require(`sequelize`);const p=[a.default,i.default,s.default,o.default],m=`sadot-migration`,h=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,g=async(e,{schemaPrefix:i,schemaVersion:a,useCustomFieldsEntries:o,useModelTypeMapping:s})=>{let d=e.define(`SequelizeMeta`,{name:{type:f.DataTypes.STRING,allowNull:!1,unique:!0,primaryKey:!0,autoIncrement:!1}},{tableName:`SequelizeMeta`,timestamps:!1,schema:`public`});t.default.info(`custom-fields: starting migrations`);let p=await d.findAll({where:{name:{[f.Op.like]:`${i}%`}},raw:!0}),m=p.at(-1),h=p.findIndex(e=>e.name===a);if(t.default.info(`custom-fields: migrations`,{currentMigrations:p,currentSadotSchemaVersion:m,newSadotSchemaVersion:a,expectedSchemaVersionIndex:h}),!m||m.name!==a){t.default.info(`custom-fields: syncing models`);try{if(await r.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldDefinition synced successfully`),await n.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldValue synced successfully`),await l.default.sync({alter:!0}),t.default.info(`custom-fields: CustomValidator synced successfully`),o&&(await c.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldEntries synced successfully`)),s&&(await u.default.sync({alter:!0}),t.default.info(`custom-fields: CustomFieldModelTypeMap synced successfully`)),h===-1&&(await d.create({name:a}),t.default.info(`custom-fields: SequelizeMeta entry created successfully`)),t.default.info(`custom-fields: models synced`),p.length&&h!==-1&&h<p.length-1){let e=p.slice(h+1);t.default.info(`custom-fields: deleting newer migrations during down migration`,{count:e.length}),await d.destroy({where:{name:{[f.Op.in]:e.map(e=>e.name)}}}),t.default.info(`custom-fields: newer migrations deleted successfully`)}}catch(e){throw t.default.error(`custom-fields: failed to sync models`,{error:e}),e}}},_=async(e,i,{schemaPrefix:a=`sadot-migration`,schemaVersion:o=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,useCustomFieldsEntries:s=!1,useModelTypeMapping:f=!1,useUmzugMigrations:p=!1,isMatPathEnabled:m}={})=>{let h=`${a}_${o}${s?`_withEntries`:``}${f?`_withTypeMapping`:``}`;if(t.default.info(`custom-fields: initialize custom-fields tables`),!e.addModels)throw Error(`sequelize instance must have addModels function`);let _=[r.default,n.default,l.default,...s?[c.default]:[],...f?[u.default]:[]];if(e.addModels(_),f&&(r.default.hasMany(u.default,{foreignKey:`customFieldDefinitionId`,as:`modelTypeMappings`}),u.default.belongsTo(r.default,{foreignKey:`customFieldDefinitionId`,as:`customFieldDefinition`})),r.default.addScope(`userScope`,()=>{if(m?.())return{};let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),l.default.addScope(`userScope`,()=>{if(m?.())return{};let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),t.default.info(`custom-fields: models added`),p){t.default.info(`custom-fields: starting umzug migrations`),await d.runSadotMigrations(e,{useCustomFieldsEntries:s,useModelTypeMapping:f}),t.default.info(`custom-fields: umzug migrations complete`);return}await g(e,{schemaPrefix:a,schemaVersion:h,useCustomFieldsEntries:s,useModelTypeMapping:f})},v=async e=>{if(t.default.info(`custom-fields: initialize custom-fields test models`),!e.addModels)throw Error(`sequelize instance must have addModels function`);e.addModels(p),await e.dropSchema(`custom-fields`,{logging:!1}),await e.createSchema(`custom-fields`,{logging:!1}),t.default.info(`custom-fields: test models added`),await a.default.sync({alter:!0}),await i.default.sync({alter:!0}),await o.default.sync({alter:!0}),await s.default.sync({alter:!0}),t.default.info(`custom-fields: test models synced`)};exports.initTables=_,exports.initTestModels=v;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["TestModel","AssociatedTestModel","ContextAwareTestModel","ContextTestModel","sequelize","productionModels: ProductionModel[]","CustomFieldDefinition","CustomFieldValue","CustomValidator","CustomFieldEntries","CustomFieldModelTypeMap","runSadotMigrations","DataTypes","Op"],"sources":["../../src/models/index.ts"],"sourcesContent":["import { DataTypes, Op } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport CustomFieldValue from './CustomFieldValue';\nimport TestModel from './tests/TestModel';\nimport ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';\nimport ContextTestModel from './tests/contextAwareModels/ContextTestModel';\nimport AssociatedTestModel from './tests/AssociatedTestModel';\nimport type { CustomFieldOptions } from '../types';\nimport CustomFieldEntries from './CustomFieldEntries';\nimport CustomValidator from './CustomValidator';\nimport CustomFieldModelTypeMap from './CustomFieldModelTypeMap';\nimport { runSadotMigrations } from '../migrations';\n\ntype ProductionModel = typeof CustomFieldDefinition | typeof CustomFieldValue | typeof CustomFieldEntries | typeof CustomValidator | typeof CustomFieldModelTypeMap;\ninterface InitTablesOptions {\n schemaPrefix?: string;\n schemaVersion?: string;\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n useUmzugMigrations?: boolean;\n isMatPathEnabled?: CustomFieldOptions['isMatPathEnabled'];\n}\n\nconst testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel];\n\nconst SADOT_MIGRATION_PREFIX = 'sadot-migration';\nconst SCHEMA_VERSION = '5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1';\n\nconst initTables = async (\n sequelize: Sequelize,\n getUser: CustomFieldOptions['getUser'],\n {\n schemaPrefix = SADOT_MIGRATION_PREFIX,\n schemaVersion = SCHEMA_VERSION,\n useCustomFieldsEntries = false,\n useModelTypeMapping = false,\n useUmzugMigrations = false,\n isMatPathEnabled,\n }: InitTablesOptions = {},\n): Promise<void> => {\n const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}${useCustomFieldsEntries ? '_withEntries' : ''}${useModelTypeMapping ? '_withTypeMapping' : ''}`;\n logger.info('custom-fields: initialize custom-fields tables');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n const productionModels: ProductionModel[] = [\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n ...(useCustomFieldsEntries ? [CustomFieldEntries] : []),\n ...(useModelTypeMapping ? [CustomFieldModelTypeMap] : []),\n ];\n\n sequelize.addModels(productionModels);\n\n // Add the association only when useModelTypeMapping is enabled\n if (useModelTypeMapping) {\n CustomFieldDefinition.hasMany(CustomFieldModelTypeMap, {\n foreignKey: 'customFieldDefinitionId',\n as: 'modelTypeMappings',\n });\n CustomFieldModelTypeMap.belongsTo(CustomFieldDefinition, {\n foreignKey: 'customFieldDefinitionId',\n as: 'customFieldDefinition',\n });\n }\n\n CustomFieldDefinition.addScope('userScope', () => {\n // When mat-path is active, the consumer is responsible for restricting entityIds\n // (typically by expanding the request's entityIds to include ancestor paths the\n // caller can see). Bypass the legacy permission filter so partner/ancestor\n // entityIds are not dropped.\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n CustomValidator.addScope('userScope', () => {\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n logger.info('custom-fields: models added');\n\n if (useUmzugMigrations) {\n logger.info('custom-fields: starting umzug migrations');\n await runSadotMigrations(sequelize, { useCustomFieldsEntries, useModelTypeMapping });\n logger.info('custom-fields: umzug migrations complete');\n return;\n }\n\n const SequelizeMeta = sequelize.define(\n 'SequelizeMeta',\n {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: false,\n },\n },\n {\n tableName: 'SequelizeMeta',\n timestamps: false,\n schema: 'public',\n },\n );\n\n logger.info('custom-fields: starting migrations');\n const migrations = await SequelizeMeta.findAll({ where: { name: { [Op.like]: `${schemaPrefix}%` } }, raw: true });\n const currentSadotSchemaVersion = migrations.at(-1);\n const expectedSchemaVersionIndex = migrations.findIndex(m => (m as any).name === CUSTOM_FIELDS_SCHEMA_VERSION);\n\n logger.info('custom-fields: migrations', {\n currentMigrations: migrations,\n currentSadotSchemaVersion,\n newSadotSchemaVersion: CUSTOM_FIELDS_SCHEMA_VERSION,\n expectedSchemaVersionIndex,\n });\n if (!currentSadotSchemaVersion || (currentSadotSchemaVersion as any).name !== CUSTOM_FIELDS_SCHEMA_VERSION) {\n logger.info('custom-fields: syncing models');\n try {\n await CustomFieldDefinition.sync({ alter: true });\n logger.info('custom-fields: CustomFieldDefinition synced successfully');\n\n await CustomFieldValue.sync({ alter: true });\n logger.info('custom-fields: CustomFieldValue synced successfully');\n\n await CustomValidator.sync({ alter: true });\n logger.info('custom-fields: CustomValidator synced successfully');\n\n // T.Y TODO: Remove the if statement once we're ready to add the new entries table for all MS\n if (useCustomFieldsEntries) {\n await CustomFieldEntries.sync({ alter: true });\n logger.info('custom-fields: CustomFieldEntries synced successfully');\n }\n\n if (useModelTypeMapping) {\n await CustomFieldModelTypeMap.sync({ alter: true });\n logger.info('custom-fields: CustomFieldModelTypeMap synced successfully');\n }\n\n if (expectedSchemaVersionIndex === -1) {\n await SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });\n logger.info('custom-fields: SequelizeMeta entry created successfully');\n }\n\n logger.info('custom-fields: models synced');\n if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {\n // We have existing migrations, and we are calling `sync`.\n // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.\n const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);\n logger.info('custom-fields: deleting newer migrations during down migration', { count: migrationsToDelete.length });\n await SequelizeMeta.destroy({ where: { name: { [Op.in]: migrationsToDelete.map(m => (m as any).name) } } });\n logger.info('custom-fields: newer migrations deleted successfully');\n }\n } catch (error) {\n logger.error('custom-fields: failed to sync models', { error });\n throw error;\n }\n }\n};\n\nconst initTestModels = async (sequelize: Sequelize): Promise<void> => {\n logger.info('custom-fields: initialize custom-fields test models');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n\n sequelize.addModels(testModels);\n await sequelize.dropSchema('custom-fields', { logging: false });\n await sequelize.createSchema('custom-fields', { logging: false });\n\n logger.info('custom-fields: test models added');\n await TestModel.sync({ alter: true });\n await AssociatedTestModel.sync({ alter: true });\n await ContextTestModel.sync({ alter: true });\n await ContextAwareTestModel.sync({ alter: true });\n logger.info('custom-fields: test models synced');\n};\n\nexport {\n CustomFieldValue,\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomValidator,\n CustomFieldModelTypeMap,\n TestModel,\n AssociatedTestModel,\n ContextAwareTestModel,\n ContextTestModel,\n initTables,\n initTestModels,\n};\n"],"mappings":"2iBAyBA,MAAM,EAAa,CAACA,EAAAA,QAAWC,EAAAA,QAAqBC,EAAAA,QAAuBC,EAAAA,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":"index.cjs","names":["TestModel","AssociatedTestModel","ContextAwareTestModel","ContextTestModel","sequelize","DataTypes","Op","CustomFieldDefinition","CustomFieldValue","CustomValidator","CustomFieldEntries","CustomFieldModelTypeMap","productionModels: ProductionModel[]","runSadotMigrations"],"sources":["../../src/models/index.ts"],"sourcesContent":["import { DataTypes, Op } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport CustomFieldValue from './CustomFieldValue';\nimport TestModel from './tests/TestModel';\nimport ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';\nimport ContextTestModel from './tests/contextAwareModels/ContextTestModel';\nimport AssociatedTestModel from './tests/AssociatedTestModel';\nimport type { CustomFieldOptions } from '../types';\nimport CustomFieldEntries from './CustomFieldEntries';\nimport CustomValidator from './CustomValidator';\nimport CustomFieldModelTypeMap from './CustomFieldModelTypeMap';\nimport { runSadotMigrations } from '../migrations';\n\ntype ProductionModel = typeof CustomFieldDefinition | typeof CustomFieldValue | typeof CustomFieldEntries | typeof CustomValidator | typeof CustomFieldModelTypeMap;\ninterface InitTablesOptions {\n schemaPrefix?: string;\n schemaVersion?: string;\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n useUmzugMigrations?: boolean;\n isMatPathEnabled?: CustomFieldOptions['isMatPathEnabled'];\n}\n\nconst testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel];\n\nconst SADOT_MIGRATION_PREFIX = 'sadot-migration';\nconst SCHEMA_VERSION = '5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1';\n\n/**\n * Legacy migration approach using sequelize.sync({ alter: true }).\n * TODO: Remove this function once all consumers have migrated to umzug.\n */\nconst legacySyncMigrations = async (\n sequelize: Sequelize,\n {\n schemaPrefix,\n schemaVersion,\n useCustomFieldsEntries,\n useModelTypeMapping,\n }: { schemaPrefix: string; schemaVersion: string; useCustomFieldsEntries: boolean; useModelTypeMapping: boolean; },\n): Promise<void> => {\n const SequelizeMeta = sequelize.define(\n 'SequelizeMeta',\n {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: false,\n },\n },\n {\n tableName: 'SequelizeMeta',\n timestamps: false,\n schema: 'public',\n },\n );\n\n logger.info('custom-fields: starting migrations');\n const migrations = await SequelizeMeta.findAll({ where: { name: { [Op.like]: `${schemaPrefix}%` } }, raw: true });\n const currentSadotSchemaVersion = migrations.at(-1);\n const expectedSchemaVersionIndex = migrations.findIndex(m => (m as any).name === schemaVersion);\n\n logger.info('custom-fields: migrations', {\n currentMigrations: migrations,\n currentSadotSchemaVersion,\n newSadotSchemaVersion: schemaVersion,\n expectedSchemaVersionIndex,\n });\n if (!currentSadotSchemaVersion || (currentSadotSchemaVersion as any).name !== schemaVersion) {\n logger.info('custom-fields: syncing models');\n try {\n await CustomFieldDefinition.sync({ alter: true });\n logger.info('custom-fields: CustomFieldDefinition synced successfully');\n\n await CustomFieldValue.sync({ alter: true });\n logger.info('custom-fields: CustomFieldValue synced successfully');\n\n await CustomValidator.sync({ alter: true });\n logger.info('custom-fields: CustomValidator synced successfully');\n\n // T.Y TODO: Remove the if statement once we're ready to add the new entries table for all MS\n if (useCustomFieldsEntries) {\n await CustomFieldEntries.sync({ alter: true });\n logger.info('custom-fields: CustomFieldEntries synced successfully');\n }\n\n if (useModelTypeMapping) {\n await CustomFieldModelTypeMap.sync({ alter: true });\n logger.info('custom-fields: CustomFieldModelTypeMap synced successfully');\n }\n\n if (expectedSchemaVersionIndex === -1) {\n await SequelizeMeta.create({ name: schemaVersion });\n logger.info('custom-fields: SequelizeMeta entry created successfully');\n }\n\n logger.info('custom-fields: models synced');\n if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {\n // We have existing migrations, and we are calling `sync`.\n // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.\n const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);\n logger.info('custom-fields: deleting newer migrations during down migration', { count: migrationsToDelete.length });\n await SequelizeMeta.destroy({ where: { name: { [Op.in]: migrationsToDelete.map(m => (m as any).name) } } });\n logger.info('custom-fields: newer migrations deleted successfully');\n }\n } catch (error) {\n logger.error('custom-fields: failed to sync models', { error });\n throw error;\n }\n }\n};\n\nconst initTables = async (\n sequelize: Sequelize,\n getUser: CustomFieldOptions['getUser'],\n {\n schemaPrefix = SADOT_MIGRATION_PREFIX,\n schemaVersion = SCHEMA_VERSION,\n useCustomFieldsEntries = false,\n useModelTypeMapping = false,\n useUmzugMigrations = false,\n isMatPathEnabled,\n }: InitTablesOptions = {},\n): Promise<void> => {\n const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}${useCustomFieldsEntries ? '_withEntries' : ''}${useModelTypeMapping ? '_withTypeMapping' : ''}`;\n logger.info('custom-fields: initialize custom-fields tables');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n const productionModels: ProductionModel[] = [\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n ...(useCustomFieldsEntries ? [CustomFieldEntries] : []),\n ...(useModelTypeMapping ? [CustomFieldModelTypeMap] : []),\n ];\n\n sequelize.addModels(productionModels);\n\n // Add the association only when useModelTypeMapping is enabled\n if (useModelTypeMapping) {\n CustomFieldDefinition.hasMany(CustomFieldModelTypeMap, {\n foreignKey: 'customFieldDefinitionId',\n as: 'modelTypeMappings',\n });\n CustomFieldModelTypeMap.belongsTo(CustomFieldDefinition, {\n foreignKey: 'customFieldDefinitionId',\n as: 'customFieldDefinition',\n });\n }\n\n CustomFieldDefinition.addScope('userScope', () => {\n // When mat-path is active, the consumer is responsible for restricting entityIds\n // (typically by expanding the request's entityIds to include ancestor paths the\n // caller can see). Bypass the legacy permission filter so partner/ancestor\n // entityIds are not dropped.\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n CustomValidator.addScope('userScope', () => {\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n logger.info('custom-fields: models added');\n\n if (useUmzugMigrations) {\n logger.info('custom-fields: starting umzug migrations');\n await runSadotMigrations(sequelize, { useCustomFieldsEntries, useModelTypeMapping });\n logger.info('custom-fields: umzug migrations complete');\n return;\n }\n\n await legacySyncMigrations(sequelize, { schemaPrefix, schemaVersion: CUSTOM_FIELDS_SCHEMA_VERSION, useCustomFieldsEntries, useModelTypeMapping });\n};\n\nconst initTestModels = async (sequelize: Sequelize): Promise<void> => {\n logger.info('custom-fields: initialize custom-fields test models');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n\n sequelize.addModels(testModels);\n await sequelize.dropSchema('custom-fields', { logging: false });\n await sequelize.createSchema('custom-fields', { logging: false });\n\n logger.info('custom-fields: test models added');\n await TestModel.sync({ alter: true });\n await AssociatedTestModel.sync({ alter: true });\n await ContextTestModel.sync({ alter: true });\n await ContextAwareTestModel.sync({ alter: true });\n logger.info('custom-fields: test models synced');\n};\n\nexport {\n CustomFieldValue,\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomValidator,\n CustomFieldModelTypeMap,\n TestModel,\n AssociatedTestModel,\n ContextAwareTestModel,\n ContextTestModel,\n initTables,\n initTestModels,\n};\n"],"mappings":"2iBAyBA,MAAM,EAAa,CAACA,EAAAA,QAAWC,EAAAA,QAAqBC,EAAAA,QAAuBC,EAAAA,QAAiB,CAEtF,EAAyB,kBACzB,EAAiB,uCAMjB,EAA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AAE,MAAO,GAAM,CAAC,CACjD,EAAA,QAAO,KAAK,oCAAoC"}
|
package/dist/models/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e from"../utils/logger/index.js";import t from"./CustomFieldValue.js";import n from"./CustomFieldDefinition.js";import r from"./tests/AssociatedTestModel.js";import i from"./tests/TestModel.js";import a from"./tests/contextAwareModels/ContextTestModel.js";import o from"./tests/contextAwareModels/ContextAwareTestModel.js";import s from"./CustomFieldEntries.js";import c from"./CustomValidator.js";import l from"./CustomFieldModelTypeMap.js";import{runSadotMigrations as u}from"../migrations/index.js";import{DataTypes as d,Op as f}from"sequelize";const p=[i,r,o,a],m=async(r,
|
|
1
|
+
import e from"../utils/logger/index.js";import t from"./CustomFieldValue.js";import n from"./CustomFieldDefinition.js";import r from"./tests/AssociatedTestModel.js";import i from"./tests/TestModel.js";import a from"./tests/contextAwareModels/ContextTestModel.js";import o from"./tests/contextAwareModels/ContextAwareTestModel.js";import s from"./CustomFieldEntries.js";import c from"./CustomValidator.js";import l from"./CustomFieldModelTypeMap.js";import{runSadotMigrations as u}from"../migrations/index.js";import{DataTypes as d,Op as f}from"sequelize";const p=[i,r,o,a],m=async(r,{schemaPrefix:i,schemaVersion:a,useCustomFieldsEntries:o,useModelTypeMapping:u})=>{let p=r.define(`SequelizeMeta`,{name:{type:d.STRING,allowNull:!1,unique:!0,primaryKey:!0,autoIncrement:!1}},{tableName:`SequelizeMeta`,timestamps:!1,schema:`public`});e.info(`custom-fields: starting migrations`);let m=await p.findAll({where:{name:{[f.like]:`${i}%`}},raw:!0}),h=m.at(-1),g=m.findIndex(e=>e.name===a);if(e.info(`custom-fields: migrations`,{currentMigrations:m,currentSadotSchemaVersion:h,newSadotSchemaVersion:a,expectedSchemaVersionIndex:g}),!h||h.name!==a){e.info(`custom-fields: syncing models`);try{if(await n.sync({alter:!0}),e.info(`custom-fields: CustomFieldDefinition synced successfully`),await t.sync({alter:!0}),e.info(`custom-fields: CustomFieldValue synced successfully`),await c.sync({alter:!0}),e.info(`custom-fields: CustomValidator synced successfully`),o&&(await s.sync({alter:!0}),e.info(`custom-fields: CustomFieldEntries synced successfully`)),u&&(await l.sync({alter:!0}),e.info(`custom-fields: CustomFieldModelTypeMap synced successfully`)),g===-1&&(await p.create({name:a}),e.info(`custom-fields: SequelizeMeta entry created successfully`)),e.info(`custom-fields: models synced`),m.length&&g!==-1&&g<m.length-1){let t=m.slice(g+1);e.info(`custom-fields: deleting newer migrations during down migration`,{count:t.length}),await p.destroy({where:{name:{[f.in]:t.map(e=>e.name)}}}),e.info(`custom-fields: newer migrations deleted successfully`)}}catch(t){throw e.error(`custom-fields: failed to sync models`,{error:t}),t}}},h=async(r,i,{schemaPrefix:a=`sadot-migration`,schemaVersion:o=`5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1`,useCustomFieldsEntries:d=!1,useModelTypeMapping:f=!1,useUmzugMigrations:p=!1,isMatPathEnabled:h}={})=>{let g=`${a}_${o}${d?`_withEntries`:``}${f?`_withTypeMapping`:``}`;if(e.info(`custom-fields: initialize custom-fields tables`),!r.addModels)throw Error(`sequelize instance must have addModels function`);let _=[n,t,c,...d?[s]:[],...f?[l]:[]];if(r.addModels(_),f&&(n.hasMany(l,{foreignKey:`customFieldDefinitionId`,as:`modelTypeMappings`}),l.belongsTo(n,{foreignKey:`customFieldDefinitionId`,as:`customFieldDefinition`})),n.addScope(`userScope`,()=>{if(h?.())return{};let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),c.addScope(`userScope`,()=>{if(h?.())return{};let e=i();return e?.permissions?{where:{entityId:[...Object.keys(e.permissions.fleets),...Object.keys(e.permissions.businessModels),...Object.keys(e.permissions.demandSources)]}}:{}}),e.info(`custom-fields: models added`),p){e.info(`custom-fields: starting umzug migrations`),await u(r,{useCustomFieldsEntries:d,useModelTypeMapping:f}),e.info(`custom-fields: umzug migrations complete`);return}await m(r,{schemaPrefix:a,schemaVersion:g,useCustomFieldsEntries:d,useModelTypeMapping:f})},g=async t=>{if(e.info(`custom-fields: initialize custom-fields test models`),!t.addModels)throw Error(`sequelize instance must have addModels function`);t.addModels(p),await t.dropSchema(`custom-fields`,{logging:!1}),await t.createSchema(`custom-fields`,{logging:!1}),e.info(`custom-fields: test models added`),await i.sync({alter:!0}),await r.sync({alter:!0}),await a.sync({alter:!0}),await o.sync({alter:!0}),e.info(`custom-fields: test models synced`)};export{h as initTables,g as initTestModels};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/models/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["TestModel","AssociatedTestModel","ContextAwareTestModel","ContextTestModel","productionModels: ProductionModel[]","CustomFieldDefinition","CustomFieldValue","CustomValidator","CustomFieldEntries","CustomFieldModelTypeMap"],"sources":["../../src/models/index.ts"],"sourcesContent":["import { DataTypes, Op } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport CustomFieldValue from './CustomFieldValue';\nimport TestModel from './tests/TestModel';\nimport ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';\nimport ContextTestModel from './tests/contextAwareModels/ContextTestModel';\nimport AssociatedTestModel from './tests/AssociatedTestModel';\nimport type { CustomFieldOptions } from '../types';\nimport CustomFieldEntries from './CustomFieldEntries';\nimport CustomValidator from './CustomValidator';\nimport CustomFieldModelTypeMap from './CustomFieldModelTypeMap';\nimport { runSadotMigrations } from '../migrations';\n\ntype ProductionModel = typeof CustomFieldDefinition | typeof CustomFieldValue | typeof CustomFieldEntries | typeof CustomValidator | typeof CustomFieldModelTypeMap;\ninterface InitTablesOptions {\n schemaPrefix?: string;\n schemaVersion?: string;\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n useUmzugMigrations?: boolean;\n isMatPathEnabled?: CustomFieldOptions['isMatPathEnabled'];\n}\n\nconst testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel];\n\nconst SADOT_MIGRATION_PREFIX = 'sadot-migration';\nconst SCHEMA_VERSION = '5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1';\n\nconst initTables = async (\n sequelize: Sequelize,\n getUser: CustomFieldOptions['getUser'],\n {\n schemaPrefix = SADOT_MIGRATION_PREFIX,\n schemaVersion = SCHEMA_VERSION,\n useCustomFieldsEntries = false,\n useModelTypeMapping = false,\n useUmzugMigrations = false,\n isMatPathEnabled,\n }: InitTablesOptions = {},\n): Promise<void> => {\n const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}${useCustomFieldsEntries ? '_withEntries' : ''}${useModelTypeMapping ? '_withTypeMapping' : ''}`;\n logger.info('custom-fields: initialize custom-fields tables');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n const productionModels: ProductionModel[] = [\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n ...(useCustomFieldsEntries ? [CustomFieldEntries] : []),\n ...(useModelTypeMapping ? [CustomFieldModelTypeMap] : []),\n ];\n\n sequelize.addModels(productionModels);\n\n // Add the association only when useModelTypeMapping is enabled\n if (useModelTypeMapping) {\n CustomFieldDefinition.hasMany(CustomFieldModelTypeMap, {\n foreignKey: 'customFieldDefinitionId',\n as: 'modelTypeMappings',\n });\n CustomFieldModelTypeMap.belongsTo(CustomFieldDefinition, {\n foreignKey: 'customFieldDefinitionId',\n as: 'customFieldDefinition',\n });\n }\n\n CustomFieldDefinition.addScope('userScope', () => {\n // When mat-path is active, the consumer is responsible for restricting entityIds\n // (typically by expanding the request's entityIds to include ancestor paths the\n // caller can see). Bypass the legacy permission filter so partner/ancestor\n // entityIds are not dropped.\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n CustomValidator.addScope('userScope', () => {\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n logger.info('custom-fields: models added');\n\n if (useUmzugMigrations) {\n logger.info('custom-fields: starting umzug migrations');\n await runSadotMigrations(sequelize, { useCustomFieldsEntries, useModelTypeMapping });\n logger.info('custom-fields: umzug migrations complete');\n return;\n }\n\n const SequelizeMeta = sequelize.define(\n 'SequelizeMeta',\n {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: false,\n },\n },\n {\n tableName: 'SequelizeMeta',\n timestamps: false,\n schema: 'public',\n },\n );\n\n logger.info('custom-fields: starting migrations');\n const migrations = await SequelizeMeta.findAll({ where: { name: { [Op.like]: `${schemaPrefix}%` } }, raw: true });\n const currentSadotSchemaVersion = migrations.at(-1);\n const expectedSchemaVersionIndex = migrations.findIndex(m => (m as any).name === CUSTOM_FIELDS_SCHEMA_VERSION);\n\n logger.info('custom-fields: migrations', {\n currentMigrations: migrations,\n currentSadotSchemaVersion,\n newSadotSchemaVersion: CUSTOM_FIELDS_SCHEMA_VERSION,\n expectedSchemaVersionIndex,\n });\n if (!currentSadotSchemaVersion || (currentSadotSchemaVersion as any).name !== CUSTOM_FIELDS_SCHEMA_VERSION) {\n logger.info('custom-fields: syncing models');\n try {\n await CustomFieldDefinition.sync({ alter: true });\n logger.info('custom-fields: CustomFieldDefinition synced successfully');\n\n await CustomFieldValue.sync({ alter: true });\n logger.info('custom-fields: CustomFieldValue synced successfully');\n\n await CustomValidator.sync({ alter: true });\n logger.info('custom-fields: CustomValidator synced successfully');\n\n // T.Y TODO: Remove the if statement once we're ready to add the new entries table for all MS\n if (useCustomFieldsEntries) {\n await CustomFieldEntries.sync({ alter: true });\n logger.info('custom-fields: CustomFieldEntries synced successfully');\n }\n\n if (useModelTypeMapping) {\n await CustomFieldModelTypeMap.sync({ alter: true });\n logger.info('custom-fields: CustomFieldModelTypeMap synced successfully');\n }\n\n if (expectedSchemaVersionIndex === -1) {\n await SequelizeMeta.create({ name: CUSTOM_FIELDS_SCHEMA_VERSION });\n logger.info('custom-fields: SequelizeMeta entry created successfully');\n }\n\n logger.info('custom-fields: models synced');\n if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {\n // We have existing migrations, and we are calling `sync`.\n // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.\n const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);\n logger.info('custom-fields: deleting newer migrations during down migration', { count: migrationsToDelete.length });\n await SequelizeMeta.destroy({ where: { name: { [Op.in]: migrationsToDelete.map(m => (m as any).name) } } });\n logger.info('custom-fields: newer migrations deleted successfully');\n }\n } catch (error) {\n logger.error('custom-fields: failed to sync models', { error });\n throw error;\n }\n }\n};\n\nconst initTestModels = async (sequelize: Sequelize): Promise<void> => {\n logger.info('custom-fields: initialize custom-fields test models');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n\n sequelize.addModels(testModels);\n await sequelize.dropSchema('custom-fields', { logging: false });\n await sequelize.createSchema('custom-fields', { logging: false });\n\n logger.info('custom-fields: test models added');\n await TestModel.sync({ alter: true });\n await AssociatedTestModel.sync({ alter: true });\n await ContextTestModel.sync({ alter: true });\n await ContextAwareTestModel.sync({ alter: true });\n logger.info('custom-fields: test models synced');\n};\n\nexport {\n CustomFieldValue,\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomValidator,\n CustomFieldModelTypeMap,\n TestModel,\n AssociatedTestModel,\n ContextAwareTestModel,\n ContextTestModel,\n initTables,\n initTestModels,\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AC,CAClE,EAAO,KAAK,0DAA0D,EAGxE,EAAO,KAAK,+BAA+B,CACvC,EAAW,QAAU,IAA+B,IAAM,EAA6B,EAAW,OAAS,EAAG,CAGhH,IAAM,EAAqB,EAAW,MAAM,EAA6B,EAAE,CAC3E,EAAO,KAAK,iEAAkE,CAAE,MAAO,EAAmB,OAAQ,CAAC,CACnH,MAAM,EAAc,QAAQ,CAAE,MAAO,CAAE,KAAM,EAAG,EAAG,IAAK,EAAmB,IAAI,GAAM,EAAU,KAAK,CAAE,CAAE,CAAE,CAAC,CAC3G,EAAO,KAAK,uDAAuD,QAE9D,EAAO,CAEd,MADA,EAAO,MAAM,uCAAwC,CAAE,QAAO,CAAC,CACzD,KAKN,EAAiB,KAAO,IAAwC,CAGpE,GAFA,EAAO,KAAK,sDAAsD,CAE9D,CAAC,EAAU,UACb,MAAU,MAAM,kDAAkD,CAGpE,EAAU,UAAU,EAAW,CAC/B,MAAM,EAAU,WAAW,gBAAiB,CAAE,QAAS,GAAO,CAAC,CAC/D,MAAM,EAAU,aAAa,gBAAiB,CAAE,QAAS,GAAO,CAAC,CAEjE,EAAO,KAAK,mCAAmC,CAC/C,MAAMT,EAAU,KAAK,CAAE,MAAO,GAAM,CAAC,CACrC,MAAMC,EAAoB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC/C,MAAME,EAAiB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC5C,MAAMD,EAAsB,KAAK,CAAE,MAAO,GAAM,CAAC,CACjD,EAAO,KAAK,oCAAoC"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["TestModel","AssociatedTestModel","ContextAwareTestModel","ContextTestModel","CustomFieldDefinition","CustomFieldValue","CustomValidator","CustomFieldEntries","CustomFieldModelTypeMap","productionModels: ProductionModel[]"],"sources":["../../src/models/index.ts"],"sourcesContent":["import { DataTypes, Op } from 'sequelize';\nimport type { Sequelize } from 'sequelize-typescript';\nimport logger from '../utils/logger';\nimport CustomFieldDefinition from './CustomFieldDefinition';\nimport CustomFieldValue from './CustomFieldValue';\nimport TestModel from './tests/TestModel';\nimport ContextAwareTestModel from './tests/contextAwareModels/ContextAwareTestModel';\nimport ContextTestModel from './tests/contextAwareModels/ContextTestModel';\nimport AssociatedTestModel from './tests/AssociatedTestModel';\nimport type { CustomFieldOptions } from '../types';\nimport CustomFieldEntries from './CustomFieldEntries';\nimport CustomValidator from './CustomValidator';\nimport CustomFieldModelTypeMap from './CustomFieldModelTypeMap';\nimport { runSadotMigrations } from '../migrations';\n\ntype ProductionModel = typeof CustomFieldDefinition | typeof CustomFieldValue | typeof CustomFieldEntries | typeof CustomValidator | typeof CustomFieldModelTypeMap;\ninterface InitTablesOptions {\n schemaPrefix?: string;\n schemaVersion?: string;\n useCustomFieldsEntries?: boolean;\n useModelTypeMapping?: boolean;\n useUmzugMigrations?: boolean;\n isMatPathEnabled?: CustomFieldOptions['isMatPathEnabled'];\n}\n\nconst testModels = [TestModel, AssociatedTestModel, ContextAwareTestModel, ContextTestModel];\n\nconst SADOT_MIGRATION_PREFIX = 'sadot-migration';\nconst SCHEMA_VERSION = '5f8e4a7c-9b2d-4e1f-8c3a-b6d9e2f7a4c1';\n\n/**\n * Legacy migration approach using sequelize.sync({ alter: true }).\n * TODO: Remove this function once all consumers have migrated to umzug.\n */\nconst legacySyncMigrations = async (\n sequelize: Sequelize,\n {\n schemaPrefix,\n schemaVersion,\n useCustomFieldsEntries,\n useModelTypeMapping,\n }: { schemaPrefix: string; schemaVersion: string; useCustomFieldsEntries: boolean; useModelTypeMapping: boolean; },\n): Promise<void> => {\n const SequelizeMeta = sequelize.define(\n 'SequelizeMeta',\n {\n name: {\n type: DataTypes.STRING,\n allowNull: false,\n unique: true,\n primaryKey: true,\n autoIncrement: false,\n },\n },\n {\n tableName: 'SequelizeMeta',\n timestamps: false,\n schema: 'public',\n },\n );\n\n logger.info('custom-fields: starting migrations');\n const migrations = await SequelizeMeta.findAll({ where: { name: { [Op.like]: `${schemaPrefix}%` } }, raw: true });\n const currentSadotSchemaVersion = migrations.at(-1);\n const expectedSchemaVersionIndex = migrations.findIndex(m => (m as any).name === schemaVersion);\n\n logger.info('custom-fields: migrations', {\n currentMigrations: migrations,\n currentSadotSchemaVersion,\n newSadotSchemaVersion: schemaVersion,\n expectedSchemaVersionIndex,\n });\n if (!currentSadotSchemaVersion || (currentSadotSchemaVersion as any).name !== schemaVersion) {\n logger.info('custom-fields: syncing models');\n try {\n await CustomFieldDefinition.sync({ alter: true });\n logger.info('custom-fields: CustomFieldDefinition synced successfully');\n\n await CustomFieldValue.sync({ alter: true });\n logger.info('custom-fields: CustomFieldValue synced successfully');\n\n await CustomValidator.sync({ alter: true });\n logger.info('custom-fields: CustomValidator synced successfully');\n\n // T.Y TODO: Remove the if statement once we're ready to add the new entries table for all MS\n if (useCustomFieldsEntries) {\n await CustomFieldEntries.sync({ alter: true });\n logger.info('custom-fields: CustomFieldEntries synced successfully');\n }\n\n if (useModelTypeMapping) {\n await CustomFieldModelTypeMap.sync({ alter: true });\n logger.info('custom-fields: CustomFieldModelTypeMap synced successfully');\n }\n\n if (expectedSchemaVersionIndex === -1) {\n await SequelizeMeta.create({ name: schemaVersion });\n logger.info('custom-fields: SequelizeMeta entry created successfully');\n }\n\n logger.info('custom-fields: models synced');\n if (migrations.length && expectedSchemaVersionIndex !== -1 && expectedSchemaVersionIndex < migrations.length - 1) {\n // We have existing migrations, and we are calling `sync`.\n // This means we are in a `down` migration, and hence we should delete newer migrations to ensure we can reapply them.\n const migrationsToDelete = migrations.slice(expectedSchemaVersionIndex + 1);\n logger.info('custom-fields: deleting newer migrations during down migration', { count: migrationsToDelete.length });\n await SequelizeMeta.destroy({ where: { name: { [Op.in]: migrationsToDelete.map(m => (m as any).name) } } });\n logger.info('custom-fields: newer migrations deleted successfully');\n }\n } catch (error) {\n logger.error('custom-fields: failed to sync models', { error });\n throw error;\n }\n }\n};\n\nconst initTables = async (\n sequelize: Sequelize,\n getUser: CustomFieldOptions['getUser'],\n {\n schemaPrefix = SADOT_MIGRATION_PREFIX,\n schemaVersion = SCHEMA_VERSION,\n useCustomFieldsEntries = false,\n useModelTypeMapping = false,\n useUmzugMigrations = false,\n isMatPathEnabled,\n }: InitTablesOptions = {},\n): Promise<void> => {\n const CUSTOM_FIELDS_SCHEMA_VERSION = `${schemaPrefix}_${schemaVersion}${useCustomFieldsEntries ? '_withEntries' : ''}${useModelTypeMapping ? '_withTypeMapping' : ''}`;\n logger.info('custom-fields: initialize custom-fields tables');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n const productionModels: ProductionModel[] = [\n CustomFieldDefinition,\n CustomFieldValue,\n CustomValidator,\n ...(useCustomFieldsEntries ? [CustomFieldEntries] : []),\n ...(useModelTypeMapping ? [CustomFieldModelTypeMap] : []),\n ];\n\n sequelize.addModels(productionModels);\n\n // Add the association only when useModelTypeMapping is enabled\n if (useModelTypeMapping) {\n CustomFieldDefinition.hasMany(CustomFieldModelTypeMap, {\n foreignKey: 'customFieldDefinitionId',\n as: 'modelTypeMappings',\n });\n CustomFieldModelTypeMap.belongsTo(CustomFieldDefinition, {\n foreignKey: 'customFieldDefinitionId',\n as: 'customFieldDefinition',\n });\n }\n\n CustomFieldDefinition.addScope('userScope', () => {\n // When mat-path is active, the consumer is responsible for restricting entityIds\n // (typically by expanding the request's entityIds to include ancestor paths the\n // caller can see). Bypass the legacy permission filter so partner/ancestor\n // entityIds are not dropped.\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n CustomValidator.addScope('userScope', () => {\n if (isMatPathEnabled?.()) return {};\n const user = getUser();\n if (!user?.permissions) {\n return {};\n }\n return {\n where: {\n entityId: [\n ...Object.keys(user.permissions.fleets),\n ...Object.keys(user.permissions.businessModels),\n ...Object.keys(user.permissions.demandSources),\n ],\n },\n };\n });\n\n logger.info('custom-fields: models added');\n\n if (useUmzugMigrations) {\n logger.info('custom-fields: starting umzug migrations');\n await runSadotMigrations(sequelize, { useCustomFieldsEntries, useModelTypeMapping });\n logger.info('custom-fields: umzug migrations complete');\n return;\n }\n\n await legacySyncMigrations(sequelize, { schemaPrefix, schemaVersion: CUSTOM_FIELDS_SCHEMA_VERSION, useCustomFieldsEntries, useModelTypeMapping });\n};\n\nconst initTestModels = async (sequelize: Sequelize): Promise<void> => {\n logger.info('custom-fields: initialize custom-fields test models');\n // Detect models and import them to the orm\n if (!sequelize.addModels) {\n throw new Error('sequelize instance must have addModels function');\n }\n\n sequelize.addModels(testModels);\n await sequelize.dropSchema('custom-fields', { logging: false });\n await sequelize.createSchema('custom-fields', { logging: false });\n\n logger.info('custom-fields: test models added');\n await TestModel.sync({ alter: true });\n await AssociatedTestModel.sync({ alter: true });\n await ContextTestModel.sync({ alter: true });\n await ContextAwareTestModel.sync({ alter: true });\n logger.info('custom-fields: test models synced');\n};\n\nexport {\n CustomFieldValue,\n CustomFieldDefinition,\n CustomFieldEntries,\n CustomValidator,\n CustomFieldModelTypeMap,\n TestModel,\n AssociatedTestModel,\n ContextAwareTestModel,\n ContextTestModel,\n initTables,\n initTestModels,\n};\n"],"mappings":"2iBAyBA,MAAM,EAAa,CAACA,EAAWC,EAAqBC,EAAuBC,EAAiB,CAStF,EAAuB,MAC3B,EACA,CACE,eACA,gBACA,yBACA,yBAEgB,CAClB,IAAM,EAAgB,EAAU,OAC9B,gBACA,CACE,KAAM,CACJ,KAAM,EAAU,OAChB,UAAW,GACX,OAAQ,GACR,WAAY,GACZ,cAAe,GAChB,CACF,CACD,CACE,UAAW,gBACX,WAAY,GACZ,OAAQ,SACT,CACF,CAED,EAAO,KAAK,qCAAqC,CACjD,IAAM,EAAa,MAAM,EAAc,QAAQ,CAAE,MAAO,CAAE,KAAM,EAAG,EAAG,MAAO,GAAG,EAAa,GAAI,CAAE,CAAE,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wB,sBAAqB,CAAC,CACpF,EAAO,KAAK,2CAA2C,CACvD,OAGF,MAAM,EAAqB,EAAW,CAAE,eAAc,cAAe,EAA8B,yBAAwB,sBAAqB,CAAC,EAG7I,EAAiB,KAAO,IAAwC,CAGpE,GAFA,EAAO,KAAK,sDAAsD,CAE9D,CAAC,EAAU,UACb,MAAU,MAAM,kDAAkD,CAGpE,EAAU,UAAU,EAAW,CAC/B,MAAM,EAAU,WAAW,gBAAiB,CAAE,QAAS,GAAO,CAAC,CAC/D,MAAM,EAAU,aAAa,gBAAiB,CAAE,QAAS,GAAO,CAAC,CAEjE,EAAO,KAAK,mCAAmC,CAC/C,MAAMJ,EAAU,KAAK,CAAE,MAAO,GAAM,CAAC,CACrC,MAAMC,EAAoB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC/C,MAAME,EAAiB,KAAK,CAAE,MAAO,GAAM,CAAC,CAC5C,MAAMD,EAAsB,KAAK,CAAE,MAAO,GAAM,CAAC,CACjD,EAAO,KAAK,oCAAoC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@autofleet/sadot",
|
|
3
|
-
"version": "1.6.0-alpha.
|
|
3
|
+
"version": "1.6.0-alpha.2",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -54,9 +54,9 @@
|
|
|
54
54
|
"npm-watch": "^0.11.0",
|
|
55
55
|
"supertest": "^7.0.0",
|
|
56
56
|
"@autofleet/errors": "^3.1.53",
|
|
57
|
+
"@autofleet/node-common": "^4.3.13",
|
|
57
58
|
"@autofleet/zehut": "^4.12.8",
|
|
58
|
-
"@autofleet/logger": "^4.5.1"
|
|
59
|
-
"@autofleet/node-common": "^4.3.13"
|
|
59
|
+
"@autofleet/logger": "^4.5.1"
|
|
60
60
|
},
|
|
61
61
|
"peerDependencies": {
|
|
62
62
|
"@autofleet/errors": "^3",
|