asma-core-helpers 0.30.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/lib/collaboration/applyOperation.d.ts +33 -1
  2. package/lib/collaboration/applyOperation.d.ts.map +1 -1
  3. package/lib/collaboration/applyOperation.js +633 -9
  4. package/lib/collaboration/applyOperation.js.map +1 -1
  5. package/lib/collaboration/operations.d.ts +109 -2
  6. package/lib/collaboration/operations.d.ts.map +1 -1
  7. package/lib/collaboration/operations.js +7 -0
  8. package/lib/collaboration/operations.js.map +1 -1
  9. package/lib/collaboration/schemas.d.ts +163 -0
  10. package/lib/collaboration/schemas.d.ts.map +1 -1
  11. package/lib/collaboration/schemas.js +173 -3
  12. package/lib/collaboration/schemas.js.map +1 -1
  13. package/lib/collaboration/templateDocument.d.ts +176 -0
  14. package/lib/collaboration/templateDocument.d.ts.map +1 -1
  15. package/lib/collaboration/templateDocument.js +9 -0
  16. package/lib/collaboration/templateDocument.js.map +1 -1
  17. package/lib/collaboration/testHelpers/documentGenerator.js +78 -1
  18. package/lib/collaboration/testHelpers/documentGenerator.js.map +1 -1
  19. package/lib/collaboration/typeContracts.d.ts +53 -0
  20. package/lib/collaboration/typeContracts.d.ts.map +1 -0
  21. package/lib/collaboration/typeContracts.js +2 -0
  22. package/lib/collaboration/typeContracts.js.map +1 -0
  23. package/lib/validation/index.d.ts +1 -1
  24. package/lib/validation/index.d.ts.map +1 -1
  25. package/lib/validation/index.js +1 -1
  26. package/lib/validation/index.js.map +1 -1
  27. package/lib/validation/rules.d.ts +4 -0
  28. package/lib/validation/rules.d.ts.map +1 -1
  29. package/lib/validation/rules.js +18 -1
  30. package/lib/validation/rules.js.map +1 -1
  31. package/package.json +1 -1
  32. package/src/collaboration/applyOperation.ts +736 -9
  33. package/src/collaboration/operations.ts +97 -0
  34. package/src/collaboration/schemas.ts +191 -1
  35. package/src/collaboration/templateDocument.ts +167 -1
  36. package/src/collaboration/testHelpers/documentGenerator.ts +77 -1
  37. package/src/collaboration/typeContracts.ts +57 -0
  38. package/src/collaboration/typedAuthoring.test.ts +641 -0
  39. package/src/collaboration/typedAuthoringHardening.test.ts +408 -0
  40. package/src/validation/index.ts +15 -1
  41. package/src/validation/rules.test.ts +106 -1
  42. package/src/validation/rules.ts +25 -1
@@ -0,0 +1,408 @@
1
+ import assert from 'node:assert/strict'
2
+ import { describe, it } from 'node:test'
3
+ import { type } from 'arktype'
4
+
5
+ import {
6
+ applyOperation,
7
+ knownActionFieldRefusal,
8
+ knownActionValueRefusal,
9
+ OperationConflictError,
10
+ } from './applyOperation.js'
11
+ import type { TemplateOp } from './operations.js'
12
+ import { templateOpSchema } from './schemas.js'
13
+ import { emptyTemplateDocument, type ActionMetadata, type QnrTemplateDocument } from './templateDocument.js'
14
+
15
+ /**
16
+ * The hardening pass over ASMA-7683's typed authoring surface.
17
+ *
18
+ * Every case here corresponds to a hole that was **reproduced at `7e90b14`** before being closed. They
19
+ * share one theme worth stating: the wire schema is not the only way into the reducer. bunjs replays a
20
+ * stored `collab_ops` log without re-validating each op, so anything the reducer alone permits is
21
+ * reachable by an op written by an older or bypassed client — and unlike a rejected request, it lands
22
+ * in a document and then in an immutable artifact.
23
+ *
24
+ * The other theme is closed-by-default: a KNOWN action's shape is finite, so an unlisted field must be
25
+ * refused rather than tolerated. `QnrAction` stays open for LEGACY records precisely so the typed path
26
+ * can be strict.
27
+ */
28
+
29
+ const doc0 = emptyTemplateDocument('tpl-harden')
30
+ const apply = (ops: TemplateOp[], from: QnrTemplateDocument = doc0): QnrTemplateDocument =>
31
+ ops.reduce((doc, op) => applyOperation(doc, op), from)
32
+ const throwsConflict = (fn: () => unknown, hint: string) =>
33
+ assert.throws(fn, (error: unknown) => error instanceof OperationConflictError, hint)
34
+
35
+ const scaffold = (): QnrTemplateDocument =>
36
+ apply([
37
+ { type: 'question.create', questionId: 'g-1', questionType: 'QuestionGrid' },
38
+ { type: 'gridColumn.create', questionId: 'g-1', columnQuestionId: 'c-1', questionType: 'TextShort' },
39
+ { type: 'question.create', questionId: 'g-2', questionType: 'QuestionGrid' },
40
+ { type: 'gridColumn.create', questionId: 'g-2', columnQuestionId: 'c-2', questionType: 'TextShort' },
41
+ { type: 'mappingNode.create', nodeId: 'n-1', entityId: 'Actor' },
42
+ ])
43
+
44
+ const action = (doc: QnrTemplateDocument, id: string) => doc.actionsById?.[id]
45
+
46
+ // ─────────────────────────── compile-time closure (the probes) ───────────────────────────
47
+
48
+ describe('the typed unions are closed at compile time', () => {
49
+ it('is enforced by src/collaboration/typeContracts.ts, not from here', () => {
50
+ // Stated rather than implied: `tsconfig.json` excludes `**/*.test.ts` from `ts:check`, and the
51
+ // test runner strips types without checking them — so a `@ts-expect-error` written HERE is
52
+ // evaluated by nothing and reads as a guarantee it cannot give. The real assertions live in a
53
+ // checked module, where reopening either union turns `pnpm ts:check` red.
54
+ //
55
+ // What is still worth asserting at runtime is that the two legal shapes behave, which the
56
+ // wire-schema and reducer suites below do.
57
+ assert.ok(true)
58
+ })
59
+ })
60
+
61
+ // ─────────────────────────── the wire schema ───────────────────────────
62
+
63
+ describe('the wire schema discriminates createTyped', () => {
64
+ it('refuses actionType on a topLevelAction', () => {
65
+ const refused = templateOpSchema({
66
+ type: 'action.createTyped',
67
+ actionId: 'x',
68
+ kind: 'topLevelAction',
69
+ actionType: 'COPY',
70
+ })
71
+
72
+ assert.ok(refused instanceof type.errors)
73
+ })
74
+
75
+ it('still accepts both legal shapes', () => {
76
+ for (const op of [
77
+ { type: 'action.createTyped', actionId: 'x', kind: 'topLevelAction', label: 'Kjør' },
78
+ { type: 'action.createTyped', actionId: 'x', kind: 'gridAction', actionType: 'UPDATE' },
79
+ ]) {
80
+ assert.equal(templateOpSchema(op) instanceof type.errors, false, JSON.stringify(op))
81
+ }
82
+ })
83
+
84
+ it('refuses an invalid actionType on the gridAction arm', () => {
85
+ const refused = templateOpSchema({
86
+ type: 'action.createTyped',
87
+ actionId: 'x',
88
+ kind: 'gridAction',
89
+ actionType: 'DELETE',
90
+ })
91
+
92
+ assert.ok(refused instanceof type.errors)
93
+ })
94
+ })
95
+
96
+ // ─────────────────────────── known-action field whitelist ───────────────────────────
97
+
98
+ describe('action.updateField on a known action is closed by a whitelist', () => {
99
+ const known = (kind: 'topLevelAction' | 'gridAction') =>
100
+ apply([{ type: 'action.createTyped', actionId: 'x-k', kind } as TemplateOp], scaffold())
101
+
102
+ it('refuses a field that is simply not in the vocabulary', () => {
103
+ // The blacklist this replaced enumerated forbidden names, so `arbitraryField` persisted and
104
+ // turned a typed record back into the broad legacy bag.
105
+ for (const field of ['arbitraryField', 'nested.thing', 'questionId', 'childActionOrder']) {
106
+ assert.notEqual(knownActionFieldRefusal('gridAction', field), undefined, field)
107
+ throwsConflict(
108
+ () => apply([{ type: 'action.updateField', actionId: 'x-k', field, value: 'x' }], known('gridAction')),
109
+ field,
110
+ )
111
+ }
112
+ })
113
+
114
+ it('permits exactly label on both kinds, and actionType only on a gridAction', () => {
115
+ assert.equal(knownActionFieldRefusal('topLevelAction', 'label'), undefined)
116
+ assert.equal(knownActionFieldRefusal('gridAction', 'label'), undefined)
117
+ assert.equal(knownActionFieldRefusal('gridAction', 'actionType'), undefined)
118
+ assert.notEqual(knownActionFieldRefusal('topLevelAction', 'actionType'), undefined)
119
+
120
+ const doc = apply(
121
+ [
122
+ { type: 'action.updateField', actionId: 'x-k', field: 'label', value: 'Ny' },
123
+ { type: 'action.updateField', actionId: 'x-k', field: 'actionType', value: 'UPDATE' },
124
+ ],
125
+ known('gridAction'),
126
+ )
127
+ assert.deepEqual(action(doc, 'x-k'), { kind: 'gridAction', label: 'Ny', actionType: 'UPDATE' })
128
+ })
129
+
130
+ it('explains WHICH rule refused, not merely that something did', () => {
131
+ // With a whitelist, every unlisted field is refused regardless — so these tailored messages are
132
+ // the only thing distinguishing "write-once", "UI buffer" and "reserved for a dedicated op" from
133
+ // a generic rejection. Asserted because an author acts on the reason: re-create the action,
134
+ // stop sending a designer flag, or use `setMetadata` instead.
135
+ assert.match(knownActionFieldRefusal('gridAction', 'kind') ?? '', /write-once/)
136
+ assert.match(knownActionFieldRefusal('gridAction', 'editable_label') ?? '', /UI edit buffer/)
137
+ assert.match(knownActionFieldRefusal('topLevelAction', 'actionType') ?? '', /belongs to a gridAction/)
138
+ assert.match(knownActionFieldRefusal('gridAction', 'metadataByQuestionId') ?? '', /typed action operations/)
139
+ assert.match(knownActionFieldRefusal('gridAction', 'metadataByQuestionId.c-1') ?? '', /typed action operations/)
140
+ // And the catch-all names what IS writable, so the next attempt can succeed.
141
+ assert.match(knownActionFieldRefusal('topLevelAction', 'arbitraryField') ?? '', /writable: label/)
142
+ })
143
+
144
+ it('validates the VALUE, so a permitted field cannot be written malformed', () => {
145
+ assert.notEqual(knownActionValueRefusal('actionType', 'DELETE'), undefined)
146
+ assert.notEqual(knownActionValueRefusal('label', 42), undefined)
147
+ assert.equal(knownActionValueRefusal('label', 'Ny'), undefined)
148
+ assert.equal(knownActionValueRefusal('actionType', 'COPY'), undefined)
149
+ // `null` is the op layer's explicit unset and stays legal for both.
150
+ assert.equal(knownActionValueRefusal('label', null), undefined)
151
+ assert.equal(knownActionValueRefusal('actionType', null), undefined)
152
+
153
+ for (const [field, value] of [['actionType', 'DELETE'], ['label', 42]] as const) {
154
+ throwsConflict(
155
+ () => apply([{ type: 'action.updateField', actionId: 'x-k', field, value }], known('gridAction')),
156
+ `${field}=${String(value)}`,
157
+ )
158
+ }
159
+
160
+ // And the unset still works, leaving minimal form behind.
161
+ const cleared = apply(
162
+ [
163
+ { type: 'action.updateField', actionId: 'x-k', field: 'label', value: 'Ny' },
164
+ { type: 'action.updateField', actionId: 'x-k', field: 'label', value: null },
165
+ ],
166
+ known('gridAction'),
167
+ )
168
+ assert.deepEqual(action(cleared, 'x-k'), { kind: 'gridAction' })
169
+ })
170
+
171
+ it('leaves LEGACY unknown-kind records completely unrestricted', () => {
172
+ // The compatibility half: the whitelist must not reach a record it was not written for.
173
+ const legacy = apply([{ type: 'action.create', actionId: 'x-l', kind: 'submit' }], scaffold())
174
+ const doc = apply(
175
+ [
176
+ { type: 'action.updateField', actionId: 'x-l', field: 'arbitraryField', value: 'x' },
177
+ { type: 'action.updateField', actionId: 'x-l', field: 'editable_label', value: true },
178
+ { type: 'action.updateField', actionId: 'x-l', field: 'actionType', value: 'DELETE' },
179
+ { type: 'action.updateField', actionId: 'x-l', field: 'label', value: 42 },
180
+ ],
181
+ legacy,
182
+ )
183
+
184
+ assert.deepEqual(action(doc, 'x-l'), {
185
+ kind: 'submit',
186
+ arbitraryField: 'x',
187
+ editable_label: true,
188
+ actionType: 'DELETE',
189
+ label: 42,
190
+ })
191
+ })
192
+ })
193
+
194
+ // ─────────────────────────── gridColumn.setAction kind check ───────────────────────────
195
+
196
+ describe('a grid may only own a known gridAction', () => {
197
+ it('refuses a topLevelAction and an unknown legacy action on include', () => {
198
+ const base = apply(
199
+ [
200
+ { type: 'action.createTyped', actionId: 'x-top', kind: 'topLevelAction' },
201
+ { type: 'action.create', actionId: 'x-legacy', kind: 'submit' },
202
+ ],
203
+ scaffold(),
204
+ )
205
+
206
+ for (const actionId of ['x-top', 'x-legacy']) {
207
+ throwsConflict(
208
+ () => apply([{ type: 'gridColumn.setAction', questionId: 'g-1', actionId, include: true }], base),
209
+ actionId,
210
+ )
211
+ }
212
+ })
213
+
214
+ it('still scrubs a malformed or legacy reference on include:false', () => {
215
+ // Removal must stay possible, or a document that already holds a bad reference is unfixable.
216
+ const malformed = {
217
+ ...scaffold(),
218
+ actionsById: { 'x-legacy': { kind: 'submit' } },
219
+ } as unknown as QnrTemplateDocument
220
+ const withRef = {
221
+ ...malformed,
222
+ questionsById: {
223
+ ...malformed.questionsById,
224
+ 'g-1': {
225
+ ...(malformed.questionsById?.['g-1'] as object),
226
+ presentation: { actionIds: ['x-legacy'] },
227
+ },
228
+ },
229
+ } as unknown as QnrTemplateDocument
230
+
231
+ const repaired = apply(
232
+ [{ type: 'gridColumn.setAction', questionId: 'g-1', actionId: 'x-legacy', include: false }],
233
+ withRef,
234
+ )
235
+
236
+ assert.equal(repaired.questionsById?.['g-1']?.presentation, undefined)
237
+ })
238
+
239
+ it('keeps one-owner enforcement', () => {
240
+ const base = apply(
241
+ [
242
+ { type: 'action.createTyped', actionId: 'x-g', kind: 'gridAction' },
243
+ { type: 'gridColumn.setAction', questionId: 'g-1', actionId: 'x-g', include: true },
244
+ ],
245
+ scaffold(),
246
+ )
247
+
248
+ throwsConflict(
249
+ () => apply([{ type: 'gridColumn.setAction', questionId: 'g-2', actionId: 'x-g', include: true }], base),
250
+ 'second owner',
251
+ )
252
+ })
253
+ })
254
+
255
+ // ─────────────────────────── setMetadata owner disambiguation ───────────────────────────
256
+
257
+ describe('action.setMetadata does not depend on key order', () => {
258
+ /** A malformed imported document: ONE grid action listed by TWO grids, in a chosen key order. */
259
+ const twoOwners = (order: 'g1first' | 'g2first'): QnrTemplateDocument => {
260
+ const g1 = { type: 'QuestionGrid', grid: { columnIds: ['c-1'] }, presentation: { actionIds: ['x-g'] } }
261
+ const g2 = { type: 'QuestionGrid', grid: { columnIds: ['c-2'] }, presentation: { actionIds: ['x-g'] } }
262
+ const c1 = { type: 'TextShort' }
263
+ const c2 = { type: 'TextShort' }
264
+
265
+ return {
266
+ documentId: 'tpl-two-owners',
267
+ revision: 1,
268
+ questionOrder: ['g-1', 'g-2'],
269
+ questionsById:
270
+ order === 'g1first'
271
+ ? { 'g-1': g1, 'g-2': g2, 'c-1': c1, 'c-2': c2 }
272
+ : { 'g-2': g2, 'g-1': g1, 'c-1': c1, 'c-2': c2 },
273
+ actionsById: { 'x-g': { kind: 'gridAction' } },
274
+ } as unknown as QnrTemplateDocument
275
+ }
276
+
277
+ it('refuses ambiguous metadata whichever grid appears first', () => {
278
+ // The defect: resolving the column vocabulary from `owners[0]` made this write succeed on one
279
+ // key order and fail on the other — two documents with identical content disagreeing, which is
280
+ // the failure DOC-LAW-1 exists to prevent.
281
+ for (const order of ['g1first', 'g2first'] as const) {
282
+ throwsConflict(
283
+ () =>
284
+ apply(
285
+ [{ type: 'action.setMetadata', actionId: 'x-g', questionId: 'c-1', metadata: { all: true } }],
286
+ twoOwners(order),
287
+ ),
288
+ order,
289
+ )
290
+ }
291
+ })
292
+
293
+ it('names the ambiguity rather than a missing column', () => {
294
+ let message = ''
295
+ try {
296
+ apply(
297
+ [{ type: 'action.setMetadata', actionId: 'x-g', questionId: 'c-1', metadata: { all: true } }],
298
+ twoOwners('g1first'),
299
+ )
300
+ } catch (error) {
301
+ message = error instanceof Error ? error.message : ''
302
+ }
303
+
304
+ assert.match(message, /owned by 2 grids/)
305
+ // Sorted, so the message itself does not reintroduce key-order dependence.
306
+ assert.match(message, /g-1, g-2/)
307
+ })
308
+
309
+ it('lets metadata:null repair an UNOWNED record', () => {
310
+ // Removal needs no owner: requiring one would make exactly the malformed documents that need
311
+ // fixing unfixable.
312
+ const unowned = {
313
+ documentId: 'tpl-unowned',
314
+ revision: 1,
315
+ questionOrder: [],
316
+ actionsById: { 'x-g': { kind: 'gridAction', metadataByQuestionId: { 'c-1': { all: true } } } },
317
+ } as unknown as QnrTemplateDocument
318
+
319
+ const repaired = apply(
320
+ [{ type: 'action.setMetadata', actionId: 'x-g', questionId: 'c-1', metadata: null }],
321
+ unowned,
322
+ )
323
+
324
+ assert.deepEqual(action(repaired, 'x-g'), { kind: 'gridAction' })
325
+ })
326
+
327
+ it('still requires the action itself to be a known gridAction, even for null', () => {
328
+ const legacy = apply([{ type: 'action.create', actionId: 'x-l', kind: 'submit' }], scaffold())
329
+
330
+ throwsConflict(
331
+ () => apply([{ type: 'action.setMetadata', actionId: 'x-l', questionId: 'c-1', metadata: null }], legacy),
332
+ 'legacy record is not a known gridAction',
333
+ )
334
+ })
335
+ })
336
+
337
+ // ─────────────────────────── direct replay of setTyped ───────────────────────────
338
+
339
+ describe('mappingFilter.setTyped is validated in the reducer, not only at the wire', () => {
340
+ const replay = (payload: Record<string, unknown>) =>
341
+ apply(
342
+ [{ type: 'mappingFilter.setTyped', filterId: 'f-1', nodeId: 'n-1', fieldId: 'Navn', ...payload } as unknown as TemplateOp],
343
+ scaffold(),
344
+ )
345
+
346
+ it('refuses every malformed payload that bypassed the wire', () => {
347
+ const cases: Array<[string, Record<string, unknown>]> = [
348
+ ['an empty in-list', { operator: 'in', values: [] }],
349
+ ['a range with no bound', { operator: 'range' }],
350
+ ['a non-boolean isNull', { operator: 'isNull', value: 'yes' }],
351
+ ['eq with no value', { operator: 'eq' }],
352
+ ['eq with a non-scalar value', { operator: 'eq', value: { a: 1 } }],
353
+ ['an in-list holding a non-scalar', { operator: 'in', values: ['a', { b: 2 }] }],
354
+ ['a range bound that is not a scalar', { operator: 'range', from: { a: 1 } }],
355
+ ['eq carrying a stale values member', { operator: 'eq', value: 'a', values: ['b'] }],
356
+ ['in carrying a stale value member', { operator: 'in', values: ['b'], value: 'a' }],
357
+ ['range carrying a stale value member', { operator: 'range', from: 1, value: 'a' }],
358
+ ['isNull carrying a stale range bound', { operator: 'isNull', value: true, to: 3 }],
359
+ ]
360
+
361
+ for (const [hint, payload] of cases) {
362
+ throwsConflict(() => replay(payload), hint)
363
+ }
364
+ })
365
+
366
+ it('refuses an unknown operator instead of storing it as a boundless range', () => {
367
+ // The worst of the set: `weird` fell past the eq/in/isNull tests into the range branch and was
368
+ // written as `{operator: 'range'}` with no bounds — a filter nothing can evaluate, bound for an
369
+ // artifact that is immutable forever.
370
+ for (const operator of ['weird', 'contains', 'startsWith', '']) {
371
+ throwsConflict(() => replay({ operator, value: 'x' }), operator || '(empty)')
372
+ }
373
+
374
+ let message = ''
375
+ try {
376
+ replay({ operator: 'contains', value: 'x' })
377
+ } catch (error) {
378
+ message = error instanceof Error ? error.message : ''
379
+ }
380
+ // The message points at the compatible path rather than just refusing.
381
+ assert.match(message, /mappingFilter\.set/)
382
+ })
383
+
384
+ it('still accepts every legal payload and replaces canonically', () => {
385
+ const legal: Array<[Record<string, unknown>, Record<string, unknown>]> = [
386
+ [{ operator: 'eq', value: 'ada' }, { fieldId: 'Navn', operator: 'eq', value: 'ada' }],
387
+ [{ operator: 'in', values: ['a', 2, true] }, { fieldId: 'Navn', operator: 'in', values: ['a', 2, true] }],
388
+ [{ operator: 'range', from: 1 }, { fieldId: 'Navn', operator: 'range', from: 1 }],
389
+ [{ operator: 'range', to: 9 }, { fieldId: 'Navn', operator: 'range', to: 9 }],
390
+ [{ operator: 'range', from: 1, to: 9 }, { fieldId: 'Navn', operator: 'range', from: 1, to: 9 }],
391
+ [{ operator: 'isNull', value: false }, { fieldId: 'Navn', operator: 'isNull', value: false }],
392
+ ]
393
+
394
+ for (const [payload, expected] of legal) {
395
+ assert.deepEqual(replay(payload).mappingFiltersById?.['f-1'], expected, JSON.stringify(payload))
396
+ }
397
+ })
398
+
399
+ it('leaves the legacy mappingFilter.set path untouched', () => {
400
+ // The compatibility guarantee: the loose op still writes an operator the typed path refuses.
401
+ const doc = apply(
402
+ [{ type: 'mappingFilter.set', filterId: 'f-1', nodeId: 'n-1', fieldId: 'Navn', operator: 'contains', value: 'ada' }],
403
+ scaffold(),
404
+ )
405
+
406
+ assert.deepEqual(doc.mappingFiltersById?.['f-1'], { fieldId: 'Navn', operator: 'contains', value: 'ada' })
407
+ })
408
+ })
@@ -14,4 +14,18 @@ export {
14
14
  type ValidationMessages,
15
15
  } from './messages.js'
16
16
 
17
- export { email, emailRegex, name, nameRegex, pattern, phoneNr, phoneNrRegex, pnr, required } from './rules.js'
17
+ export {
18
+ email,
19
+ emailRegex,
20
+ hasDigit,
21
+ httpUrl,
22
+ name,
23
+ nameChars,
24
+ nameCharsRegex,
25
+ nameRegex,
26
+ pattern,
27
+ phoneNr,
28
+ phoneNrRegex,
29
+ pnr,
30
+ required,
31
+ } from './rules.js'
@@ -1,7 +1,7 @@
1
1
  import assert from 'node:assert/strict'
2
2
  import { describe, it } from 'node:test'
3
3
 
4
- import { email, name, pattern, phoneNr, pnr, required } from './rules.js'
4
+ import { email, hasDigit, httpUrl, name, nameChars, pattern, phoneNr, pnr, required } from './rules.js'
5
5
 
6
6
  describe('required', () => {
7
7
  it('rejects empty, whitespace, null, undefined', () => {
@@ -38,6 +38,86 @@ describe('name', () => {
38
38
  assert.equal(name('john'), false)
39
39
  assert.equal(name(''), false)
40
40
  })
41
+
42
+ it('accepts the real names it has to accept', () => {
43
+ for (const real of [
44
+ 'Bo Henki Steinsland-Tønnessen',
45
+ 'Bjørn Emil Gloppen Jørgensen',
46
+ 'Bjørge Øfstaas',
47
+ 'Kenneth Jul-Larsen',
48
+ 'Gun Jorunn Haughom Sørheim',
49
+ 'Lone Mjørnaren Darum Jr.',
50
+ 'Martine Mosengen Sr.',
51
+ 'Tommy André Pedersen',
52
+ 'Tuva Elisabeth Næs Andersen',
53
+ 'Willian Garthner II ',
54
+ 'Porsgrunn commune IKT',
55
+ 'Bargan, Constantin',
56
+ ]) {
57
+ assert.equal(name(real), true, real)
58
+ }
59
+ })
60
+
61
+ it('accepts every dash an editor may have substituted for the typed hyphen', () => {
62
+ assert.equal(name('Anne-Marie Hansen'), true)
63
+ assert.equal(name('Anne\u2013Marie Hansen'), true)
64
+ assert.equal(name('Anne\u2014Marie Hansen'), true)
65
+ })
66
+
67
+ it('accepts both apostrophes — editors substitute the typographic one silently', () => {
68
+ assert.equal(name("O'Brien"), true)
69
+ assert.equal(name('O\u2019Brien'), true)
70
+ assert.equal(name("Lars D'Angelo Næss"), true)
71
+ })
72
+
73
+ it('treats Norwegian letters as ordinary letters', () => {
74
+ assert.equal(name('Æse Ørn Ådne'), true)
75
+ assert.equal(name('Øystein'), true)
76
+ })
77
+
78
+ it('rejects digits anywhere, not just as the first character', () => {
79
+ assert.equal(name('Ivan123'), false)
80
+ assert.equal(name('123'), false)
81
+ assert.equal(name('Ivan 123'), false)
82
+ assert.equal(name('Willian Garthner 2'), false)
83
+ })
84
+
85
+ it('rejects a lower-case opening and punctuation the set does not cover', () => {
86
+ assert.equal(name('kenneth Jul-Larsen'), false)
87
+ assert.equal(name('Foo;Bar'), false)
88
+ assert.equal(name('Foo@Bar'), false)
89
+ })
90
+ })
91
+
92
+ describe('nameChars', () => {
93
+ it('accepts every character a name is built from', () => {
94
+ assert.equal(nameChars('Bargan, Constantin'), true)
95
+ assert.equal(nameChars("Lone Mjørnaren Darum Jr. O'Brien"), true)
96
+ assert.equal(nameChars('vasilii'), true) // case is not its business
97
+ })
98
+
99
+ it('rejects anything else, which is what lets the field name the real problem', () => {
100
+ assert.equal(nameChars('Vasilii&'), false)
101
+ assert.equal(nameChars('Foo;Bar'), false)
102
+ assert.equal(nameChars('Foo@Bar'), false)
103
+ assert.equal(nameChars('Ivan123'), false)
104
+ })
105
+
106
+ it('agrees with nameRegex about every character it allows', () => {
107
+ for (const char of ["-", ".", ",", "'", "\u2019"]) {
108
+ assert.equal(nameChars(`Aa${char}bb`), true, char)
109
+ assert.equal(name(`Aa${char}bb`), true, char)
110
+ }
111
+ })
112
+ })
113
+
114
+ describe('hasDigit', () => {
115
+ it('separates "there is a number in here" from every other name failure', () => {
116
+ assert.equal(hasDigit('Ivan123'), true)
117
+ assert.equal(hasDigit('123'), true)
118
+ assert.equal(hasDigit('ivan'), false)
119
+ assert.equal(hasDigit('Ann-Kristin'), false)
120
+ })
41
121
  })
42
122
 
43
123
  describe('phoneNr', () => {
@@ -70,3 +150,28 @@ describe('pnr', () => {
70
150
  assert.equal(pnr('00000000000'), false)
71
151
  })
72
152
  })
153
+
154
+ describe('httpUrl', () => {
155
+ it('accepts ordinary web addresses', () => {
156
+ assert.equal(httpUrl('https://example.com'), true)
157
+ assert.equal(httpUrl('http://example.com'), true)
158
+ assert.equal(httpUrl('https://dok.adcuris.no/ad-voca/uO5TQY5Z2K271Ycumsj5'), true)
159
+ assert.equal(httpUrl(' https://example.com '), true)
160
+ })
161
+
162
+ it('accepts ports, fragments, internationalised hosts and full path/query syntax', () => {
163
+ assert.equal(httpUrl('https://example.com:8080'), true)
164
+ assert.equal(httpUrl('https://example.com/page#section'), true)
165
+ assert.equal(httpUrl('https://bxrum.no'.replace('x', '\u00e6')), true)
166
+ assert.equal(httpUrl('https://example.com/a+b,c~d'), true)
167
+ assert.equal(httpUrl('https://x.no/a?b=c&d=e'), true)
168
+ })
169
+
170
+ it('rejects non-web schemes and scheme-less input', () => {
171
+ assert.equal(httpUrl('mailto:a@b.c'), false)
172
+ assert.equal(httpUrl('foo:bar'), false)
173
+ assert.equal(httpUrl('javascript:alert(1)'), false)
174
+ assert.equal(httpUrl('example.com'), false)
175
+ assert.equal(httpUrl(''), false)
176
+ })
177
+ })
@@ -3,7 +3,22 @@ import { getValidNorwegianPersonalNumber } from '../helpers/validateNorwegianPer
3
3
  /** Copied from directory/asma-app-directory ActorToUpsertValidator regex helpers — keep pilot behavior identical. */
4
4
  export const phoneNrRegex = /^\+?\d{6,13}$/
5
5
  export const emailRegex = /^[\w.-]+@([\w-]+\.)+[\w-]{2,4}$/
6
- export const nameRegex = /^\s*\p{Lu}[\p{L}0-9-]*(\s+\p{L}[\p{L}0-9-]*)*\s*$/u
6
+ const NAME_PUNCTUATION = ".,'\u2019\u2013\u2014-"
7
+
8
+ export const nameRegex = new RegExp(
9
+ `^\\s*\\p{Lu}[\\p{L}${NAME_PUNCTUATION}]*(\\s+\\p{L}[\\p{L}${NAME_PUNCTUATION}]*)*\\s*$`,
10
+ 'u',
11
+ )
12
+
13
+ export const nameCharsRegex = new RegExp(`^[\\p{L}\\s${NAME_PUNCTUATION}]*$`, 'u')
14
+
15
+ export function hasDigit(value: string): boolean {
16
+ return /\d/.test(value)
17
+ }
18
+
19
+ export function nameChars(value: string): boolean {
20
+ return nameCharsRegex.test(value)
21
+ }
7
22
 
8
23
  export function required(value: unknown): boolean {
9
24
  if (value == null) return false
@@ -30,3 +45,12 @@ export function pattern(value: string, regex: RegExp): boolean {
30
45
  export function pnr(value: string): boolean {
31
46
  return getValidNorwegianPersonalNumber(value) != null
32
47
  }
48
+
49
+ export function httpUrl(value: string): boolean {
50
+ try {
51
+ const { protocol } = new URL(value.trim())
52
+ return protocol === 'http:' || protocol === 'https:'
53
+ } catch {
54
+ return false
55
+ }
56
+ }