create-protobase 0.53.5 → 0.53.7

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 (104) hide show
  1. package/dist/templates/erp/package.json +10 -7
  2. package/dist/templates/property-portal/.env.example +18 -0
  3. package/dist/templates/property-portal/API.md +66 -0
  4. package/dist/templates/property-portal/_.gitignore +4 -0
  5. package/dist/templates/property-portal/_bunfig.toml +4 -0
  6. package/dist/templates/property-portal/config/agencies/data.ts +17 -0
  7. package/dist/templates/property-portal/config/agencies/ui.ts +20 -0
  8. package/dist/templates/property-portal/config/alerts/data.ts +20 -0
  9. package/dist/templates/property-portal/config/alerts/ui.ts +18 -0
  10. package/dist/templates/property-portal/config/bottom-bar.test.ts +30 -0
  11. package/dist/templates/property-portal/config/bottom-bar.ts +17 -0
  12. package/dist/templates/property-portal/config/config.test.ts +73 -0
  13. package/dist/templates/property-portal/config/favorites/data.ts +13 -0
  14. package/dist/templates/property-portal/config/favorites/ui.ts +26 -0
  15. package/dist/templates/property-portal/config/home/page.tsx +19 -0
  16. package/dist/templates/property-portal/config/index.ts +18 -0
  17. package/dist/templates/property-portal/config/listing_photos/data.ts +15 -0
  18. package/dist/templates/property-portal/config/listing_photos/ui.ts +20 -0
  19. package/dist/templates/property-portal/config/listings/data.ts +55 -0
  20. package/dist/templates/property-portal/config/listings/labels.ts +40 -0
  21. package/dist/templates/property-portal/config/listings/rules.test.ts +27 -0
  22. package/dist/templates/property-portal/config/listings/rules.ts +25 -0
  23. package/dist/templates/property-portal/config/listings/ui.ts +121 -0
  24. package/dist/templates/property-portal/config/map-layers.test.ts +16 -0
  25. package/dist/templates/property-portal/config/notes/data.ts +19 -0
  26. package/dist/templates/property-portal/config/notes/ui.ts +16 -0
  27. package/dist/templates/property-portal/config/photo-variants.ts +10 -0
  28. package/dist/templates/property-portal/config/places/data.ts +15 -0
  29. package/dist/templates/property-portal/config/places/ui.ts +23 -0
  30. package/dist/templates/property-portal/config/roles.test.ts +89 -0
  31. package/dist/templates/property-portal/config/roles.ts +40 -0
  32. package/dist/templates/property-portal/config/saved_searches/data.ts +25 -0
  33. package/dist/templates/property-portal/config/saved_searches/filter.ts +20 -0
  34. package/dist/templates/property-portal/config/saved_searches/rules.test.ts +14 -0
  35. package/dist/templates/property-portal/config/saved_searches/rules.ts +10 -0
  36. package/dist/templates/property-portal/config/saved_searches/ui.ts +32 -0
  37. package/dist/templates/property-portal/db/connection.ts +7 -0
  38. package/dist/templates/property-portal/db/drop.ts +15 -0
  39. package/dist/templates/property-portal/db/kysely.ts +13 -0
  40. package/dist/templates/property-portal/db/migrate.ts +31 -0
  41. package/dist/templates/property-portal/db/migrations/001_market.sql +101 -0
  42. package/dist/templates/property-portal/db/migrations/002_auth.sql +36 -0
  43. package/dist/templates/property-portal/db/migrations/003_jobs.sql +576 -0
  44. package/dist/templates/property-portal/db/migrations/004_members.sql +71 -0
  45. package/dist/templates/property-portal/db/migrations/005_listing_published.sql +14 -0
  46. package/dist/templates/property-portal/db/migrations/006_price_split.sql +61 -0
  47. package/dist/templates/property-portal/db/migrations/007_listing_position.sql +2 -0
  48. package/dist/templates/property-portal/db/migrations/007_photo_placeholders.sql +4 -0
  49. package/dist/templates/property-portal/db/migrations/008_saved_searches.sql +42 -0
  50. package/dist/templates/property-portal/db/migrations/009_listing_position_exact.sql +3 -0
  51. package/dist/templates/property-portal/db/migrations/010_saved_search_name.sql +3 -0
  52. package/dist/templates/property-portal/db/migrations/011_filter_indexes.sql +36 -0
  53. package/dist/templates/property-portal/db/migrations/012_sort_indexes.sql +4 -0
  54. package/dist/templates/property-portal/db/migrations/013_alert_mail.sql +26 -0
  55. package/dist/templates/property-portal/db/migrations/014_auth.sql +4 -0
  56. package/dist/templates/property-portal/db/migrations/015_auth.sql +319 -0
  57. package/dist/templates/property-portal/emails/alerted-listing.tsx +63 -0
  58. package/dist/templates/property-portal/emails/daily-digest.tsx +26 -0
  59. package/dist/templates/property-portal/emails/emails.test.ts +53 -0
  60. package/dist/templates/property-portal/emails/instant-alert.tsx +26 -0
  61. package/dist/templates/property-portal/jobs/alerted-listings.test.ts +19 -0
  62. package/dist/templates/property-portal/jobs/alerted-listings.ts +42 -0
  63. package/dist/templates/property-portal/jobs/daily-alerts.ts +21 -0
  64. package/dist/templates/property-portal/jobs/email-alerts.ts +44 -0
  65. package/dist/templates/property-portal/jobs/match-listing.ts +30 -0
  66. package/dist/templates/property-portal/jobs/match.test.ts +51 -0
  67. package/dist/templates/property-portal/jobs/match.ts +15 -0
  68. package/dist/templates/property-portal/jobs/offered.test.ts +9 -0
  69. package/dist/templates/property-portal/jobs/offered.ts +12 -0
  70. package/dist/templates/property-portal/map/tiles-proxy.test.ts +78 -0
  71. package/dist/templates/property-portal/map/tiles-proxy.ts +48 -0
  72. package/dist/templates/property-portal/map/tiles.ts +16 -0
  73. package/dist/templates/property-portal/node-types.d.ts +1 -0
  74. package/dist/templates/property-portal/package.json +42 -0
  75. package/dist/templates/property-portal/protobase.config.ts +57 -0
  76. package/dist/templates/property-portal/protobase.ui.tsx +21 -0
  77. package/dist/templates/property-portal/seed/builders/agency.ts +22 -0
  78. package/dist/templates/property-portal/seed/builders/distance.test.ts +14 -0
  79. package/dist/templates/property-portal/seed/builders/distance.ts +12 -0
  80. package/dist/templates/property-portal/seed/builders/listing.ts +177 -0
  81. package/dist/templates/property-portal/seed/builders/member.ts +136 -0
  82. package/dist/templates/property-portal/seed/builders/search-filter.test.ts +17 -0
  83. package/dist/templates/property-portal/seed/builders/search-filter.ts +44 -0
  84. package/dist/templates/property-portal/seed/calendar.ts +4 -0
  85. package/dist/templates/property-portal/seed/cli.ts +50 -0
  86. package/dist/templates/property-portal/seed/copy.ts +22 -0
  87. package/dist/templates/property-portal/seed/data/names.ts +61 -0
  88. package/dist/templates/property-portal/seed/data/places.ts +54 -0
  89. package/dist/templates/property-portal/seed/format.ts +20 -0
  90. package/dist/templates/property-portal/seed/maintenance.ts +65 -0
  91. package/dist/templates/property-portal/seed/photos/canvas.ts +48 -0
  92. package/dist/templates/property-portal/seed/photos/draw.ts +202 -0
  93. package/dist/templates/property-portal/seed/photos/library.ts +44 -0
  94. package/dist/templates/property-portal/seed/photos/png.ts +34 -0
  95. package/dist/templates/property-portal/seed/rng.ts +36 -0
  96. package/dist/templates/property-portal/seed/scales.ts +9 -0
  97. package/dist/templates/property-portal/seed/steps/market.ts +54 -0
  98. package/dist/templates/property-portal/seed/steps/members.ts +41 -0
  99. package/dist/templates/property-portal/seed/world.ts +98 -0
  100. package/dist/templates/property-portal/tsconfig.json +24 -0
  101. package/dist/templates/property-portal/vitest.config.ts +4 -0
  102. package/dist/templates/real-estate/package.json +10 -7
  103. package/dist/templates/scratch/package.json +10 -7
  104. package/package.json +2 -2
@@ -0,0 +1,14 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { distanceKm } from './distance'
3
+
4
+ const amsterdam = { latitude: 52.3676, longitude: 4.9041 }
5
+ const haarlem = { latitude: 52.3874, longitude: 4.6462 }
6
+ const utrecht = { latitude: 52.0907, longitude: 5.1214 }
7
+
8
+ describe('distanceKm', () => {
9
+ it('measures along the earth', () => {
10
+ expect(distanceKm(amsterdam, haarlem)).toBeCloseTo(17.6, 0)
11
+ expect(distanceKm(amsterdam, utrecht)).toBeCloseTo(34.2, 0)
12
+ expect(distanceKm(amsterdam, amsterdam)).toBe(0)
13
+ })
14
+ })
@@ -0,0 +1,12 @@
1
+ type Point = { latitude: number; longitude: number }
2
+
3
+ const earthRadiusKm = 6371
4
+
5
+ /** The great-circle distance between two points, in kilometres (haversine): which places a search around one takes in. */
6
+ export const distanceKm = (a: Point, b: Point) => {
7
+ const rad = (degrees: number) => (degrees * Math.PI) / 180
8
+ const dLat = rad(b.latitude - a.latitude)
9
+ const dLon = rad(b.longitude - a.longitude)
10
+ const h = Math.sin(dLat / 2) ** 2 + Math.cos(rad(a.latitude)) * Math.cos(rad(b.latitude)) * Math.sin(dLon / 2) ** 2
11
+ return 2 * earthRadiusKm * Math.asin(Math.sqrt(h))
12
+ }
@@ -0,0 +1,177 @@
1
+ import { DAY, seedNow } from '../calendar'
2
+ import { agentNames, details, openings, streets } from '../data/names'
3
+ import type { PlaceSeed } from '../data/places'
4
+ import { exteriorPhoto, roomPhoto } from '../photos/library'
5
+ import type { PropertyType, RoomKind } from '../photos/draw'
6
+ import { int, pick, rngAt, weighted, type Rand } from '../rng'
7
+ import type { SeededAgency } from './agency'
8
+
9
+ type EnergyLabel = 'a_plus_4' | 'a_plus_3' | 'a_plus_2' | 'a_plus' | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g'
10
+
11
+ export type SeededPhoto = { position: number; photo: string; caption: string }
12
+
13
+ export type SeededListing = {
14
+ id: number
15
+ agencyId: number
16
+ placeId: number
17
+ country: 'NL' | 'ES'
18
+ propertyType: PropertyType
19
+ status: 'available' | 'under_offer' | 'sold' | 'let'
20
+ address: string
21
+ postalCode: string
22
+ latitude: number
23
+ longitude: number
24
+ /** False when the listing gives its position only roughly. */
25
+ positionExact: boolean
26
+ /** The asking price, empty when the home is not for sale. */
27
+ purchasePrice: number | null
28
+ /** The rent per month, empty when the home is not for rent. */
29
+ rentPrice: number | null
30
+ livingArea: number
31
+ plotArea: number | null
32
+ rooms: number
33
+ bedrooms: number
34
+ bathrooms: number
35
+ builtYear: number
36
+ energyLabel: EnergyLabel | null
37
+ garden: boolean
38
+ balcony: boolean
39
+ parking: boolean
40
+ description: string
41
+ photo: string
42
+ agentName: string
43
+ agentPhone: string
44
+ publishedAt: number | null
45
+ createdAt: number
46
+ photos: SeededPhoto[]
47
+ }
48
+
49
+ // The asking price per m² in a place's centre; the rent per month is a 230th of it.
50
+ const pricePerM2: Record<string, number> = {
51
+ Amsterdam: 7800, Utrecht: 5600, Amstelveen: 6200, Haarlem: 5800, 'Den Haag': 4600, Leiden: 4900, Delft: 4600, Hilversum: 5000, Rotterdam: 4300,
52
+ Madrid: 5000, Barcelona: 4800, Marbella: 5200, 'San Sebastián': 6000, Palma: 4600, 'Pozuelo de Alarcón': 4700, Sitges: 4900, Málaga: 3600,
53
+ }
54
+ const defaultPerM2 = { NL: 3900, ES: 2300 }
55
+
56
+ // The share of the listings that give their position only roughly, common on Spanish portals.
57
+ const approximatePosition = { NL: 0.05, ES: 0.3 }
58
+
59
+ // The share of the homes for sale that are let in the meantime, common in the Netherlands (leegstandswet).
60
+ const letWhileForSale = { NL: 0.12, ES: 0.04 }
61
+
62
+ const typeWeights = {
63
+ NL: [['apartment', 40], ['house', 22], ['townhouse', 22], ['villa', 4], ['studio', 6], ['penthouse', 6]],
64
+ ES: [['apartment', 55], ['house', 10], ['townhouse', 8], ['villa', 12], ['studio', 7], ['penthouse', 8]],
65
+ } as const
66
+
67
+ const areas: Record<PropertyType, [number, number]> = { apartment: [45, 130], house: [100, 220], townhouse: [90, 180], villa: [160, 420], studio: [22, 45], penthouse: [90, 240] }
68
+ const plots: Partial<Record<PropertyType, [number, number]>> = { house: [150, 600], townhouse: [60, 180], villa: [400, 2000] }
69
+
70
+ const labels = {
71
+ NL: [['a_plus_2', 2], ['a_plus', 6], ['a', 25], ['b', 15], ['c', 20], ['d', 12], ['e', 9], ['f', 6], ['g', 5]],
72
+ ES: [['a', 6], ['b', 6], ['c', 10], ['d', 18], ['e', 33], ['f', 12], ['g', 8], [null, 7]],
73
+ } as const
74
+ const newBuildLabels = [['a_plus_4', 2], ['a_plus_3', 3], ['a_plus_2', 4], ['a_plus', 4], ['a', 3]] as const
75
+
76
+ const letters = 'ABCDEGHJKLMNPRSTVWXZ'
77
+
78
+ const addressOf = (country: 'NL' | 'ES', type: PropertyType, rand: Rand) => {
79
+ const street = pick(rand, streets[country])
80
+ const number = int(rand, 1, 240)
81
+ const flat = type === 'apartment' || type === 'penthouse' || type === 'studio'
82
+ if (country === 'NL') return `${street} ${number}${flat ? `-${int(rand, 1, 4)}` : ''}`
83
+ return `${street}, ${number}${flat ? `, ${int(rand, 1, 8)}º` : ''}`
84
+ }
85
+
86
+ const postalOf = (place: PlaceSeed, rand: Rand) =>
87
+ place.country === 'NL' ? `${place.postal}${String(int(rand, 10, 99))} ${letters[int(rand, 0, letters.length - 1)]}${letters[int(rand, 0, letters.length - 1)]}` : `${place.postal}${String(int(rand, 0, 999)).padStart(3, '0')}`
88
+
89
+ const phoneOf = (country: 'NL' | 'ES', rand: Rand) => (country === 'NL' ? `+31 6 ${int(rand, 1000, 9999)} ${int(rand, 1000, 9999)}` : `+34 6${int(rand, 10, 99)} ${int(rand, 100, 999)} ${int(rand, 100, 999)}`)
90
+
91
+ // Listings run younger: most of the year's were published in its last months.
92
+ const ageOf = (rand: Rand) => Math.floor(365 * Math.pow(rand(), 1.6) * DAY)
93
+
94
+ const statusOf = (offer: 'sale' | 'rent', age: number, rand: Rand): SeededListing['status'] => {
95
+ const days = age / DAY
96
+ const roll = rand()
97
+ if (offer === 'rent') return days > 45 && roll < 0.7 ? 'let' : days > 14 && roll < 0.8 ? 'under_offer' : 'available'
98
+ if (days > 90) return roll < 0.65 ? 'sold' : roll < 0.8 ? 'under_offer' : 'available'
99
+ if (days > 30) return roll < 0.1 ? 'sold' : roll < 0.4 ? 'under_offer' : 'available'
100
+ return 'available'
101
+ }
102
+
103
+ const captions: Record<RoomKind, string> = { living: 'Living room', kitchen: 'Kitchen', bedroom: 'Bedroom', bathroom: 'Bathroom', garden: 'Garden' }
104
+
105
+ /** Listing `ordinal`, rebuilt from its ordinal alone: a home in a place picked by weight, listed by an agency there. */
106
+ export const listingAt = (places: PlaceSeed[], agenciesByPlace: Map<number, SeededAgency[]>, agenciesByCountry: Record<'NL' | 'ES', SeededAgency[]>, ordinal: number): SeededListing => {
107
+ const rand = rngAt(401, ordinal)
108
+ const placeIndex = weighted(rand, places.map((place, index) => [index, place.weight] as const))
109
+ const place = places[placeIndex]!
110
+ const country = place.country
111
+ const agency = pick(rand, agenciesByPlace.get(placeIndex + 1) ?? agenciesByCountry[country])
112
+ const propertyType = weighted(rand, typeWeights[country]) as PropertyType
113
+ const offerType = rand() < (country === 'NL' ? 0.7 : 0.6) ? 'sale' : 'rent'
114
+ const [minArea, maxArea] = areas[propertyType]
115
+ const livingArea = int(rand, minArea, maxArea)
116
+ const rooms = propertyType === 'studio' ? 1 : Math.max(2, Math.min(9, Math.round(livingArea / 30) + int(rand, -1, 1)))
117
+ const plot = plots[propertyType]
118
+ const builtYear = propertyType === 'townhouse' && rand() < 0.6 ? int(rand, 1650, 1930) : int(rand, 1930, 2025)
119
+ const energyLabel = builtYear >= 2015 ? weighted(rand, newBuildLabels) : (weighted(rand, labels[country]) as EnergyLabel | null)
120
+ const perM2 = (pricePerM2[place.name] ?? defaultPerM2[country]) * (0.8 + rand() * 0.45) * (propertyType === 'villa' || propertyType === 'penthouse' ? 1.2 : 1)
121
+ // A draw of its own, so the rest of the listing is the same whether it is let in the meantime or not.
122
+ const alsoLet = offerType === 'sale' && rngAt(405, ordinal)() < letWhileForSale[country]
123
+ const purchasePrice = offerType === 'sale' ? Math.round((perM2 * livingArea) / 5000) * 5000 : null
124
+ const rentPrice = offerType === 'rent' || alsoLet ? Math.round((perM2 * livingArea) / 230 / 25) * 25 : null
125
+ const garden = plot !== undefined && rand() < 0.85
126
+ const balcony = !garden && rand() < 0.65
127
+ const parking = rand() < (country === 'ES' ? 0.45 : 0.25)
128
+ const draft = rand() < 0.02
129
+ const age = ageOf(rand)
130
+ const publishedAt = draft ? null : seedNow - age
131
+ const status = draft ? 'available' : statusOf(offerType, age, rand)
132
+ const sentences = [details.transport, details.quiet, details.renovated, details.original, details.insulated].filter(() => rand() < 0.35)
133
+ const description = [
134
+ `${pick(rand, openings[propertyType]!)} in ${place.name}, ${livingArea} m² with ${rooms === 1 ? 'one room' : `${rooms} rooms`}.`,
135
+ ...(garden ? [details.garden] : []),
136
+ ...(balcony ? [details.balcony] : []),
137
+ ...(parking ? [details.parking] : []),
138
+ ...sentences,
139
+ ].join(' ')
140
+ const names = agentNames[country]
141
+ const variant = int(rand, 0, 5)
142
+ const shownRooms: RoomKind[] = garden ? ['living', 'kitchen', 'bedroom', 'bathroom', 'garden'] : ['living', 'kitchen', 'bedroom', 'bathroom']
143
+ const inside = shownRooms.slice(0, int(rand, 2, 5))
144
+ const photo = exteriorPhoto(propertyType, variant)
145
+ return {
146
+ id: ordinal + 1,
147
+ agencyId: agency.id,
148
+ placeId: placeIndex + 1,
149
+ country,
150
+ propertyType,
151
+ status,
152
+ address: addressOf(country, propertyType, rand),
153
+ postalCode: postalOf(place, rand),
154
+ latitude: Number((place.latitude + (rand() - 0.5) * 0.06).toFixed(6)),
155
+ longitude: Number((place.longitude + (rand() - 0.5) * 0.09).toFixed(6)),
156
+ positionExact: rngAt(407, ordinal)() >= approximatePosition[country],
157
+ purchasePrice,
158
+ rentPrice,
159
+ livingArea,
160
+ plotArea: plot ? int(rand, plot[0], plot[1]) : null,
161
+ rooms,
162
+ bedrooms: Math.max(0, rooms - 1 - (rooms > 4 && rand() < 0.5 ? 1 : 0)),
163
+ bathrooms: 1 + (livingArea > 120 ? 1 : 0) + (propertyType === 'villa' ? 1 : 0),
164
+ builtYear,
165
+ energyLabel,
166
+ garden,
167
+ balcony,
168
+ parking,
169
+ description,
170
+ photo,
171
+ agentName: `${pick(rand, names.first)} ${pick(rand, names.last)}`,
172
+ agentPhone: phoneOf(country, rand),
173
+ publishedAt,
174
+ createdAt: (publishedAt ?? seedNow) - int(rand, 1, 6) * DAY,
175
+ photos: [{ position: 1, photo, caption: 'Outside' }, ...inside.map((kind, index) => ({ position: index + 2, photo: roomPhoto(kind, variant + index), caption: captions[kind] }))],
176
+ }
177
+ }
@@ -0,0 +1,136 @@
1
+ import { DAY, seedNow } from '../calendar'
2
+ import type { PlaceSeed } from '../data/places'
3
+ import { int, pick, rngAt, weighted } from '../rng'
4
+ import { distanceKm } from './distance'
5
+ import type { SeededListing } from './listing'
6
+ import { searchFilter, type SearchCriteria } from './search-filter'
7
+
8
+ export type SeededUser = { id: string; name: string; email: string; role: 'admin' | 'member'; createdAt: number; demo: boolean }
9
+
10
+ /** A saved search: its filter as the listings page would have saved it, and the criteria it was printed from. */
11
+ export type SeededSearch = {
12
+ id: number
13
+ userId: string
14
+ name: string
15
+ criteria: SearchCriteria
16
+ filter: string
17
+ alertFrequency: 'instant' | 'daily' | 'none'
18
+ /** When the member last opened its results: the listings published since are new to them. */
19
+ seenAt: number
20
+ createdAt: number
21
+ }
22
+
23
+ /** The accounts to sign in with, all with the demo password; their ids mark them as the seed's own. */
24
+ export const demoUsers: SeededUser[] = [
25
+ { id: 'seed-admin', name: 'Portal admin', email: 'admin@portal.example', role: 'admin', createdAt: seedNow - 400 * DAY, demo: true },
26
+ { id: 'seed-anna', name: 'Anna de Vries', email: 'anna@portal.example', role: 'member', createdAt: seedNow - 120 * DAY, demo: true },
27
+ { id: 'seed-bram', name: 'Bram Jansen', email: 'bram@portal.example', role: 'member', createdAt: seedNow - 90 * DAY, demo: true },
28
+ ]
29
+
30
+ export const demoPassword = 'property-portal-demo'
31
+
32
+ const placeId = (places: PlaceSeed[], name: string) => places.findIndex((place) => place.name === name) + 1
33
+
34
+ // The places a search of `name` takes in: it and those within `radiusKm` of its centre, as a member ticks them.
35
+ const around = (places: PlaceSeed[], name: string, radiusKm: number) => {
36
+ const centre = places[placeId(places, name) - 1]!
37
+ return places.flatMap((place, index) => (place === centre || distanceKm(centre, place) <= radiusKm ? [index + 1] : []))
38
+ }
39
+
40
+ const anything: SearchCriteria = { forSale: false, forRent: false, placeIds: [], propertyType: null, energyLabels: [], purchasePrice: null, rentPrice: null, livingArea: null, bedrooms: null, garden: false }
41
+
42
+ type SearchFields = Pick<SeededSearch, 'id' | 'userId' | 'name'> & Partial<Pick<SeededSearch, 'alertFrequency' | 'seenAt' | 'createdAt'>> & { criteria: Partial<SearchCriteria> }
43
+
44
+ const search = ({ criteria, ...fields }: SearchFields): SeededSearch => {
45
+ const full = { ...anything, ...criteria }
46
+ return { alertFrequency: 'daily', createdAt: seedNow - 80 * DAY, seenAt: seedNow - 3 * DAY, ...fields, criteria: full, filter: searchFilter(full) }
47
+ }
48
+
49
+ /** Anna looks to buy around Amsterdam, or to buy or rent a house near Haarlem; Bram to rent in Madrid or Barcelona. */
50
+ export const demoSearches = (places: PlaceSeed[]): SeededSearch[] => [
51
+ search({ id: 1, userId: 'seed-anna', name: 'Around Amsterdam', alertFrequency: 'instant', seenAt: seedNow - 21 * DAY, criteria: { forSale: true, placeIds: around(places, 'Amsterdam', 20), purchasePrice: [250_000, 950_000], livingArea: [55, 250] } }),
52
+ search({ id: 2, userId: 'seed-anna', name: 'Family house near Haarlem', seenAt: seedNow - 30 * DAY, criteria: { forSale: true, forRent: true, placeIds: around(places, 'Haarlem', 15), propertyType: 'house', bedrooms: [3, 6] } }),
53
+ search({ id: 3, userId: 'seed-bram', name: 'Piso en Madrid', seenAt: seedNow - 14 * DAY, criteria: { forRent: true, placeIds: around(places, 'Madrid', 15), rentPrice: [800, 3_000], bedrooms: [1, 4] } }),
54
+ search({ id: 4, userId: 'seed-bram', name: 'Barcelona by the sea', alertFrequency: 'none', seenAt: seedNow - 30 * DAY, criteria: { forRent: true, placeIds: around(places, 'Barcelona', 25), rentPrice: [900, 3_500] } }),
55
+ ]
56
+
57
+ const typicalPrice = { sale: { NL: 450_000, ES: 300_000 }, rent: { NL: 1_800, ES: 1_300 } }
58
+
59
+ // The share of generated profiles looking both ways, with a range for each: a draw of their own.
60
+ const lookingBothWays = 0.1
61
+
62
+ const firstNames = ['Sanne', 'Daan', 'Lotte', 'Ruben', 'Iris', 'Jesse', 'Noor', 'Lucía', 'Javier', 'Carmen', 'Pablo', 'Elena', 'Sofía', 'Diego']
63
+ const lastNames = ['de Jong', 'Bakker', 'Visser', 'Smit', 'Meijer', 'García', 'Martínez', 'López', 'Sánchez', 'Ruiz', 'Moreno', 'Peters']
64
+
65
+ /** Member `ordinal`: an account with no password, there for the volume and for other people's rows. */
66
+ export const memberAt = (ordinal: number): SeededUser => {
67
+ const rand = rngAt(501, ordinal)
68
+ const number = String(ordinal + 1).padStart(5, '0')
69
+ return { id: `seed-member-${number}`, name: `${pick(rand, firstNames)} ${pick(rand, lastNames)}`, email: `member-${number}@portal.example`, role: 'member', createdAt: seedNow - int(rand, 1, 700) * DAY, demo: false }
70
+ }
71
+
72
+ /** One to three saved searches of a generated member, in places they would look, at the prices there. */
73
+ export const searchesOf = (places: PlaceSeed[], user: SeededUser, ordinal: number, firstId: number): SeededSearch[] => {
74
+ const rand = rngAt(502, ordinal)
75
+ const country = rand() < 0.55 ? 'NL' : 'ES'
76
+ const local = places.flatMap((place, index) => (place.country === country ? [[index + 1, place.weight] as const] : []))
77
+ return Array.from({ length: int(rand, 1, 3) }, (_, index) => {
78
+ const offerType = rand() < 0.6 ? 'sale' : 'rent'
79
+ const both = rngAt(505, firstId + index)() < lookingBothWays
80
+ const typical = typicalPrice[offerType][country]
81
+ const placeId = rand() < 0.9 ? weighted(rand, local) : null
82
+ const propertyType = rand() < 0.7 ? pick(rand, ['apartment', 'house', 'townhouse', 'villa']) : null
83
+ const share = 0.7 + rand() * 0.8
84
+ const price: [number, number] = [rand() < 0.2 ? Math.round(typical * 0.5) : 0, Math.round(typical * share)]
85
+ const minArea = rand() < 0.5 ? pick(rand, [40, 60, 80, 100]) : null
86
+ const minBedrooms = rand() < 0.3 ? int(rand, 1, 3) : null
87
+ const createdAt = Math.max(user.createdAt, seedNow - int(rand, 5, 300) * DAY)
88
+ const place = placeId === null ? undefined : places[placeId - 1]!
89
+ return search({
90
+ id: firstId + index,
91
+ userId: user.id,
92
+ name: `${place?.name ?? 'Anywhere'}, ${offerType === 'sale' ? 'to buy' : 'to rent'}`,
93
+ alertFrequency: rand() < 0.4 ? 'instant' : rand() < 0.9 ? 'daily' : 'none',
94
+ createdAt,
95
+ seenAt: Math.max(createdAt, seedNow - int(rand, 0, 20) * DAY),
96
+ criteria: {
97
+ // Both ways, a home fits by the flags alone: a price range keeps out the homes not offered that way.
98
+ forSale: offerType === 'sale' || both,
99
+ forRent: offerType === 'rent' || both,
100
+ placeIds: placeId === null ? [] : [placeId],
101
+ propertyType,
102
+ purchasePrice: offerType === 'sale' && !both ? price : null,
103
+ rentPrice: offerType === 'rent' && !both ? price : null,
104
+ livingArea: minArea === null ? null : [minArea, 400],
105
+ bedrooms: minBedrooms === null ? null : [minBedrooms, 8],
106
+ energyLabels: rand() < 0.15 ? ['a_plus_2', 'a_plus', 'a', 'b'].slice(0, int(rand, 2, 4)) : [],
107
+ },
108
+ })
109
+ })
110
+ }
111
+
112
+ const noteTexts = [
113
+ 'Viewing booked for Saturday at 11:00.',
114
+ 'Ask the agent about the service charges and the reserve fund.',
115
+ 'Lovely garden, but a long way from the station.',
116
+ 'Compare with the one two streets further on.',
117
+ 'The kitchen needs work: count on about €15,000.',
118
+ 'Bid at most €10,000 over the asking price.',
119
+ 'Noisy street at rush hour; go back in the evening.',
120
+ 'Light all day. The second bedroom is small.',
121
+ 'Check the energy label paperwork before bidding.',
122
+ 'Agent said there are already three viewings planned.',
123
+ ]
124
+
125
+ /** A member's favorites among the published listings where they look, and the notes they wrote on some of them. */
126
+ export const savedBy = (user: SeededUser, ordinal: number, candidates: SeededListing[], count: number) => {
127
+ const rand = rngAt(503, ordinal)
128
+ const chosen = new Map<number, SeededListing>()
129
+ for (let tries = 0; tries < count * 3 && chosen.size < count && candidates.length > 0; tries++) {
130
+ const listing = pick(rand, candidates)
131
+ chosen.set(listing.id, listing)
132
+ }
133
+ const favorites = [...chosen.values()].map((listing) => ({ listing, createdAt: Math.min(seedNow, Math.max(user.createdAt, listing.publishedAt!) + int(rand, 1, 10) * DAY) }))
134
+ const notes = favorites.filter(() => rand() < 0.5).map(({ listing, createdAt }) => ({ listing, body: pick(rand, noteTexts), createdAt: Math.min(seedNow, createdAt + int(rand, 0, 3) * DAY) }))
135
+ return { favorites, notes }
136
+ }
@@ -0,0 +1,17 @@
1
+ import { describe, expect, it } from 'vitest'
2
+ import { readSearchFilter } from '../../config/saved_searches/filter'
3
+ import { searchFilter, type SearchCriteria } from './search-filter'
4
+
5
+ const anything: SearchCriteria = { forSale: false, forRent: false, placeIds: [], propertyType: null, energyLabels: [], purchasePrice: null, rentPrice: null, livingArea: null, bedrooms: null, garden: false }
6
+
7
+ describe('searchFilter', () => {
8
+ it('prints the criteria as the listings page prints its panel, a filter of the listings', () => {
9
+ const filter = searchFilter({ ...anything, forSale: true, forRent: true, placeIds: [1, 8], propertyType: 'house', purchasePrice: [300_000, 950_000], bedrooms: [3, 6], garden: true })
10
+ expect(filter).toBe('(for_sale = true OR for_rent = true) AND in(place_id, "1", "8") AND property_type = "house" AND purchase_price >= 300000 AND purchase_price <= 950000 AND bedrooms >= 3 AND bedrooms <= 6 AND garden = true')
11
+ expect(readSearchFilter(filter).ok).toBe(true)
12
+ })
13
+
14
+ it('is empty for a search of every listing', () => {
15
+ expect(searchFilter(anything)).toBe('')
16
+ })
17
+ })
@@ -0,0 +1,44 @@
1
+ import { createWhere, printFilter, type FilterExpr } from '@protobase/schema'
2
+
3
+ const w = createWhere()
4
+
5
+ /** What a seeded search looks for, as the listings page's filter panel sets it: each part empty when it does not narrow. */
6
+ export type SearchCriteria = {
7
+ forSale: boolean
8
+ forRent: boolean
9
+ placeIds: number[]
10
+ propertyType: string | null
11
+ energyLabels: string[]
12
+ purchasePrice: [number, number] | null
13
+ rentPrice: [number, number] | null
14
+ livingArea: [number, number] | null
15
+ bedrooms: [number, number] | null
16
+ garden: boolean
17
+ }
18
+
19
+ // The panel holds a facet's values as text, so a relation's keys print quoted too: `in(place_id, "1", "8")`.
20
+ const choice = (field: string, values: Array<string | number>): FilterExpr[] => {
21
+ const texts = values.map(String)
22
+ return texts.length === 0 ? [] : [texts.length === 1 ? w.eq(field, texts[0]!) : w.in(field, texts as never[])]
23
+ }
24
+ const range = (field: string, span: [number, number] | null): FilterExpr[] => (span ? [w.gte(field, span[0]), w.lte(field, span[1])] : [])
25
+
26
+ /**
27
+ * The search's filter as the listings page's address holds it once the panel is set so: the flags, the facets in the
28
+ * view's order, then the ranges and the toggles, as the page prints them.
29
+ */
30
+ export const searchFilter = (criteria: SearchCriteria) => {
31
+ const offers = [...(criteria.forSale ? [w.eq('for_sale', true)] : []), ...(criteria.forRent ? [w.eq('for_rent', true)] : [])]
32
+ const clauses = [
33
+ ...(offers.length === 0 ? [] : [offers.length === 1 ? offers[0]! : w.or(...offers)]),
34
+ ...choice('place_id', criteria.placeIds),
35
+ ...choice('property_type', criteria.propertyType === null ? [] : [criteria.propertyType]),
36
+ ...choice('energy_label', criteria.energyLabels),
37
+ ...range('purchase_price', criteria.purchasePrice),
38
+ ...range('rent_price', criteria.rentPrice),
39
+ ...range('living_area', criteria.livingArea),
40
+ ...range('bedrooms', criteria.bedrooms),
41
+ ...(criteria.garden ? [w.eq('garden', true)] : []),
42
+ ]
43
+ return clauses.length === 0 ? '' : printFilter(w.and(...clauses))
44
+ }
@@ -0,0 +1,4 @@
1
+ export const DAY = 86_400_000
2
+
3
+ /** The moment the sample data ends: listings are published in the year up to it. */
4
+ export const seedNow = Date.UTC(2026, 9, 12, 9, 0)
@@ -0,0 +1,50 @@
1
+ import { connect } from '../db/connection'
2
+ import { analyzeAll, createIndexes, dropIndexes, resetSequences, setTriggers, truncateAll } from './maintenance'
3
+ import { writePhotoLibrary } from './photos/library'
4
+ import { isScale, scales } from './scales'
5
+ import { seedMarket } from './steps/market'
6
+ import { seedMembers } from './steps/members'
7
+ import { buildWorld } from './world'
8
+
9
+ const flag = process.argv.indexOf('--scale')
10
+ const scale = flag === -1 ? 'small' : process.argv[flag + 1]
11
+ if (!isScale(scale)) throw new Error(`Unknown scale "${scale}", expected one of: ${Object.keys(scales).join(', ')}`)
12
+
13
+ const started = performance.now()
14
+ const step = async (name: string, run: () => Promise<unknown>) => {
15
+ const before = performance.now()
16
+ await run()
17
+ console.log(`${name} (${((performance.now() - before) / 1000).toFixed(1)}s)`)
18
+ }
19
+
20
+ let world: ReturnType<typeof buildWorld> | undefined
21
+ await step('build', async () => {
22
+ world = buildWorld(scale)
23
+ })
24
+ let photos: Awaited<ReturnType<typeof writePhotoLibrary>> | undefined
25
+ await step('photos', async () => {
26
+ photos = await writePhotoLibrary(process.env)
27
+ })
28
+
29
+ // One connection for the load, with foreign keys and checks on; only the publish trigger is off, since the seed
30
+ // writes the alerts its job would have recorded. tests/examples/property-portal/smoke.test.ts checks the rest.
31
+ const loader = connect({ max: 1 })
32
+ await step('truncate', () => truncateAll(loader))
33
+ const indexes = await dropIndexes(loader)
34
+ await setTriggers(loader, false)
35
+ try {
36
+ await step('market', () => seedMarket(loader, world!, photos!))
37
+ await step('members', () => seedMembers(loader, world!))
38
+ } finally {
39
+ await setTriggers(loader, true)
40
+ }
41
+ await loader.end()
42
+
43
+ const sql = connect({ max: 4 })
44
+ await step('indexes', () => createIndexes(sql, indexes))
45
+ await step('sequences', () => resetSequences(sql))
46
+ await sql`insert into public.seed_info (scale) values (${scale})`
47
+ await step('analyze', () => analyzeAll(sql))
48
+ await sql.end()
49
+
50
+ console.log(`seeded ${scale} in ${((performance.now() - started) / 1000).toFixed(1)}s`)
@@ -0,0 +1,22 @@
1
+ import { Readable } from 'node:stream'
2
+ import { pipeline } from 'node:stream/promises'
3
+ import type { Db } from '../db/connection'
4
+
5
+ const batchSize = 2000
6
+
7
+ function* batches(rows: Iterable<string>) {
8
+ let batch: string[] = []
9
+ for (const line of rows) {
10
+ batch.push(line)
11
+ if (batch.length < batchSize) continue
12
+ yield batch.join('')
13
+ batch = []
14
+ }
15
+ if (batch.length > 0) yield batch.join('')
16
+ }
17
+
18
+ // Streams COPY text-format rows into `schema.table (columns)`.
19
+ export const copyRows = async (sql: Db, target: string, rows: Iterable<string>) => {
20
+ const writable = await sql.unsafe(`copy ${target} from stdin`).writable()
21
+ await pipeline(Readable.from(batches(rows)), writable)
22
+ }
@@ -0,0 +1,61 @@
1
+ /** Street names, by country; a listing's address is one with a house number in the country's way. */
2
+ export const streets = {
3
+ NL: [
4
+ 'Keizersgracht', 'Prinsengracht', 'Herengracht', 'Kerkstraat', 'Molenweg', 'Dorpsstraat', 'Stationsweg', 'Julianalaan',
5
+ 'Wilhelminastraat', 'Beatrixlaan', 'Parkweg', 'Schoolstraat', 'Lindelaan', 'Eikenlaan', 'Beukenlaan', 'Rozengracht',
6
+ 'Vondelstraat', 'Van Goghstraat', 'Rembrandtlaan', 'Oranjestraat', 'Nieuwe Binnenweg', 'Burgemeester de Withstraat',
7
+ 'Koningin Emmaplein', 'Spaarne', 'Oudegracht', 'Singel', 'Havenstraat', 'Zeeweg', 'Polderweg', 'Hoofdstraat',
8
+ ],
9
+ ES: [
10
+ 'Calle Mayor', 'Calle de Serrano', 'Calle de Alcalá', 'Gran Vía', 'Avenida de la Constitución', 'Calle del Sol',
11
+ 'Paseo de Gracia', 'Carrer de Mallorca', 'Calle Real', 'Calle San Fernando', 'Avenida del Mar', 'Calle de la Paz',
12
+ 'Calle Larios', 'Calle Nueva', 'Calle de las Flores', 'Avenida de Andalucía', 'Calle Colón', 'Carrer de Balmes',
13
+ 'Calle de Velázquez', 'Paseo Marítimo', 'Calle del Carmen', 'Calle Cervantes', 'Plaza de España', 'Calle Goya',
14
+ ],
15
+ } as const
16
+
17
+ /** Agency names: a first part and a second, joined by the country's word order. */
18
+ export const agencyNames = {
19
+ NL: {
20
+ first: ['Van der Berg', 'De Vries', 'Bakker', 'Jansen', 'Visser', 'Smit', 'Mulder', 'De Boer', 'Dekker', 'Brouwer', 'Hendriks', 'Kok'],
21
+ second: ['Makelaars', 'Makelaardij', 'Wonen', 'Vastgoed', 'Woningmakelaars', 'Huis & Hypotheek'],
22
+ },
23
+ ES: {
24
+ first: ['Inmobiliaria', 'Fincas', 'Casas', 'Hogar', 'Viviendas', 'Gestión Inmobiliaria'],
25
+ second: ['del Sol', 'Mediterráneo', 'Castellana', 'Costa', 'Centro', 'Ribera', 'Atlántico', 'Alhambra', 'Retiro', 'Diagonal'],
26
+ },
27
+ } as const
28
+
29
+ /** People who show homes. */
30
+ export const agentNames = {
31
+ NL: {
32
+ first: ['Sanne', 'Daan', 'Lotte', 'Bram', 'Femke', 'Ruben', 'Iris', 'Jesse', 'Noor', 'Thijs', 'Eva', 'Lars'],
33
+ last: ['de Jong', 'Janssen', 'de Groot', 'van Dijk', 'Meijer', 'Bos', 'Vos', 'Peters', 'Hendriks', 'van Leeuwen'],
34
+ },
35
+ ES: {
36
+ first: ['Lucía', 'Javier', 'Carmen', 'Pablo', 'María', 'Alejandro', 'Elena', 'Daniel', 'Sofía', 'Sergio', 'Laura', 'Diego'],
37
+ last: ['García', 'Martínez', 'López', 'Sánchez', 'Pérez', 'Gómez', 'Fernández', 'Ruiz', 'Díaz', 'Moreno'],
38
+ },
39
+ } as const
40
+
41
+ /** The opening line of a description, by property type. */
42
+ export const openings: Record<string, readonly string[]> = {
43
+ apartment: ['A bright apartment', 'A well-kept apartment', 'A spacious flat', 'A light apartment with high ceilings'],
44
+ house: ['A family home', 'A detached house', 'A semi-detached house', 'A comfortable family house'],
45
+ townhouse: ['A characterful townhouse', 'A terraced house', 'A narrow canal-side townhouse', 'A renovated townhouse'],
46
+ villa: ['A modern villa', 'A villa with a pool', 'A light-filled villa', 'A quiet villa'],
47
+ studio: ['A compact studio', 'A smart studio', 'A studio close to everything'],
48
+ penthouse: ['A penthouse with views', 'A top-floor penthouse', 'A penthouse with a roof terrace'],
49
+ }
50
+
51
+ /** Further sentences a description may use, each about one thing. */
52
+ export const details = {
53
+ garden: 'The garden faces south and gets the sun all afternoon.',
54
+ balcony: 'The balcony is large enough for a table and four chairs.',
55
+ parking: 'A parking space comes with the home.',
56
+ renovated: 'The kitchen and bathroom were renewed recently.',
57
+ transport: 'Shops, schools and the station are within walking distance.',
58
+ quiet: 'It lies in a quiet street, close to a park.',
59
+ original: 'Original details such as the stairs and ceilings have been kept.',
60
+ insulated: 'Well insulated, with double glazing and solar panels.',
61
+ } as const
@@ -0,0 +1,54 @@
1
+ /**
2
+ * The places listings are in: name, region, latitude, longitude and how many listings it draws relative to the others.
3
+ * Coordinates are each place's centre, as a search around it measures from.
4
+ */
5
+ export type PlaceSeed = { name: string; region: string; country: 'NL' | 'ES'; latitude: number; longitude: number; weight: number; postal: string }
6
+
7
+ const nl = (name: string, region: string, latitude: number, longitude: number, weight: number, postal: string): PlaceSeed => ({ name, region, country: 'NL', latitude, longitude, weight, postal })
8
+ const es = (name: string, region: string, latitude: number, longitude: number, weight: number, postal: string): PlaceSeed => ({ name, region, country: 'ES', latitude, longitude, weight, postal })
9
+
10
+ // `postal` is the first part of the place's postal codes: four digits in the Netherlands, two (the province) in Spain.
11
+ export const places: PlaceSeed[] = [
12
+ nl('Amsterdam', 'Noord-Holland', 52.3676, 4.9041, 10, '10'),
13
+ nl('Rotterdam', 'Zuid-Holland', 51.9244, 4.4777, 8, '30'),
14
+ nl('Den Haag', 'Zuid-Holland', 52.0705, 4.3007, 7, '25'),
15
+ nl('Utrecht', 'Utrecht', 52.0907, 5.1214, 7, '35'),
16
+ nl('Eindhoven', 'Noord-Brabant', 51.4416, 5.4697, 5, '56'),
17
+ nl('Groningen', 'Groningen', 53.2194, 6.5665, 4, '97'),
18
+ nl('Haarlem', 'Noord-Holland', 52.3874, 4.6462, 4, '20'),
19
+ nl('Amstelveen', 'Noord-Holland', 52.3114, 4.8701, 2, '11'),
20
+ nl('Zaandam', 'Noord-Holland', 52.4420, 4.8292, 2, '15'),
21
+ nl('Leiden', 'Zuid-Holland', 52.1601, 4.4970, 3, '23'),
22
+ nl('Delft', 'Zuid-Holland', 52.0116, 4.3571, 2, '26'),
23
+ nl('Amersfoort', 'Utrecht', 52.1561, 5.3878, 3, '38'),
24
+ nl('Zeist', 'Utrecht', 52.0893, 5.2312, 1, '37'),
25
+ nl('Nijmegen', 'Gelderland', 51.8126, 5.8372, 3, '65'),
26
+ nl('Arnhem', 'Gelderland', 51.9851, 5.8987, 3, '68'),
27
+ nl('Zwolle', 'Overijssel', 52.5168, 6.0830, 2, '80'),
28
+ nl('Maastricht', 'Limburg', 50.8514, 5.6910, 2, '62'),
29
+ nl('Breda', 'Noord-Brabant', 51.5719, 4.7683, 3, '48'),
30
+ nl('Tilburg', 'Noord-Brabant', 51.5555, 5.0913, 3, '50'),
31
+ nl('Den Bosch', 'Noord-Brabant', 51.6978, 5.3037, 2, '52'),
32
+ nl('Almere', 'Flevoland', 52.3508, 5.2647, 3, '13'),
33
+ nl('Hilversum', 'Noord-Holland', 52.2292, 5.1669, 2, '12'),
34
+ es('Madrid', 'Comunidad de Madrid', 40.4168, -3.7038, 10, '28'),
35
+ es('Barcelona', 'Cataluña', 41.3874, 2.1686, 9, '08'),
36
+ es('Valencia', 'Comunitat Valenciana', 39.4699, -0.3763, 6, '46'),
37
+ es('Sevilla', 'Andalucía', 37.3891, -5.9845, 5, '41'),
38
+ es('Málaga', 'Andalucía', 36.7213, -4.4214, 5, '29'),
39
+ es('Marbella', 'Andalucía', 36.5101, -4.8825, 3, '29'),
40
+ es('Granada', 'Andalucía', 37.1773, -3.5986, 2, '18'),
41
+ es('Bilbao', 'País Vasco', 43.2630, -2.9350, 3, '48'),
42
+ es('San Sebastián', 'País Vasco', 43.3183, -1.9812, 2, '20'),
43
+ es('Zaragoza', 'Aragón', 41.6488, -0.8891, 3, '50'),
44
+ es('Alicante', 'Comunitat Valenciana', 38.3452, -0.4810, 4, '03'),
45
+ es('Palma', 'Illes Balears', 39.5696, 2.6502, 3, '07'),
46
+ es('Las Palmas de Gran Canaria', 'Canarias', 28.1235, -15.4363, 2, '35'),
47
+ es('Getafe', 'Comunidad de Madrid', 40.3057, -3.7329, 1, '28'),
48
+ es('Pozuelo de Alarcón', 'Comunidad de Madrid', 40.4351, -3.8135, 1, '28'),
49
+ es('Sitges', 'Cataluña', 41.2370, 1.8059, 1, '08'),
50
+ es('Badalona', 'Cataluña', 41.4500, 2.2474, 1, '08'),
51
+ es('Girona', 'Cataluña', 41.9794, 2.8214, 1, '17'),
52
+ es('Santander', 'Cantabria', 43.4623, -3.8099, 1, '39'),
53
+ es('Valladolid', 'Castilla y León', 41.6523, -4.7245, 1, '47'),
54
+ ]
@@ -0,0 +1,20 @@
1
+ const escapes: Record<string, string> = { '\\': '\\\\', '\t': '\\t', '\n': '\\n', '\r': '\\r' }
2
+
3
+ const cell = (value: unknown) => {
4
+ if (value === null || value === undefined) return '\\N'
5
+ return String(value).replace(/[\\\t\n\r]/g, (char) => escapes[char]!)
6
+ }
7
+
8
+ // One COPY text-format row.
9
+ export const row = (...values: unknown[]) => values.map(cell).join('\t') + '\n'
10
+
11
+ export const iso = (ms: number) => new Date(ms).toISOString()
12
+
13
+ export const slugify = (text: string) =>
14
+ text
15
+ .normalize('NFD')
16
+ .replace(/[̀-ͯ]/g, '')
17
+ .toLowerCase()
18
+ .replace(/&/g, 'and')
19
+ .replace(/[^a-z0-9]+/g, '-')
20
+ .replace(/^-|-$/g, '')