@panneau/protocol 5.0.0-alpha.4 → 5.0.0-alpha.41
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/addresses.d.ts +23 -0
- package/dist/addresses.d.ts.map +1 -0
- package/dist/addresses.js +52 -0
- package/dist/addresses.js.map +1 -0
- package/dist/aggregates.d.ts +135 -0
- package/dist/aggregates.d.ts.map +1 -0
- package/dist/aggregates.js +236 -0
- package/dist/aggregates.js.map +1 -0
- package/dist/compound.d.ts +20 -0
- package/dist/compound.d.ts.map +1 -0
- package/dist/compound.js +27 -0
- package/dist/compound.js.map +1 -0
- package/dist/conditions.d.ts +1 -1
- package/dist/conformance/index.d.ts +6 -0
- package/dist/conformance/index.d.ts.map +1 -1
- package/dist/conformance/index.js +970 -11
- package/dist/conformance/index.js.map +1 -1
- package/dist/constants.d.ts +108 -2
- package/dist/constants.d.ts.map +1 -1
- package/dist/constants.js +181 -3
- package/dist/constants.js.map +1 -1
- package/dist/context.d.ts +15 -0
- package/dist/context.d.ts.map +1 -0
- package/dist/context.js +34 -0
- package/dist/context.js.map +1 -0
- package/dist/currencies.d.ts +22 -0
- package/dist/currencies.d.ts.map +1 -0
- package/dist/currencies.js +231 -0
- package/dist/currencies.js.map +1 -0
- package/dist/dashboards.d.ts +95 -0
- package/dist/dashboards.d.ts.map +1 -0
- package/dist/dashboards.js +140 -0
- package/dist/dashboards.js.map +1 -0
- package/dist/index.d.ts +4 -4
- package/dist/index.js +22 -8
- package/dist/libraries.d.ts +33 -0
- package/dist/libraries.d.ts.map +1 -0
- package/dist/libraries.js +59 -0
- package/dist/libraries.js.map +1 -0
- package/dist/links.d.ts +38 -0
- package/dist/links.d.ts.map +1 -0
- package/dist/links.js +65 -0
- package/dist/links.js.map +1 -0
- package/dist/lint.d.ts +4 -4
- package/dist/lint.d.ts.map +1 -1
- package/dist/lint.js +540 -15
- package/dist/lint.js.map +1 -1
- package/dist/mock/auth.d.ts +71 -0
- package/dist/mock/auth.d.ts.map +1 -0
- package/dist/mock/auth.js +346 -0
- package/dist/mock/auth.js.map +1 -0
- package/dist/mock/example.d.ts +1 -1
- package/dist/mock/example.d.ts.map +1 -1
- package/dist/mock/example.js +49 -28
- package/dist/mock/example.js.map +1 -1
- package/dist/mock/index.d.ts +96 -5
- package/dist/mock/index.d.ts.map +1 -1
- package/dist/mock/index.js +505 -44
- package/dist/mock/index.js.map +1 -1
- package/dist/openapi.d.ts.map +1 -1
- package/dist/openapi.js +462 -50
- package/dist/openapi.js.map +1 -1
- package/dist/periods.d.ts +61 -0
- package/dist/periods.d.ts.map +1 -0
- package/dist/periods.js +130 -0
- package/dist/periods.js.map +1 -0
- package/dist/problem.d.ts +1 -1
- package/dist/query.d.ts +18 -0
- package/dist/query.d.ts.map +1 -1
- package/dist/query.js +34 -8
- package/dist/query.js.map +1 -1
- package/dist/resourceTypes.d.ts +39 -0
- package/dist/resourceTypes.d.ts.map +1 -0
- package/dist/resourceTypes.js +34 -0
- package/dist/resourceTypes.js.map +1 -0
- package/dist/rules.d.ts +18 -5
- package/dist/rules.d.ts.map +1 -1
- package/dist/rules.js +233 -15
- package/dist/rules.js.map +1 -1
- package/dist/runtime/index.d.ts +23 -10
- package/dist/runtime/index.d.ts.map +1 -1
- package/dist/runtime/index.js +16 -3
- package/dist/schemas/action.d.ts +119 -10
- package/dist/schemas/action.d.ts.map +1 -1
- package/dist/schemas/action.js +20 -3
- package/dist/schemas/action.js.map +1 -1
- package/dist/schemas/api.d.ts +266 -5
- package/dist/schemas/api.d.ts.map +1 -1
- package/dist/schemas/api.js +134 -16
- package/dist/schemas/api.js.map +1 -1
- package/dist/schemas/boot.d.ts +25 -1
- package/dist/schemas/boot.d.ts.map +1 -1
- package/dist/schemas/boot.js +2 -1
- package/dist/schemas/boot.js.map +1 -1
- package/dist/schemas/common.d.ts +1 -0
- package/dist/schemas/common.d.ts.map +1 -1
- package/dist/schemas/common.js +2 -1
- package/dist/schemas/common.js.map +1 -1
- package/dist/schemas/definition.d.ts +1414 -30
- package/dist/schemas/definition.d.ts.map +1 -1
- package/dist/schemas/definition.js +77 -17
- package/dist/schemas/definition.js.map +1 -1
- package/dist/schemas/field.d.ts +358 -2
- package/dist/schemas/field.d.ts.map +1 -1
- package/dist/schemas/field.js +161 -20
- package/dist/schemas/field.js.map +1 -1
- package/dist/schemas/index.d.ts +5820 -46
- package/dist/schemas/index.d.ts.map +1 -1
- package/dist/schemas/index.js +69 -7
- package/dist/schemas/index.js.map +1 -1
- package/dist/schemas/jsonRules.d.ts +83 -0
- package/dist/schemas/jsonRules.d.ts.map +1 -0
- package/dist/schemas/jsonRules.js +46 -0
- package/dist/schemas/jsonRules.js.map +1 -0
- package/dist/schemas/layout.d.ts +2 -1
- package/dist/schemas/layout.d.ts.map +1 -1
- package/dist/schemas/layout.js +2 -1
- package/dist/schemas/layout.js.map +1 -1
- package/dist/schemas/list.d.ts +34 -2
- package/dist/schemas/list.d.ts.map +1 -1
- package/dist/schemas/list.js +21 -6
- package/dist/schemas/list.js.map +1 -1
- package/dist/schemas/resource.d.ts +826 -17
- package/dist/schemas/resource.d.ts.map +1 -1
- package/dist/schemas/resource.js +26 -4
- package/dist/schemas/resource.js.map +1 -1
- package/dist/schemas/theme.d.ts +6 -2
- package/dist/schemas/theme.d.ts.map +1 -1
- package/dist/schemas/theme.js +1 -0
- package/dist/schemas/theme.js.map +1 -1
- package/dist/schemas/widget.d.ts +4379 -0
- package/dist/schemas/widget.d.ts.map +1 -0
- package/dist/schemas/widget.js +269 -0
- package/dist/schemas/widget.js.map +1 -0
- package/dist/search.d.ts +51 -0
- package/dist/search.d.ts.map +1 -0
- package/dist/search.js +53 -0
- package/dist/search.js.map +1 -0
- package/dist/themes.d.ts +1 -1
- package/dist/transforms.d.ts +17 -0
- package/dist/transforms.d.ts.map +1 -0
- package/dist/transforms.js +34 -0
- package/dist/transforms.js.map +1 -0
- package/dist/validate.d.ts +5 -3
- package/dist/validate.d.ts.map +1 -1
- package/dist/validate.js +36 -2
- package/dist/validate.js.map +1 -1
- package/dist/values.d.ts +5 -1
- package/dist/values.d.ts.map +1 -1
- package/dist/values.js +16 -2
- package/dist/values.js.map +1 -1
- package/dist/widgets.d.ts +232 -0
- package/dist/widgets.d.ts.map +1 -0
- package/dist/widgets.js +630 -0
- package/dist/widgets.js.map +1 -0
- package/package.json +6 -3
- package/schema/boot.schema.json +1461 -104
- package/schema/definition.schema.json +1459 -105
- package/schema/openapi.json +7176 -2000
package/dist/lint.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"lint.js","names":[],"sources":["../src/lint.ts"],"sourcesContent":["import type { DefinitionInput, Field, LayoutNode, ResourceInput } from './schemas';\nimport type { ValidationIssue } from './validate';\n\nfunction fieldNames(fields: Field[]): Set<string> {\n return new Set(fields.map((field) => field.name));\n}\n\nfunction checkLayout(\n nodes: LayoutNode[],\n names: Set<string>,\n path: string,\n issues: ValidationIssue[],\n) {\n nodes.forEach((node, index) => {\n const nodePath = `${path}.${index}`;\n if (node.type === 'field') {\n if (node.name === undefined) {\n issues.push({ path: nodePath, message: 'A `field` node needs a `name`.' });\n } else if (!names.has(node.name)) {\n issues.push({\n path: `${nodePath}.name`,\n message: `No field named \\`${node.name}\\`.`,\n });\n }\n }\n if (node.type === 'component' && node.component === undefined) {\n issues.push({ path: nodePath, message: 'A `component` node needs a `component`.' });\n }\n if (node.type === 'tabs' && node.children?.some((child) => child.type !== 'tab')) {\n issues.push({\n path: `${nodePath}.children`,\n message: 'The children of `tabs` must be `tab` nodes.',\n });\n }\n if (node.children !== undefined) {\n checkLayout(node.children, names, `${nodePath}.children`, issues);\n }\n });\n}\n\nfunction checkResource(resource: ResourceInput, path: string, issues: ValidationIssue[]) {\n const names = fieldNames(resource.fields);\n if (names.size !== resource.fields.length) {\n issues.push({ path: `${path}.fields`, message: 'Field names must be unique.' });\n }\n if (resource.form?.layout !== undefined) {\n checkLayout(resource.form.layout, names, `${path}.form.layout`, issues);\n }\n (resource.list?.columns ?? []).forEach((column, index) => {\n if (column.field !== undefined && !names.has(column.field)) {\n issues.push({\n path: `${path}.list.columns.${index}.field`,\n message: `No field named \\`${column.field}\\`.`,\n });\n }\n });\n (resource.actions ?? []).forEach((action, index) => {\n if (action.layout !== undefined) {\n checkLayout(\n action.layout,\n fieldNames(action.fields ?? []),\n `${path}.actions.${index}.layout`,\n issues,\n );\n }\n });\n if (resource.kind === 'media') {\n const file = resource.fields.findIndex((field) => field.name === 'file');\n const field = resource.fields[file];\n if (field === undefined) {\n issues.push({\n path: `${path}.fields`,\n message: 'A resource of kind `media` needs a `file` field.',\n });\n } else if (field.type !== 'file' || field.multiple === true) {\n issues.push({\n path: `${path}.fields.${file}`,\n message: 'The `file` field of a `media` resource must be a single `file`.',\n });\n }\n }\n resource.fields.forEach((field, index) => {\n if (field.type === 'relation' && field.resource === undefined) {\n issues.push({\n path: `${path}.fields.${index}.resource`,\n message: 'A `relation` field needs a `resource`.',\n });\n }\n });\n}\n\n/**\n * Checks what the schema can't: references between parts of a definition (layout nodes and\n * columns that name existing fields, relations and media fields that name a resource, unique\n * names), and the `file` field of `media` resources.\n */\nexport function lintDefinition(definition: DefinitionInput): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const resourceIds = new Set(definition.resources.map((resource) => resource.id));\n const libraries = definition.resources\n .filter((resource) => resource.kind === 'media')\n .map((resource) => resource.id);\n definition.resources.forEach((resource, index) => {\n checkResource(resource, `resources.${index}`, issues);\n resource.fields.forEach((field, fieldIndex) => {\n if (\n field.type === 'relation' &&\n field.resource !== undefined &&\n !resourceIds.has(field.resource)\n ) {\n issues.push({\n path: `resources.${index}.fields.${fieldIndex}.resource`,\n message: `No resource \\`${field.resource}\\`.`,\n });\n }\n if (field.type === 'media') {\n const fieldPath = `resources.${index}.fields.${fieldIndex}.resource`;\n if (field.resource === undefined) {\n if (libraries.length !== 1) {\n issues.push({\n path: fieldPath,\n message:\n libraries.length === 0\n ? 'A `media` field needs a resource of kind `media`.'\n : 'A `media` field needs a `resource` when there are several libraries.',\n });\n }\n } else if (!libraries.includes(field.resource)) {\n issues.push({\n path: fieldPath,\n message: `No resource of kind \\`media\\` named \\`${field.resource}\\`.`,\n });\n }\n }\n });\n });\n return issues;\n}\n"],"mappings":";AAGA,SAAS,WAAW,QAA8B;CAC9C,OAAO,IAAI,IAAI,OAAO,KAAK,UAAU,MAAM,IAAI,CAAC;AACpD;AAEA,SAAS,YACL,OACA,OACA,MACA,QACF;CACE,MAAM,SAAS,MAAM,UAAU;EAC3B,MAAM,WAAW,GAAG,KAAK,GAAG;EAC5B,IAAI,KAAK,SAAS,SAAS;GACvB,IAAI,KAAK,SAAS,KAAA,GACd,OAAO,KAAK;IAAE,MAAM;IAAU,SAAS;GAAiC,CAAC;QACtE,IAAI,CAAC,MAAM,IAAI,KAAK,IAAI,GAC3B,OAAO,KAAK;IACR,MAAM,GAAG,SAAS;IAClB,SAAS,oBAAoB,KAAK,KAAK;GAC3C,CAAC;EAET;EACA,IAAI,KAAK,SAAS,eAAe,KAAK,cAAc,KAAA,GAChD,OAAO,KAAK;GAAE,MAAM;GAAU,SAAS;EAA0C,CAAC;EAEtF,IAAI,KAAK,SAAS,UAAU,KAAK,UAAU,MAAM,UAAU,MAAM,SAAS,KAAK,GAC3E,OAAO,KAAK;GACR,MAAM,GAAG,SAAS;GAClB,SAAS;EACb,CAAC;EAEL,IAAI,KAAK,aAAa,KAAA,GAClB,YAAY,KAAK,UAAU,OAAO,GAAG,SAAS,YAAY,MAAM;CAExE,CAAC;AACL;AAEA,SAAS,cAAc,UAAyB,MAAc,QAA2B;CACrF,MAAM,QAAQ,WAAW,SAAS,MAAM;CACxC,IAAI,MAAM,SAAS,SAAS,OAAO,QAC/B,OAAO,KAAK;EAAE,MAAM,GAAG,KAAK;EAAU,SAAS;CAA8B,CAAC;CAElF,IAAI,SAAS,MAAM,WAAW,KAAA,GAC1B,YAAY,SAAS,KAAK,QAAQ,OAAO,GAAG,KAAK,e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,UAAU,aAAa,SAAS,MAAM;EACpD,SAAS,OAAO,SAAS,OAAO,eAAe;GAC3C,IACI,MAAM,SAAS,cACf,MAAM,aAAa,KAAA,KACnB,CAAC,YAAY,IAAI,MAAM,QAAQ,GAE/B,OAAO,KAAK;IACR,MAAM,aAAa,MAAM,UAAU,WAAW;IAC9C,SAAS,iBAAiB,MAAM,SAAS;GAC7C,CAAC;GAEL,IAAI,MAAM,SAAS,SAAS;IACxB,MAAM,YAAY,aAAa,MAAM,UAAU,WAAW;IAC1D,IAAI,MAAM,aAAa,KAAA,GACf;SAAA,UAAU,WAAW,GACrB,OAAO,KAAK;MACR,MAAM;MACN,SACI,UAAU,WAAW,IACf,sDACA;KACd,CAAC;IAAA,OAEF,IAAI,CAAC,UAAU,SAAS,MAAM,QAAQ,GACzC,OAAO,KAAK;KACR,MAAM;KACN,SAAS,yCAAyC,MAAM,SAAS;IACrE,CAAC;GAET;EACJ,CAAC;CACL,CAAC;CACD,OAAO;AACX"}
|
|
1
|
+
{"version":3,"file":"lint.js","names":[],"sources":["../src/lint.ts"],"sourcesContent":["import { parseAggregateGroup, parseAggregateMeasure } from './aggregates';\nimport { DASHBOARD_COMPONENT, HOME_PAGE, getSummaryPeriodFilter } from './dashboards';\nimport { ITEM_TYPE_KEY } from './resourceTypes';\nimport type {\n DefinitionInput,\n Field,\n LayoutNode,\n OverviewPeriod,\n ResourceInput,\n Widget,\n} from './schemas';\nimport type { ValidationIssue } from './validate';\nimport {\n GROUPED_WIDGET_TYPES,\n RESOURCE_WIDGET_TYPES,\n WIDGET_RESERVED_QUERY_PARAMS,\n getWidgetResource,\n getWidgetSources,\n isBuiltInWidgetType,\n} from './widgets';\n\nfunction fieldNames(fields: Field[]): Set<string> {\n return new Set(fields.map((field) => field.name));\n}\n\nfunction checkLayout(\n nodes: LayoutNode[],\n names: Set<string>,\n path: string,\n issues: ValidationIssue[],\n) {\n nodes.forEach((node, index) => {\n const nodePath = `${path}.${index}`;\n if (node.type === 'field') {\n if (node.name === undefined) {\n issues.push({ path: nodePath, message: 'A `field` node needs a `name`.' });\n } else if (!names.has(node.name)) {\n issues.push({\n path: `${nodePath}.name`,\n message: `No field named \\`${node.name}\\`.`,\n });\n }\n }\n if (node.type === 'component' && node.component === undefined) {\n issues.push({ path: nodePath, message: 'A `component` node needs a `component`.' });\n }\n if (node.type === 'tabs' && node.children?.some((child) => child.type !== 'tab')) {\n issues.push({\n path: `${nodePath}.children`,\n message: 'The children of `tabs` must be `tab` nodes.',\n });\n }\n if (node.children !== undefined) {\n checkLayout(node.children, names, `${nodePath}.children`, issues);\n }\n });\n}\n\n/**\n * The types of a resource (decision 0077): unique ids, fields named apart from those of the\n * resource, and no field `type` in the form, which holds the item's type.\n */\nfunction checkTypes(\n resource: ResourceInput,\n names: Set<string>,\n path: string,\n issues: ValidationIssue[],\n) {\n const ids = new Set<string>();\n (resource.types ?? []).forEach((type, index) => {\n const typePath = `${path}.types.${index}`;\n if (ids.has(type.id)) {\n issues.push({ path: `${typePath}.id`, message: `Duplicate type id \\`${type.id}\\`.` });\n }\n ids.add(type.id);\n const own = fieldNames(type.fields);\n if (own.size !== type.fields.length) {\n issues.push({ path: `${typePath}.fields`, message: 'Field names must be unique.' });\n }\n type.fields.forEach((field, fieldIndex) => {\n if (names.has(field.name)) {\n issues.push({\n path: `${typePath}.fields.${fieldIndex}.name`,\n message: `The resource already has a field named \\`${field.name}\\`.`,\n });\n } else if (field.name === ITEM_TYPE_KEY) {\n issues.push({\n path: `${typePath}.fields.${fieldIndex}.name`,\n message: `\\`${ITEM_TYPE_KEY}\\` holds the type of the item.`,\n });\n }\n });\n });\n const typeField = resource.fields.findIndex((field) => field.name === ITEM_TYPE_KEY);\n if (ids.size > 0 && typeField !== -1 && resource.fields[typeField]?.notInForm !== true) {\n issues.push({\n path: `${path}.fields.${typeField}`,\n message: `\\`${ITEM_TYPE_KEY}\\` holds the type of the item, set when it is created: its field must be \\`notInForm\\`.`,\n });\n }\n}\n\n/** The fields of a resource and of its types, with their paths. */\nfunction allFields(resource: ResourceInput, path: string): { field: Field; path: string }[] {\n return [\n ...resource.fields.map((field, index) => ({ field, path: `${path}.fields.${index}` })),\n ...(resource.types ?? []).flatMap((type, typeIndex) =>\n type.fields.map((field, index) => ({\n field,\n path: `${path}.types.${typeIndex}.fields.${index}`,\n })),\n ),\n ];\n}\n\n/** Field types whose values can be summed: numbers, and amounts of `money` of one currency. */\nconst SUMMABLE_TYPES = ['number', 'range', 'duration', 'money'];\n/** Field types whose days can be grouped by. */\nconst DATE_TYPES = ['date', 'datetime'];\n/** Field types whose values are structures that can't be grouped by. */\nconst UNGROUPABLE_TYPES = [\n 'richtext',\n 'media',\n 'image',\n 'file',\n 'group',\n 'repeater',\n 'json',\n 'embed',\n 'location',\n 'address',\n 'link',\n 'daterange',\n 'money',\n];\n\n/**\n * The aggregates of a list (decision 0084): each one names a field of the resource that the user\n * can view, `sum` a number or `money` of one currency, `dates` a date, `groupBy` a value.\n */\nfunction checkAggregates(resource: ResourceInput, path: string, issues: ValidationIssue[]) {\n const aggregates = resource.list?.aggregates;\n if (aggregates === undefined) {\n return;\n }\n const fields = allFields(resource, path).map(({ field }) => field);\n const check = (key: 'sum' | 'groupBy' | 'dates', accepts: (field: Field) => string | null) => {\n (aggregates[key] ?? []).forEach((name, index) => {\n const issuePath = `${path}.list.aggregates.${key}.${index}`;\n const field = fields.find((candidate) => candidate.name === name);\n const message =\n field === undefined\n ? `No field named \\`${name}\\`.`\n : field.abilities?.view === false\n ? `The user can't view \\`${name}\\`: it can't be aggregated.`\n : accepts(field);\n if (message !== null) {\n issues.push({ path: issuePath, message });\n }\n });\n };\n check('sum', (field) => {\n if (!SUMMABLE_TYPES.includes(field.type)) {\n return `\\`${field.name}\\` can't be summed: only \\`number\\`, \\`range\\`, \\`duration\\` and \\`money\\` fields can.`;\n }\n const currency = (field.settings as { currency?: unknown } | undefined)?.currency;\n return field.type === 'money' && typeof currency !== 'string'\n ? `\\`${field.name}\\` can't be summed: amounts add up only in one \\`currency\\`.`\n : null;\n });\n check('dates', (field) =>\n DATE_TYPES.includes(field.type)\n ? null\n : `\\`${field.name}\\` must be a \\`date\\` or a \\`datetime\\` to be grouped by period.`,\n );\n check('groupBy', (field) =>\n UNGROUPABLE_TYPES.includes(field.type)\n ? `The items can't be grouped by a \\`${field.type}\\` field.`\n : null,\n );\n}\n\nfunction checkResource(resource: ResourceInput, path: string, issues: ValidationIssue[]) {\n const names = fieldNames(resource.fields);\n if (names.size !== resource.fields.length) {\n issues.push({ path: `${path}.fields`, message: 'Field names must be unique.' });\n }\n checkTypes(resource, names, path, issues);\n if (resource.form?.layout !== undefined) {\n // The layout can name the fields of the types: the forms of the other types leave them out.\n const typeNames = (resource.types ?? []).flatMap((type) => [...fieldNames(type.fields)]);\n checkLayout(\n resource.form.layout,\n new Set([...names, ...typeNames]),\n `${path}.form.layout`,\n issues,\n );\n }\n (resource.list?.columns ?? []).forEach((column, index) => {\n if (column.field !== undefined && !names.has(column.field)) {\n issues.push({\n path: `${path}.list.columns.${index}.field`,\n message: `No field named \\`${column.field}\\`.`,\n });\n }\n });\n const calendar = resource.list?.calendar;\n if (calendar !== undefined) {\n const field = resource.fields.find((candidate) => candidate.name === calendar.field);\n const filter = calendar.filter ?? calendar.field;\n if (field === undefined) {\n issues.push({\n path: `${path}.list.calendar.field`,\n message: `No field named \\`${calendar.field}\\`.`,\n });\n } else if (!['date', 'datetime', 'daterange'].includes(field.type)) {\n issues.push({\n path: `${path}.list.calendar.field`,\n message: 'The field of a calendar must be a `date`, a `datetime` or a `daterange`.',\n });\n }\n if (\n !(resource.list?.filters ?? []).some(\n (candidate) => candidate.id === filter && candidate.type === 'date-range',\n )\n ) {\n issues.push({\n path: `${path}.list.calendar`,\n message: `The calendar needs a \\`date-range\\` filter \\`${filter}\\` in the list.`,\n });\n }\n }\n checkAggregates(resource, path, issues);\n (resource.actions ?? []).forEach((action, index) => {\n if (action.layout !== undefined) {\n checkLayout(\n action.layout,\n fieldNames(action.fields ?? []),\n `${path}.actions.${index}.layout`,\n issues,\n );\n }\n });\n if (resource.kind === 'media') {\n const file = resource.fields.findIndex((field) => field.name === 'file');\n const field = resource.fields[file];\n if (field === undefined) {\n issues.push({\n path: `${path}.fields`,\n message: 'A resource of kind `media` needs a `file` field.',\n });\n } else if (field.type !== 'file' || field.multiple === true) {\n issues.push({\n path: `${path}.fields.${file}`,\n message: 'The `file` field of a `media` resource must be a single `file`.',\n });\n }\n }\n allFields(resource, path).forEach(({ field, path: fieldPath }) => {\n if (field.type === 'relation' && field.resource === undefined) {\n issues.push({\n path: `${fieldPath}.resource`,\n message: 'A `relation` field needs a `resource`.',\n });\n } else if (field.type === 'relation' && Array.isArray(field.resource)) {\n issues.push({\n path: `${fieldPath}.resource`,\n message: 'A `relation` field names one resource.',\n });\n }\n });\n}\n\n/**\n * Checks what the schema can't: references between parts of a definition (layout nodes and\n * columns that name existing fields, relations, `media` and `image` fields that name a resource,\n * unique names), the types of resources, and the `file` field of `media` resources.\n */\nexport function lintDefinition(definition: DefinitionInput): ValidationIssue[] {\n const issues: ValidationIssue[] = [];\n const resourceIds = new Set(definition.resources.map((resource) => resource.id));\n const libraries = definition.resources\n .filter((resource) => resource.kind === 'media')\n .map((resource) => resource.id);\n definition.resources.forEach((resource, index) => {\n checkResource(resource, `resources.${index}`, issues);\n if (resource.summary !== undefined) {\n const summaryPath = `resources.${index}.summary`;\n const period = resource.summary.period;\n if (period !== undefined) {\n checkPeriod(period, `${summaryPath}.period`, issues);\n if (getSummaryPeriodFilter(resource) === null) {\n issues.push({\n path: `${summaryPath}.period${period.filter !== undefined ? '.filter' : ''}`,\n message:\n period.filter !== undefined\n ? `The list of \\`${resource.id}\\` has no \\`date-range\\` filter \\`${period.filter}\\`.`\n : `The period of a summary is a \\`date-range\\` filter of the list of \\`${resource.id}\\`: it has none.`,\n });\n }\n }\n checkWidgets(definition, resource.summary.widgets, `${summaryPath}.widgets`, issues, {\n summaryOf: resource.id,\n hasPeriod: period !== undefined,\n });\n }\n allFields(resource, `resources.${index}`).forEach(({ field, path }) => {\n if (\n field.type === 'relation' &&\n typeof field.resource === 'string' &&\n !resourceIds.has(field.resource)\n ) {\n issues.push({\n path: `${path}.resource`,\n message: `No resource \\`${field.resource}\\`.`,\n });\n }\n if (field.type === 'media' || field.type === 'image') {\n const fieldPath = `${path}.resource`;\n if (field.resource === undefined) {\n // Every library of the definition (decision 0027).\n if (libraries.length === 0) {\n issues.push({\n path: fieldPath,\n message: `${field.type === 'image' ? 'An' : 'A'} \\`${field.type}\\` field needs a resource of kind \\`media\\`.`,\n });\n }\n } else {\n const named =\n typeof field.resource === 'string' ? [field.resource] : field.resource;\n named.forEach((id, idIndex) => {\n if (!libraries.includes(id)) {\n issues.push({\n path:\n typeof field.resource === 'string'\n ? fieldPath\n : `${fieldPath}.${String(idIndex)}`,\n message: `No resource of kind \\`media\\` named \\`${id}\\`.`,\n });\n }\n });\n }\n // A field without transforms keeps no crop (decision 0087).\n if (field.transforms === false) {\n if (field.ratios !== undefined && field.ratios.length > 0) {\n issues.push({\n path: `${path}.ratios`,\n message: 'A field without transforms has no editor to suggest ratios.',\n });\n }\n field.rules?.forEach((rule, ruleIndex) => {\n if (rule.rule === 'crop') {\n issues.push({\n path: `${path}.rules.${String(ruleIndex)}`,\n message:\n 'A field without transforms keeps no crop for the `crop` rule.',\n });\n }\n });\n }\n }\n });\n });\n checkDashboards(definition, issues);\n return issues;\n}\n\n/**\n * The dashboards (decision 0084): the widgets of each page whose component is the built-in\n * `dashboard`, and those of `dashboard`, the shorthand of the home page, unless `pages.home` has\n * its own, which can't come with them. Only a `dashboard` page has widgets.\n */\nfunction checkDashboards(definition: DefinitionInput, issues: ValidationIssue[]) {\n const home = definition.pages?.[HOME_PAGE];\n const homePeriod =\n (home?.component === DASHBOARD_COMPONENT ? home.period : undefined) ??\n definition.dashboard?.period;\n Object.entries(definition.pages ?? {}).forEach(([id, page]) => {\n if (page.period !== undefined) {\n if (page.component !== DASHBOARD_COMPONENT) {\n issues.push({\n path: `pages.${id}.period`,\n message: `Only a \\`${DASHBOARD_COMPONENT}\\` page has a period.`,\n });\n } else {\n checkPeriod(page.period, `pages.${id}.period`, issues);\n }\n }\n if (page.widgets === undefined) {\n return;\n }\n if (page.component !== DASHBOARD_COMPONENT) {\n issues.push({\n path: `pages.${id}.widgets`,\n message: `Only a \\`${DASHBOARD_COMPONENT}\\` page has widgets.`,\n });\n return;\n }\n checkWidgets(definition, page.widgets, `pages.${id}.widgets`, issues, {\n hasPeriod: (id === HOME_PAGE ? homePeriod : page.period) !== undefined,\n });\n });\n if (definition.dashboard === undefined) {\n return;\n }\n if (definition.dashboard.period !== undefined) {\n if (home?.component === DASHBOARD_COMPONENT && home.period !== undefined) {\n issues.push({\n path: 'dashboard.period',\n message: `\\`pages.${HOME_PAGE}.period\\` replaces it: set only one.`,\n });\n } else {\n checkPeriod(definition.dashboard.period, 'dashboard.period', issues);\n }\n }\n if (home?.component === DASHBOARD_COMPONENT && home.widgets !== undefined) {\n if (definition.dashboard.widgets.length > 0) {\n issues.push({\n path: 'dashboard.widgets',\n message: `\\`pages.${HOME_PAGE}.widgets\\` replaces them: set only one.`,\n });\n }\n return;\n }\n checkWidgets(definition, definition.dashboard.widgets, 'dashboard.widgets', issues, {\n hasPeriod: homePeriod !== undefined,\n });\n}\n\n/** A period (decision 0084): its options once each, and its default among them. */\nfunction checkPeriod(period: OverviewPeriod, path: string, issues: ValidationIssue[]) {\n if (new Set(period.options).size !== period.options.length) {\n issues.push({ path: `${path}.options`, message: 'Each period is offered once.' });\n }\n if (period.default !== undefined && !period.options.includes(period.default)) {\n issues.push({\n path: `${path}.default`,\n message: `\\`${period.default}\\` isn't one of the options.`,\n });\n }\n}\n\nconst FILTER_PARAM = /^filter\\[([^\\]]+)\\]/;\n\n/** The settings of a widget that go with a `resource`. */\nconst RESOURCE_SETTINGS = ['query', 'measure', 'group', 'target', 'points', 'by', 'split'] as const;\n\n/** The settings of a built-in widget that only some types have (decision 0089), and those types. */\nconst TYPED_SETTINGS: Record<string, readonly string[]> = {\n goodWhen: ['metric', 'table'],\n points: ['metric', 'table'],\n by: ['metric'],\n split: ['series'],\n sources: ['series'],\n stacked: ['series'],\n rows: ['table'],\n};\n\n/** A `measure` of the aggregates of a list: `count`, or the `sum:` of a field of its `sum`. */\nfunction checkMeasure(\n value: unknown,\n resource: ResourceInput,\n path: string,\n issues: ValidationIssue[],\n) {\n if (value === undefined) {\n return;\n }\n const measure = typeof value === 'string' ? parseAggregateMeasure(value) : null;\n if (measure === null) {\n issues.push({ path, message: 'The measure must be `count` or `sum:{field}`.' });\n } else if (\n measure.type === 'sum' &&\n !(resource.list?.aggregates?.sum ?? []).includes(measure.field)\n ) {\n issues.push({\n path,\n message: `The list of \\`${resource.id}\\` can't sum \\`${measure.field}\\`: it isn't in the \\`sum\\` of its aggregates.`,\n });\n }\n}\n\n/** A group on the period of a date of the aggregates of a list: `day:created_at`. */\nfunction checkPeriodGroup(\n value: unknown,\n resource: ResourceInput,\n path: string,\n issues: ValidationIssue[],\n what: string,\n) {\n const group = typeof value === 'string' ? parseAggregateGroup(value) : null;\n if (group?.type !== 'period') {\n issues.push({ path, message: `${what} needs a period of a date: \\`day:created_at\\`.` });\n } else if (!(resource.list?.aggregates?.dates ?? []).includes(group.field)) {\n issues.push({\n path,\n message: `The list of \\`${resource.id}\\` can't group by \\`${group.field}\\`: it isn't in the \\`dates\\` of its aggregates.`,\n });\n }\n}\n\n/** A field of the `groupBy` of the aggregates of a list. */\nfunction checkGroupByField(\n value: unknown,\n resource: ResourceInput,\n path: string,\n issues: ValidationIssue[],\n) {\n if (typeof value !== 'string' || !(resource.list?.aggregates?.groupBy ?? []).includes(value)) {\n issues.push({\n path,\n message: `The list of \\`${resource.id}\\` can't group by \\`${String(value)}\\`: it isn't in the \\`groupBy\\` of its aggregates.`,\n });\n }\n}\n\n/** The filters of a query of a widget or of a source: filters of the list, never the paging. */\nfunction checkQuery(\n query: unknown,\n resource: ResourceInput,\n path: string,\n issues: ValidationIssue[],\n) {\n if (query === null || typeof query !== 'object') {\n return;\n }\n const filters = new Set((resource.list?.filters ?? []).map((filter) => filter.id));\n Object.keys(query).forEach((key) => {\n const filter = FILTER_PARAM.exec(key)?.[1];\n if ((WIDGET_RESERVED_QUERY_PARAMS as readonly string[]).includes(key)) {\n issues.push({ path: `${path}.${key}`, message: `The client sets \\`${key}\\`.` });\n } else if (filter !== undefined && !filters.has(filter)) {\n issues.push({\n path: `${path}.${key}`,\n message: `The list of \\`${resource.id}\\` has no filter \\`${filter}\\`.`,\n });\n }\n });\n}\n\n/** `period`: a `date-range` filter of the list of the resource. */\nfunction checkPeriodFilter(\n period: unknown,\n resource: ResourceInput,\n path: string,\n issues: ValidationIssue[],\n) {\n if (\n typeof period === 'string' &&\n !(resource.list?.filters ?? []).some(\n (filter) => filter.id === period && filter.type === 'date-range',\n )\n ) {\n issues.push({\n path,\n message: `The list of \\`${resource.id}\\` has no \\`date-range\\` filter \\`${period}\\`.`,\n });\n }\n}\n\n/**\n * The `sources` of a `series` or the `rows` of a `table` (decision 0089): each on a resource that\n * exists and declares aggregates, with a measure, a group on a period of a date (required for a\n * line of a series), a period and a query, and an alert, that its list declares.\n */\nfunction checkSources(\n definition: DefinitionInput,\n widget: Widget,\n path: string,\n issues: ValidationIssue[],\n hasPeriod: boolean,\n) {\n const settings = widget.settings ?? {};\n const key = widget.type === 'series' ? 'sources' : 'rows';\n const entries = settings[key];\n if (!Array.isArray(entries)) {\n return;\n }\n const sources = getWidgetSources(widget);\n // One chart has one period: the lines of a series, or the trends of a table, share it\n const periods = new Set(\n sources.flatMap((source) => {\n const group = source.group !== null ? parseAggregateGroup(source.group) : null;\n return group?.type === 'period' ? [group.period] : [];\n }),\n );\n if (periods.size > 1) {\n issues.push({\n path: `${path}.settings.${key}`,\n message: `Its ${widget.type === 'series' ? 'lines' : 'trends'} have different periods (${[...periods].join(', ')}): they share one.`,\n });\n }\n entries.forEach((entry: unknown, index) => {\n const sourcePath = `${path}.settings.${key}.${index}`;\n const source = sources[index];\n if (source === undefined || entry === null || typeof entry !== 'object') {\n return;\n }\n const raw = entry as Record<string, unknown>;\n const resource = definition.resources.find((candidate) => candidate.id === source.resource);\n if (resource === undefined) {\n issues.push({\n path: `${sourcePath}.resource`,\n message: `No resource \\`${source.resource}\\`.`,\n });\n return;\n }\n if (resource.list?.aggregates === undefined) {\n issues.push({\n path: `${sourcePath}.resource`,\n message: `The list of \\`${resource.id}\\` declares no \\`aggregates\\`.`,\n });\n return;\n }\n checkMeasure(raw.measure, resource, `${sourcePath}.measure`, issues);\n const groupKey = widget.type === 'series' ? 'group' : 'points';\n if (widget.type === 'series' || source.group !== null) {\n checkPeriodGroup(\n source.group,\n resource,\n `${raw[groupKey] !== undefined ? sourcePath : `${path}.settings`}.${groupKey}`,\n issues,\n widget.type === 'series' ? 'A line of a `series`' : 'The trend of a row',\n );\n }\n if (typeof source.period === 'string') {\n // The widget's own `period` is checked with the widget\n if (!hasPeriod && raw.period !== undefined) {\n issues.push({\n path: `${raw.period !== undefined ? sourcePath : `${path}.settings`}.period`,\n message: 'Its overview has no `period`.',\n });\n }\n checkPeriodFilter(\n source.period,\n resource,\n `${raw.period !== undefined ? sourcePath : `${path}.settings`}.period`,\n issues,\n );\n }\n checkQuery(raw.query, resource, `${sourcePath}.query`, issues);\n const alert = raw.alert as Record<string, unknown> | undefined;\n if (alert !== undefined && alert !== null && typeof alert === 'object') {\n checkQuery(alert.query, resource, `${sourcePath}.alert.query`, issues);\n }\n });\n}\n\n/**\n * The measure and the group of a widget on a resource (decision 0084): a `sum:` and a group name\n * aggregates of its list, a `series` needs a period of a date, a `breakdown` a field of `groupBy`,\n * and a `list` has neither.\n */\nfunction checkAggregateSettings(\n widget: { type: string; settings?: Record<string, unknown> | undefined },\n resource: ResourceInput,\n path: string,\n issues: ValidationIssue[],\n) {\n const settings = widget.settings ?? {};\n const aggregates = resource.list?.aggregates ?? {};\n const grouped = (GROUPED_WIDGET_TYPES as readonly string[]).includes(widget.type);\n if (widget.type === 'list') {\n ['measure', 'group'].forEach((key) => {\n if (settings[key] !== undefined) {\n issues.push({\n path: `${path}.settings.${key}`,\n message: `A \\`list\\` shows items: it has no \\`${key}\\`.`,\n });\n }\n });\n return;\n }\n if (settings.measure !== undefined) {\n const measure =\n typeof settings.measure === 'string' ? parseAggregateMeasure(settings.measure) : null;\n if (measure === null) {\n issues.push({\n path: `${path}.settings.measure`,\n message: 'The measure must be `count` or `sum:{field}`.',\n });\n } else if (measure.type === 'sum' && !(aggregates.sum ?? []).includes(measure.field)) {\n issues.push({\n path: `${path}.settings.measure`,\n message: `The list of \\`${resource.id}\\` can't sum \\`${measure.field}\\`: it isn't in the \\`sum\\` of its aggregates.`,\n });\n }\n }\n if (!grouped) {\n if (settings.group !== undefined) {\n issues.push({\n path: `${path}.settings.group`,\n message: `A \\`${widget.type}\\` isn't grouped: only a \\`series\\` and a \\`breakdown\\` are.`,\n });\n }\n if (widget.type === 'metric') {\n if (resource.list?.aggregates === undefined) {\n issues.push({\n path: `${path}.settings.resource`,\n message: `The list of \\`${resource.id}\\` declares no \\`aggregates\\`: a \\`metric\\` reads them.`,\n });\n return;\n }\n if (settings.points !== undefined) {\n checkPeriodGroup(\n settings.points,\n resource,\n `${path}.settings.points`,\n issues,\n 'The trend of a `metric`',\n );\n }\n if (settings.by !== undefined) {\n checkGroupByField(settings.by, resource, `${path}.settings.by`, issues);\n }\n }\n return;\n }\n const group = typeof settings.group === 'string' ? parseAggregateGroup(settings.group) : null;\n if (widget.type === 'series') {\n if (group?.type !== 'period') {\n issues.push({\n path: `${path}.settings.group`,\n message:\n 'A `series` on a resource needs a `group` on the period of a date: `day:created_at`.',\n });\n } else if (!(aggregates.dates ?? []).includes(group.field)) {\n issues.push({\n path: `${path}.settings.group`,\n message: `The list of \\`${resource.id}\\` can't group by \\`${group.field}\\`: it isn't in the \\`dates\\` of its aggregates.`,\n });\n }\n if (settings.split !== undefined) {\n checkGroupByField(settings.split, resource, `${path}.settings.split`, issues);\n // Each line reads the aggregates filtered by its value\n if (\n !(resource.list?.filters ?? []).some(\n (filter) => filter.id === settings.split && filter.type !== 'date-range',\n )\n ) {\n issues.push({\n path: `${path}.settings.split`,\n message: `The list of \\`${resource.id}\\` has no filter \\`${String(settings.split)}\\` to read each of its values.`,\n });\n }\n }\n return;\n }\n if (group?.type !== 'field') {\n issues.push({\n path: `${path}.settings.group`,\n message: 'A `breakdown` on a resource needs a `group` on a field: `status`.',\n });\n } else if (!(aggregates.groupBy ?? []).includes(group.field)) {\n issues.push({\n path: `${path}.settings.group`,\n message: `The list of \\`${resource.id}\\` can't group by \\`${group.field}\\`: it isn't in the \\`groupBy\\` of its aggregates.`,\n });\n }\n}\n\n/**\n * The widgets of a dashboard or of the summary of a resource (decisions 0064 and 0084): unique ids,\n * and the built-in types on a resource that exists, with filters of its list and aggregates it\n * declares. A `stat` that counts reads the total of the list, so the list can't be paged with\n * cursors, which give no total. Only the widgets of a summary follow its list (`followsList`): those\n * on its resource, and those with data of their own.\n */\nfunction checkWidgets(\n definition: DefinitionInput,\n widgets: Widget[],\n widgetsPath: string,\n issues: ValidationIssue[],\n { summaryOf, hasPeriod = false }: { summaryOf?: string; hasPeriod?: boolean } = {},\n) {\n const ids = new Set<string>();\n widgets.forEach((widget, index) => {\n const path = `${widgetsPath}.${index}`;\n if (ids.has(widget.id)) {\n issues.push({ path: `${path}.id`, message: `Duplicate widget id \\`${widget.id}\\`.` });\n }\n ids.add(widget.id);\n const follows = widget.settings?.followsList;\n if (follows !== undefined) {\n const other = getWidgetResource(widget)?.resource;\n if (summaryOf === undefined) {\n issues.push({\n path: `${path}.settings.followsList`,\n message: 'Only the widgets of the summary of a resource follow its list.',\n });\n } else if (other !== undefined && other !== summaryOf) {\n issues.push({\n path: `${path}.settings.followsList`,\n message: `A widget on \\`${other}\\` doesn't follow the list of \\`${summaryOf}\\`.`,\n });\n }\n }\n if (!isBuiltInWidgetType(widget.type)) {\n return;\n }\n const settings = widget.settings ?? {};\n const onResource = typeof settings.resource === 'string';\n if (settings.period !== undefined && !hasPeriod) {\n issues.push({\n path: `${path}.settings.period`,\n message: `Its ${summaryOf !== undefined ? 'summary' : 'dashboard'} has no \\`period\\`.`,\n });\n }\n Object.entries(TYPED_SETTINGS).forEach(([key, types]) => {\n if (settings[key] !== undefined && !types.includes(widget.type)) {\n issues.push({\n path: `${path}.settings.${key}`,\n message: `Only a ${types.map((type) => `\\`${type}\\``).join(' or a ')} has \\`${key}\\`.`,\n });\n }\n });\n const sourcesKey = widget.type === 'series' ? 'sources' : 'rows';\n if (\n settings[sourcesKey] !== undefined &&\n TYPED_SETTINGS[sourcesKey]?.includes(widget.type)\n ) {\n if (onResource) {\n issues.push({\n path: `${path}.settings.${sourcesKey}`,\n message: `\\`${sourcesKey}\\` name their resources: the widget has no \\`resource\\`.`,\n });\n return;\n }\n ['query', 'measure', 'target', 'by', 'split'].forEach((key) => {\n if (settings[key] !== undefined) {\n issues.push({\n path: `${path}.settings.${key}`,\n message: `\\`${key}\\` goes with a \\`resource\\`, not \\`${sourcesKey}\\`.`,\n });\n }\n });\n checkSources(definition, widget, path, issues, hasPeriod);\n return;\n }\n if (!onResource) {\n if (typeof settings.period === 'string') {\n issues.push({\n path: `${path}.settings.period`,\n message:\n '`period` names a `date-range` filter of the list of its `resource`: without one, it can only be `false`.',\n });\n }\n RESOURCE_SETTINGS.forEach((key) => {\n if (settings[key] !== undefined) {\n issues.push({\n path: `${path}.settings.${key}`,\n message: `\\`${key}\\` goes with a \\`resource\\`.`,\n });\n }\n });\n return;\n }\n if (!(RESOURCE_WIDGET_TYPES as readonly string[]).includes(widget.type)) {\n issues.push({\n path: `${path}.settings.resource`,\n message: `A \\`${widget.type}\\` widget has data of its own: it can't read a resource.`,\n });\n return;\n }\n const resource = definition.resources.find(\n (candidate) => candidate.id === settings.resource,\n );\n if (resource === undefined) {\n issues.push({\n path: `${path}.settings.resource`,\n message: `No resource \\`${String(settings.resource)}\\`.`,\n });\n return;\n }\n if (settings.target !== undefined && widget.type !== 'stat' && widget.type !== 'metric') {\n issues.push({\n path: `${path}.settings.target`,\n message: 'Only a `stat` and a `metric` have a `target`.',\n });\n }\n checkAggregateSettings(widget, resource, path, issues);\n const sums = typeof settings.measure === 'string' && settings.measure.startsWith('sum:');\n if (widget.type === 'stat' && !sums && resource.list?.pagination === 'cursor') {\n issues.push({\n path: `${path}.settings.resource`,\n message: `The list of \\`${resource.id}\\` is paged with cursors and has no total: it can't feed a \\`stat\\` that counts.`,\n });\n }\n checkPeriodFilter(settings.period, resource, `${path}.settings.period`, issues);\n checkQuery(settings.query, resource, `${path}.settings.query`, issues);\n });\n}\n"],"mappings":";;;;;AAqBA,SAAS,WAAW,QAA8B;CAC9C,OAAO,IAAI,IAAI,OAAO,KAAK,UAAU,MAAM,IAAI,CAAC;AACpD;AAEA,SAAS,YACL,OACA,OACA,MACA,QACF;CACE,MAAM,SAAS,MAAM,UAAU;EAC3B,MAAM,WAAW,GAAG,KAAK,GAAG;EAC5B,IAAI,KAAK,SAAS,SAAS;GACvB,IAAI,KAAK,SAAS,KAAA,GACd,OAAO,KAAK;IAAE,MAAM;IAAU,SAAS;GAAiC,CAAC;QACtE,IAAI,CAAC,MAAM,IAAI,KAAK,IAAI,GAC3B,OAAO,KAAK;IACR,MAAM,GAAG,SAAS;IAClB,SAAS,oBAAoB,KAAK,KAAK;GAC3C,CAAC;EAET;EACA,IAAI,KAAK,SAAS,eAAe,KAAK,cAAc,KAAA,GAChD,OAAO,KAAK;GAAE,MAAM;GAAU,SAAS;EAA0C,CAAC;EAEtF,IAAI,KAAK,SAAS,UAAU,KAAK,UAAU,MAAM,UAAU,MAAM,SAAS,KAAK,GAC3E,OAAO,KAAK;GACR,MAAM,GAAG,SAAS;GAClB,SAAS;EACb,CAAC;EAEL,IAAI,KAAK,aAAa,KAAA,GAClB,YAAY,KAAK,UAAU,OAAO,GAAG,SAAS,YAAY,MAAM;CAExE,CAAC;AACL;;;;;AAMA,SAAS,W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IAAI,OAAO,SAAS,WAAW,UAC3B,OAAO,KAAK;IACR,MAAM,GAAG,KAAK;IACd,SACI;GACR,CAAC;GAEL,kBAAkB,SAAS,QAAQ;IAC/B,IAAI,SAAS,SAAS,KAAA,GAClB,OAAO,KAAK;KACR,MAAM,GAAG,KAAK,YAAY;KAC1B,SAAS,KAAK,IAAI;IACtB,CAAC;GAET,CAAC;GACD;EACJ;EACA,IAAI,CAAE,sBAA4C,SAAS,OAAO,IAAI,GAAG;GACrE,OAAO,KAAK;IACR,MAAM,GAAG,KAAK;IACd,SAAS,OAAO,OAAO,KAAK;GAChC,CAAC;GACD;EACJ;EACA,MAAM,WAAW,WAAW,UAAU,MACjC,cAAc,UAAU,OAAO,SAAS,QAC7C;EACA,IAAI,aAAa,KAAA,GAAW;GACxB,OAAO,KAAK;IACR,MAAM,GAAG,KAAK;IACd,SAAS,iBAAiB,OAAO,SAAS,QAAQ,EAAE;GACxD,CAAC;GACD;EACJ;EACA,IAAI,SAAS,WAAW,KAAA,KAAa,OAAO,SAAS,UAAU,OAAO,SAAS,UAC3E,OAAO,KAAK;GACR,MAAM,GAAG,KAAK;GACd,SAAS;EACb,CAAC;EAEL,uBAAuB,QAAQ,UAAU,MAAM,MAAM;EACrD,MAAM,OAAO,OAAO,SAAS,YAAY,YAAY,SAAS,QAAQ,WAAW,MAAM;EACvF,IAAI,OAAO,SAAS,UAAU,CAAC,QAAQ,SAAS,MAAM,eAAe,UACjE,OAAO,KAAK;GACR,MAAM,GAAG,KAAK;GACd,SAAS,iBAAiB,SAAS,GAAG;EAC1C,CAAC;EAEL,kBAAkB,SAAS,QAAQ,UAAU,GAAG,KAAK,mBAAmB,MAAM;EAC9E,WAAW,SAAS,OAAO,UAAU,GAAG,KAAK,kBAAkB,MAAM;CACzE,CAAC;AACL"}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { Auth, User } from '../schemas/index.js';
|
|
2
|
+
/** A user of the mock backend. */
|
|
3
|
+
export interface MockUser {
|
|
4
|
+
/** Defaults to the position of the user in `users`, from 1. */
|
|
5
|
+
id?: string;
|
|
6
|
+
/** Defaults to the email. */
|
|
7
|
+
name?: string;
|
|
8
|
+
email: string;
|
|
9
|
+
password: string;
|
|
10
|
+
/** Whether the email address is verified, for `auth.emailVerification`. Defaults to true. */
|
|
11
|
+
emailVerified?: boolean;
|
|
12
|
+
/**
|
|
13
|
+
* Whether the user has two-factor authentication, for `auth.twoFactor`: their password login
|
|
14
|
+
* then asks for `twoFactorCode` or a recovery code. Defaults to false.
|
|
15
|
+
*/
|
|
16
|
+
twoFactor?: boolean;
|
|
17
|
+
/** Recovery codes of a user with `twoFactor`. Defaults to none. */
|
|
18
|
+
recoveryCodes?: string[];
|
|
19
|
+
/** Whether the backend requires two-factor authentication for the user. Defaults to false. */
|
|
20
|
+
twoFactorRequired?: boolean;
|
|
21
|
+
/**
|
|
22
|
+
* The passkeys of the user, for `auth.passkeys`: the `id` of their credential, and a name. The
|
|
23
|
+
* mock doesn't check signatures: a credential with one of these ids logs in.
|
|
24
|
+
*/
|
|
25
|
+
passkeys?: {
|
|
26
|
+
id: string;
|
|
27
|
+
name: string;
|
|
28
|
+
}[];
|
|
29
|
+
}
|
|
30
|
+
/** An email that the mock backend "sends", with the path of its link under the app's base path. */
|
|
31
|
+
export interface MockMail {
|
|
32
|
+
kind: 'password-reset' | 'email-verification';
|
|
33
|
+
to: string;
|
|
34
|
+
token: string;
|
|
35
|
+
/** The page of the app that the link opens, with its query: `auth/reset-password?token=…`. */
|
|
36
|
+
path: string;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The auth of the mock backend: its users, and who is logged in. With it, the routes of the
|
|
40
|
+
* `panneau` auth mode answer (`/auth/login`, `/auth/logout`, `/auth/session`, and those of
|
|
41
|
+
* `auth.passwordReset` and `auth.emailVerification`), and the other routes answer `401` to
|
|
42
|
+
* guests.
|
|
43
|
+
*/
|
|
44
|
+
export interface MockAuthOptions {
|
|
45
|
+
users: MockUser[];
|
|
46
|
+
/** The email of the user logged in at the start. Defaults to the first user; `null`: a guest. */
|
|
47
|
+
loggedIn?: string | null;
|
|
48
|
+
/** Called with each email the backend sends: there is no mailbox. */
|
|
49
|
+
onMail?: (mail: MockMail) => void;
|
|
50
|
+
/** The code of the authenticator app of every user, for `auth.twoFactor`. Defaults to `123456`. */
|
|
51
|
+
twoFactorCode?: string;
|
|
52
|
+
/**
|
|
53
|
+
* The email of the user that each OAuth provider of `auth.providers` logs in, at once, when the
|
|
54
|
+
* app goes to its `redirect` (decision 0052). A provider without one fails with `access`.
|
|
55
|
+
*/
|
|
56
|
+
providerUsers?: Record<string, string>;
|
|
57
|
+
}
|
|
58
|
+
type Values = Record<string, unknown>;
|
|
59
|
+
export interface MockAuth {
|
|
60
|
+
/** The current user, as the definition and `/auth/session` give it. */
|
|
61
|
+
user(): User | null;
|
|
62
|
+
/** The answer of a route of `/auth/…`, without its first segment. */
|
|
63
|
+
answer(segments: string[], method: string, readBody: () => Promise<Values>, url?: URL): Promise<Response>;
|
|
64
|
+
/** The answer of a route of `/account/…`, without its first segment, or null for another. */
|
|
65
|
+
account(segments: string[], method: string, readBody: () => Promise<Values>): Promise<Response> | null;
|
|
66
|
+
/** The answer to a request of another route by the current user, when it is refused. */
|
|
67
|
+
refuse(): Response | null;
|
|
68
|
+
}
|
|
69
|
+
export declare function createMockAuth(options: MockAuthOptions, settings: Auth | undefined): MockAuth;
|
|
70
|
+
export {};
|
|
71
|
+
//# sourceMappingURL=auth.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../../src/mock/auth.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,YAAY,CAAC;AAI7C,kCAAkC;AAClC,MAAM,WAAW,QAAQ;IACrB,+DAA+D;IAC/D,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,6BAA6B;IAC7B,IAAI,CAAC,EA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,MAAM,CAAC,EAC/B,GAAG,CAAC,EAAE,GAAG,GACV,OAAO,CAAC,QAAQ,CAAC,CAAC;IACrB,6FAA6F;IAC7F,OAAO,CACH,QAAQ,EAAE,MAAM,EAAE,EAClB,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,GAChC,OAAO,CAAC,QAAQ,CAAC,GAAG,IAAI,CAAC;IAC5B,wFAAwF;IACxF,MAAM,IAAI,QAAQ,GAAG,IAAI,CAAC;CAC7B;AAED,wBAAgB,cAAc,CAAC,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,IAAI,GAAG,SAAS,GAAG,QAAQ,CA8a7F"}
|
|
@@ -0,0 +1,346 @@
|
|
|
1
|
+
import { PROBLEM_CONTENT_TYPE } from "../version.js";
|
|
2
|
+
import { AUTH_ERROR_PARAM, AUTH_PAGE_PATHS, EMAIL_UNVERIFIED_PROBLEM_TYPE, TWO_FACTOR_REQUIRED_PROBLEM_TYPE } from "../constants.js";
|
|
3
|
+
//#region src/mock/auth.ts
|
|
4
|
+
/** The secret that the mock backend gives every two-factor setup. */
|
|
5
|
+
var SECRET = "JBSWY3DPEHPK3PXP";
|
|
6
|
+
var EMAIL = /^[^\s@]+@[^\s@]+$/;
|
|
7
|
+
function json(status, body) {
|
|
8
|
+
return new Response(status === 204 ? null : JSON.stringify(body), {
|
|
9
|
+
status,
|
|
10
|
+
headers: status === 204 ? {} : { "Content-Type": "application/json" }
|
|
11
|
+
});
|
|
12
|
+
}
|
|
13
|
+
function problem(status, title, extra = {}) {
|
|
14
|
+
const body = {
|
|
15
|
+
type: "about:blank",
|
|
16
|
+
title,
|
|
17
|
+
status,
|
|
18
|
+
...extra
|
|
19
|
+
};
|
|
20
|
+
return new Response(JSON.stringify(body), {
|
|
21
|
+
status,
|
|
22
|
+
headers: { "Content-Type": PROBLEM_CONTENT_TYPE }
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
function invalid(errors) {
|
|
26
|
+
return problem(422, "The given data was invalid.", {
|
|
27
|
+
type: "urn:panneau:problem:validation",
|
|
28
|
+
errors
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
function randomToken() {
|
|
32
|
+
return Array.from(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
33
|
+
}
|
|
34
|
+
/** Text in base64url, without padding, as WebAuthn's JSON form has binary values. */
|
|
35
|
+
function base64Url(text) {
|
|
36
|
+
return btoa(text).replace(/=+$/, "").replace(/\+/g, "-").replace(/\//g, "_");
|
|
37
|
+
}
|
|
38
|
+
/** A credential in the JSON form of the WebAuthn spec: the mock only reads its id. */
|
|
39
|
+
function isCredential(value) {
|
|
40
|
+
return value !== null && typeof value === "object" && typeof value.id === "string" && value.id !== "";
|
|
41
|
+
}
|
|
42
|
+
function recoveryCodes() {
|
|
43
|
+
return Array.from({ length: 8 }, () => `${randomToken().slice(0, 5)}-${randomToken().slice(0, 5)}`);
|
|
44
|
+
}
|
|
45
|
+
function createMockAuth(options, settings) {
|
|
46
|
+
let nextPasskey = 1;
|
|
47
|
+
const accounts = options.users.map((user, index) => ({
|
|
48
|
+
id: user.id ?? String(index + 1),
|
|
49
|
+
name: user.name ?? user.email,
|
|
50
|
+
email: user.email,
|
|
51
|
+
password: user.password,
|
|
52
|
+
emailVerified: user.emailVerified ?? true,
|
|
53
|
+
twoFactor: user.twoFactor === true ? "enabled" : "disabled",
|
|
54
|
+
recoveryCodes: [...user.recoveryCodes ?? []],
|
|
55
|
+
twoFactorRequired: user.twoFactorRequired ?? false,
|
|
56
|
+
passkeys: (user.passkeys ?? []).map((passkey) => ({
|
|
57
|
+
id: String(nextPasskey++),
|
|
58
|
+
credentialId: passkey.id,
|
|
59
|
+
name: passkey.name,
|
|
60
|
+
createdAt: (/* @__PURE__ */ new Date(0)).toISOString(),
|
|
61
|
+
lastUsedAt: null
|
|
62
|
+
}))
|
|
63
|
+
}));
|
|
64
|
+
const code = options.twoFactorCode ?? "123456";
|
|
65
|
+
let pending = null;
|
|
66
|
+
let current = options.loggedIn === null ? null : (options.loggedIn !== void 0 ? accounts.find((account) => account.email === options.loggedIn) : accounts[0]) ?? null;
|
|
67
|
+
const resets = /* @__PURE__ */ new Map();
|
|
68
|
+
const verifications = /* @__PURE__ */ new Map();
|
|
69
|
+
const find = (email) => typeof email === "string" ? accounts.find((account) => account.email.toLowerCase() === email.toLowerCase()) : void 0;
|
|
70
|
+
const userOf = (account) => ({
|
|
71
|
+
id: account.id,
|
|
72
|
+
name: account.name,
|
|
73
|
+
email: account.email,
|
|
74
|
+
abilities: {}
|
|
75
|
+
});
|
|
76
|
+
const send = (kind, account) => {
|
|
77
|
+
const token = randomToken();
|
|
78
|
+
const query = new URLSearchParams({ token });
|
|
79
|
+
if (kind === "password-reset") {
|
|
80
|
+
resets.set(token, account);
|
|
81
|
+
query.set("email", account.email);
|
|
82
|
+
} else verifications.set(token, account);
|
|
83
|
+
const page = kind === "password-reset" ? AUTH_PAGE_PATHS.resetPassword : AUTH_PAGE_PATHS.verifyEmail;
|
|
84
|
+
options.onMail?.({
|
|
85
|
+
kind,
|
|
86
|
+
to: account.email,
|
|
87
|
+
token,
|
|
88
|
+
path: `${page}?${query.toString()}`
|
|
89
|
+
});
|
|
90
|
+
};
|
|
91
|
+
const routes = {
|
|
92
|
+
"GET session": () => Promise.resolve(current !== null ? json(200, { user: userOf(current) }) : problem(401, "Unauthenticated.")),
|
|
93
|
+
"POST login": async (body) => {
|
|
94
|
+
const { email, password } = await body();
|
|
95
|
+
const account = find(email);
|
|
96
|
+
if (account === void 0 || account.password !== password) return invalid({ email: ["These credentials do not match our records."] });
|
|
97
|
+
if (settings?.twoFactor === true && account.twoFactor === "enabled") {
|
|
98
|
+
pending = { account };
|
|
99
|
+
return json(202, { twoFactor: true });
|
|
100
|
+
}
|
|
101
|
+
current = account;
|
|
102
|
+
return json(200, { user: userOf(account) });
|
|
103
|
+
},
|
|
104
|
+
"POST logout": () => {
|
|
105
|
+
current = null;
|
|
106
|
+
pending = null;
|
|
107
|
+
return Promise.resolve(json(204, null));
|
|
108
|
+
}
|
|
109
|
+
};
|
|
110
|
+
if (settings?.twoFactor === true) {
|
|
111
|
+
routes["POST two-factor/challenge"] = async (body) => {
|
|
112
|
+
const answer = await body();
|
|
113
|
+
if (pending === null) return invalid({ code: ["The login has expired. Log in again."] });
|
|
114
|
+
const { account } = pending;
|
|
115
|
+
if (typeof answer.recoveryCode === "string") {
|
|
116
|
+
const index = account.recoveryCodes.indexOf(answer.recoveryCode);
|
|
117
|
+
if (index === -1) return invalid({ recoveryCode: ["This recovery code is invalid."] });
|
|
118
|
+
account.recoveryCodes.splice(index, 1);
|
|
119
|
+
} else if (answer.code !== code) return invalid({ code: ["This code is invalid."] });
|
|
120
|
+
pending = null;
|
|
121
|
+
current = account;
|
|
122
|
+
return json(200, { user: userOf(account) });
|
|
123
|
+
};
|
|
124
|
+
routes["POST password/confirm"] = async (body) => {
|
|
125
|
+
const { password } = await body();
|
|
126
|
+
if (current === null) return problem(401, "Unauthenticated.");
|
|
127
|
+
return password === current.password ? json(204, null) : invalid({ password: ["The password is incorrect."] });
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
if (settings?.passkeys === true) {
|
|
131
|
+
routes["POST passkeys/options"] = () => Promise.resolve(json(200, { options: {
|
|
132
|
+
challenge: randomToken(),
|
|
133
|
+
timeout: 6e4,
|
|
134
|
+
userVerification: "preferred",
|
|
135
|
+
allowCredentials: []
|
|
136
|
+
} }));
|
|
137
|
+
routes["POST passkeys/login"] = async (body) => {
|
|
138
|
+
const { credential } = await body();
|
|
139
|
+
const id = isCredential(credential) ? credential.id : null;
|
|
140
|
+
const account = accounts.find((candidate) => candidate.passkeys.some((passkey) => passkey.credentialId === id));
|
|
141
|
+
const passkey = account?.passkeys.find((candidate) => candidate.credentialId === id);
|
|
142
|
+
if (account === void 0 || passkey === void 0) return invalid({ credential: ["This passkey isn’t known. It may have been removed."] });
|
|
143
|
+
passkey.lastUsedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
144
|
+
pending = null;
|
|
145
|
+
current = account;
|
|
146
|
+
return json(200, { user: userOf(account) });
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
if (settings?.passwordReset === true) {
|
|
150
|
+
routes["POST password/forgot"] = async (body) => {
|
|
151
|
+
const { email } = await body();
|
|
152
|
+
if (typeof email !== "string" || !EMAIL.test(email)) return invalid({ email: ["The email field must be a valid email address."] });
|
|
153
|
+
const account = find(email);
|
|
154
|
+
if (account !== void 0) send("password-reset", account);
|
|
155
|
+
return json(204, null);
|
|
156
|
+
};
|
|
157
|
+
routes["POST password/reset"] = async (body) => {
|
|
158
|
+
const { token, email, password } = await body();
|
|
159
|
+
const account = typeof token === "string" ? resets.get(token) : void 0;
|
|
160
|
+
if (account === void 0 || find(email) !== account) return invalid({ email: ["This password reset token is invalid."] });
|
|
161
|
+
if (typeof password !== "string" || password.length < 8) return invalid({ password: ["The password field must be at least 8 characters."] });
|
|
162
|
+
account.password = password;
|
|
163
|
+
resets.delete(token);
|
|
164
|
+
return json(204, null);
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
if (settings?.emailVerification === true) {
|
|
168
|
+
routes["POST email/verification"] = () => {
|
|
169
|
+
if (current === null) return Promise.resolve(problem(401, "Unauthenticated."));
|
|
170
|
+
if (!current.emailVerified) send("email-verification", current);
|
|
171
|
+
return Promise.resolve(json(204, null));
|
|
172
|
+
};
|
|
173
|
+
routes["POST email/verify"] = async (body) => {
|
|
174
|
+
const { token } = await body();
|
|
175
|
+
const account = typeof token === "string" ? verifications.get(token) : void 0;
|
|
176
|
+
if (account === void 0) return invalid({ token: ["This verification link is invalid or has expired."] });
|
|
177
|
+
account.emailVerified = true;
|
|
178
|
+
verifications.delete(token);
|
|
179
|
+
return json(204, null);
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
const conflict = (title) => problem(409, title);
|
|
183
|
+
const twoFactorRoutes = {
|
|
184
|
+
GET: (account) => json(200, {
|
|
185
|
+
status: account.twoFactor,
|
|
186
|
+
required: account.twoFactorRequired
|
|
187
|
+
}),
|
|
188
|
+
POST: (account) => {
|
|
189
|
+
if (account.twoFactor === "enabled") return conflict("Two-factor authentication is already on.");
|
|
190
|
+
account.twoFactor = "pending";
|
|
191
|
+
return json(200, {
|
|
192
|
+
secret: SECRET,
|
|
193
|
+
otpauthUrl: `otpauth://totp/${encodeURIComponent(`Panneau:${account.email}`)}?secret=${SECRET}&issuer=Panneau`
|
|
194
|
+
});
|
|
195
|
+
},
|
|
196
|
+
DELETE: (account) => {
|
|
197
|
+
if (account.twoFactorRequired) return conflict("Two-factor authentication is required for this account.");
|
|
198
|
+
account.twoFactor = "disabled";
|
|
199
|
+
account.recoveryCodes = [];
|
|
200
|
+
return json(204, null);
|
|
201
|
+
},
|
|
202
|
+
"POST confirm": async (account, body) => {
|
|
203
|
+
if (account.twoFactor !== "pending") return conflict("Two-factor authentication isn’t being set up.");
|
|
204
|
+
if ((await body()).code !== code) return invalid({ code: ["This code is invalid."] });
|
|
205
|
+
account.twoFactor = "enabled";
|
|
206
|
+
account.recoveryCodes = recoveryCodes();
|
|
207
|
+
return json(200, { recoveryCodes: account.recoveryCodes });
|
|
208
|
+
},
|
|
209
|
+
"POST recovery-codes": (account) => {
|
|
210
|
+
if (account.twoFactor !== "enabled") return conflict("Two-factor authentication is off.");
|
|
211
|
+
account.recoveryCodes = recoveryCodes();
|
|
212
|
+
return json(200, { recoveryCodes: account.recoveryCodes });
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
const accountRoutes = {
|
|
216
|
+
GET: (account) => json(200, { data: userOf(account) }),
|
|
217
|
+
PATCH: async (account, body) => {
|
|
218
|
+
const { name, email } = await body();
|
|
219
|
+
const errors = {};
|
|
220
|
+
if (typeof name !== "string" || name.trim() === "") errors.name = ["The name field is required."];
|
|
221
|
+
if (typeof email !== "string" || !EMAIL.test(email)) errors.email = ["The email field must be a valid email address."];
|
|
222
|
+
else if (find(email) !== void 0 && find(email) !== account) errors.email = ["The email has already been taken."];
|
|
223
|
+
if (Object.keys(errors).length > 0) return invalid(errors);
|
|
224
|
+
const changed = email.toLowerCase() !== account.email.toLowerCase();
|
|
225
|
+
account.name = name;
|
|
226
|
+
account.email = email;
|
|
227
|
+
if (changed && settings?.emailVerification === true) {
|
|
228
|
+
account.emailVerified = false;
|
|
229
|
+
send("email-verification", account);
|
|
230
|
+
}
|
|
231
|
+
return json(200, { data: userOf(account) });
|
|
232
|
+
},
|
|
233
|
+
"PUT password": async (account, body) => {
|
|
234
|
+
const { currentPassword, password } = await body();
|
|
235
|
+
if (currentPassword !== account.password) return invalid({ currentPassword: ["The provided password does not match your current password."] });
|
|
236
|
+
if (typeof password !== "string" || password.length < 8) return invalid({ password: ["The password field must be at least 8 characters."] });
|
|
237
|
+
account.password = password;
|
|
238
|
+
return json(204, null);
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
const redirectToProvider = (id, url) => {
|
|
242
|
+
if (!(settings?.providers ?? []).some((provider) => provider.id === id)) return problem(404, "Not found.");
|
|
243
|
+
const next = url?.searchParams.get("next") ?? "/";
|
|
244
|
+
const local = next.startsWith("/") && !next.startsWith("//") ? next : "/";
|
|
245
|
+
const account = find(options.providerUsers?.[id]);
|
|
246
|
+
if (account === void 0) return new Response(null, {
|
|
247
|
+
status: 302,
|
|
248
|
+
headers: { Location: `/?${AUTH_ERROR_PARAM}=access` }
|
|
249
|
+
});
|
|
250
|
+
current = account;
|
|
251
|
+
return new Response(null, {
|
|
252
|
+
status: 302,
|
|
253
|
+
headers: { Location: local }
|
|
254
|
+
});
|
|
255
|
+
};
|
|
256
|
+
const passkeyOf = ({ id, name, createdAt, lastUsedAt }) => ({
|
|
257
|
+
id,
|
|
258
|
+
name,
|
|
259
|
+
authenticator: null,
|
|
260
|
+
createdAt,
|
|
261
|
+
lastUsedAt
|
|
262
|
+
});
|
|
263
|
+
const passkeyRoutes = async (account, method, segments, body) => {
|
|
264
|
+
const [, second] = segments;
|
|
265
|
+
if (method === "GET" && second === void 0) return json(200, { data: account.passkeys.map(passkeyOf) });
|
|
266
|
+
if (method === "POST" && second === "options") return json(200, { options: {
|
|
267
|
+
challenge: randomToken(),
|
|
268
|
+
rp: { name: "Panneau" },
|
|
269
|
+
user: {
|
|
270
|
+
id: base64Url(account.id),
|
|
271
|
+
name: account.email,
|
|
272
|
+
displayName: account.name
|
|
273
|
+
},
|
|
274
|
+
pubKeyCredParams: [{
|
|
275
|
+
type: "public-key",
|
|
276
|
+
alg: -7
|
|
277
|
+
}, {
|
|
278
|
+
type: "public-key",
|
|
279
|
+
alg: -257
|
|
280
|
+
}],
|
|
281
|
+
authenticatorSelection: {
|
|
282
|
+
residentKey: "required",
|
|
283
|
+
userVerification: "preferred"
|
|
284
|
+
},
|
|
285
|
+
excludeCredentials: account.passkeys.map((passkey) => ({
|
|
286
|
+
type: "public-key",
|
|
287
|
+
id: passkey.credentialId
|
|
288
|
+
})),
|
|
289
|
+
timeout: 6e4
|
|
290
|
+
} });
|
|
291
|
+
if (method === "POST" && second === void 0) {
|
|
292
|
+
const { name, credential } = await body();
|
|
293
|
+
if (!isCredential(credential)) return invalid({ credential: ["This passkey could not be added. Try again."] });
|
|
294
|
+
const passkey = {
|
|
295
|
+
id: String(nextPasskey++),
|
|
296
|
+
credentialId: credential.id,
|
|
297
|
+
name: typeof name === "string" && name.trim() !== "" ? name : "Passkey",
|
|
298
|
+
createdAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
299
|
+
lastUsedAt: null
|
|
300
|
+
};
|
|
301
|
+
account.passkeys.push(passkey);
|
|
302
|
+
return json(201, { data: passkeyOf(passkey) });
|
|
303
|
+
}
|
|
304
|
+
const index = account.passkeys.findIndex((passkey) => passkey.id === second);
|
|
305
|
+
if (method === "DELETE" && segments.length === 2 && index !== -1) {
|
|
306
|
+
account.passkeys.splice(index, 1);
|
|
307
|
+
return json(204, null);
|
|
308
|
+
}
|
|
309
|
+
return problem(404, "Not found.");
|
|
310
|
+
};
|
|
311
|
+
const refuseUnverified = (account) => settings?.emailVerification === true && !account.emailVerified ? problem(403, "Your email address is not verified.", { type: EMAIL_UNVERIFIED_PROBLEM_TYPE }) : null;
|
|
312
|
+
return {
|
|
313
|
+
user: () => current !== null ? userOf(current) : null,
|
|
314
|
+
account: (segments, method, readBody) => {
|
|
315
|
+
const twoFactor = segments[0] === "two-factor" && settings?.twoFactor === true;
|
|
316
|
+
const passkeys = segments[0] === "passkeys" && settings?.passkeys === true;
|
|
317
|
+
if (!twoFactor && !passkeys && settings?.account !== true) return null;
|
|
318
|
+
if (current === null) return Promise.resolve(problem(401, "Unauthenticated."));
|
|
319
|
+
if (passkeys) {
|
|
320
|
+
const refusedPasskeys = refuse();
|
|
321
|
+
return refusedPasskeys !== null ? Promise.resolve(refusedPasskeys) : passkeyRoutes(current, method, segments, readBody);
|
|
322
|
+
}
|
|
323
|
+
const refused = twoFactor ? refuseUnverified(current) : refuse();
|
|
324
|
+
const route = twoFactor ? twoFactorRoutes[[method, ...segments.slice(1)].join(" ")] : accountRoutes[[method, ...segments].join(" ")];
|
|
325
|
+
if (refused !== null || route === void 0) return Promise.resolve(refused ?? problem(404, "Not found."));
|
|
326
|
+
return Promise.resolve(route(current, readBody));
|
|
327
|
+
},
|
|
328
|
+
answer: (segments, method, readBody, url) => {
|
|
329
|
+
if (method === "GET" && segments.length === 3 && segments[0] === "providers" && segments[2] === "redirect") return Promise.resolve(redirectToProvider(segments[1] ?? "", url));
|
|
330
|
+
const route = routes[`${method} ${segments.join("/")}`];
|
|
331
|
+
return route !== void 0 ? route(readBody) : Promise.resolve(problem(404, "Not found."));
|
|
332
|
+
},
|
|
333
|
+
refuse
|
|
334
|
+
};
|
|
335
|
+
function refuse() {
|
|
336
|
+
if (current === null) return problem(401, "Unauthenticated.");
|
|
337
|
+
const unverified = refuseUnverified(current);
|
|
338
|
+
if (unverified !== null) return unverified;
|
|
339
|
+
if (settings?.twoFactor === true && current.twoFactorRequired && current.twoFactor !== "enabled") return problem(403, "Two-factor authentication is required for this account.", { type: TWO_FACTOR_REQUIRED_PROBLEM_TYPE });
|
|
340
|
+
return null;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
//#endregion
|
|
344
|
+
export { createMockAuth };
|
|
345
|
+
|
|
346
|
+
//# sourceMappingURL=auth.js.map
|