saaslayer 0.0.1 → 0.0.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.
@@ -0,0 +1,21 @@
1
+ // Kept in lockstep with @revenue-engine/typeid — same API, same byte format.
2
+ export const TYPEID_ALPHABET: string
3
+ export const TYPEID_SUFFIX_LENGTH: 26
4
+ export const MAX_CALLER_ID_LENGTH: 255
5
+
6
+ export type ParsedTypeId = {
7
+ prefix: string
8
+ suffix: string
9
+ }
10
+
11
+ export function uuidV7BytesFromEntropy(timestampMs: number, entropy: Uint8Array): Buffer
12
+ export function encodeTypeIdSuffix(bytes: Uint8Array): string
13
+ export function isValidTypeIdSuffix(value: unknown): boolean
14
+ export function generateTypeId(prefix: string, approvedPrefixes?: Iterable<string> | Set<string>): string
15
+ export function generateTypeIdSuffix(): string
16
+ export function typeIdFromBytes(prefix: string, bytes: Uint8Array, approvedPrefixes?: Iterable<string> | Set<string>): string
17
+ export function parseTypeId(id: unknown, approvedPrefixes?: Iterable<string> | Set<string>): ParsedTypeId | null
18
+ export function isTypeId(id: unknown, approvedPrefixes?: Iterable<string> | Set<string>): boolean
19
+ export function assertTypeIdPrefix(id: string, expectedPrefix: string, approvedPrefixes?: Iterable<string> | Set<string>): void
20
+ export function validateCallerId(id: unknown): string
21
+ export function validateRefId(fieldName: string, value: unknown): unknown
@@ -0,0 +1,237 @@
1
+ // The platform's single id generator — a verbatim port of @revenue-engine/typeid (byte-identical ids:
2
+ // monotonic UUIDv7 encoded as a 26-char TypeID base32 suffix, lowercase). CommonJS for the saaslayer
3
+ // service runtime. generateTypeIdSuffix() -> the BARE k-sortable body (custom:suid); generateTypeId(prefix,
4
+ // approvedPrefixes) -> "<prefix>_<body>". Keep this in lockstep with @revenue-engine/typeid.
5
+ const { randomBytes } = require('node:crypto')
6
+
7
+ const TYPEID_ALPHABET = '0123456789abcdefghjkmnpqrstvwxyz'
8
+ const TYPEID_SUFFIX_LENGTH = 26
9
+ const MAX_CALLER_ID_LENGTH = 255
10
+
11
+ const TYPEID_ALPHABET_SET = new Set(TYPEID_ALPHABET)
12
+ const PREFIX_PATTERN = /^[a-z][a-z0-9_]{0,62}$/
13
+
14
+ let lastTs = 0
15
+ let seq = 0
16
+
17
+ function assertPrefix(prefix) {
18
+ if (typeof prefix !== 'string' || !PREFIX_PATTERN.test(prefix)) {
19
+ throw new Error(`Invalid TypeID prefix: "${prefix}"`)
20
+ }
21
+ }
22
+
23
+ function normalizeApprovedPrefixes(prefixes) {
24
+ if (!prefixes) return null
25
+ return prefixes instanceof Set ? prefixes : new Set(prefixes)
26
+ }
27
+
28
+ function assertApprovedPrefix(prefix, approvedPrefixes) {
29
+ const set = normalizeApprovedPrefixes(approvedPrefixes)
30
+ assertPrefix(prefix)
31
+ if (set && !set.has(prefix)) {
32
+ throw new Error(`Unknown TypeID prefix: "${prefix}"`)
33
+ }
34
+ }
35
+
36
+ function uuidV7Bytes() {
37
+ const now = Date.now()
38
+ if (now > lastTs) {
39
+ lastTs = now
40
+ seq = 0
41
+ } else {
42
+ seq += 1
43
+ if (seq > 0xfff) {
44
+ while (Date.now() <= lastTs) { /* spin to the next ms */ }
45
+ lastTs = Date.now()
46
+ seq = 0
47
+ }
48
+ }
49
+
50
+ const buf = Buffer.alloc(16)
51
+ writeTimestamp(buf, lastTs)
52
+ buf[6] = 0x70 | ((seq >> 8) & 0x0f)
53
+ buf[7] = seq & 0xff
54
+
55
+ const rand = randomBytes(8)
56
+ buf[8] = 0x80 | (rand[0] & 0x3f)
57
+ buf[9] = rand[1]
58
+ buf[10] = rand[2]
59
+ buf[11] = rand[3]
60
+ buf[12] = rand[4]
61
+ buf[13] = rand[5]
62
+ buf[14] = rand[6]
63
+ buf[15] = rand[7]
64
+ return buf
65
+ }
66
+
67
+ function writeTimestamp(buf, timestampMs) {
68
+ const hi = Math.floor(timestampMs / 0x100000000)
69
+ const lo = timestampMs - hi * 0x100000000
70
+ buf.writeUInt16BE(hi, 0)
71
+ buf.writeUInt32BE(lo, 2)
72
+ }
73
+
74
+ function uuidV7BytesFromEntropy(timestampMs, entropy) {
75
+ if (!Number.isSafeInteger(timestampMs) || timestampMs < 0 || timestampMs > 0xffffffffffff) {
76
+ throw new Error(`Invalid UUIDv7 timestamp: ${timestampMs}`)
77
+ }
78
+ if (!(entropy instanceof Uint8Array) || entropy.length < 10) {
79
+ throw new Error('UUIDv7 entropy must be at least 10 bytes')
80
+ }
81
+
82
+ const buf = Buffer.alloc(16)
83
+ writeTimestamp(buf, timestampMs)
84
+ buf[6] = 0x70 | (entropy[0] & 0x0f)
85
+ buf[7] = entropy[1]
86
+ buf[8] = 0x80 | (entropy[2] & 0x3f)
87
+ buf[9] = entropy[3]
88
+ buf[10] = entropy[4]
89
+ buf[11] = entropy[5]
90
+ buf[12] = entropy[6]
91
+ buf[13] = entropy[7]
92
+ buf[14] = entropy[8]
93
+ buf[15] = entropy[9]
94
+ return buf
95
+ }
96
+
97
+ function encodeTypeIdSuffix(bytes) {
98
+ if (!(bytes instanceof Uint8Array) || bytes.length !== 16) {
99
+ throw new Error('TypeID suffix encoding requires exactly 16 bytes')
100
+ }
101
+
102
+ let n = 0n
103
+ for (let i = 0; i < 16; i += 1) {
104
+ n = (n << 8n) | BigInt(bytes[i])
105
+ }
106
+
107
+ const chars = new Array(TYPEID_SUFFIX_LENGTH)
108
+ for (let i = TYPEID_SUFFIX_LENGTH - 1; i >= 0; i -= 1) {
109
+ chars[i] = TYPEID_ALPHABET[Number(n & 0x1fn)]
110
+ n >>= 5n
111
+ }
112
+ return chars.join('')
113
+ }
114
+
115
+ function isValidTypeIdSuffix(value) {
116
+ if (typeof value !== 'string' || value.length !== TYPEID_SUFFIX_LENGTH) return false
117
+ if (!'01234567'.includes(value[0].toLowerCase())) return false
118
+ for (let i = 0; i < value.length; i += 1) {
119
+ if (!TYPEID_ALPHABET_SET.has(value[i].toLowerCase())) return false
120
+ }
121
+ return true
122
+ }
123
+
124
+ function generateTypeId(prefix, approvedPrefixes) {
125
+ assertApprovedPrefix(prefix, approvedPrefixes)
126
+ return `${prefix}_${encodeTypeIdSuffix(uuidV7Bytes())}`
127
+ }
128
+
129
+ function generateTypeIdSuffix() {
130
+ return encodeTypeIdSuffix(uuidV7Bytes())
131
+ }
132
+
133
+ function typeIdFromBytes(prefix, bytes, approvedPrefixes) {
134
+ assertApprovedPrefix(prefix, approvedPrefixes)
135
+ return `${prefix}_${encodeTypeIdSuffix(bytes)}`
136
+ }
137
+
138
+ function parseTypeId(id, approvedPrefixes) {
139
+ if (typeof id !== 'string' || id.length === 0) return null
140
+ const idx = id.lastIndexOf('_')
141
+ if (idx < 1) return null
142
+
143
+ const prefix = id.slice(0, idx).toLowerCase()
144
+ const suffix = id.slice(idx + 1).toLowerCase()
145
+ if (!PREFIX_PATTERN.test(prefix)) return null
146
+ const set = normalizeApprovedPrefixes(approvedPrefixes)
147
+ if (set && !set.has(prefix)) return null
148
+ if (!isValidTypeIdSuffix(suffix)) return null
149
+ return { prefix, suffix }
150
+ }
151
+
152
+ function isTypeId(id, approvedPrefixes) {
153
+ return parseTypeId(id, approvedPrefixes) !== null
154
+ }
155
+
156
+ function assertTypeIdPrefix(id, expectedPrefix, approvedPrefixes) {
157
+ const parsed = parseTypeId(id, approvedPrefixes)
158
+ if (!parsed) {
159
+ throw new Error(`Value is not a TypeID: "${id}"`)
160
+ }
161
+ if (parsed.prefix !== expectedPrefix) {
162
+ throw new Error(`Expected TypeID prefix "${expectedPrefix}" but got "${parsed.prefix}"`)
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Shape checks shared by caller-chosen ids and references: string, non-empty after trim, bounded, no control
168
+ * characters, no "#" key delimiter.
169
+ * @param {unknown} id
170
+ * @returns {string} trimmed id
171
+ */
172
+ function validateIdShape(id) {
173
+ if (typeof id !== 'string') {
174
+ throw new TypeError('Caller ID must be a string')
175
+ }
176
+
177
+ const trimmed = id.trim()
178
+ if (!trimmed) {
179
+ throw new Error('Caller ID must not be empty after trimming')
180
+ }
181
+ if (trimmed.length > MAX_CALLER_ID_LENGTH) {
182
+ throw new Error(`Caller ID exceeds max length of ${MAX_CALLER_ID_LENGTH}`)
183
+ }
184
+ if (/[\x00-\x1f\x7f]/.test(trimmed)) {
185
+ throw new Error('Caller ID must not contain ASCII control characters')
186
+ }
187
+ if (trimmed.includes('#')) {
188
+ throw new Error('Caller ID must not contain "#" (DynamoDB key delimiter)')
189
+ }
190
+ return trimmed
191
+ }
192
+
193
+ /**
194
+ * Validate a caller-chosen id for a new entity. Rejects "*" so an id can never act as a wildcard when substituted
195
+ * into a pattern (F18: `like` + `${subject.id}`).
196
+ * @param {unknown} id
197
+ * @returns {string} trimmed id
198
+ */
199
+ function validateCallerId(id) {
200
+ const trimmed = validateIdShape(id)
201
+ if (trimmed.includes('*')) {
202
+ throw new Error('Caller ID must not contain "*" (pattern wildcard)')
203
+ }
204
+ return trimmed
205
+ }
206
+
207
+ /**
208
+ * Validate a reference field (an existing id, or a scope where "*" keeps its catch-all meaning).
209
+ * @param {string} fieldName
210
+ * @param {unknown} value
211
+ */
212
+ function validateRefId(fieldName, value) {
213
+ if (value == null) return value
214
+ try {
215
+ return validateIdShape(value)
216
+ } catch (err) {
217
+ const message = err instanceof Error ? err.message : String(err)
218
+ throw new Error(`${fieldName}: ${message}`)
219
+ }
220
+ }
221
+
222
+ module.exports = {
223
+ TYPEID_ALPHABET,
224
+ TYPEID_SUFFIX_LENGTH,
225
+ MAX_CALLER_ID_LENGTH,
226
+ uuidV7BytesFromEntropy,
227
+ encodeTypeIdSuffix,
228
+ isValidTypeIdSuffix,
229
+ generateTypeId,
230
+ generateTypeIdSuffix,
231
+ typeIdFromBytes,
232
+ parseTypeId,
233
+ isTypeId,
234
+ assertTypeIdPrefix,
235
+ validateCallerId,
236
+ validateRefId,
237
+ }