@env-ctrl/angular 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Andrei Shelenhouski
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,114 @@
1
- # Temporary Holding Version
1
+ # @env-ctrl/angular
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Runtime configuration for Angular apps from [env-ctrl](https://envctrl.com): API URLs, feature flags, analytics IDs,
4
+ anything that is safe to ship to the browser. Change a value in env-ctrl and the next page load picks it up, with no
5
+ rebuild and no `environment.prod.ts`.
6
+
7
+ ```bash
8
+ npm i @env-ctrl/angular
9
+ ```
10
+
11
+ ```ts
12
+ // app.config.ts
13
+ import { provideEnvCtrl } from '@env-ctrl/angular';
14
+
15
+ export const appConfig: ApplicationConfig = {
16
+ providers: [
17
+ provideEnvCtrl({ token: 'ec_pub_…' }), // a *public* token: it is visible in the bundle, by design
18
+ ],
19
+ };
20
+ ```
21
+
22
+ ```ts
23
+ // anywhere: components, services, guards, interceptors
24
+ import { injectEnvCtrl } from '@env-ctrl/angular';
25
+
26
+ const env = injectEnvCtrl<'API_URL' | 'SENTRY_DSN' | 'BETA_CHECKOUT'>();
27
+ env.require('API_URL'); // string, or an error naming the key
28
+ env.get('SENTRY_DSN'); // string | undefined
29
+ env.boolean('BETA_CHECKOUT', false);
30
+ env.number('RETRIES', 3);
31
+ ```
32
+
33
+ The values are loaded by an app initializer, so they are there before the first component renders.
34
+
35
+ ## Which environment?
36
+
37
+ The token decides: each public token belongs to one environment of one project, and the API returns that
38
+ environment's values. To deploy **one build** to several environments, give one token per site address and the app
39
+ picks it by the host it is served on:
40
+
41
+ ```ts
42
+ provideEnvCtrl({
43
+ token: {
44
+ 'shop.com': 'ec_pub_…', // prod
45
+ 'staging.shop.com': 'ec_pub_…', // stage
46
+ '*.preview.shop.com': 'ec_pub_…', // preview deployments (subdomains only)
47
+ localhost: 'ec_pub_…', // dev, any port ('localhost:4200' for one port)
48
+ },
49
+ });
50
+ ```
51
+
52
+ Matching: exact `host:port`, then exact host, then the longest `*.` wildcard (with a port it matches that port only), then a `'*'` entry. An address with no
53
+ match uses `fallback`, or fails with an error naming the host. In the browser the host is `location.host`; with SSR
54
+ it is the request's `Host` header, which Angular checks against `allowedHosts` (keep that list tight). Prerendered
55
+ pages have no request, so the browser picks the token there.
56
+
57
+ All tokens of the map are in the bundle. That is fine for public tokens; restrict each to its site's origin.
58
+
59
+ ## Public tokens only
60
+
61
+ A public token (`ec_pub_…`, project → *Access tokens* → Public) returns **only the keys you mark _public_** in env-ctrl,
62
+ never secrets. Everything it returns ends up in your users' browsers, so treat it that way. Restrict the token to your
63
+ origins (and IP ranges, if any) when you create it; it is rate limited.
64
+
65
+ ### Guard against pasting the wrong token
66
+
67
+ Only public tokens get through, before anything is sent:
68
+
69
+ - **Compile time.** `token` (and every value of a token map) is typed `` `ec_pub_${string}` ``: a service (`ec_svc_…`), agent (`ec_mcp_…`) or personal
70
+ (`ec_pat_…`) token in `app.config.ts` is a type error in the editor and fails `ng build` / `ng serve`.
71
+ - **Start-up.** If the type is bypassed (a `string` from elsewhere, `as any`), `provideEnvCtrl()` throws at once with
72
+ what the token is and what to do. The token is never put in a request. A secret token that reached frontend code is
73
+ already exposed: revoke it.
74
+
75
+ For server-side secrets use `@env-ctrl/node` or the CLI (`npx @env-ctrl/cli run -- node server.js`) with a service
76
+ token instead.
77
+
78
+ ## Options
79
+
80
+ | Option | Default | |
81
+ |---|---|---|
82
+ | `token` | required | Public token, or one per site address (see *Which environment?*). Without one (e.g. local development) the `fallback` values are used. |
83
+ | `apiUrl` | `https://api.envctrl.com` | Your domain when self-hosted. |
84
+ | `timeoutMs` | `5000` | Give up on the request after this long. |
85
+ | `cache` | `true` | Keep the last values in `localStorage` and use them when env-ctrl can't be reached (network error, timeout, 5xx, 429). Never after 401/403: a revoked token stops working. |
86
+ | `maxCacheAgeMs` | 7 days | Ignore older cached values. |
87
+ | `fallback` | none | Values to use when nothing else is available. |
88
+ | `onError` | `'throw'` | When nothing can be loaded: `'throw'` fails the bootstrap, `'warn'` logs and starts with `fallback` (empty if none). A 401/403 (revoked token, origin or IP not allowed) never uses the cache or the fallback, so it always ends up here. |
89
+ | `transferState` | `true` | SSR: pass the server's values to the browser so it doesn't fetch them again. |
90
+ | `serverOrigin` | the page's origin | SSR: the `Origin` header the server sends, for tokens limited to origins. Set it only if the server sees another address than users (a proxy rewriting `Host`). |
91
+
92
+ `env.source` tells where the values came from: `network`, `cache`, `fallback` or `transfer`.
93
+
94
+ ## Server-side rendering
95
+
96
+ With `@angular/ssr` the server fetches the configs once per request and hands them to the browser in the page
97
+ (`TransferState`), so the browser does not request them again. The server sends the page's origin as `Origin`, so
98
+ origin-restricted tokens work. It never writes the cache. If the server's fetch fails, it renders with the fallback
99
+ and the browser loads the values itself, so the page may change once they arrive.
100
+
101
+ The server keeps each answer in memory for 60 seconds (the API's own cache time) and concurrent renders share one
102
+ request: public tokens are rate limited per client IP, and all your SSR traffic comes from the server's IP. If the
103
+ token has an IP allow-list, add the server's outgoing address. Behind a proxy the host and origin come from the
104
+ forwarded request URL (`X-Forwarded-Host` / `-Proto`), not the internal `Host` header.
105
+
106
+ Prerendered pages (`RenderMode.Prerender`) are built without a request: the server does not fetch (values would be
107
+ frozen at build time) and renders with `fallback`; the browser loads current values on start.
108
+
109
+ ## Requirements
110
+
111
+ Angular 20 or newer (standalone `ApplicationConfig`, `provideAppInitializer`, `REQUEST` for SSR). With `NgModule` bootstrapping, add
112
+ `provideEnvCtrl(...)` to the root module's `providers`.
113
+
114
+ MIT licensed.
package/dist/core.d.ts ADDED
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Framework-free part: fetches the public configs of one env-ctrl environment, with an offline cache.
3
+ * Public tokens (ec_pub_…) return only keys marked public, never secrets: these values end up in the
4
+ * browser, so anything served here must be safe to expose.
5
+ */
6
+ export declare const DEFAULT_API_URL = "https://api.envctrl.com";
7
+ /**
8
+ * A public token. The type rejects service (ec_svc_), agent (ec_mcp_) and personal (ec_pat_) tokens at compile time:
9
+ * those read secrets and must never be in a browser bundle.
10
+ */
11
+ export type PublicToken = `ec_pub_${string}`;
12
+ /**
13
+ * Throws unless the token is a public one, without sending it anywhere. A secret token that reached a frontend is
14
+ * already exposed, so the message says to revoke it.
15
+ */
16
+ export declare function assertPublicToken(token: string | undefined): void;
17
+ /**
18
+ * One public token per site address, for one build deployed to several environments:
19
+ * `{ 'shop.com': 'ec_pub_…', 'staging.shop.com': 'ec_pub_…', '*.preview.shop.com': 'ec_pub_…', localhost: 'ec_pub_…' }`.
20
+ * Keys are host names, optionally with a port ('localhost:4200'), a leading wildcard ('*.example.com', subdomains
21
+ * only) or '*' for anything else.
22
+ */
23
+ export type TokenByHost = Readonly<Record<string, PublicToken>>;
24
+ /** Every token of the option, to check them all up front. */
25
+ export declare function tokensOf(token: PublicToken | TokenByHost | '' | undefined): string[];
26
+ /**
27
+ * The token for this host: exact host:port, then exact host, then the longest matching wildcard, then '*'.
28
+ * Undefined when nothing matches.
29
+ */
30
+ export declare function tokenForHost(token: PublicToken | TokenByHost | '' | undefined, host: string | undefined): string | undefined;
31
+ export interface PublicConfigOptions {
32
+ /**
33
+ * Public token (ec_pub_…), created in the project's Access tokens tab, or one per site address (TokenByHost).
34
+ * Other kinds of token fail to compile.
35
+ */
36
+ token: PublicToken | TokenByHost | '' | undefined;
37
+ /** Default https://api.envctrl.com (self-hosted: your domain). */
38
+ apiUrl?: string;
39
+ /** Abort the request after this many milliseconds (default 5000). */
40
+ timeoutMs?: number;
41
+ /**
42
+ * Keep the last values in localStorage and use them when the API can't be reached (network error, timeout, 5xx,
43
+ * 429), never after 401/403 (revoked token). Default true.
44
+ */
45
+ cache?: boolean;
46
+ /** Ignore cached values older than this (default 7 days). */
47
+ maxCacheAgeMs?: number;
48
+ /** Used when nothing else is available (API down and no cache, or no token in development). */
49
+ fallback?: Record<string, string>;
50
+ /**
51
+ * Origin header for fetches on the server (SSR). Default: the origin of the page request, so origin-restricted
52
+ * tokens (each token of a map with its own site) pass. Set it when the server sees a different address than users,
53
+ * e.g. 'https://shop.example.com' behind a proxy that rewrites Host.
54
+ */
55
+ serverOrigin?: string;
56
+ }
57
+ export type ConfigSource = 'network' | 'cache' | 'fallback' | 'transfer';
58
+ export interface LoadedConfig {
59
+ values: Record<string, string>;
60
+ source: ConfigSource;
61
+ /** When the values were fetched from the API (ISO timestamp); absent for fallback values. */
62
+ fetchedAt?: string;
63
+ /** Why the API was not used, when source is cache or fallback. */
64
+ error?: string;
65
+ }
66
+ export declare class EnvCtrlError extends Error {
67
+ readonly status?: number | undefined;
68
+ readonly name = "EnvCtrlError";
69
+ constructor(message: string, status?: number | undefined);
70
+ }
71
+ interface Env {
72
+ fetch: typeof fetch;
73
+ storage: Pick<Storage, 'getItem' | 'setItem'> | null;
74
+ now: () => number;
75
+ /** True on the server: the Origin header is set (serverOrigin, else the request's origin). */
76
+ server: boolean;
77
+ /** SSR: origin of the page request, sent as Origin when serverOrigin is not set. */
78
+ origin: string | undefined;
79
+ /** Host the app is served on (browser: location.host; SSR: the request's Host), to pick from a TokenByHost. */
80
+ host: string | undefined;
81
+ }
82
+ /** Test hook: forget the server-side cache. */
83
+ export declare function clearServerCache(): void;
84
+ export declare function loadPublicConfig(opts: PublicConfigOptions, env?: Partial<Env>): Promise<LoadedConfig>;
85
+ export {};
package/dist/core.js ADDED
@@ -0,0 +1,220 @@
1
+ /**
2
+ * Framework-free part: fetches the public configs of one env-ctrl environment, with an offline cache.
3
+ * Public tokens (ec_pub_…) return only keys marked public, never secrets: these values end up in the
4
+ * browser, so anything served here must be safe to expose.
5
+ */
6
+ export const DEFAULT_API_URL = 'https://api.envctrl.com';
7
+ const WEEK_MS = 7 * 24 * 60 * 60 * 1000;
8
+ const SECRET_PREFIXES = {
9
+ ec_svc_: 'a service token (reads secrets)',
10
+ ec_mcp_: 'an agent (MCP) token',
11
+ ec_pat_: 'a personal access token (acts as you in every workspace)',
12
+ };
13
+ /**
14
+ * Throws unless the token is a public one, without sending it anywhere. A secret token that reached a frontend is
15
+ * already exposed, so the message says to revoke it.
16
+ */
17
+ export function assertPublicToken(token) {
18
+ if (!token)
19
+ return;
20
+ const t = token.trim();
21
+ const secret = Object.keys(SECRET_PREFIXES).find((p) => t.startsWith(p));
22
+ if (secret) {
23
+ throw new EnvCtrlError(`env-ctrl: this is ${SECRET_PREFIXES[secret]}, not a public token. It must never be in browser code: ` +
24
+ 'revoke it in env-ctrl (project → Access tokens) and create a Public token (ec_pub_…) instead.');
25
+ }
26
+ if (!t.startsWith('ec_pub_')) {
27
+ throw new EnvCtrlError('env-ctrl: not a public token (expected ec_pub_…; create one in project → Access tokens → Public).');
28
+ }
29
+ }
30
+ /** Every token of the option, to check them all up front. */
31
+ export function tokensOf(token) {
32
+ if (!token)
33
+ return [];
34
+ return typeof token === 'string' ? [token] : Object.values(token);
35
+ }
36
+ /**
37
+ * The token for this host: exact host:port, then exact host, then the longest matching wildcard, then '*'.
38
+ * Undefined when nothing matches.
39
+ */
40
+ export function tokenForHost(token, host) {
41
+ if (!token || typeof token === 'string')
42
+ return token ? token.trim() : undefined;
43
+ if (!host)
44
+ return token['*']?.trim();
45
+ const map = new Map(Object.entries(token).map(([k, v]) => [k.trim().toLowerCase(), v.trim()]));
46
+ const withPort = host.trim().toLowerCase();
47
+ const name = withPort.replace(/:\d+$/, '').replace(/^\[|\]$/g, '');
48
+ const exact = map.get(withPort) ?? map.get(name);
49
+ if (exact)
50
+ return exact;
51
+ let best;
52
+ for (const [k, v] of map) {
53
+ if (!k.startsWith('*.'))
54
+ continue;
55
+ // '*.example.com:8080' matches that port only; '*.example.com' any port.
56
+ const target = /:\d+$/.test(k) ? withPort : name;
57
+ if (target.endsWith(k.slice(1)) && (!best || k.length > best[0]))
58
+ best = [k.length, v];
59
+ }
60
+ return best?.[1] ?? map.get('*');
61
+ }
62
+ export class EnvCtrlError extends Error {
63
+ status;
64
+ name = 'EnvCtrlError';
65
+ constructor(message, status) {
66
+ super(message);
67
+ this.status = status;
68
+ }
69
+ }
70
+ function defaultStorage() {
71
+ try {
72
+ return typeof localStorage === 'undefined' ? null : localStorage;
73
+ }
74
+ catch {
75
+ return null; // e.g. blocked third-party storage
76
+ }
77
+ }
78
+ function cacheKey(apiUrl, token) {
79
+ // The token is public; the tail is enough to tell environments apart without storing it whole.
80
+ return `envctrl.public:${apiUrl}:${token.slice(-12)}`;
81
+ }
82
+ /** Network errors, timeouts, 5xx and 429 count as an outage; 4xx (401 revoked, 403 origin) do not. */
83
+ function isOutage(status) {
84
+ return status === undefined || status === 429 || status >= 500;
85
+ }
86
+ /**
87
+ * SSR: every render needs the configs, and the API limits public requests per client IP (one server = one IP).
88
+ * Answers are shared per API URL + token for SERVER_TTL_MS (the API's own max-age), and concurrent renders share one
89
+ * request.
90
+ */
91
+ const SERVER_TTL_MS = 60_000;
92
+ const serverCache = new Map();
93
+ const inFlight = new Map();
94
+ /** Test hook: forget the server-side cache. */
95
+ export function clearServerCache() {
96
+ serverCache.clear();
97
+ inFlight.clear();
98
+ }
99
+ export async function loadPublicConfig(opts, env = {}) {
100
+ const e = {
101
+ fetch: env.fetch ?? globalThis.fetch.bind(globalThis),
102
+ storage: env.storage === undefined ? defaultStorage() : env.storage,
103
+ now: env.now ?? Date.now,
104
+ server: env.server ?? false,
105
+ host: env.host ?? (typeof location === 'undefined' ? undefined : location.host),
106
+ origin: env.origin,
107
+ };
108
+ const fallback = (error) => ({ values: { ...(opts.fallback ?? {}) }, source: 'fallback', error });
109
+ if (!opts.token)
110
+ return fallback('no token');
111
+ // Before any request: a secret token must not end up in a URL or a log.
112
+ for (const t of tokensOf(opts.token))
113
+ assertPublicToken(t);
114
+ const token = tokenForHost(opts.token, e.host);
115
+ if (!token) {
116
+ const why = `no token for ${e.host ?? 'this host'} (add it to the token map, or a '*' entry)`;
117
+ if (opts.fallback)
118
+ return fallback(why);
119
+ throw new EnvCtrlError(`env-ctrl: ${why}`);
120
+ }
121
+ const apiUrl = (opts.apiUrl ?? DEFAULT_API_URL).replace(/\/+$/, '');
122
+ const useCache = opts.cache !== false && !e.server;
123
+ const key = cacheKey(apiUrl, token);
124
+ const skey = `${apiUrl}|${token}`; // server memory only: the whole token is fine as a key
125
+ if (e.server) {
126
+ const hit = serverCache.get(skey);
127
+ if (hit && e.now() - hit.at < SERVER_TTL_MS)
128
+ return { values: { ...hit.values }, source: 'network', fetchedAt: hit.fetchedAt };
129
+ }
130
+ try {
131
+ let values;
132
+ if (e.server) {
133
+ let p = inFlight.get(skey);
134
+ if (!p) {
135
+ p = fetchValues(apiUrl, token, opts, e).finally(() => inFlight.delete(skey));
136
+ inFlight.set(skey, p);
137
+ }
138
+ values = { ...(await p) };
139
+ }
140
+ else {
141
+ values = await fetchValues(apiUrl, token, opts, e);
142
+ }
143
+ const fetchedAt = new Date(e.now()).toISOString();
144
+ if (e.server)
145
+ serverCache.set(skey, { at: e.now(), values, fetchedAt });
146
+ if (useCache) {
147
+ try {
148
+ e.storage?.setItem(key, JSON.stringify({ values, fetchedAt }));
149
+ }
150
+ catch {
151
+ // quota / private mode: the cache is only a convenience
152
+ }
153
+ }
154
+ return { values, source: 'network', fetchedAt };
155
+ }
156
+ catch (err) {
157
+ const status = err instanceof EnvCtrlError ? err.status : undefined;
158
+ const message = err instanceof Error ? err.message : String(err);
159
+ if (!isOutage(status))
160
+ throw err;
161
+ if (useCache) {
162
+ const cached = readCache(e, key, opts.maxCacheAgeMs ?? WEEK_MS);
163
+ if (cached)
164
+ return { ...cached, source: 'cache', error: message };
165
+ }
166
+ if (opts.fallback)
167
+ return fallback(message);
168
+ throw err;
169
+ }
170
+ }
171
+ async function fetchValues(apiUrl, token, opts, e) {
172
+ const ctrl = new AbortController();
173
+ const timer = setTimeout(() => ctrl.abort(), opts.timeoutMs ?? 5000);
174
+ // Token in the query: a plain GET without custom headers needs no CORS preflight.
175
+ const url = `${apiUrl}/v1/public/config?token=${encodeURIComponent(token)}`;
176
+ const headers = { Accept: 'application/json' };
177
+ // Browsers send Origin themselves; on the server, the page's own origin, so each token of a map passes its own
178
+ // origin allow-list.
179
+ const origin = e.server ? (opts.serverOrigin ?? e.origin) : undefined;
180
+ if (origin)
181
+ headers['Origin'] = origin;
182
+ let res;
183
+ let body;
184
+ // The timeout covers the body too: a response that stalls after its headers must not hang the bootstrap.
185
+ try {
186
+ res = await e.fetch(url, { headers, signal: ctrl.signal, credentials: 'omit' });
187
+ if (res.ok)
188
+ body = await res.json();
189
+ }
190
+ catch (err) {
191
+ throw new EnvCtrlError(ctrl.signal.aborted ? `env-ctrl did not answer within ${opts.timeoutMs ?? 5000} ms` : `env-ctrl unreachable: ${err.message}`);
192
+ }
193
+ finally {
194
+ clearTimeout(timer);
195
+ }
196
+ if (!res.ok) {
197
+ const why = res.status === 401 ? 'token rejected (revoked, expired or not a public token)'
198
+ : res.status === 403 ? 'origin or IP not allowed for this token'
199
+ : `HTTP ${res.status}`;
200
+ throw new EnvCtrlError(`env-ctrl: ${why}`, res.status);
201
+ }
202
+ // No status: a garbled answer (proxy, CDN) counts as an outage, so the cache and the fallback apply.
203
+ if (!body || typeof body !== 'object' || Array.isArray(body))
204
+ throw new EnvCtrlError('env-ctrl: unexpected response');
205
+ return Object.fromEntries(Object.entries(body).map(([k, v]) => [k, String(v)]));
206
+ }
207
+ function readCache(e, key, maxAgeMs) {
208
+ try {
209
+ const raw = e.storage?.getItem(key);
210
+ if (!raw)
211
+ return null;
212
+ const c = JSON.parse(raw);
213
+ if (!c.values || !c.fetchedAt || e.now() - Date.parse(c.fetchedAt) > maxAgeMs)
214
+ return null;
215
+ return { values: c.values, fetchedAt: c.fetchedAt };
216
+ }
217
+ catch {
218
+ return null;
219
+ }
220
+ }
@@ -0,0 +1,54 @@
1
+ import { EnvironmentProviders, InjectionToken } from '@angular/core';
2
+ import { ConfigSource, PublicConfigOptions } from './core.js';
3
+ export { DEFAULT_API_URL, EnvCtrlError, assertPublicToken, clearServerCache, loadPublicConfig, tokenForHost } from './core.js';
4
+ export type { ConfigSource, LoadedConfig, PublicConfigOptions, PublicToken, TokenByHost } from './core.js';
5
+ export interface EnvCtrlOptions extends PublicConfigOptions {
6
+ /**
7
+ * What to do when the configs can't be loaded: always after 401/403 (revoked token, origin or IP not allowed:
8
+ * cache and fallback are ignored, so a misconfiguration is not hidden), and on outages when there is neither a
9
+ * cached copy nor a fallback. 'throw' (default) fails the bootstrap; 'warn' logs and starts with the fallback
10
+ * values (empty if none).
11
+ */
12
+ onError?: 'throw' | 'warn';
13
+ /**
14
+ * SSR: hand the server's values to the browser so it skips its own request (default true). Prerendered pages never
15
+ * carry values (the server has no request at build time and leaves loading to the browser).
16
+ */
17
+ transferState?: boolean;
18
+ }
19
+ /**
20
+ * The loaded public configs. Available once the app has started (it is filled by an app initializer), so read it in
21
+ * components, services and guards, not in other app initializers registered before provideEnvCtrl().
22
+ */
23
+ export declare class EnvCtrlConfig<K extends string = string> {
24
+ private state;
25
+ /** All values (read-only). */
26
+ get values(): Readonly<Record<K, string | undefined>>;
27
+ /** network, cache (API unreachable), fallback, or transfer (rendered on the server). */
28
+ get source(): ConfigSource;
29
+ get fetchedAt(): string | undefined;
30
+ /** Why the API was not used, when source is cache or fallback. */
31
+ get error(): string | undefined;
32
+ get(key: K): string | undefined;
33
+ get(key: K, fallback: string): string;
34
+ /** The value, or an error naming the missing key. */
35
+ require(key: K): string;
36
+ number(key: K, fallback?: number): number | undefined;
37
+ boolean(key: K, fallback?: boolean): boolean | undefined;
38
+ }
39
+ export declare const ENVCTRL_OPTIONS: InjectionToken<EnvCtrlOptions>;
40
+ /**
41
+ * Loads the public configs of one environment before the app renders.
42
+ *
43
+ * ```ts
44
+ * bootstrapApplication(App, { providers: [provideEnvCtrl({ token: 'ec_pub_…' })] });
45
+ * ```
46
+ *
47
+ * With SSR the server fetches once and hands the values to the browser through TransferState.
48
+ */
49
+ export declare function provideEnvCtrl(options: EnvCtrlOptions): EnvironmentProviders;
50
+ /**
51
+ * The loaded configs. Pass your key names for autocompletion and typo checks:
52
+ * `injectEnvCtrl<'API_URL' | 'SENTRY_DSN'>()`.
53
+ */
54
+ export declare function injectEnvCtrl<K extends string = string>(): EnvCtrlConfig<K>;
package/dist/index.js ADDED
@@ -0,0 +1,133 @@
1
+ import { InjectionToken, PLATFORM_ID, REQUEST, TransferState, inject, makeEnvironmentProviders, makeStateKey, provideAppInitializer, } from '@angular/core';
2
+ import { EnvCtrlError, assertPublicToken, loadPublicConfig, tokensOf } from './core.js';
3
+ export { DEFAULT_API_URL, EnvCtrlError, assertPublicToken, clearServerCache, loadPublicConfig, tokenForHost } from './core.js';
4
+ /**
5
+ * The loaded public configs. Available once the app has started (it is filled by an app initializer), so read it in
6
+ * components, services and guards, not in other app initializers registered before provideEnvCtrl().
7
+ */
8
+ export class EnvCtrlConfig {
9
+ state = { values: {}, source: 'fallback' };
10
+ /** @internal */
11
+ set(state) {
12
+ this.state = { ...state, values: Object.freeze({ ...state.values }) };
13
+ }
14
+ /** All values (read-only). */
15
+ get values() {
16
+ return this.state.values;
17
+ }
18
+ /** network, cache (API unreachable), fallback, or transfer (rendered on the server). */
19
+ get source() {
20
+ return this.state.source;
21
+ }
22
+ get fetchedAt() {
23
+ return this.state.fetchedAt;
24
+ }
25
+ /** Why the API was not used, when source is cache or fallback. */
26
+ get error() {
27
+ return this.state.error;
28
+ }
29
+ get(key, fallback) {
30
+ return this.state.values[key] ?? fallback;
31
+ }
32
+ /** The value, or an error naming the missing key. */
33
+ require(key) {
34
+ const v = this.state.values[key];
35
+ if (v === undefined)
36
+ throw new EnvCtrlError(`env-ctrl: ${key} is not set (is it marked public and set in this environment?)`);
37
+ return v;
38
+ }
39
+ number(key, fallback) {
40
+ const v = this.state.values[key];
41
+ if (v === undefined || v.trim() === '')
42
+ return fallback;
43
+ const n = Number(v);
44
+ return Number.isFinite(n) ? n : fallback;
45
+ }
46
+ boolean(key, fallback) {
47
+ const v = this.state.values[key]?.trim().toLowerCase();
48
+ if (v === undefined || v === '')
49
+ return fallback;
50
+ if (['true', '1', 'yes', 'on'].includes(v))
51
+ return true;
52
+ if (['false', '0', 'no', 'off'].includes(v))
53
+ return false;
54
+ return fallback;
55
+ }
56
+ }
57
+ export const ENVCTRL_OPTIONS = new InjectionToken('ENVCTRL_OPTIONS');
58
+ const STATE_KEY = makeStateKey('envctrl.public');
59
+ /**
60
+ * Loads the public configs of one environment before the app renders.
61
+ *
62
+ * ```ts
63
+ * bootstrapApplication(App, { providers: [provideEnvCtrl({ token: 'ec_pub_…' })] });
64
+ * ```
65
+ *
66
+ * With SSR the server fetches once and hands the values to the browser through TransferState.
67
+ */
68
+ export function provideEnvCtrl(options) {
69
+ // Right away, in development too: a secret token in app.config.ts fails on the first `ng serve`, not in production.
70
+ for (const t of tokensOf(options.token))
71
+ assertPublicToken(t);
72
+ return makeEnvironmentProviders([
73
+ { provide: ENVCTRL_OPTIONS, useValue: options },
74
+ { provide: EnvCtrlConfig, useFactory: () => new EnvCtrlConfig() },
75
+ provideAppInitializer(async () => {
76
+ const config = inject(EnvCtrlConfig);
77
+ const opts = inject(ENVCTRL_OPTIONS);
78
+ const transfer = opts.transferState === false ? null : inject(TransferState, { optional: true });
79
+ const server = inject(PLATFORM_ID) === 'server';
80
+ const handed = !server ? transfer?.get(STATE_KEY, null) : null;
81
+ if (handed) {
82
+ transfer?.remove(STATE_KEY);
83
+ config.set({ ...handed, source: 'transfer' });
84
+ return;
85
+ }
86
+ // On the server without a request we are prerendering at build time: values fetched now would be frozen into
87
+ // the HTML, so render with the fallback and let the browser fetch. With a request, its Host picks the token
88
+ // from a map (Angular checks it against allowedHosts) and its origin goes out as Origin.
89
+ const request = server ? inject(REQUEST, { optional: true }) : null;
90
+ if (server && !request) {
91
+ config.set({ values: { ...(opts.fallback ?? {}) }, source: 'fallback', error: 'prerendering: the browser loads the values' });
92
+ return;
93
+ }
94
+ // Host and origin from request.url, which Angular builds from X-Forwarded-Host/Proto behind a proxy: the raw
95
+ // Host header there can be an internal name.
96
+ let host;
97
+ let origin;
98
+ try {
99
+ const u = new URL(request.url);
100
+ host = u.host;
101
+ origin = u.origin;
102
+ }
103
+ catch {
104
+ host = request?.headers.get('host') ?? undefined;
105
+ }
106
+ try {
107
+ const loaded = await loadPublicConfig(opts, server ? { server, host, origin } : {});
108
+ config.set(loaded);
109
+ // Only fresh values: after a failed server fetch the browser tries the API itself (its values may then differ
110
+ // from the server-rendered HTML until that load completes).
111
+ if (server && loaded.source === 'network')
112
+ transfer?.set(STATE_KEY, loaded);
113
+ if (loaded.error && loaded.source !== 'network')
114
+ console.warn(`env-ctrl: ${loaded.error}; using ${loaded.source} values`);
115
+ }
116
+ catch (err) {
117
+ if (opts.onError === 'warn') {
118
+ console.warn(`env-ctrl: ${err.message}; starting with the fallback values`);
119
+ config.set({ values: { ...(opts.fallback ?? {}) }, source: 'fallback', error: err.message });
120
+ return;
121
+ }
122
+ throw err;
123
+ }
124
+ }),
125
+ ]);
126
+ }
127
+ /**
128
+ * The loaded configs. Pass your key names for autocompletion and typo checks:
129
+ * `injectEnvCtrl<'API_URL' | 'SENTRY_DSN'>()`.
130
+ */
131
+ export function injectEnvCtrl() {
132
+ return inject(EnvCtrlConfig);
133
+ }
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "@env-ctrl/angular",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Public runtime config for Angular apps from env-ctrl (envctrl.com): API URLs, feature flags and keys safe for the browser, loaded before the app renders, SSR-aware.",
5
+ "homepage": "https://envctrl.com",
6
+ "keywords": [
7
+ "angular",
8
+ "config",
9
+ "runtime-config",
10
+ "environment",
11
+ "feature-flags",
12
+ "envctrl"
13
+ ],
14
+ "author": "Andrei Shelenhouski",
15
+ "license": "MIT",
16
+ "type": "module",
17
+ "sideEffects": false,
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "default": "./dist/index.js"
22
+ }
23
+ },
24
+ "files": [
25
+ "dist",
26
+ "README.md"
27
+ ],
28
+ "peerDependencies": {
29
+ "@angular/core": ">=20.0.0"
30
+ },
31
+ "devDependencies": {
32
+ "@angular/core": "^22.2.0",
33
+ "rxjs": "~7.8.0",
34
+ "typescript": "~6.0.2"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "scripts": {
40
+ "build": "rm -rf dist && tsc -p tsconfig.json",
41
+ "test": "npm run build && node --test test.mjs",
42
+ "prepublishOnly": "npm run build"
43
+ }
44
+ }