@supatype/types 0.9.2 → 0.10.1
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/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +23 -15
- package/.turbo/turbo-typecheck.log +1 -1
- package/CHANGELOG.md +19 -1
- package/dist/auth-settings-groups.d.ts +216 -0
- package/dist/auth-settings-groups.d.ts.map +1 -0
- package/dist/auth-settings-groups.js +424 -0
- package/dist/auth-settings-groups.js.map +1 -0
- package/dist/auth-settings.d.ts +168 -0
- package/dist/auth-settings.d.ts.map +1 -0
- package/dist/auth-settings.js +501 -0
- package/dist/auth-settings.js.map +1 -0
- package/dist/function-secret-name.d.ts +14 -0
- package/dist/function-secret-name.d.ts.map +1 -0
- package/dist/function-secret-name.js +20 -0
- package/dist/function-secret-name.js.map +1 -0
- package/dist/index.d.ts +145 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -1
- package/dist/index.js.map +1 -1
- package/dist/public-env.d.ts +70 -0
- package/dist/public-env.d.ts.map +1 -0
- package/dist/public-env.js +146 -0
- package/dist/public-env.js.map +1 -0
- package/dist/seed-contract.d.ts +103 -0
- package/dist/seed-contract.d.ts.map +1 -0
- package/dist/seed-contract.js +99 -0
- package/dist/seed-contract.js.map +1 -0
- package/package.json +1 -1
- package/src/auth-settings-groups.ts +604 -0
- package/src/auth-settings.ts +649 -0
- package/src/function-secret-name.ts +21 -0
- package/src/index.ts +176 -2
- package/src/public-env.ts +167 -0
- package/src/seed-contract.ts +167 -0
- package/tests/auth-settings-groups.test.ts +342 -0
- package/tests/auth-settings.test.ts +327 -0
- package/tests/bucket-access.test.ts +33 -1
- package/tests/channel.test.ts +94 -0
- package/tests/function-secret-name.test.ts +17 -0
- package/tests/public-env.test.ts +179 -0
- package/tests/seed-contract.test.ts +110 -0
- package/tests/standalone-build.test.ts +35 -0
- package/tsconfig.json +2 -1
- package/tsconfig.tsbuildinfo +1 -1
package/src/index.ts
CHANGED
|
@@ -168,8 +168,42 @@ export type BucketRole<R extends string = string> = Access<"BucketRole", {
|
|
|
168
168
|
readonly role: R
|
|
169
169
|
}>
|
|
170
170
|
|
|
171
|
-
/**
|
|
172
|
-
|
|
171
|
+
/**
|
|
172
|
+
* The `N`th folder of an object's path, counting from 1: in `u1/photos/a.png`, `Folder<1>` is `u1`
|
|
173
|
+
* and `Folder<2>` is `photos`. Null when the path is not that deep, so a comparison denies.
|
|
174
|
+
*
|
|
175
|
+
* Bucket rules only: a model's rule reads its own columns. `Eq<Folder<1>, AuthUid>` on `create` and
|
|
176
|
+
* `update` keeps each user to their own folder; `BucketOwner` alone does not, because the storage
|
|
177
|
+
* service writes `owner` as the caller on every upload whatever the path says.
|
|
178
|
+
*/
|
|
179
|
+
export type Folder<TIndex extends number> = Access<"Folder", {
|
|
180
|
+
readonly kind: "Folder"
|
|
181
|
+
readonly index: TIndex
|
|
182
|
+
}>
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* A rule one bucket operation can take: a `Bucket*` rule, or a rule about the caller (`AuthUid`,
|
|
186
|
+
* `AuthRole`, `Claim`) and the object's path (`Folder`) joined with `Any`, `All` and `Not`.
|
|
187
|
+
* Rules that name a model's columns are refused, naming the bucket and the operation.
|
|
188
|
+
*/
|
|
189
|
+
export type BucketRule =
|
|
190
|
+
| BucketPublic
|
|
191
|
+
| BucketPrivate
|
|
192
|
+
| BucketLoggedIn
|
|
193
|
+
| BucketOwner
|
|
194
|
+
| BucketRole<string>
|
|
195
|
+
| Any<readonly unknown[]>
|
|
196
|
+
| All<readonly unknown[]>
|
|
197
|
+
| Not<unknown>
|
|
198
|
+
| Eq<unknown, unknown>
|
|
199
|
+
| Neq<unknown, unknown>
|
|
200
|
+
| Gt<unknown, unknown>
|
|
201
|
+
| Gte<unknown, unknown>
|
|
202
|
+
| Lt<unknown, unknown>
|
|
203
|
+
| Lte<unknown, unknown>
|
|
204
|
+
| Like<unknown, unknown>
|
|
205
|
+
| IsNull<unknown>
|
|
206
|
+
| NotNull<unknown>
|
|
173
207
|
|
|
174
208
|
/**
|
|
175
209
|
* A bucket's rules on `storage.objects`: the same four operations as {@link ModelMeta.access}, each
|
|
@@ -891,6 +925,135 @@ export type Exists<TSource> = Access<"Exists", {
|
|
|
891
925
|
readonly kind: "Exists"
|
|
892
926
|
readonly source: TSource
|
|
893
927
|
}>
|
|
928
|
+
|
|
929
|
+
// ─── Realtime channels ───────────────────────────────────────────────────────
|
|
930
|
+
//
|
|
931
|
+
// A channel is declared the way a bucket is: an exported type alias that only `@supatype/cli`
|
|
932
|
+
// reads. The pattern names the topics it covers, `params` types the `{name}` segments, and
|
|
933
|
+
// `access` holds one rule per operation. The same rule language as a model, with the
|
|
934
|
+
// channel's parameters standing where a model has a row's columns.
|
|
935
|
+
|
|
936
|
+
/**
|
|
937
|
+
* A channel pattern's parameter, used inside a `Rows<>` filter: `Eq<"id", Param<"id">>`.
|
|
938
|
+
*
|
|
939
|
+
* At the top level of a channel rule a bare string already names a parameter
|
|
940
|
+
* (`In<"id", MyLots>`), exactly as a bare string names a column on a model. Inside a `Rows<>`
|
|
941
|
+
* filter a bare string is a column of the source table, which is why a parameter needs this
|
|
942
|
+
* operand there. `Param<>` is also accepted at the top level for authors who prefer to be explicit.
|
|
943
|
+
*
|
|
944
|
+
* Only valid in a {@link Channel} rule: anywhere else the CLI refuses it at extract time.
|
|
945
|
+
*/
|
|
946
|
+
export type Param<TName extends string> = Access<"Param", {
|
|
947
|
+
readonly kind: "Param"
|
|
948
|
+
readonly name: TName
|
|
949
|
+
}>
|
|
950
|
+
|
|
951
|
+
/**
|
|
952
|
+
* The broadcast event name, for a `send` rule: `All<[Event<"bid">, ...]>`.
|
|
953
|
+
*
|
|
954
|
+
* Checked by the realtime server against each message, with no database call. Only valid inside
|
|
955
|
+
* `send`, and only as a member of `All<[...]>`: under `Any` or `Not` the database could not say
|
|
956
|
+
* what it means. A message whose event is not named is refused.
|
|
957
|
+
*/
|
|
958
|
+
export type Event<TName extends string> = Access<"Event", {
|
|
959
|
+
readonly kind: "Event"
|
|
960
|
+
readonly name: TName
|
|
961
|
+
}>
|
|
962
|
+
|
|
963
|
+
/**
|
|
964
|
+
* What a broadcast payload's field must be. The set is closed because the realtime server
|
|
965
|
+
* evaluates it per message.
|
|
966
|
+
*
|
|
967
|
+
* - `string`: a string, at most `maxLength` characters when given.
|
|
968
|
+
* - `number`: a finite number, within `min` and `max` when given.
|
|
969
|
+
* - `boolean`: a boolean.
|
|
970
|
+
* - `required`: present and not null, of any type.
|
|
971
|
+
*/
|
|
972
|
+
export type PayloadCheck =
|
|
973
|
+
| { readonly kind: "string"; readonly maxLength?: number }
|
|
974
|
+
| { readonly kind: "number"; readonly min?: number; readonly max?: number }
|
|
975
|
+
| { readonly kind: "boolean" }
|
|
976
|
+
| { readonly kind: "required" }
|
|
977
|
+
|
|
978
|
+
/**
|
|
979
|
+
* A rule on one field of the broadcast payload, for a `send` rule:
|
|
980
|
+
* `Payload<"amount", { kind: "number"; min: 1 }>`.
|
|
981
|
+
*
|
|
982
|
+
* Shape only. Whether the amount is a good bid is for an RPC function, since a broadcast is
|
|
983
|
+
* not a transaction. Only valid inside `send`, and only as a member of `All<[...]>`.
|
|
984
|
+
*/
|
|
985
|
+
export type Payload<TField extends string, TCheck extends PayloadCheck> = Access<"Payload", {
|
|
986
|
+
readonly kind: "Payload"
|
|
987
|
+
readonly field: TField
|
|
988
|
+
readonly check: TCheck
|
|
989
|
+
}>
|
|
990
|
+
|
|
991
|
+
/** What a channel parameter can hold. A closed set: each one is a pattern and a cast in the engine. */
|
|
992
|
+
export type ChannelParamType = UUID | string | Int
|
|
993
|
+
|
|
994
|
+
/** The `{name}` segments of a channel pattern: `ChannelParamNames<"a:{x}:{y}">` is `"x" | "y"`. */
|
|
995
|
+
export type ChannelParamNames<TPattern extends string> =
|
|
996
|
+
TPattern extends `${string}{${infer TName}}${infer TRest}` ? TName | ChannelParamNames<TRest> : never
|
|
997
|
+
|
|
998
|
+
/** A rule one channel operation can take. The model rule language, minus the row-bound rules. */
|
|
999
|
+
export type ChannelRule = Public | Private | LoggedIn | Role<string> | ComposedAccessRule
|
|
1000
|
+
|
|
1001
|
+
/** What `send` can take beyond a {@link ChannelRule}: checks on the event and the payload. */
|
|
1002
|
+
export type ChannelSendRule = ChannelRule | Event<string> | Payload<string, PayloadCheck>
|
|
1003
|
+
|
|
1004
|
+
/**
|
|
1005
|
+
* A channel's rules. An operation left out is denied to every caller but the service role, as on
|
|
1006
|
+
* a model. At least one must be declared.
|
|
1007
|
+
*
|
|
1008
|
+
* - `join`: subscribe, and receive broadcasts and presence.
|
|
1009
|
+
* - `send`: broadcast on the channel.
|
|
1010
|
+
* - `track`: appear in the channel's presence.
|
|
1011
|
+
*/
|
|
1012
|
+
export type ChannelAccess = {
|
|
1013
|
+
join?: ChannelRule
|
|
1014
|
+
send?: ChannelSendRule
|
|
1015
|
+
track?: ChannelRule
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
/** Second generic on {@link Channel}. `params` types every `{name}` in the pattern, and only those. */
|
|
1019
|
+
export type ChannelConfig<TPattern extends string = string> = {
|
|
1020
|
+
params?: { readonly [K in ChannelParamNames<TPattern>]: ChannelParamType }
|
|
1021
|
+
access: ChannelAccess
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
/** Makes a `params` key the pattern does not name a type error, which an object type alone lets through. */
|
|
1025
|
+
type NoExtraParams<TPattern extends string, TConfig extends { params?: unknown }> = {
|
|
1026
|
+
params?: { readonly [K in Exclude<keyof NonNullable<TConfig["params"]>, ChannelParamNames<TPattern>>]: never }
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
/**
|
|
1030
|
+
* Declares a realtime channel. Export `type LotChannel = Channel<"lot:{id}", { ... }>`.
|
|
1031
|
+
*
|
|
1032
|
+
* ```ts
|
|
1033
|
+
* type MyLots = Rows<"lot_watchers", "lot_id", Eq<"user_id", AuthUid>>
|
|
1034
|
+
*
|
|
1035
|
+
* export type LotChannel = Channel<"lot:{id}", {
|
|
1036
|
+
* params: { id: UUID }
|
|
1037
|
+
* access: {
|
|
1038
|
+
* join: Any<[In<"id", MyLots>, Role<"auctioneer">]>
|
|
1039
|
+
* send: Exists<Rows<"lots", "id", All<[Eq<"id", Param<"id">>, Eq<"seller_id", AuthUid>]>>>
|
|
1040
|
+
* track: All<[LoggedIn, In<"id", MyLots>]>
|
|
1041
|
+
* }
|
|
1042
|
+
* }>
|
|
1043
|
+
* ```
|
|
1044
|
+
*
|
|
1045
|
+
* A pattern is `:`-separated segments: a literal, a `{name}` that matches one segment, or a final
|
|
1046
|
+
* `*` that matches one or more remaining segments. Two declarations that can match the same topic
|
|
1047
|
+
* are refused. Parameters are `UUID`, `string` or `Int`, and the engine checks the shape before
|
|
1048
|
+
* the cast, so `lot:abc` against `{ id: UUID }` is "does not fit" rather than a Postgres error.
|
|
1049
|
+
*
|
|
1050
|
+
* Declaring a channel enforces its pattern at once, for every client. `realtime.channels` in
|
|
1051
|
+
* `supatype.config.ts` decides what happens to a topic no declaration matches.
|
|
1052
|
+
*/
|
|
1053
|
+
export type Channel<
|
|
1054
|
+
TPattern extends string,
|
|
1055
|
+
TConfig extends ChannelConfig<TPattern> & NoExtraParams<TPattern, TConfig>,
|
|
1056
|
+
> = Primitive<`Channel:${TPattern}`, { pattern: TPattern; config: TConfig }>
|
|
894
1057
|
type BoundOwnerForFields<TFields extends Record<string, unknown>> = Access<"Owner", {
|
|
895
1058
|
readonly kind: "Owner"
|
|
896
1059
|
readonly key: OwnerEligibleFieldKeys<TFields>
|
|
@@ -1461,3 +1624,14 @@ export type LocalizedModel<
|
|
|
1461
1624
|
TFields extends Record<string, unknown>,
|
|
1462
1625
|
TMeta extends LocalizedModelMeta<TFields> = {},
|
|
1463
1626
|
> = Model<ApplyAutoLocalizedFields<TFields>, TMeta>
|
|
1627
|
+
|
|
1628
|
+
export * from "./public-env.js"
|
|
1629
|
+
export * from "./seed-contract.js"
|
|
1630
|
+
export * from "./auth-settings.js"
|
|
1631
|
+
export * from "./auth-settings-groups.js"
|
|
1632
|
+
export {
|
|
1633
|
+
FUNCTION_SECRET_NAME_PATTERN,
|
|
1634
|
+
FUNCTION_SECRET_NAME_RULE,
|
|
1635
|
+
functionSecretNameProblem,
|
|
1636
|
+
isFunctionSecretName,
|
|
1637
|
+
} from "./function-secret-name.js"
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A static site's public values: the non-secret settings its pages read, set per environment in
|
|
3
|
+
* `build.publicEnv` of supatype.config.ts or in Studio, served at `/supatype-env.js` and passed to
|
|
4
|
+
* the build under each framework's prefix. Every visitor can read them, so what may be one is
|
|
5
|
+
* decided here, once, for the CLI, the self-host control plane and the checks Cloud repeats.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/** Each framework's public prefix: Vite, SvelteKit and Astro (`PUBLIC_`), Next.js, Expo. */
|
|
9
|
+
export const FRONTEND_PUBLIC_PREFIXES = ["VITE_", "PUBLIC_", "NEXT_PUBLIC_", "EXPO_PUBLIC_"] as const
|
|
10
|
+
|
|
11
|
+
/** Prefixes a name may not start with: a framework's, which the build adds itself, and Supatype's own. */
|
|
12
|
+
const RESERVED_PREFIXES: readonly string[] = [...FRONTEND_PUBLIC_PREFIXES, "SUPATYPE_"]
|
|
13
|
+
|
|
14
|
+
/** What a project may set. Bytes are UTF-8 bytes. */
|
|
15
|
+
export const PUBLIC_ENV_LIMITS = {
|
|
16
|
+
/** Values a project may set. */
|
|
17
|
+
names: 50,
|
|
18
|
+
/** One name. */
|
|
19
|
+
nameBytes: 64,
|
|
20
|
+
/** One value. */
|
|
21
|
+
valueBytes: 2048,
|
|
22
|
+
/** Every name and value together. */
|
|
23
|
+
totalBytes: 16384,
|
|
24
|
+
} as const
|
|
25
|
+
|
|
26
|
+
/** Upper-case letters, digits and underscores, starting with a letter: a name every framework and shell accepts. */
|
|
27
|
+
export const PUBLIC_ENV_NAME = /^[A-Z][A-Z0-9_]*$/
|
|
28
|
+
|
|
29
|
+
/** `build.publicEnv`: a value for every environment, or a map of environment name to value. */
|
|
30
|
+
export type PublicEnvDeclaration = Readonly<Record<string, string | Readonly<Record<string, string>>>>
|
|
31
|
+
|
|
32
|
+
/** An environment name as Cloud accepts it. */
|
|
33
|
+
export const ENVIRONMENT_NAME = /^[a-z0-9][a-z0-9_-]{0,62}$/
|
|
34
|
+
|
|
35
|
+
const isObject = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value)
|
|
36
|
+
|
|
37
|
+
/** Whether `value` is a `build.publicEnv`: each name one string, or a map of environment name to string. */
|
|
38
|
+
export function isPublicEnvDeclaration(value: unknown): value is PublicEnvDeclaration {
|
|
39
|
+
if (!isObject(value)) return false
|
|
40
|
+
return Object.values(value).every(
|
|
41
|
+
(entry) =>
|
|
42
|
+
typeof entry === "string" ||
|
|
43
|
+
(isObject(entry) && Object.entries(entry).every(([environment, text]) => ENVIRONMENT_NAME.test(environment) && typeof text === "string")),
|
|
44
|
+
)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Where a value is set: the config's build.publicEnv (read-only in Studio), or Studio. */
|
|
48
|
+
export const PUBLIC_ENV_SOURCES = ["config", "studio"] as const
|
|
49
|
+
export type PublicEnvSource = (typeof PUBLIC_ENV_SOURCES)[number]
|
|
50
|
+
|
|
51
|
+
/** How each source is said to a person. */
|
|
52
|
+
export const PUBLIC_ENV_SOURCE_LABELS: Readonly<Record<PublicEnvSource, string>> = {
|
|
53
|
+
config: "set in supatype.config.ts",
|
|
54
|
+
studio: "set in Studio",
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** One value in effect on an environment, with where it is set. */
|
|
58
|
+
export interface PublicEnvEntry {
|
|
59
|
+
name: string
|
|
60
|
+
value: string
|
|
61
|
+
source: PublicEnvSource
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Whether `value` is a {@link PublicEnvEntry}. */
|
|
65
|
+
export function isPublicEnvEntry(value: unknown): value is PublicEnvEntry {
|
|
66
|
+
if (!isObject(value)) return false
|
|
67
|
+
return typeof value["name"] === "string" && typeof value["value"] === "string" && PUBLIC_ENV_SOURCES.some((source) => source === value["source"])
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** One refusal. `name` is the value's name, or empty for a problem with the set as a whole. */
|
|
71
|
+
export interface PublicEnvProblem {
|
|
72
|
+
name: string
|
|
73
|
+
reason: string
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const bytesOf = (text: string): number => new TextEncoder().encode(text).length
|
|
77
|
+
|
|
78
|
+
const PRIVATE_KEY_BLOCK = /-----BEGIN [A-Z ]*PRIVATE KEY-----/
|
|
79
|
+
/** Stripe's secret and restricted keys: `sk_live_...`, `sk_test_...`, `rk_live_...`. */
|
|
80
|
+
const SECRET_KEY_PREFIX = /\b(?:sk|rk)_[A-Za-z0-9_]{6,}/
|
|
81
|
+
|
|
82
|
+
/** The role claim of a JWT, or undefined for anything that is not one. The signature is not checked. */
|
|
83
|
+
function jwtRole(value: string): string | undefined {
|
|
84
|
+
const parts = value.split(".")
|
|
85
|
+
if (parts.length !== 3 || parts[1] === undefined) return undefined
|
|
86
|
+
try {
|
|
87
|
+
const payload = atob(parts[1].replace(/-/g, "+").replace(/_/g, "/"))
|
|
88
|
+
const claims: unknown = JSON.parse(payload)
|
|
89
|
+
if (typeof claims !== "object" || claims === null || !("role" in claims)) return undefined
|
|
90
|
+
return typeof claims.role === "string" ? claims.role : undefined
|
|
91
|
+
} catch {
|
|
92
|
+
return undefined
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Why `value` looks like a secret, or undefined when it does not: a private key block, an `sk_` or
|
|
98
|
+
* `rk_` key, a token claiming the service role, or one of `secrets` (a key the caller holds). The
|
|
99
|
+
* reason never repeats the value.
|
|
100
|
+
*/
|
|
101
|
+
export function secretLookingReason(value: string, secrets: readonly string[] = []): string | undefined {
|
|
102
|
+
if (PRIVATE_KEY_BLOCK.test(value)) return "looks like a private key"
|
|
103
|
+
if (SECRET_KEY_PREFIX.test(value)) return "looks like a secret key (sk_ or rk_)"
|
|
104
|
+
if (jwtRole(value) === "service_role") return "is a service role key"
|
|
105
|
+
if (secrets.some((secret) => secret !== "" && secret === value)) return "is a secret this project holds"
|
|
106
|
+
return undefined
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function nameProblem(name: string): string | undefined {
|
|
110
|
+
if (!PUBLIC_ENV_NAME.test(name)) return "must be upper case letters, digits and underscores, starting with a letter"
|
|
111
|
+
if (bytesOf(name) > PUBLIC_ENV_LIMITS.nameBytes) return `must be at most ${PUBLIC_ENV_LIMITS.nameBytes} bytes`
|
|
112
|
+
const reserved = RESERVED_PREFIXES.find((prefix) => name.startsWith(prefix))
|
|
113
|
+
if (reserved !== undefined) return `must not start with ${reserved}: the build adds each framework's prefix itself, and SUPATYPE_ names are Supatype's own`
|
|
114
|
+
return undefined
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Everything wrong with `values` as one environment's public values, each said once: a name that is
|
|
119
|
+
* not allowed, a value over the limit or that looks secret, and a set over its limits. Empty when
|
|
120
|
+
* `values` may be set. `secrets` are keys the caller holds that no value may equal.
|
|
121
|
+
*/
|
|
122
|
+
export function publicEnvProblems(values: Readonly<Record<string, string>>, secrets: readonly string[] = []): PublicEnvProblem[] {
|
|
123
|
+
const problems: PublicEnvProblem[] = []
|
|
124
|
+
const entries = Object.entries(values)
|
|
125
|
+
for (const [name, value] of entries) {
|
|
126
|
+
const bad = nameProblem(name)
|
|
127
|
+
if (bad !== undefined) problems.push({ name, reason: bad })
|
|
128
|
+
if (bytesOf(value) > PUBLIC_ENV_LIMITS.valueBytes) problems.push({ name, reason: `must be at most ${PUBLIC_ENV_LIMITS.valueBytes} bytes` })
|
|
129
|
+
const secret = secretLookingReason(value, secrets)
|
|
130
|
+
if (secret !== undefined) problems.push({ name, reason: `${secret}, and every visitor can read a public value` })
|
|
131
|
+
}
|
|
132
|
+
if (entries.length > PUBLIC_ENV_LIMITS.names) problems.push({ name: "", reason: `at most ${PUBLIC_ENV_LIMITS.names} values may be set` })
|
|
133
|
+
const total = entries.reduce((sum, [name, value]) => sum + bytesOf(name) + bytesOf(value), 0)
|
|
134
|
+
if (total > PUBLIC_ENV_LIMITS.totalBytes) problems.push({ name: "", reason: `the values may total at most ${PUBLIC_ENV_LIMITS.totalBytes} bytes` })
|
|
135
|
+
return problems
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* The values `declared` gives environment `environment`: a plain string for every environment, an
|
|
140
|
+
* entry of a map for the one it names. A name whose map does not name the environment is left out.
|
|
141
|
+
*/
|
|
142
|
+
export function publicEnvFor(declared: PublicEnvDeclaration | undefined, environment: string): Record<string, string> {
|
|
143
|
+
const values: Record<string, string> = {}
|
|
144
|
+
for (const [name, value] of Object.entries(declared ?? {})) {
|
|
145
|
+
if (typeof value === "string") values[name] = value
|
|
146
|
+
else if (Object.hasOwn(value, environment)) {
|
|
147
|
+
const picked = value[environment]
|
|
148
|
+
if (picked !== undefined) values[name] = picked
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return values
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Each value under every framework's prefix, the names a build reads: `MAPS_KEY` is `VITE_MAPS_KEY`, `NEXT_PUBLIC_MAPS_KEY` and so on. */
|
|
155
|
+
export function prefixedPublicEnv(values: Readonly<Record<string, string>>): Record<string, string> {
|
|
156
|
+
return Object.fromEntries(
|
|
157
|
+
Object.entries(values).flatMap(([name, value]) => FRONTEND_PUBLIC_PREFIXES.map((prefix) => [`${prefix}${name}`, value] as const)),
|
|
158
|
+
)
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* The refusals as one message, naming each value and never repeating it. A problem with the set as
|
|
163
|
+
* a whole has no name and is said as the public values'.
|
|
164
|
+
*/
|
|
165
|
+
export function publicEnvRefusal(problems: readonly PublicEnvProblem[], separator = "; "): string {
|
|
166
|
+
return problems.map((p) => (p.name === "" ? `The public values: ${p.reason}` : `${p.name} ${p.reason}`)).join(separator)
|
|
167
|
+
}
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The request and answers of a remote seed: `supatype seed` against a linked Cloud project or a
|
|
3
|
+
* linked self-hosted server. Both control planes serve the same routes from this one shape, so a
|
|
4
|
+
* seed behaves the same on either.
|
|
5
|
+
*
|
|
6
|
+
* `POST /projects/:ref/seed` takes {@link RemoteSeedRequest} and answers {@link RemoteSeedApplied}.
|
|
7
|
+
* `GET /projects/:ref/seed/status` answers {@link RemoteSeedStatus}. Both read the target
|
|
8
|
+
* environment from the `X-Supatype-Environment` header, as every other project route does.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** The capability feature a control plane lists when it serves the seed routes. */
|
|
12
|
+
export const REMOTE_SEED_FEATURE = "seed"
|
|
13
|
+
|
|
14
|
+
/** Default caps on one request. A control plane may raise them per project. */
|
|
15
|
+
export const REMOTE_SEED_MAX_BODY_BYTES = 10 * 1024 * 1024
|
|
16
|
+
export const REMOTE_SEED_MAX_FILES = 100
|
|
17
|
+
|
|
18
|
+
/** What the CLI sends to apply seeds. */
|
|
19
|
+
export interface RemoteSeedRequest {
|
|
20
|
+
/** The schema AST, as push sends it. */
|
|
21
|
+
readonly ast: unknown
|
|
22
|
+
/**
|
|
23
|
+
* Each seed file's collected document, as the exact JSON text the CLI made, with its `file` key.
|
|
24
|
+
* Strings rather than objects: the engine's run-once ledger hashes this text, and parsing and
|
|
25
|
+
* re-serialising it on the server would change the hash.
|
|
26
|
+
*/
|
|
27
|
+
readonly irDocuments: readonly string[]
|
|
28
|
+
readonly atomic: boolean
|
|
29
|
+
readonly runOnce: boolean
|
|
30
|
+
/**
|
|
31
|
+
* The name a seed's `environment` condition reads. Absent means the target environment's
|
|
32
|
+
* name. A value that differs from the target is refused.
|
|
33
|
+
*/
|
|
34
|
+
readonly environment?: string
|
|
35
|
+
/** Must be true when the target is production. The server checks it, not only the CLI. */
|
|
36
|
+
readonly confirmProduction: boolean
|
|
37
|
+
/** Where the request came from, as push's audit fields give it. */
|
|
38
|
+
readonly pushedFrom?: string
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The answer when the engine ran, whether or not the seed applied. */
|
|
42
|
+
export interface RemoteSeedApplied {
|
|
43
|
+
/** The engine's seed result document, unchanged. */
|
|
44
|
+
readonly data: unknown
|
|
45
|
+
readonly run: { readonly id: string }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The answer to a status request. */
|
|
49
|
+
export interface RemoteSeedStatus {
|
|
50
|
+
/** The engine's seed status document, unchanged. */
|
|
51
|
+
readonly data: unknown
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The `error` codes a remote seed refusal carries, beside a human `message`. */
|
|
55
|
+
export const REMOTE_SEED_REFUSALS = [
|
|
56
|
+
"validation_error",
|
|
57
|
+
"environment_mismatch",
|
|
58
|
+
"production_confirmation_required",
|
|
59
|
+
"seed_busy",
|
|
60
|
+
"schema_not_pushed",
|
|
61
|
+
"payload_too_large",
|
|
62
|
+
"seed_too_large_for_plan",
|
|
63
|
+
"server_busy",
|
|
64
|
+
] as const
|
|
65
|
+
|
|
66
|
+
export type RemoteSeedRefusal = (typeof REMOTE_SEED_REFUSALS)[number]
|
|
67
|
+
|
|
68
|
+
/** Whether `value` is one of the refusal codes. */
|
|
69
|
+
export function isRemoteSeedRefusal(value: unknown): value is RemoteSeedRefusal {
|
|
70
|
+
return REMOTE_SEED_REFUSALS.some((code) => code === value)
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** A seed the plan cannot run: the plan, the seed's size, and the most that plan takes. */
|
|
74
|
+
export interface RemoteSeedPlanLimit {
|
|
75
|
+
readonly plan: string
|
|
76
|
+
readonly seedBytes: number
|
|
77
|
+
readonly maxBytes: number
|
|
78
|
+
/** True for a staging or preview seed, which is sized and capped as Free whatever the project's plan. */
|
|
79
|
+
readonly nonProduction?: boolean
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** A size as whole megabytes, rounded up so a limit is never shown as less than it is over. */
|
|
83
|
+
const megabytes = (bytes: number): string => `${Math.max(1, Math.ceil(bytes / (1024 * 1024)))} MB`
|
|
84
|
+
|
|
85
|
+
/** What a request over a cap names: the byte size, or the file count. */
|
|
86
|
+
export type RemoteSeedLimit = { readonly maxBytes: number } | { readonly maxFiles: number }
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The words of every refusal whose text does not depend on what the request said. Both control
|
|
90
|
+
* planes build their refusal from this table, so the same refusal reads the same on either host.
|
|
91
|
+
* `validation_error` is not here: its text is whatever the body check found wrong.
|
|
92
|
+
*/
|
|
93
|
+
export const REMOTE_SEED_MESSAGES = {
|
|
94
|
+
environment_mismatch: (said: { readonly requested: string; readonly target: string }): string =>
|
|
95
|
+
`The seed's environment condition is "${said.requested}" but the target is "${said.target}". ` +
|
|
96
|
+
`Seed with --env ${said.requested}, or drop --environment.`,
|
|
97
|
+
production_confirmation_required: (): string =>
|
|
98
|
+
"This seed targets production. Confirm it (supatype seed --confirm-production) and send it again.",
|
|
99
|
+
seed_busy: (): string => "Another seed is already running on this environment. Wait for it to finish.",
|
|
100
|
+
schema_not_pushed: (said: { readonly environment: string; readonly changes: number }): string =>
|
|
101
|
+
`The ${said.environment} database does not have the schema in this seed yet (${said.changes} change(s) to push). ` +
|
|
102
|
+
`Run \`supatype push --env ${said.environment}\` first.`,
|
|
103
|
+
payload_too_large: (said: RemoteSeedLimit): string =>
|
|
104
|
+
"maxBytes" in said
|
|
105
|
+
? `A seed request may be at most ${said.maxBytes} bytes.`
|
|
106
|
+
: `At most ${said.maxFiles} seed files can be sent at once.`,
|
|
107
|
+
seed_too_large_for_plan: (said: RemoteSeedPlanLimit): string =>
|
|
108
|
+
said.nonProduction === true
|
|
109
|
+
? `This seed is ${megabytes(said.seedBytes)}. Staging and preview environments run at Free size on every plan and take seeds up to ${megabytes(said.maxBytes)}, ` +
|
|
110
|
+
"so no plan raises that. Split it into smaller seed files and seed them one after another, or seed production."
|
|
111
|
+
: `This seed is ${megabytes(said.seedBytes)}, more than the ${said.plan} plan can run at once (up to ${megabytes(said.maxBytes)}). ` +
|
|
112
|
+
"Split it into smaller seed files and seed them one after another, or move to a larger plan.",
|
|
113
|
+
server_busy: (): string =>
|
|
114
|
+
"The server is taking as many seed uploads as it can right now. Wait a moment and send the seed again.",
|
|
115
|
+
} as const
|
|
116
|
+
|
|
117
|
+
/** A refusal as the CLI prints it: its code in brackets, then its message. */
|
|
118
|
+
export function formatRemoteSeedRefusal(code: RemoteSeedRefusal, message: string): string {
|
|
119
|
+
return `[${code}] ${message}`
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** A refusal body: 400, 409, 413 or 503, with no engine run. */
|
|
123
|
+
export interface RemoteSeedRefused {
|
|
124
|
+
readonly error: RemoteSeedRefusal
|
|
125
|
+
readonly message: string
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
129
|
+
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Checks a parsed request body. Answers the request, or a message naming what is wrong, so both
|
|
134
|
+
* control planes refuse a bad body with the same words.
|
|
135
|
+
*/
|
|
136
|
+
export function parseRemoteSeedRequest(body: unknown): RemoteSeedRequest | { readonly invalid: string } {
|
|
137
|
+
if (!isRecord(body)) return { invalid: "The body must be a JSON object." }
|
|
138
|
+
const { ast, irDocuments, atomic, runOnce, environment, confirmProduction, pushedFrom } = body
|
|
139
|
+
if (ast === undefined || ast === null) return { invalid: "`ast` is required." }
|
|
140
|
+
if (!Array.isArray(irDocuments) || irDocuments.length === 0) {
|
|
141
|
+
return { invalid: "`irDocuments` must be a non-empty array of strings." }
|
|
142
|
+
}
|
|
143
|
+
if (!irDocuments.every((doc): doc is string => typeof doc === "string")) {
|
|
144
|
+
return { invalid: "Every entry of `irDocuments` must be a string." }
|
|
145
|
+
}
|
|
146
|
+
if (irDocuments.length > REMOTE_SEED_MAX_FILES) {
|
|
147
|
+
return { invalid: `At most ${REMOTE_SEED_MAX_FILES} seed files can be sent at once.` }
|
|
148
|
+
}
|
|
149
|
+
if (typeof atomic !== "boolean" || typeof runOnce !== "boolean" || typeof confirmProduction !== "boolean") {
|
|
150
|
+
return { invalid: "`atomic`, `runOnce` and `confirmProduction` must be booleans." }
|
|
151
|
+
}
|
|
152
|
+
if (environment !== undefined && (typeof environment !== "string" || environment.trim() === "")) {
|
|
153
|
+
return { invalid: "`environment` must be a non-empty string when given." }
|
|
154
|
+
}
|
|
155
|
+
if (pushedFrom !== undefined && typeof pushedFrom !== "string") {
|
|
156
|
+
return { invalid: "`pushedFrom` must be a string when given." }
|
|
157
|
+
}
|
|
158
|
+
return {
|
|
159
|
+
ast,
|
|
160
|
+
irDocuments,
|
|
161
|
+
atomic,
|
|
162
|
+
runOnce,
|
|
163
|
+
confirmProduction,
|
|
164
|
+
...(environment !== undefined && { environment }),
|
|
165
|
+
...(pushedFrom !== undefined && { pushedFrom }),
|
|
166
|
+
}
|
|
167
|
+
}
|