@schematichq/schematic-angular 1.5.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -202,6 +202,86 @@ export class EntitlementComponent {
202
202
 
203
203
  *Note: `isPending$` checks if entitlement data has been loaded, typically via `identify`. It should be used to wrap flag and entitlement checks, but never the initial call to `identify`.*
204
204
 
205
+ For features metered by credit burndown, the emitted entitlement also carries the company's credit position:
206
+
207
+ | Property | Type | Description |
208
+ | --- | --- | --- |
209
+ | `creditId` | `string \| undefined` | The ID of the credit funding this feature |
210
+ | `creditSettled` | `number \| undefined` | The spendable balance, including any amount held by an open lease. This is the number to show end users |
211
+ | `creditRemaining` | `number \| undefined` | The balance available to fund new consumption, excluding any open lease hold |
212
+ | `creditReserved` | `number \| undefined` | The unspent amount held by an open credit lease, `0` when none is open |
213
+
214
+ All four are `undefined` when the feature is not credit-based.
215
+
216
+ ```typescript
217
+ @Component({
218
+ selector: "app-credit-feature",
219
+ standalone: true,
220
+ imports: [AsyncPipe],
221
+ template: `
222
+ @if (entitlement$ | async; as entitlement) {
223
+ @if (entitlement.value) {
224
+ <app-feature [creditsRemaining]="entitlement.creditSettled" />
225
+ } @else {
226
+ <app-out-of-credits />
227
+ }
228
+ }
229
+ `,
230
+ })
231
+ export class CreditFeatureComponent {
232
+ private schematic = inject(SchematicService);
233
+ entitlement$ = this.schematic.entitlement$("my-flag-key");
234
+ }
235
+ ```
236
+
237
+ These values refresh with each flag check. For a balance that also updates on the credit partials arriving between checks, pipe `creditId` into [`creditBalance$`](#credit-balances) instead.
238
+
239
+ ### Usage warnings
240
+
241
+ If a usage warning is configured on the entitlement, the emitted entitlement carries it as `warningTiers`, so you can warn a customer before they hit the limit rather than after:
242
+
243
+ | Property | Type | Description |
244
+ | --- | --- | --- |
245
+ | `warningTiers` | `WarningTier[] \| undefined` | The usage warning thresholds configured on the entitlement, each a `{ key, value }` pair in the entitlement's usage units. `undefined` when none are configured |
246
+ | `softLimit` | `number \| undefined` | For usage-based pricing, the soft limit for overage charges or the next tier boundary |
247
+
248
+ The dashboard writes a single tier under the key `default`.
249
+
250
+ ```typescript
251
+ import { Component, inject } from "@angular/core";
252
+ import { AsyncPipe } from "@angular/common";
253
+ import { map } from "rxjs";
254
+ import { SchematicService } from "@schematichq/schematic-angular";
255
+
256
+ @Component({
257
+ selector: "app-usage-warning",
258
+ standalone: true,
259
+ imports: [AsyncPipe],
260
+ template: `
261
+ @if (approachingLimit$ | async) {
262
+ <app-approaching-limit />
263
+ }
264
+ <app-feature />
265
+ `,
266
+ })
267
+ export class UsageWarningComponent {
268
+ private schematic = inject(SchematicService);
269
+ entitlement$ = this.schematic.entitlement$("my-flag-key");
270
+ approachingLimit$ = this.entitlement$.pipe(
271
+ map((entitlement) => {
272
+ const warning = entitlement.warningTiers?.find(
273
+ (tier) => tier.key === "default",
274
+ );
275
+ return (
276
+ typeof entitlement.featureUsage === "number" &&
277
+ typeof warning?.value === "number" &&
278
+ entitlement.featureUsage >= warning.value
279
+ );
280
+ }),
281
+ );
282
+ }
283
+ ```
284
+
205
285
  ### Checking plans
206
286
 
207
287
  Use `plan$` to get an Observable of the current plan information:
@@ -265,7 +345,84 @@ export class CreditMeterComponent {
265
345
  | `balance` | `number` | The spendable balance, or `0` while loading or when the company holds no balance in this credit |
266
346
  | `isLoading` | `boolean` | `true` while the balance is still loading and no value has arrived yet |
267
347
 
268
- It surfaces the `settled` (spendable) balance. The credit ID is available on a feature's entitlement: `entitlement$(key)` emits `creditId` for credit-based features.
348
+ It surfaces the `settled` (spendable) balance. The credit ID is available on a feature's entitlement, and `creditBalance$` accepts an Observable of credit IDs as well as a plain one, so you can pipe the entitlement straight in:
349
+
350
+ ```typescript
351
+ import { map } from "rxjs";
352
+
353
+ @Component({
354
+ selector: "app-credit-meter",
355
+ standalone: true,
356
+ imports: [AsyncPipe],
357
+ template: `
358
+ @if (creditBalance$ | async; as credit) {
359
+ @if (credit.isLoading) {
360
+ <div>Loading…</div>
361
+ } @else {
362
+ <div>{{ credit.balance }} credits remaining</div>
363
+ }
364
+ }
365
+ `,
366
+ })
367
+ export class CreditMeterComponent {
368
+ private schematic = inject(SchematicService);
369
+ creditBalance$ = this.schematic.creditBalance$(
370
+ this.schematic
371
+ .entitlement$("my-flag-key")
372
+ .pipe(map((entitlement) => entitlement.creditId)),
373
+ );
374
+ }
375
+ ```
376
+
377
+ It switches to the new credit as the source emits. While the ID is `undefined`, it emits the client's loading state and a balance of `0`.
378
+
379
+ ### Credit spend policies
380
+
381
+ Use `creditSpendPolicies$` to observe the spend limits that bind the current company and user. It emits over the DataStream, so a policy edited or deleted in the dashboard arrives without a refetch:
382
+
383
+ ```typescript
384
+ import { Component, inject } from "@angular/core";
385
+ import { AsyncPipe } from "@angular/common";
386
+ import { SchematicService } from "@schematichq/schematic-angular";
387
+
388
+ @Component({
389
+ selector: "app-spend-limits",
390
+ standalone: true,
391
+ imports: [AsyncPipe],
392
+ template: `
393
+ @if (spendPolicies$ | async; as spend) {
394
+ @if (spend.isLoading) {
395
+ <div>Loading…</div>
396
+ } @else {
397
+ <ul>
398
+ @for (policy of spend.policies; track policy.id) {
399
+ <li>
400
+ @if (policy.kind === "window" && policy.window) {
401
+ {{ policy.scope }} limit: {{ policy.consumed }} of {{ policy.limit }} credits used this {{ policy.window.unit }}
402
+ } @else {
403
+ {{ policy.scope }} limit: {{ policy.limit }} credits per request
404
+ }
405
+ </li>
406
+ }
407
+ </ul>
408
+ }
409
+ }
410
+ `,
411
+ })
412
+ export class SpendLimitsComponent {
413
+ private schematic = inject(SchematicService);
414
+ spendPolicies$ = this.schematic.creditSpendPolicies$();
415
+ }
416
+ ```
417
+
418
+ `creditSpendPolicies$` emits an object with the following properties:
419
+
420
+ | Property | Type | Description |
421
+ | --- | --- | --- |
422
+ | `policies` | `CreditSpendPolicies` | Company-scope policies first, then the user's own; empty when none bind |
423
+ | `isLoading` | `boolean` | `true` while the policies are still loading and nothing has arrived yet |
424
+
425
+ A `per_draw` policy caps a single draw. A `window` policy caps what can be spent in one period: `consumed` is what the current period has spent, `resetsAt` is when the period ends, and `window` names the period. Each new spend sends an updated `consumed`. Once `resetsAt` has passed, read `consumed` as `0` until the next update arrives.
269
426
 
270
427
  ## API Reference
271
428
 
@@ -286,7 +443,8 @@ Injectable service providing all Schematic functionality:
286
443
  | `flagValue$(key, fallback?)` | `Observable<boolean>` | Observe a feature flag's boolean value |
287
444
  | `entitlement$(key, fallback?)` | `Observable<CheckFlagReturn>` | Observe detailed entitlement data |
288
445
  | `plan$()` | `Observable<CheckPlanReturn \| undefined>` | Observe plan information |
289
- | `creditBalance$(creditId)` | `Observable<SchematicCreditBalance>` | Observe a company's lease-aware credit balance |
446
+ | `creditBalance$(creditId)` | `Observable<SchematicCreditBalance>` | Observe a company's lease-aware credit balance. Takes a credit ID or an Observable of credit IDs |
447
+ | `creditSpendPolicies$()` | `Observable<SchematicCreditSpendPolicies>` | Observe the credit spend policies binding the current context |
290
448
  | `isPending$()` | `Observable<boolean>` | Observe loading state |
291
449
 
292
450
  ### `SCHEMATIC_CLIENT`
@@ -1,193 +1,227 @@
1
- import * as i0 from '@angular/core';
2
- import { InjectionToken, inject, Injectable, makeEnvironmentProviders, DestroyRef } from '@angular/core';
3
- import * as SchematicJS from '@schematichq/schematic-js';
4
- export { RuleType, Schematic, TrialStatus, UsagePeriod } from '@schematichq/schematic-js';
5
- import { Observable, distinctUntilChanged, shareReplay, finalize } from 'rxjs';
6
-
1
+ import * as i0 from "@angular/core";
2
+ import { DestroyRef, Injectable, InjectionToken, inject, makeEnvironmentProviders } from "@angular/core";
3
+ import * as SchematicJS from "@schematichq/schematic-js";
4
+ import { RuleType, Schematic, TrialStatus, UsagePeriod } from "@schematichq/schematic-js";
5
+ import { Observable, distinctUntilChanged, finalize, isObservable, map, shareReplay, switchMap } from "rxjs";
7
6
  const SCHEMATIC_CLIENT = new InjectionToken("SchematicClient");
8
-
9
7
  function shallowEqual(a, b) {
10
- if (a === b)
11
- return true;
12
- if (!a || !b)
13
- return false;
14
- const keysA = Object.keys(a);
15
- const keysB = Object.keys(b);
16
- if (keysA.length !== keysB.length)
17
- return false;
18
- return keysA.every((key) => {
19
- const valA = a[key];
20
- const valB = b[key];
21
- if (valA instanceof Date && valB instanceof Date) {
22
- return valA.getTime() === valB.getTime();
23
- }
24
- return valA === valB;
25
- });
26
- }
27
- class SchematicService {
28
- client = inject(SCHEMATIC_CLIENT);
29
- flagValueCache = new Map();
30
- entitlementCache = new Map();
31
- creditBalanceCache = new Map();
32
- planCache;
33
- isPendingCache;
34
- getClient() {
35
- return this.client;
36
- }
37
- setContext(context) {
38
- this.client.setContext(context);
39
- }
40
- identify(body) {
41
- this.client.identify(body);
42
- }
43
- track(body) {
44
- this.client.track(body);
45
- }
46
- flagValue$(key, fallback = false) {
47
- const cacheKey = `${key}:${fallback}`;
48
- let cached = this.flagValueCache.get(cacheKey);
49
- if (cached)
50
- return cached;
51
- cached = new Observable((subscriber) => {
52
- const current = this.client.getFlagValue(key);
53
- subscriber.next(current ?? fallback);
54
- const unsubscribe = this.client.addFlagValueListener(key, () => {
55
- const value = this.client.getFlagValue(key);
56
- subscriber.next(value ?? fallback);
57
- });
58
- return () => unsubscribe();
59
- }).pipe(distinctUntilChanged(), shareReplay({ bufferSize: 1, refCount: true }), finalize(() => this.flagValueCache.delete(cacheKey)));
60
- this.flagValueCache.set(cacheKey, cached);
61
- return cached;
62
- }
63
- entitlement$(key, fallback = false) {
64
- const cacheKey = `${key}:${fallback}`;
65
- let cached = this.entitlementCache.get(cacheKey);
66
- if (cached)
67
- return cached;
68
- const fallbackCheck = {
69
- flag: key,
70
- reason: "Fallback",
71
- value: fallback,
72
- };
73
- cached = new Observable((subscriber) => {
74
- const current = this.client.getFlagCheck(key);
75
- subscriber.next(current ?? fallbackCheck);
76
- const unsubscribe = this.client.addFlagCheckListener(key, () => {
77
- const check = this.client.getFlagCheck(key);
78
- subscriber.next(check ?? fallbackCheck);
79
- });
80
- return () => unsubscribe();
81
- }).pipe(distinctUntilChanged(shallowEqual), shareReplay({ bufferSize: 1, refCount: true }), finalize(() => this.entitlementCache.delete(cacheKey)));
82
- this.entitlementCache.set(cacheKey, cached);
83
- return cached;
84
- }
85
- plan$() {
86
- if (this.planCache)
87
- return this.planCache;
88
- this.planCache = new Observable((subscriber) => {
89
- subscriber.next(this.client.getPlan());
90
- const unsubscribe = this.client.addPlanListener(() => {
91
- subscriber.next(this.client.getPlan());
92
- });
93
- return () => unsubscribe();
94
- }).pipe(distinctUntilChanged(shallowEqual), shareReplay({ bufferSize: 1, refCount: true }), finalize(() => {
95
- this.planCache = undefined;
96
- }));
97
- return this.planCache;
98
- }
99
- /**
100
- * Observe a company's live, lease-aware credit balance for a single credit type.
101
- *
102
- * Surfaces the spendable `settled` balance, sourced from the streamed credit
103
- * balances map (keyed by credit ID). It emits as partials arrive over the
104
- * DataStream, so it stays accurate during an open lease — when the raw
105
- * `remaining` would otherwise read stale / falsely "exhausted".
106
- *
107
- * The credit ID is available on a feature's entitlement: `entitlement$(key)`
108
- * emits `creditId` for credit-based features.
109
- */
110
- creditBalance$(creditId) {
111
- let cached = this.creditBalanceCache.get(creditId);
112
- if (cached)
113
- return cached;
114
- cached = new Observable((subscriber) => {
115
- const emit = () => {
116
- const balance = this.client.getCreditBalance(creditId);
117
- subscriber.next({
118
- balance: balance?.settled ?? 0,
119
- isLoading: balance === undefined && this.client.getIsPending(),
120
- });
121
- };
122
- emit();
123
- const unsubscribeBalance = this.client.addCreditBalanceListener(() => emit());
124
- const unsubscribePending = this.client.addIsPendingListener(() => emit());
125
- return () => {
126
- unsubscribeBalance();
127
- unsubscribePending();
128
- };
129
- }).pipe(distinctUntilChanged(shallowEqual), shareReplay({ bufferSize: 1, refCount: true }), finalize(() => this.creditBalanceCache.delete(creditId)));
130
- this.creditBalanceCache.set(creditId, cached);
131
- return cached;
132
- }
133
- isPending$() {
134
- if (this.isPendingCache)
135
- return this.isPendingCache;
136
- this.isPendingCache = new Observable((subscriber) => {
137
- subscriber.next(this.client.getIsPending());
138
- const unsubscribe = this.client.addIsPendingListener(() => {
139
- subscriber.next(this.client.getIsPending());
140
- });
141
- return () => unsubscribe();
142
- }).pipe(distinctUntilChanged(), shareReplay({ bufferSize: 1, refCount: true }), finalize(() => {
143
- this.isPendingCache = undefined;
144
- }));
145
- return this.isPendingCache;
146
- }
147
- static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: SchematicService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
148
- static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: SchematicService });
8
+ if (a === b) return true;
9
+ if (!a || !b) return false;
10
+ const keysA = Object.keys(a);
11
+ const keysB = Object.keys(b);
12
+ if (keysA.length !== keysB.length) return false;
13
+ return keysA.every((key) => {
14
+ const valA = a[key];
15
+ const valB = b[key];
16
+ if (valA instanceof Date && valB instanceof Date) return valA.getTime() === valB.getTime();
17
+ return valA === valB;
18
+ });
149
19
  }
150
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: SchematicService, decorators: [{
151
- type: Injectable
152
- }] });
153
-
154
- const version = "1.5.0";
155
-
20
+ var SchematicService = class SchematicService {
21
+ client = inject(SCHEMATIC_CLIENT);
22
+ flagValueCache = /* @__PURE__ */ new Map();
23
+ entitlementCache = /* @__PURE__ */ new Map();
24
+ creditBalanceCache = /* @__PURE__ */ new Map();
25
+ creditSpendPoliciesCache;
26
+ planCache;
27
+ isPendingCache;
28
+ getClient() {
29
+ return this.client;
30
+ }
31
+ setContext(context) {
32
+ this.client.setContext(context);
33
+ }
34
+ identify(body) {
35
+ this.client.identify(body);
36
+ }
37
+ track(body) {
38
+ this.client.track(body);
39
+ }
40
+ flagValue$(key, fallback = false) {
41
+ const cacheKey = `${key}:${fallback}`;
42
+ let cached = this.flagValueCache.get(cacheKey);
43
+ if (cached) return cached;
44
+ cached = new Observable((subscriber) => {
45
+ const current = this.client.getFlagValue(key);
46
+ subscriber.next(current ?? fallback);
47
+ const unsubscribe = this.client.addFlagValueListener(key, () => {
48
+ const value = this.client.getFlagValue(key);
49
+ subscriber.next(value ?? fallback);
50
+ });
51
+ return () => unsubscribe();
52
+ }).pipe(distinctUntilChanged(), shareReplay({
53
+ bufferSize: 1,
54
+ refCount: true
55
+ }), finalize(() => this.flagValueCache.delete(cacheKey)));
56
+ this.flagValueCache.set(cacheKey, cached);
57
+ return cached;
58
+ }
59
+ entitlement$(key, fallback = false) {
60
+ const cacheKey = `${key}:${fallback}`;
61
+ let cached = this.entitlementCache.get(cacheKey);
62
+ if (cached) return cached;
63
+ const fallbackCheck = {
64
+ flag: key,
65
+ reason: "Fallback",
66
+ value: fallback
67
+ };
68
+ cached = new Observable((subscriber) => {
69
+ const current = this.client.getFlagCheck(key);
70
+ subscriber.next(current ?? fallbackCheck);
71
+ const unsubscribe = this.client.addFlagCheckListener(key, () => {
72
+ const check = this.client.getFlagCheck(key);
73
+ subscriber.next(check ?? fallbackCheck);
74
+ });
75
+ return () => unsubscribe();
76
+ }).pipe(distinctUntilChanged(shallowEqual), shareReplay({
77
+ bufferSize: 1,
78
+ refCount: true
79
+ }), finalize(() => this.entitlementCache.delete(cacheKey)));
80
+ this.entitlementCache.set(cacheKey, cached);
81
+ return cached;
82
+ }
83
+ plan$() {
84
+ if (this.planCache) return this.planCache;
85
+ this.planCache = new Observable((subscriber) => {
86
+ subscriber.next(this.client.getPlan());
87
+ const unsubscribe = this.client.addPlanListener(() => {
88
+ subscriber.next(this.client.getPlan());
89
+ });
90
+ return () => unsubscribe();
91
+ }).pipe(distinctUntilChanged(shallowEqual), shareReplay({
92
+ bufferSize: 1,
93
+ refCount: true
94
+ }), finalize(() => {
95
+ this.planCache = void 0;
96
+ }));
97
+ return this.planCache;
98
+ }
99
+ creditBalance$(creditId) {
100
+ if (isObservable(creditId)) return creditId.pipe(distinctUntilChanged(), switchMap((id) => this.creditBalanceFor(id)), distinctUntilChanged(shallowEqual), shareReplay({
101
+ bufferSize: 1,
102
+ refCount: true
103
+ }));
104
+ return this.creditBalanceFor(creditId);
105
+ }
106
+ noCreditBalance$() {
107
+ return this.isPending$().pipe(map((isLoading) => ({
108
+ balance: 0,
109
+ isLoading
110
+ })));
111
+ }
112
+ creditBalanceFor(creditId) {
113
+ if (creditId === void 0) return this.noCreditBalance$();
114
+ let cached = this.creditBalanceCache.get(creditId);
115
+ if (cached) return cached;
116
+ cached = new Observable((subscriber) => {
117
+ const emit = () => {
118
+ const balance = this.client.getCreditBalance(creditId);
119
+ subscriber.next({
120
+ balance: balance?.settled ?? 0,
121
+ isLoading: balance === void 0 && this.client.getIsPending()
122
+ });
123
+ };
124
+ emit();
125
+ const unsubscribeBalance = this.client.addCreditBalanceListener(() => emit());
126
+ const unsubscribePending = this.client.addIsPendingListener(() => emit());
127
+ return () => {
128
+ unsubscribeBalance();
129
+ unsubscribePending();
130
+ };
131
+ }).pipe(distinctUntilChanged(shallowEqual), shareReplay({
132
+ bufferSize: 1,
133
+ refCount: true
134
+ }), finalize(() => this.creditBalanceCache.delete(creditId)));
135
+ this.creditBalanceCache.set(creditId, cached);
136
+ return cached;
137
+ }
138
+ creditSpendPolicies$() {
139
+ if (this.creditSpendPoliciesCache) return this.creditSpendPoliciesCache;
140
+ this.creditSpendPoliciesCache = new Observable((subscriber) => {
141
+ const emit = () => {
142
+ const policies = this.client.getCreditSpendPolicies();
143
+ subscriber.next({
144
+ policies,
145
+ isLoading: policies.length === 0 && this.client.getIsPending()
146
+ });
147
+ };
148
+ emit();
149
+ const unsubscribePolicies = this.client.addCreditSpendPolicyListener(() => emit());
150
+ const unsubscribePending = this.client.addIsPendingListener(() => emit());
151
+ return () => {
152
+ unsubscribePolicies();
153
+ unsubscribePending();
154
+ };
155
+ }).pipe(distinctUntilChanged(shallowEqual), shareReplay({
156
+ bufferSize: 1,
157
+ refCount: true
158
+ }), finalize(() => {
159
+ this.creditSpendPoliciesCache = void 0;
160
+ }));
161
+ return this.creditSpendPoliciesCache;
162
+ }
163
+ isPending$() {
164
+ if (this.isPendingCache) return this.isPendingCache;
165
+ this.isPendingCache = new Observable((subscriber) => {
166
+ subscriber.next(this.client.getIsPending());
167
+ const unsubscribe = this.client.addIsPendingListener(() => {
168
+ subscriber.next(this.client.getIsPending());
169
+ });
170
+ return () => unsubscribe();
171
+ }).pipe(distinctUntilChanged(), shareReplay({
172
+ bufferSize: 1,
173
+ refCount: true
174
+ }), finalize(() => {
175
+ this.isPendingCache = void 0;
176
+ }));
177
+ return this.isPendingCache;
178
+ }
179
+ static ɵfac = i0.ɵɵngDeclareFactory({
180
+ minVersion: "12.0.0",
181
+ version: "22.2.0",
182
+ ngImport: i0,
183
+ type: SchematicService,
184
+ deps: [],
185
+ target: i0.ɵɵFactoryTarget.Injectable
186
+ });
187
+ static ɵprov = i0.ɵɵngDeclareInjectable({
188
+ minVersion: "12.0.0",
189
+ version: "22.2.0",
190
+ ngImport: i0,
191
+ type: SchematicService
192
+ });
193
+ };
194
+ i0.ɵɵngDeclareClassMetadata({
195
+ minVersion: "12.0.0",
196
+ version: "22.2.0",
197
+ ngImport: i0,
198
+ type: SchematicService,
199
+ decorators: [{ type: Injectable }]
200
+ });
201
+ const version = "1.7.0";
156
202
  function provideSchematic(config) {
157
- const { client: providedClient, publishableKey, additionalHeaders, ...restOpts } = config;
158
- return makeEnvironmentProviders([
159
- {
160
- provide: SCHEMATIC_CLIENT,
161
- useFactory: () => {
162
- const isProvidedClient = !!providedClient;
163
- const client = isProvidedClient
164
- ? providedClient
165
- : new SchematicJS.Schematic(publishableKey, {
166
- ...restOpts,
167
- useWebSocket: true,
168
- additionalHeaders: {
169
- "X-Schematic-Client-Version": `schematic-angular@${version}`,
170
- ...additionalHeaders,
171
- },
172
- });
173
- const destroyRef = inject(DestroyRef);
174
- destroyRef.onDestroy(() => {
175
- if (!isProvidedClient) {
176
- client.cleanup().catch((error) => {
177
- console.error("Error during Schematic cleanup:", error);
178
- });
179
- }
180
- });
181
- return client;
182
- },
183
- },
184
- SchematicService,
185
- ]);
203
+ const { client: providedClient, publishableKey, additionalHeaders, ...restOpts } = config;
204
+ return makeEnvironmentProviders([{
205
+ provide: SCHEMATIC_CLIENT,
206
+ useFactory: () => {
207
+ const isProvidedClient = !!providedClient;
208
+ const client = isProvidedClient ? providedClient : new SchematicJS.Schematic(publishableKey, {
209
+ ...restOpts,
210
+ useWebSocket: true,
211
+ additionalHeaders: {
212
+ "X-Schematic-Client-Version": `schematic-angular@${version}`,
213
+ ...additionalHeaders
214
+ }
215
+ });
216
+ inject(DestroyRef).onDestroy(() => {
217
+ if (!isProvidedClient) client.cleanup().catch((error) => {
218
+ console.error("Error during Schematic cleanup:", error);
219
+ });
220
+ });
221
+ return client;
222
+ }
223
+ }, SchematicService]);
186
224
  }
225
+ export { RuleType, SCHEMATIC_CLIENT, Schematic, SchematicService, TrialStatus, UsagePeriod, provideSchematic };
187
226
 
188
- /**
189
- * Generated bundle index. Do not edit.
190
- */
191
-
192
- export { SCHEMATIC_CLIENT, SchematicService, provideSchematic };
193
- //# sourceMappingURL=schematichq-schematic-angular.mjs.map
227
+ //# sourceMappingURL=schematichq-schematic-angular.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"schematichq-schematic-angular.mjs","sources":["../../src/token.ts","../../src/schematic.service.ts","../../src/version.ts","../../src/provide.ts","../../src/schematichq-schematic-angular.ts"],"sourcesContent":["import { InjectionToken } from \"@angular/core\";\nimport * as SchematicJS from \"@schematichq/schematic-js\";\n\nexport const SCHEMATIC_CLIENT = new InjectionToken<SchematicJS.Schematic>(\n \"SchematicClient\",\n);\n","import { Injectable, inject } from \"@angular/core\";\nimport * as SchematicJS from \"@schematichq/schematic-js\";\nimport { Observable, distinctUntilChanged, finalize, shareReplay } from \"rxjs\";\nimport { SCHEMATIC_CLIENT } from \"./token\";\n\n/** A company's credit balance for a single credit type, plus a loading flag */\nexport type SchematicCreditBalance = {\n /** The spendable balance; 0 while loading or when the company holds no balance in this credit */\n balance: number;\n /** True while the balance is still loading and no value has arrived yet */\n isLoading: boolean;\n};\n\nfunction shallowEqual<T extends Record<string, unknown>>(\n a: T | undefined,\n b: T | undefined,\n): boolean {\n if (a === b) return true;\n if (!a || !b) return false;\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n if (keysA.length !== keysB.length) return false;\n return keysA.every((key) => {\n const valA = a[key];\n const valB = b[key];\n if (valA instanceof Date && valB instanceof Date) {\n return valA.getTime() === valB.getTime();\n }\n return valA === valB;\n });\n}\n\n@Injectable()\nexport class SchematicService {\n private client = inject(SCHEMATIC_CLIENT);\n\n private flagValueCache = new Map<string, Observable<boolean>>();\n private entitlementCache = new Map<\n string,\n Observable<SchematicJS.CheckFlagReturn>\n >();\n private creditBalanceCache = new Map<\n string,\n Observable<SchematicCreditBalance>\n >();\n private planCache?: Observable<SchematicJS.CheckPlanReturn | undefined>;\n private isPendingCache?: Observable<boolean>;\n\n getClient(): SchematicJS.Schematic {\n return this.client;\n }\n\n setContext(context: SchematicJS.SchematicContext): void {\n this.client.setContext(context);\n }\n\n identify(body: SchematicJS.EventBodyIdentify): void {\n this.client.identify(body);\n }\n\n track(body: SchematicJS.EventBodyTrack): void {\n this.client.track(body);\n }\n\n flagValue$(key: string, fallback: boolean = false): Observable<boolean> {\n const cacheKey = `${key}:${fallback}`;\n let cached = this.flagValueCache.get(cacheKey);\n if (cached) return cached;\n\n cached = new Observable<boolean>((subscriber) => {\n const current = this.client.getFlagValue(key);\n subscriber.next(current ?? fallback);\n\n const unsubscribe = this.client.addFlagValueListener(key, () => {\n const value = this.client.getFlagValue(key);\n subscriber.next(value ?? fallback);\n });\n\n return () => unsubscribe();\n }).pipe(\n distinctUntilChanged(),\n shareReplay({ bufferSize: 1, refCount: true }),\n finalize(() => this.flagValueCache.delete(cacheKey)),\n );\n\n this.flagValueCache.set(cacheKey, cached);\n return cached;\n }\n\n entitlement$(\n key: string,\n fallback: boolean = false,\n ): Observable<SchematicJS.CheckFlagReturn> {\n const cacheKey = `${key}:${fallback}`;\n let cached = this.entitlementCache.get(cacheKey);\n if (cached) return cached;\n\n const fallbackCheck: SchematicJS.CheckFlagReturn = {\n flag: key,\n reason: \"Fallback\",\n value: fallback,\n };\n\n cached = new Observable<SchematicJS.CheckFlagReturn>((subscriber) => {\n const current = this.client.getFlagCheck(key);\n subscriber.next(current ?? fallbackCheck);\n\n const unsubscribe = this.client.addFlagCheckListener(key, () => {\n const check = this.client.getFlagCheck(key);\n subscriber.next(check ?? fallbackCheck);\n });\n\n return () => unsubscribe();\n }).pipe(\n distinctUntilChanged(shallowEqual),\n shareReplay({ bufferSize: 1, refCount: true }),\n finalize(() => this.entitlementCache.delete(cacheKey)),\n );\n\n this.entitlementCache.set(cacheKey, cached);\n return cached;\n }\n\n plan$(): Observable<SchematicJS.CheckPlanReturn | undefined> {\n if (this.planCache) return this.planCache;\n\n this.planCache = new Observable<SchematicJS.CheckPlanReturn | undefined>(\n (subscriber) => {\n subscriber.next(this.client.getPlan());\n\n const unsubscribe = this.client.addPlanListener(() => {\n subscriber.next(this.client.getPlan());\n });\n\n return () => unsubscribe();\n },\n ).pipe(\n distinctUntilChanged(shallowEqual),\n shareReplay({ bufferSize: 1, refCount: true }),\n finalize(() => {\n this.planCache = undefined;\n }),\n );\n\n return this.planCache;\n }\n\n /**\n * Observe a company's live, lease-aware credit balance for a single credit type.\n *\n * Surfaces the spendable `settled` balance, sourced from the streamed credit\n * balances map (keyed by credit ID). It emits as partials arrive over the\n * DataStream, so it stays accurate during an open lease — when the raw\n * `remaining` would otherwise read stale / falsely \"exhausted\".\n *\n * The credit ID is available on a feature's entitlement: `entitlement$(key)`\n * emits `creditId` for credit-based features.\n */\n creditBalance$(creditId: string): Observable<SchematicCreditBalance> {\n let cached = this.creditBalanceCache.get(creditId);\n if (cached) return cached;\n\n cached = new Observable<SchematicCreditBalance>((subscriber) => {\n const emit = () => {\n const balance = this.client.getCreditBalance(creditId);\n subscriber.next({\n balance: balance?.settled ?? 0,\n isLoading: balance === undefined && this.client.getIsPending(),\n });\n };\n\n emit();\n\n const unsubscribeBalance = this.client.addCreditBalanceListener(() =>\n emit(),\n );\n const unsubscribePending = this.client.addIsPendingListener(() => emit());\n\n return () => {\n unsubscribeBalance();\n unsubscribePending();\n };\n }).pipe(\n distinctUntilChanged(shallowEqual),\n shareReplay({ bufferSize: 1, refCount: true }),\n finalize(() => this.creditBalanceCache.delete(creditId)),\n );\n\n this.creditBalanceCache.set(creditId, cached);\n return cached;\n }\n\n isPending$(): Observable<boolean> {\n if (this.isPendingCache) return this.isPendingCache;\n\n this.isPendingCache = new Observable<boolean>((subscriber) => {\n subscriber.next(this.client.getIsPending());\n\n const unsubscribe = this.client.addIsPendingListener(() => {\n subscriber.next(this.client.getIsPending());\n });\n\n return () => unsubscribe();\n }).pipe(\n distinctUntilChanged(),\n shareReplay({ bufferSize: 1, refCount: true }),\n finalize(() => {\n this.isPendingCache = undefined;\n }),\n );\n\n return this.isPendingCache;\n }\n}\n","export const version = \"1.5.0\";\n","import { DestroyRef, inject, makeEnvironmentProviders } from \"@angular/core\";\nimport * as SchematicJS from \"@schematichq/schematic-js\";\n\nimport { SchematicService } from \"./schematic.service\";\nimport { SCHEMATIC_CLIENT } from \"./token\";\nimport { version } from \"./version\";\n\ntype BaseSchematicConfig = Omit<SchematicJS.SchematicOptions, \"useWebSocket\">;\n\ntype SchematicConfigWithClient = BaseSchematicConfig & {\n client: SchematicJS.Schematic;\n publishableKey?: never;\n};\n\ntype SchematicConfigWithKey = BaseSchematicConfig & {\n client?: never;\n publishableKey: string;\n};\n\nexport type SchematicConfig =\n | SchematicConfigWithClient\n | SchematicConfigWithKey;\n\nexport function provideSchematic(config: SchematicConfig) {\n const {\n client: providedClient,\n publishableKey,\n additionalHeaders,\n ...restOpts\n } = config;\n\n return makeEnvironmentProviders([\n {\n provide: SCHEMATIC_CLIENT,\n useFactory: () => {\n const isProvidedClient = !!providedClient;\n\n const client = isProvidedClient\n ? providedClient\n : new SchematicJS.Schematic(publishableKey!, {\n ...restOpts,\n useWebSocket: true,\n additionalHeaders: {\n \"X-Schematic-Client-Version\": `schematic-angular@${version}`,\n ...additionalHeaders,\n },\n });\n\n const destroyRef = inject(DestroyRef);\n destroyRef.onDestroy(() => {\n if (!isProvidedClient) {\n client.cleanup().catch((error: unknown) => {\n console.error(\"Error during Schematic cleanup:\", error);\n });\n }\n });\n\n return client;\n },\n },\n SchematicService,\n ]);\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './index';\n"],"names":[],"mappings":";;;;;;MAGa,gBAAgB,GAAG,IAAI,cAAc,CAChD,iBAAiB;;ACSnB,SAAS,YAAY,CACnB,CAAgB,EAChB,CAAgB,EAAA;IAEhB,IAAI,CAAC,KAAK,CAAC;AAAE,QAAA,OAAO,IAAI;AACxB,IAAA,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC;AAAE,QAAA,OAAO,KAAK;IAC1B,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;IAC5B,MAAM,KAAK,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC;AAC5B,IAAA,IAAI,KAAK,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM;AAAE,QAAA,OAAO,KAAK;AAC/C,IAAA,OAAO,KAAK,CAAC,KAAK,CAAC,CAAC,GAAG,KAAI;AACzB,QAAA,MAAM,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC;AACnB,QAAA,MAAM,IAAI,GAAG,CAAC,CAAC,GAAG,CAAC;QACnB,IAAI,IAAI,YAAY,IAAI,IAAI,IAAI,YAAY,IAAI,EAAE;YAChD,OAAO,IAAI,CAAC,OAAO,EAAE,KAAK,IAAI,CAAC,OAAO,EAAE;QAC1C;QACA,OAAO,IAAI,KAAK,IAAI;AACtB,IAAA,CAAC,CAAC;AACJ;MAGa,gBAAgB,CAAA;AACnB,IAAA,MAAM,G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D,4BAAA,GAAG,iBAAiB;AACrB,yBAAA;AACF,qBAAA,CAAC;AAEN,gBAAA,MAAM,UAAU,GAAG,MAAM,CAAC,UAAU,CAAC;AACrC,gBAAA,UAAU,CAAC,SAAS,CAAC,MAAK;oBACxB,IAAI,CAAC,gBAAgB,EAAE;wBACrB,MAAM,CAAC,OAAO,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,KAAI;AACxC,4BAAA,OAAO,CAAC,KAAK,CAAC,iCAAiC,EAAE,KAAK,CAAC;AACzD,wBAAA,CAAC,CAAC;oBACJ;AACF,gBAAA,CAAC,CAAC;AAEF,gBAAA,OAAO,MAAM;YACf,CAAC;AACF,SAAA;QACD,gBAAgB;AACjB,KAAA,CAAC;AACJ;;AC9DA;;AAEG;;;;"}
1
+ {"version":3,"file":"schematichq-schematic-angular.mjs","names":[],"sources":["../../src/token.ts","../../src/schematic.service.ts","../../src/version.ts","../../src/provide.ts"],"sourcesContent":["import { InjectionToken } from \"@angular/core\";\nimport * as SchematicJS from \"@schematichq/schematic-js\";\n\nexport const SCHEMATIC_CLIENT = new InjectionToken<SchematicJS.Schematic>(\n \"SchematicClient\",\n);\n","import { Injectable, inject } from \"@angular/core\";\nimport * as SchematicJS from \"@schematichq/schematic-js\";\nimport {\n Observable,\n distinctUntilChanged,\n finalize,\n isObservable,\n map,\n shareReplay,\n switchMap,\n} from \"rxjs\";\nimport { SCHEMATIC_CLIENT } from \"./token\";\n\n/** A company's credit balance for a single credit type, plus a loading flag */\nexport type SchematicCreditBalance = {\n /** The spendable balance; 0 while loading or when the company holds no balance in this credit */\n balance: number;\n /** True while the balance is still loading and no value has arrived yet */\n isLoading: boolean;\n};\n\n/** The credit spend policies binding the current context, plus a loading flag */\nexport type SchematicCreditSpendPolicies = {\n /** Company-scope policies first, then the user's own; empty when none bind */\n policies: SchematicJS.CreditSpendPolicies;\n /** True while the policies are still loading and nothing has arrived yet */\n isLoading: boolean;\n};\n\nfunction shallowEqual<T extends Record<string, unknown>>(\n a: T | undefined,\n b: T | undefined,\n): boolean {\n if (a === b) return true;\n if (!a || !b) return false;\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n if (keysA.length !== keysB.length) return false;\n return keysA.every((key) => {\n const valA = a[key];\n const valB = b[key];\n if (valA instanceof Date && valB instanceof Date) {\n return valA.getTime() === valB.getTime();\n }\n return valA === valB;\n });\n}\n\n@Injectable()\nexport class SchematicService {\n private client = inject(SCHEMATIC_CLIENT);\n\n private flagValueCache = new Map<string, Observable<boolean>>();\n private entitlementCache = new Map<\n string,\n Observable<SchematicJS.CheckFlagReturn>\n >();\n private creditBalanceCache = new Map<\n string,\n Observable<SchematicCreditBalance>\n >();\n private creditSpendPoliciesCache?: Observable<SchematicCreditSpendPolicies>;\n private planCache?: Observable<SchematicJS.CheckPlanReturn | undefined>;\n private isPendingCache?: Observable<boolean>;\n\n getClient(): SchematicJS.Schematic {\n return this.client;\n }\n\n setContext(context: SchematicJS.SchematicContext): void {\n this.client.setContext(context);\n }\n\n identify(body: SchematicJS.EventBodyIdentify): void {\n this.client.identify(body);\n }\n\n track(body: SchematicJS.EventBodyTrack): void {\n this.client.track(body);\n }\n\n flagValue$(key: string, fallback: boolean = false): Observable<boolean> {\n const cacheKey = `${key}:${fallback}`;\n let cached = this.flagValueCache.get(cacheKey);\n if (cached) return cached;\n\n cached = new Observable<boolean>((subscriber) => {\n const current = this.client.getFlagValue(key);\n subscriber.next(current ?? fallback);\n\n const unsubscribe = this.client.addFlagValueListener(key, () => {\n const value = this.client.getFlagValue(key);\n subscriber.next(value ?? fallback);\n });\n\n return () => unsubscribe();\n }).pipe(\n distinctUntilChanged(),\n shareReplay({ bufferSize: 1, refCount: true }),\n finalize(() => this.flagValueCache.delete(cacheKey)),\n );\n\n this.flagValueCache.set(cacheKey, cached);\n return cached;\n }\n\n entitlement$(\n key: string,\n fallback: boolean = false,\n ): Observable<SchematicJS.CheckFlagReturn> {\n const cacheKey = `${key}:${fallback}`;\n let cached = this.entitlementCache.get(cacheKey);\n if (cached) return cached;\n\n const fallbackCheck: SchematicJS.CheckFlagReturn = {\n flag: key,\n reason: \"Fallback\",\n value: fallback,\n };\n\n cached = new Observable<SchematicJS.CheckFlagReturn>((subscriber) => {\n const current = this.client.getFlagCheck(key);\n subscriber.next(current ?? fallbackCheck);\n\n const unsubscribe = this.client.addFlagCheckListener(key, () => {\n const check = this.client.getFlagCheck(key);\n subscriber.next(check ?? fallbackCheck);\n });\n\n return () => unsubscribe();\n }).pipe(\n distinctUntilChanged(shallowEqual),\n shareReplay({ bufferSize: 1, refCount: true }),\n finalize(() => this.entitlementCache.delete(cacheKey)),\n );\n\n this.entitlementCache.set(cacheKey, cached);\n return cached;\n }\n\n plan$(): Observable<SchematicJS.CheckPlanReturn | undefined> {\n if (this.planCache) return this.planCache;\n\n this.planCache = new Observable<SchematicJS.CheckPlanReturn | undefined>(\n (subscriber) => {\n subscriber.next(this.client.getPlan());\n\n const unsubscribe = this.client.addPlanListener(() => {\n subscriber.next(this.client.getPlan());\n });\n\n return () => unsubscribe();\n },\n ).pipe(\n distinctUntilChanged(shallowEqual),\n shareReplay({ bufferSize: 1, refCount: true }),\n finalize(() => {\n this.planCache = undefined;\n }),\n );\n\n return this.planCache;\n }\n\n /**\n * Observe a company's live, lease-aware credit balance for a single credit type.\n *\n * Surfaces the spendable `settled` balance, sourced from the streamed credit\n * balances map (keyed by credit ID). It emits as partials arrive over the\n * DataStream, so it stays accurate during an open lease — when the raw\n * `remaining` would otherwise read stale / falsely \"exhausted\".\n *\n * The credit ID is available on a feature's entitlement: `entitlement$(key)`\n * emits `creditId` for credit-based features. Pass that stream straight in:\n * this accepts an Observable of credit IDs as well as a plain one, switching\n * to the new credit as the source emits. While the ID is undefined it emits\n * the client's loading state and a balance of 0.\n */\n creditBalance$(\n creditId: string | undefined | Observable<string | undefined>,\n ): Observable<SchematicCreditBalance> {\n if (isObservable(creditId)) {\n return creditId.pipe(\n distinctUntilChanged(),\n switchMap((id) => this.creditBalanceFor(id)),\n distinctUntilChanged(shallowEqual),\n shareReplay({ bufferSize: 1, refCount: true }),\n );\n }\n\n return this.creditBalanceFor(creditId);\n }\n\n /**\n * Emits a zeroed balance that still tracks the client's loading state, for\n * when there is no credit ID to read (a check that has not arrived yet, or a\n * feature that is not credit-based).\n */\n private noCreditBalance$(): Observable<SchematicCreditBalance> {\n return this.isPending$().pipe(\n map((isLoading) => ({ balance: 0, isLoading })),\n );\n }\n\n private creditBalanceFor(\n creditId: string | undefined,\n ): Observable<SchematicCreditBalance> {\n if (creditId === undefined) return this.noCreditBalance$();\n\n let cached = this.creditBalanceCache.get(creditId);\n if (cached) return cached;\n\n cached = new Observable<SchematicCreditBalance>((subscriber) => {\n const emit = () => {\n const balance = this.client.getCreditBalance(creditId);\n subscriber.next({\n balance: balance?.settled ?? 0,\n isLoading: balance === undefined && this.client.getIsPending(),\n });\n };\n\n emit();\n\n const unsubscribeBalance = this.client.addCreditBalanceListener(() =>\n emit(),\n );\n const unsubscribePending = this.client.addIsPendingListener(() => emit());\n\n return () => {\n unsubscribeBalance();\n unsubscribePending();\n };\n }).pipe(\n distinctUntilChanged(shallowEqual),\n shareReplay({ bufferSize: 1, refCount: true }),\n finalize(() => this.creditBalanceCache.delete(creditId)),\n );\n\n this.creditBalanceCache.set(creditId, cached);\n return cached;\n }\n\n /**\n * Observe every credit spend policy binding the current context, company-scope\n * first. It emits as partials arrive over the DataStream, so a policy edited\n * or deleted in the dashboard arrives without a refetch. A window policy also\n * carries `consumed` and `resetsAt`, which move as credits are spent.\n */\n creditSpendPolicies$(): Observable<SchematicCreditSpendPolicies> {\n if (this.creditSpendPoliciesCache) return this.creditSpendPoliciesCache;\n\n this.creditSpendPoliciesCache =\n new Observable<SchematicCreditSpendPolicies>((subscriber) => {\n const emit = () => {\n const policies = this.client.getCreditSpendPolicies();\n subscriber.next({\n policies,\n isLoading: policies.length === 0 && this.client.getIsPending(),\n });\n };\n\n emit();\n\n const unsubscribePolicies = this.client.addCreditSpendPolicyListener(\n () => emit(),\n );\n const unsubscribePending = this.client.addIsPendingListener(() =>\n emit(),\n );\n\n return () => {\n unsubscribePolicies();\n unsubscribePending();\n };\n }).pipe(\n distinctUntilChanged(shallowEqual),\n shareReplay({ bufferSize: 1, refCount: true }),\n finalize(() => {\n this.creditSpendPoliciesCache = undefined;\n }),\n );\n\n return this.creditSpendPoliciesCache;\n }\n\n isPending$(): Observable<boolean> {\n if (this.isPendingCache) return this.isPendingCache;\n\n this.isPendingCache = new Observable<boolean>((subscriber) => {\n subscriber.next(this.client.getIsPending());\n\n const unsubscribe = this.client.addIsPendingListener(() => {\n subscriber.next(this.client.getIsPending());\n });\n\n return () => unsubscribe();\n }).pipe(\n distinctUntilChanged(),\n shareReplay({ bufferSize: 1, refCount: true }),\n finalize(() => {\n this.isPendingCache = undefined;\n }),\n );\n\n return this.isPendingCache;\n }\n}\n","export const version = \"1.7.0\";\n","import { DestroyRef, inject, makeEnvironmentProviders } from \"@angular/core\";\nimport * as SchematicJS from \"@schematichq/schematic-js\";\n\nimport { SchematicService } from \"./schematic.service\";\nimport { SCHEMATIC_CLIENT } from \"./token\";\nimport { version } from \"./version\";\n\ntype BaseSchematicConfig = Omit<SchematicJS.SchematicOptions, \"useWebSocket\">;\n\ntype SchematicConfigWithClient = BaseSchematicConfig & {\n client: SchematicJS.Schematic;\n publishableKey?: never;\n};\n\ntype SchematicConfigWithKey = BaseSchematicConfig & {\n client?: never;\n publishableKey: string;\n};\n\nexport type SchematicConfig =\n SchematicConfigWithClient | SchematicConfigWithKey;\n\nexport function provideSchematic(config: SchematicConfig) {\n const {\n client: providedClient,\n publishableKey,\n additionalHeaders,\n ...restOpts\n } = config;\n\n return makeEnvironmentProviders([\n {\n provide: SCHEMATIC_CLIENT,\n useFactory: () => {\n const isProvidedClient = !!providedClient;\n\n const client = isProvidedClient\n ? providedClient\n : new SchematicJS.Schematic(publishableKey!, {\n ...restOpts,\n useWebSocket: true,\n additionalHeaders: {\n \"X-Schematic-Client-Version\": `schematic-angular@${version}`,\n ...additionalHeaders,\n },\n });\n\n const destroyRef = inject(DestroyRef);\n destroyRef.onDestroy(() => {\n if (!isProvidedClient) {\n client.cleanup().catch((error: unknown) => {\n console.error(\"Error during Schematic cleanup:\", error);\n });\n }\n });\n\n return client;\n },\n },\n SchematicService,\n ]);\n}\n"],"mappings":";;;;;AAGA,MAAa,mBAAmB,IAAI,eAClC,iBAAiB;ACyBnB,SAAS,aACP,GACA,GAAgB;CAEhB,IAAI,MAAM,GAAG,OAAO;CACpB,IAAI,CAAC,KAAK,CAAC,GAAG,OAAO;CACrB,MAAM,QAAQ,OAAO,KAAK,CAAC;CAC3B,MAAM,QAAQ,OAAO,KAAK,CAAC;CAC3B,IAAI,MAAM,WAAW,MAAM,QAAQ,OAAO;CAC1C,OAAO,MAAM,OAAO,QAAO;EACzB,MAAM,OAAO,EAAE;EACf,MAAM,OAAO,EAAE;EACf,IAAI,gBAAgB,QAAQ,gBAAgB,MAC1C,OAAO,KAAK,QAAO,MAAO,KAAK,QAAO;EAExC,OAAO,SAAS;CAClB,CAAC;AACH;AAGA,IAAa,mBAAb,MAAa,iBAAgB;CACnB,SAAS,OAAO,gBAAgB;CAEhC,iCAAiB,IAAI,IAAG;CACxB,mCAAmB,IAAI,IAAG;CAI1B,qCAAqB,IAAI,IAAG;CAI5B;CACA;CACA;CAER,YAAS;EACP,OAAO,KAAK;CACd;CAEA,WAAW,SAAqC;EAC9C,KAAK,OAAO,WAAW,OAAO;CAChC;CAEA,SAAS,MAAmC;EAC1C,KAAK,OAAO,SAAS,IAAI;CAC3B;CAEA,MAAM,MAAgC;EACpC,KAAK,OAAO,MAAM,IAAI;CACxB;CAEA,WAAW,KAAa,WAAoB,OAAK;EAC/C,MAAM,WAAW,GAAG,IAAG,GAAI;EAC3B,IAAI,SAAS,KAAK,eAAe,IAAI,QAAQ;EAC7C,IAAI,QAAQ,OAAO;EAEnB,SAAS,IAAI,YAAqB,eAAc;GAC9C,MAAM,UAAU,KAAK,OA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AAA;;AAAhB,GAAA,yBAAA;CAAA,YAAA;CAAA,SAAA;CAAA,UAAA;CAAA,MAAA;CAAgB,YAAA,CAAA,EAD5B,MAAA,WAAA,CAAA;;AChDD,MAAa,UAAU;ACsBvB,SAAgB,iBAAiB,QAAuB;CACtD,MAAM,EACJ,QAAQ,gBACR,gBACA,mBACA,GAAG,aACD;CAEJ,OAAO,yBAAyB,CAC9B;EACE,SAAS;EACT,kBAAiB;GACf,MAAM,mBAAmB,CAAC,CAAC;GAE3B,MAAM,SAAS,mBACX,iBACA,IAAI,YAAY,UAAU,gBAAiB;IACzC,GAAG;IACH,cAAc;IACd,mBAAmB;KACjB,8BAA8B,qBAAqB;KACnD,GAAG;IACJ;GACF,CAAA;GAGL,AADmB,OAAO,UAC1B,CAAA,CAAW,gBAAe;IACxB,IAAI,CAAC,kBACH,OAAO,QAAO,CAAE,CAAC,OAAO,UAAkB;KACxC,QAAQ,MAAM,mCAAmC,KAAK;IACxD,CAAC;GAEL,CAAC;GAED,OAAO;EACT;CACD,GACD,gBACD,CAAA;AACH"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@schematichq/schematic-angular",
3
- "version": "1.5.0",
3
+ "version": "1.7.0",
4
4
  "author": "Schematic <engineering@schematichq.com>",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -8,19 +8,14 @@
8
8
  "url": "git+ssh://git@github.com/SchematicHQ/schematic-js.git"
9
9
  },
10
10
  "dependencies": {
11
- "@schematichq/schematic-js": "^1.5.0",
11
+ "@schematichq/schematic-js": "^1.10.0",
12
12
  "tslib": "^2.3.0"
13
13
  },
14
14
  "peerDependencies": {
15
15
  "@angular/core": ">=19.0.0",
16
16
  "rxjs": ">=7.0.0"
17
17
  },
18
- "resolutions": {
19
- "minimatch": ">=3.1.3",
20
- "esbuild": ">=0.28.1",
21
- "@babel/core": "^7.29.6"
22
- },
23
- "packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e",
18
+ "packageManager": "pnpm@11.9.0+sha512.bd682d5d03fe525ef7c9fd6780c6884d1e756ac4c9c9fe00c538782824310dcf90e3ddc4f53835f06dfaebd5085e41855e0bcbb3b60de2ac5bbab89e5036f03b",
24
19
  "module": "fesm2022/schematichq-schematic-angular.mjs",
25
20
  "typings": "types/schematichq-schematic-angular.d.ts",
26
21
  "exports": {
@@ -1,60 +1,80 @@
1
- import * as i0 from '@angular/core';
2
- import { InjectionToken } from '@angular/core';
3
- import * as SchematicJS from '@schematichq/schematic-js';
4
- export { CheckFlagReturn, CheckPlanReturn, CompanyCreditBalance, CreditBalance, CreditBalances, Event, EventBody, EventBodyIdentify, EventBodyTrack, EventType, Keys, RuleType, Schematic, SchematicContext, SchematicOptions, StoragePersister, Traits, TrialStatus, UsagePeriod } from '@schematichq/schematic-js';
5
- import { Observable } from 'rxjs';
6
-
1
+ import * as SchematicJS from "@schematichq/schematic-js";
2
+ import { CheckFlagReturn, CheckPlanReturn, CompanyCreditBalance, CreditBalance, CreditBalances, CreditSpendPolicies, CreditSpendPolicy, CreditSpendPolicyKind, CreditSpendPolicyScope, CreditSpendWindow, Event, EventBody, EventBodyIdentify, EventBodyTrack, EventType, Keys, RuleType, Schematic, SchematicContext, SchematicOptions, StoragePersister, Traits, TrialStatus, UsagePeriod, WarningTier } from "@schematichq/schematic-js";
3
+ import * as i0 from "@angular/core";
4
+ import { InjectionToken } from "@angular/core";
5
+ import { Observable } from "rxjs";
7
6
  type BaseSchematicConfig = Omit<SchematicJS.SchematicOptions, "useWebSocket">;
8
7
  type SchematicConfigWithClient = BaseSchematicConfig & {
9
- client: SchematicJS.Schematic;
10
- publishableKey?: never;
8
+ client: SchematicJS.Schematic;
9
+ publishableKey?: never;
11
10
  };
12
11
  type SchematicConfigWithKey = BaseSchematicConfig & {
13
- client?: never;
14
- publishableKey: string;
12
+ client?: never;
13
+ publishableKey: string;
15
14
  };
16
15
  type SchematicConfig = SchematicConfigWithClient | SchematicConfigWithKey;
17
- declare function provideSchematic(config: SchematicConfig): i0.EnvironmentProviders;
18
-
19
- declare const SCHEMATIC_CLIENT: InjectionToken<SchematicJS.Schematic>;
20
-
16
+ export declare function provideSchematic(config: SchematicConfig): import("@angular/core").EnvironmentProviders;
17
+ export declare const SCHEMATIC_CLIENT: InjectionToken<SchematicJS.Schematic>;
21
18
  /** A company's credit balance for a single credit type, plus a loading flag */
22
19
  type SchematicCreditBalance = {
23
- /** The spendable balance; 0 while loading or when the company holds no balance in this credit */
24
- balance: number;
25
- /** True while the balance is still loading and no value has arrived yet */
26
- isLoading: boolean;
20
+ /** The spendable balance; 0 while loading or when the company holds no balance in this credit */
21
+ balance: number;
22
+ /** True while the balance is still loading and no value has arrived yet */
23
+ isLoading: boolean;
27
24
  };
28
- declare class SchematicService {
29
- private client;
30
- private flagValueCache;
31
- private entitlementCache;
32
- private creditBalanceCache;
33
- private planCache?;
34
- private isPendingCache?;
35
- getClient(): SchematicJS.Schematic;
36
- setContext(context: SchematicJS.SchematicContext): void;
37
- identify(body: SchematicJS.EventBodyIdentify): void;
38
- track(body: SchematicJS.EventBodyTrack): void;
39
- flagValue$(key: string, fallback?: boolean): Observable<boolean>;
40
- entitlement$(key: string, fallback?: boolean): Observable<SchematicJS.CheckFlagReturn>;
41
- plan$(): Observable<SchematicJS.CheckPlanReturn | undefined>;
42
- /**
43
- * Observe a company's live, lease-aware credit balance for a single credit type.
44
- *
45
- * Surfaces the spendable `settled` balance, sourced from the streamed credit
46
- * balances map (keyed by credit ID). It emits as partials arrive over the
47
- * DataStream, so it stays accurate during an open lease — when the raw
48
- * `remaining` would otherwise read stale / falsely "exhausted".
49
- *
50
- * The credit ID is available on a feature's entitlement: `entitlement$(key)`
51
- * emits `creditId` for credit-based features.
52
- */
53
- creditBalance$(creditId: string): Observable<SchematicCreditBalance>;
54
- isPending$(): Observable<boolean>;
55
- static ɵfac: i0.ɵɵFactoryDeclaration<SchematicService, never>;
56
- static ɵprov: i0.ɵɵInjectableDeclaration<SchematicService>;
25
+ /** The credit spend policies binding the current context, plus a loading flag */
26
+ type SchematicCreditSpendPolicies = {
27
+ /** Company-scope policies first, then the user's own; empty when none bind */
28
+ policies: SchematicJS.CreditSpendPolicies;
29
+ /** True while the policies are still loading and nothing has arrived yet */
30
+ isLoading: boolean;
31
+ };
32
+ export declare class SchematicService {
33
+ private client;
34
+ private flagValueCache;
35
+ private entitlementCache;
36
+ private creditBalanceCache;
37
+ private creditSpendPoliciesCache?;
38
+ private planCache?;
39
+ private isPendingCache?;
40
+ getClient(): SchematicJS.Schematic;
41
+ setContext(context: SchematicJS.SchematicContext): void;
42
+ identify(body: SchematicJS.EventBodyIdentify): void;
43
+ track(body: SchematicJS.EventBodyTrack): void;
44
+ flagValue$(key: string, fallback?: boolean): Observable<boolean>;
45
+ entitlement$(key: string, fallback?: boolean): Observable<SchematicJS.CheckFlagReturn>;
46
+ plan$(): Observable<SchematicJS.CheckPlanReturn | undefined>;
47
+ /**
48
+ * Observe a company's live, lease-aware credit balance for a single credit type.
49
+ *
50
+ * Surfaces the spendable `settled` balance, sourced from the streamed credit
51
+ * balances map (keyed by credit ID). It emits as partials arrive over the
52
+ * DataStream, so it stays accurate during an open lease — when the raw
53
+ * `remaining` would otherwise read stale / falsely "exhausted".
54
+ *
55
+ * The credit ID is available on a feature's entitlement: `entitlement$(key)`
56
+ * emits `creditId` for credit-based features. Pass that stream straight in:
57
+ * this accepts an Observable of credit IDs as well as a plain one, switching
58
+ * to the new credit as the source emits. While the ID is undefined it emits
59
+ * the client's loading state and a balance of 0.
60
+ */
61
+ creditBalance$(creditId: string | undefined | Observable<string | undefined>): Observable<SchematicCreditBalance>;
62
+ /**
63
+ * Emits a zeroed balance that still tracks the client's loading state, for
64
+ * when there is no credit ID to read (a check that has not arrived yet, or a
65
+ * feature that is not credit-based).
66
+ */
67
+ private noCreditBalance$;
68
+ private creditBalanceFor;
69
+ /**
70
+ * Observe every credit spend policy binding the current context, company-scope
71
+ * first. It emits as partials arrive over the DataStream, so a policy edited
72
+ * or deleted in the dashboard arrives without a refetch. A window policy also
73
+ * carries `consumed` and `resetsAt`, which move as credits are spent.
74
+ */
75
+ creditSpendPolicies$(): Observable<SchematicCreditSpendPolicies>;
76
+ isPending$(): Observable<boolean>;
77
+ static ɵfac: i0.ɵɵFactoryDeclaration<SchematicService, never>;
78
+ static ɵprov: i0.ɵɵInjectableDeclaration<any>;
57
79
  }
58
-
59
- export { SCHEMATIC_CLIENT, SchematicService, provideSchematic };
60
- export type { SchematicConfig, SchematicCreditBalance };
80
+ export { type CheckFlagReturn, type CheckPlanReturn, type CompanyCreditBalance, type CreditBalance, type CreditBalances, type CreditSpendPolicies, type CreditSpendPolicy, type CreditSpendPolicyKind, type CreditSpendPolicyScope, type CreditSpendWindow, type Event, type EventBody, type EventBodyIdentify, type EventBodyTrack, type EventType, type Keys, RuleType, Schematic, type SchematicConfig, type SchematicContext, type SchematicCreditBalance, type SchematicCreditSpendPolicies, type SchematicOptions, type StoragePersister, type Traits, TrialStatus, UsagePeriod, type WarningTier };