import { CallExpressionShape, Plugin } from '@servicenow/sdk-build-core' import { NowIdShape } from '../now-id-plugin' export const SPAngularProviderPlugin = Plugin.create({ name: 'SPAngularProviderPlugin', records: { sp_angular_provider: { relationships: { m2m_sp_ng_pro_sp_ng_pro: { via: 'required_by', descendant: true }, }, toShape(record, { descendants }) { const requiredProviders = descendants.query('m2m_sp_ng_pro_sp_ng_pro').map((p) => p.get('requires')) return { success: true, value: new CallExpressionShape({ source: record, callee: 'SPAngularProvider', args: [ record.transform(({ $ }) => ({ $id: $.val(NowIdShape.from(record)), name: $, type: $, script: $.def(''), requires: $.val(requiredProviders.length > 0 ? requiredProviders : undefined), })), ], }), } }, }, m2m_sp_ng_pro_sp_ng_pro: { coalesce: ['required_by', 'requires'], }, }, shapes: [ { shape: CallExpressionShape, fileTypes: ['fluent'], async toRecord(callExpression, { factory, diagnostics }) { if (callExpression.getCallee() !== 'SPAngularProvider') { return { success: false } } const providerObj = callExpression.getArgument(0).asObject() const providerId = providerObj.get('$id') const requires = providerObj.get('requires').ifArray()?.getElements() || [] requires .filter((provider) => provider.equals(providerId)) .forEach((provider) => diagnostics.error(provider, 'recursive dependency detected')) const providerRecord = await factory.createRecord({ source: callExpression, table: 'sp_angular_provider', explicitId: providerObj.get('$id'), properties: providerObj.transform(({ $ }) => ({ name: $, type: $.def('directive'), script: $.def(''), })), }) return { success: true, value: providerRecord.with( ...(await Promise.all( requires.map(async (child) => { return factory.createRecord({ source: callExpression, table: 'm2m_sp_ng_pro_sp_ng_pro', properties: { required_by: providerRecord.getId(), requires: child.ifString()?.getValue() ?? child.ifRecord()?.getId(), }, }) }) )) ), } }, }, ], })