import { SDTFQuery, SpecifyDesignTokenTypeName, WhereNode, } from '@specifyapp/specify-design-token-format'; type applyTo = | { collection: string | true; } | { group: string | true; } | { token: string | true; } | SDTFQuery; type options = { authorizedTokens?: Array; selectChildren?: boolean; tokensOnly?: boolean; }; export function getSdtfQuery( applyTo: applyTo | Array | undefined, options?: options, ): SDTFQuery { if (Array.isArray(applyTo)) return { where: applyTo.flatMap(v => formatWhere(v, options ?? {})) }; else return { where: formatWhere(applyTo, options ?? {}) }; } function formatWhere( applyTo: applyTo | undefined, { authorizedTokens, tokensOnly = false, selectChildren = false }: options, ): WhereNode | Array { const withTypes = !!authorizedTokens ? { withTypes: { include: authorizedTokens } } : {}; const andWhere = tokensOnly ?? false ? { andWhere: { token: '.*', select: true }, ...withTypes } : undefined; if (!applyTo) { return { token: '.*', ...withTypes, select: { token: true, }, }; } else if ('collection' in applyTo) { const matcher = applyTo.collection === true ? '.*' : applyTo.collection; return { collection: matcher, ...(!!andWhere ? andWhere : { select: selectChildren ? { collection: true, children: true } : true }), } as SDTFQuery['where']; } else if ('group' in applyTo) { const matcher = applyTo.group === true ? '.*' : applyTo.group; return { group: matcher, ...(!!andWhere ? andWhere : { select: selectChildren ? { group: true, children: true } : true }), } as SDTFQuery['where']; } else if ('token' in applyTo) { const matcher = applyTo.token === true ? '.*' : applyTo.token; return { token: matcher, ...withTypes, select: true, }; } else { return applyTo.where; } }