@bcis/sdk 0.1.3 → 0.2.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/LICENSE +185 -0
- package/README.md +61 -1
- package/dist/index.d.mts +95 -1
- package/dist/index.d.ts +95 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship made available under
|
|
36
|
+
the License, as indicated by a copyright notice that is included in
|
|
37
|
+
or attached to the work (an example is provided in the Appendix below).
|
|
38
|
+
|
|
39
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
40
|
+
form, that is based on (or derived from) the Work and for which the
|
|
41
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
42
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
43
|
+
of this License, Derivative Works shall not include works that remain
|
|
44
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
45
|
+
the Work and derivative works thereof.
|
|
46
|
+
|
|
47
|
+
"Contribution" shall mean, as submitted to the Licensor for inclusion
|
|
48
|
+
in the Work by the copyright owner or by an individual or Legal Entity
|
|
49
|
+
authorized to submit on behalf of the copyright owner. For the purposes
|
|
50
|
+
of this definition, "submitted" means any form of electronic, verbal,
|
|
51
|
+
or written communication sent to the Licensor or its representatives,
|
|
52
|
+
including but not limited to communication on electronic mailing lists,
|
|
53
|
+
source code control systems, and issue tracking systems that are managed
|
|
54
|
+
by, or on behalf of, the Licensor for the purpose of discussing and
|
|
55
|
+
improving the Work, but excluding communication that is conspicuously
|
|
56
|
+
marked or designated in writing by the copyright owner as "Not a
|
|
57
|
+
Contribution."
|
|
58
|
+
|
|
59
|
+
"Contributor" shall mean Licensor and any Legal Entity on behalf of
|
|
60
|
+
whom a Contribution has been received by the Licensor and subsequently
|
|
61
|
+
incorporated within the Work.
|
|
62
|
+
|
|
63
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
64
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
65
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
66
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
67
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
68
|
+
Work and such Derivative Works in Source or Object form.
|
|
69
|
+
|
|
70
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
71
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
72
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
73
|
+
(except as stated in this section) patent license to make, have made,
|
|
74
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
75
|
+
where such license applies only to those patent claims licensable
|
|
76
|
+
by such Contributor that are necessarily infringed by their
|
|
77
|
+
Contribution(s) alone or by the combination of their Contribution(s)
|
|
78
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
79
|
+
institute patent litigation against any entity (including a cross-claim
|
|
80
|
+
or counterclaim in a lawsuit) alleging that the Work or any
|
|
81
|
+
Contribution embodied within the Work constitutes direct or contributory
|
|
82
|
+
patent infringement, then any patent licenses granted to You under
|
|
83
|
+
this License for that Work shall terminate as of the date such
|
|
84
|
+
litigation is filed.
|
|
85
|
+
|
|
86
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
87
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
88
|
+
modifications, and in Source or Object form, provided that You
|
|
89
|
+
meet the following conditions:
|
|
90
|
+
|
|
91
|
+
(a) You must give any other recipients of the Work or Derivative Works
|
|
92
|
+
a copy of this License; and
|
|
93
|
+
|
|
94
|
+
(b) You must cause any modified files to carry prominent notices
|
|
95
|
+
stating that You changed the files; and
|
|
96
|
+
|
|
97
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
98
|
+
that You distribute, all copyright, patent, trademark, and
|
|
99
|
+
attribution notices from the Source form of the Work,
|
|
100
|
+
excluding those notices that do not pertain to any part of
|
|
101
|
+
the Derivative Works; and
|
|
102
|
+
|
|
103
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
104
|
+
distribution, You must include a readable copy of the attribution
|
|
105
|
+
notices contained within such NOTICE file, in at least one
|
|
106
|
+
of the following places: within a NOTICE text file distributed
|
|
107
|
+
as part of the Derivative Works; within the Source form or
|
|
108
|
+
documentation, if provided along with the Derivative Works; or,
|
|
109
|
+
within a display generated by the Derivative Works, if and
|
|
110
|
+
wherever such third-party notices normally appear. The contents
|
|
111
|
+
of the NOTICE file are for informational purposes only and
|
|
112
|
+
do not modify the License. You may add Your own attribution
|
|
113
|
+
notices within Derivative Works that You distribute, alongside
|
|
114
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
115
|
+
that such additional attribution notices cannot be construed
|
|
116
|
+
as modifying the License.
|
|
117
|
+
|
|
118
|
+
You may add Your own license statement for Your modifications and
|
|
119
|
+
may provide additional grant of rights to use, copy, modify, merge,
|
|
120
|
+
publish, distribute, sublicense, and/or sell copies of the
|
|
121
|
+
Contribution, either on Your own behalf and on Your sole
|
|
122
|
+
responsibility, or together with other Contributors, on the terms
|
|
123
|
+
and conditions of this License.
|
|
124
|
+
|
|
125
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
126
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
127
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
128
|
+
this License, without any additional terms or conditions.
|
|
129
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
130
|
+
the terms of any separate license agreement you may have executed
|
|
131
|
+
with Licensor regarding such Contributions.
|
|
132
|
+
|
|
133
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
134
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
135
|
+
except as required for reasonable and customary use in describing the
|
|
136
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
137
|
+
|
|
138
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
139
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
140
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
141
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
142
|
+
implied, including, without limitation, any warranties or conditions
|
|
143
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
144
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
145
|
+
appropriateness of using or redistributing the Work and assume any
|
|
146
|
+
risks associated with Your exercise of permissions under this License.
|
|
147
|
+
|
|
148
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
149
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
150
|
+
unless required by applicable law (such as deliberate and grossly
|
|
151
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
152
|
+
liable to You for damages, including any direct, indirect, special,
|
|
153
|
+
incidental, or exemplary damages of any character arising as a
|
|
154
|
+
result of this License or out of the use or inability to use the
|
|
155
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
156
|
+
work stoppage, computer failure or malfunction, or all other
|
|
157
|
+
commercial damages or losses), even if such Contributor has been
|
|
158
|
+
advised of the possibility of such damages.
|
|
159
|
+
|
|
160
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
161
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
162
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
163
|
+
or other liability obligations and/or rights consistent with this
|
|
164
|
+
License. However, in accepting such obligations, You may act only
|
|
165
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
166
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
167
|
+
defend, and hold each Contributor harmless for any liability
|
|
168
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
169
|
+
of your accepting any such warranty or additional liability.
|
|
170
|
+
|
|
171
|
+
END OF TERMS AND CONDITIONS
|
|
172
|
+
|
|
173
|
+
Copyright 2025 BCIS (Building Cost Information Service)
|
|
174
|
+
|
|
175
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
176
|
+
you may not use this file except in compliance with the License.
|
|
177
|
+
You may obtain a copy of the License at
|
|
178
|
+
|
|
179
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
180
|
+
|
|
181
|
+
Unless required by applicable law or agreed to in writing, software
|
|
182
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
183
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
184
|
+
See the License for the specific language governing permissions and
|
|
185
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -24,7 +24,7 @@ Use this flow for back-end or machine-to-machine integrations.
|
|
|
24
24
|
Tokens are fetched and renewed automatically — no user interaction required.
|
|
25
25
|
|
|
26
26
|
```typescript
|
|
27
|
-
import { AuthManager, CoreApiClient, ResidentialRebuildClient, ScheduleOfRatesClient } from '@bcis/sdk';
|
|
27
|
+
import { AuthManager, CoreApiClient, DurationCalculatorClient, ResidentialRebuildClient, ScheduleOfRatesClient } from '@bcis/sdk';
|
|
28
28
|
|
|
29
29
|
const auth = new AuthManager({
|
|
30
30
|
flow: 'client-credentials',
|
|
@@ -149,6 +149,63 @@ Returns codes lists or other supporting data
|
|
|
149
149
|
|
|
150
150
|
---
|
|
151
151
|
|
|
152
|
+
### `DurationCalculatorClient`
|
|
153
|
+
|
|
154
|
+
**Base URL:** `https://api.bcis.co.uk/rebuild-core`
|
|
155
|
+
|
|
156
|
+
Duration calculator API Documentation
|
|
157
|
+
|
|
158
|
+
**Instantiation:**
|
|
159
|
+
|
|
160
|
+
```typescript
|
|
161
|
+
import { AuthManager, DurationCalculatorClient } from '@bcis/sdk';
|
|
162
|
+
|
|
163
|
+
const client = new DurationCalculatorClient(auth);
|
|
164
|
+
|
|
165
|
+
// Override the base URL (e.g. for a staging environment):
|
|
166
|
+
// const client = new DurationCalculatorClient(auth, { baseUrl: 'https://api.bcis.co.uk/rebuild-core' });
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
**Methods:**
|
|
170
|
+
|
|
171
|
+
#### `getModels(params: GetModelsParams): Promise<DurationModelsDto>`
|
|
172
|
+
|
|
173
|
+
This endpoint provides a list of models, quarters, and locations. Parameters from these lists will be used to perform duration calculations.
|
|
174
|
+
|
|
175
|
+
| Parameter | Type | Required | Description |
|
|
176
|
+
|-----------|------|:--------:|-------------|
|
|
177
|
+
| `publication-date` | string | | The date of the publication in YYYY-MM-DD format. Can be used to reproduce a calculation as it would have been performed |
|
|
178
|
+
|
|
179
|
+
#### `getOptions(params: GetOptionsParams): Promise<DurationModelOptionsDto>`
|
|
180
|
+
|
|
181
|
+
This endpoint provides a list of: building functions, procurements, selection of contractor, and client organisations. Parameters from these lists will be used to perform duration calculations.
|
|
182
|
+
|
|
183
|
+
| Parameter | Type | Required | Description |
|
|
184
|
+
|-----------|------|:--------:|-------------|
|
|
185
|
+
| `model-id` | number | ✓ | There are two separate models that underlie the calculator: one for new build projects and one for refurbishment schemes |
|
|
186
|
+
|
|
187
|
+
#### `calculateDuration(params: CalculateDurationParams): Promise<CalculationResultDto>`
|
|
188
|
+
|
|
189
|
+
This endpoint provides the calculated construction duration based on the minimal details that might be available at the feasibility stage of a construction project.
|
|
190
|
+
For each estimate we provide two interval measures:
|
|
191
|
+
- Confidence interval: quantifies the uncertainty around the estimated mean duration. It gives a range that is likely to contain the true mean duration for projects with the same predictor values.
|
|
192
|
+
- Prediction interval: quantifies the likely range of outcomes for an individual project. It is wider than the confidence interval because it accounts both for uncertainty in the mean estimate and for the natural variability between individual projects.
|
|
193
|
+
Example: a CI of 5–13 weeks means the expected mean is likely in that range; a PI of 3–20 weeks means an individual project's duration is likely to fall somewhere in that wider range.
|
|
194
|
+
|
|
195
|
+
| Parameter | Type | Required | Description |
|
|
196
|
+
|-----------|------|:--------:|-------------|
|
|
197
|
+
| `publication-date` | string | | The date on which the project details are published. Can be used to reproduce a calculation as it would have been perfor |
|
|
198
|
+
| `organisation-id` | number | ✓ | The appropriate sector for the client organisation |
|
|
199
|
+
| `contractor-selection-id` | number | ✓ | The selection of contractor that best describes the way in which the contractor will be selected. |
|
|
200
|
+
| `procurement-id` | number | ✓ | The procurement process that best describes the way in which the project will be procured. |
|
|
201
|
+
| `function-group-id` | number | ✓ | The building function of the project. It is based on groups of building functions rather than the full list of building |
|
|
202
|
+
| `location-id` | number | ✓ | The location of the project. Is used to adjust the contract value to UK mean location. |
|
|
203
|
+
| `date-applicable` | string | ✓ | The quarter at which the contract value has been priced. Is used to adjust the contract value to the base price level us |
|
|
204
|
+
| `contract-value` | number | ✓ | The anticipated cost of construction expressed as at the anticipated start on site. |
|
|
205
|
+
| `model-id` | number | ✓ | There are two separate models that underlie the calculator: one for new build projects and one for refurbishment schemes |
|
|
206
|
+
|
|
207
|
+
---
|
|
208
|
+
|
|
152
209
|
### `ResidentialRebuildClient`
|
|
153
210
|
|
|
154
211
|
**Base URL:** `https://api.bcis.co.uk/residential-rebuild-calculator`
|
|
@@ -288,6 +345,9 @@ import type {
|
|
|
288
345
|
IndicesResponseDto,
|
|
289
346
|
TpsResponseDto,
|
|
290
347
|
CodesResponseDto,
|
|
348
|
+
DurationModelsDto,
|
|
349
|
+
DurationModelOptionsDto,
|
|
350
|
+
CalculationResultDto,
|
|
291
351
|
CalculationResponse,
|
|
292
352
|
UsageResponse,
|
|
293
353
|
EditionsDto,
|
package/dist/index.d.mts
CHANGED
|
@@ -330,6 +330,100 @@ declare class CoreApiClient {
|
|
|
330
330
|
codesUpdate(params: CodesUpdateParams): Promise<CodesResponseDto>;
|
|
331
331
|
}
|
|
332
332
|
|
|
333
|
+
interface DurationModelsDto {
|
|
334
|
+
models: Array<{
|
|
335
|
+
modelId: number;
|
|
336
|
+
title: string;
|
|
337
|
+
countryName: string;
|
|
338
|
+
currency: string;
|
|
339
|
+
currencyCode: string;
|
|
340
|
+
editionId: number;
|
|
341
|
+
defaultModel: boolean;
|
|
342
|
+
}>;
|
|
343
|
+
quarters: Array<{
|
|
344
|
+
dateApplicable: string;
|
|
345
|
+
quarter: string;
|
|
346
|
+
defaultQuarter: boolean;
|
|
347
|
+
}>;
|
|
348
|
+
locations: Array<{
|
|
349
|
+
locationId: number;
|
|
350
|
+
location: string;
|
|
351
|
+
defaultLocation: boolean;
|
|
352
|
+
}>;
|
|
353
|
+
}
|
|
354
|
+
interface DurationModelOptionsDto {
|
|
355
|
+
buildingFunctions: Array<{
|
|
356
|
+
id: number;
|
|
357
|
+
description: string;
|
|
358
|
+
defaultOption: boolean;
|
|
359
|
+
}>;
|
|
360
|
+
procurements: Array<{
|
|
361
|
+
id: number;
|
|
362
|
+
description: string;
|
|
363
|
+
defaultOption: boolean;
|
|
364
|
+
}>;
|
|
365
|
+
selectionOfContractors: Array<{
|
|
366
|
+
id: number;
|
|
367
|
+
description: string;
|
|
368
|
+
defaultOption: boolean;
|
|
369
|
+
}>;
|
|
370
|
+
clientOrganisations: Array<{
|
|
371
|
+
id: number;
|
|
372
|
+
description: string;
|
|
373
|
+
defaultOption: boolean;
|
|
374
|
+
}>;
|
|
375
|
+
}
|
|
376
|
+
interface CalculationResultDto {
|
|
377
|
+
estimatedDuration: number;
|
|
378
|
+
confidenceIntervalLower: number;
|
|
379
|
+
confidenceIntervalUpper: number;
|
|
380
|
+
predictionIntervalLower: number;
|
|
381
|
+
predictionIntervalUpper: number;
|
|
382
|
+
message?: string;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
interface GetModelsParams {
|
|
386
|
+
/** The date of the publication in YYYY-MM-DD format. Can be used to reproduce a calculation as it would have been performed at the given date. */
|
|
387
|
+
'publication-date'?: string;
|
|
388
|
+
}
|
|
389
|
+
interface GetOptionsParams {
|
|
390
|
+
/** There are two separate models that underlie the calculator: one for new build projects and one for refurbishment schemes. */
|
|
391
|
+
'model-id': number;
|
|
392
|
+
}
|
|
393
|
+
interface CalculateDurationParams {
|
|
394
|
+
/** The date on which the project details are published. Can be used to reproduce a calculation as it would have been performed at the given date. */
|
|
395
|
+
'publication-date'?: string;
|
|
396
|
+
/** The appropriate sector for the client organisation */
|
|
397
|
+
'organisation-id': number;
|
|
398
|
+
/** The selection of contractor that best describes the way in which the contractor will be selected. */
|
|
399
|
+
'contractor-selection-id': number;
|
|
400
|
+
/** The procurement process that best describes the way in which the project will be procured. */
|
|
401
|
+
'procurement-id': number;
|
|
402
|
+
/** The building function of the project. It is based on groups of building functions rather than the full list of building function codes used elsewhere in BCIS. */
|
|
403
|
+
'function-group-id': number;
|
|
404
|
+
/** The location of the project. Is used to adjust the contract value to UK mean location. */
|
|
405
|
+
'location-id': number;
|
|
406
|
+
/** The quarter at which the contract value has been priced. Is used to adjust the contract value to the base price level used by the models */
|
|
407
|
+
'date-applicable': string;
|
|
408
|
+
/** The anticipated cost of construction expressed as at the anticipated start on site. */
|
|
409
|
+
'contract-value': number;
|
|
410
|
+
/** There are two separate models that underlie the calculator: one for new build projects and one for refurbishment schemes. */
|
|
411
|
+
'model-id': number;
|
|
412
|
+
}
|
|
413
|
+
declare class DurationCalculatorClient {
|
|
414
|
+
private readonly client;
|
|
415
|
+
private readonly baseUrl;
|
|
416
|
+
constructor(auth: AuthManager, options?: {
|
|
417
|
+
baseUrl?: string;
|
|
418
|
+
});
|
|
419
|
+
/** Retrieve the list of models, quarters, and locations available for duration calculations */
|
|
420
|
+
getModels(params: GetModelsParams): Promise<DurationModelsDto>;
|
|
421
|
+
/** Retrieve a list of options for the duration-calculation parameters */
|
|
422
|
+
getOptions(params: GetOptionsParams): Promise<DurationModelOptionsDto>;
|
|
423
|
+
/** Retrieve the calculated construction duration */
|
|
424
|
+
calculateDuration(params: CalculateDurationParams): Promise<CalculationResultDto>;
|
|
425
|
+
}
|
|
426
|
+
|
|
333
427
|
type UsageResponse = Array<{
|
|
334
428
|
/** Month of calculations report */
|
|
335
429
|
calculationMonth?: string;
|
|
@@ -638,4 +732,4 @@ declare class ScheduleOfRatesClient {
|
|
|
638
732
|
getBuildUp(params: GetBuildUpParams): Promise<GetBuildUpResponseDto>;
|
|
639
733
|
}
|
|
640
734
|
|
|
641
|
-
export { type AbpResponseDto, type AuthConfig, AuthManager, type AuthorizationCodeConfig, BcisApiError, type CalculationResponse, type ClientCredentialsConfig, type CodesResponseDto, CoreApiClient, type EditionsDto, type Error$1 as Error, type GetBuildUpResponseDto, type GetRateResponseDto, type GetResourceResponseDto, type IndicesResponseDto, ResidentialRebuildClient, ScheduleOfRatesClient, type TokenResponse, type TpsResponseDto, type UsageResponse };
|
|
735
|
+
export { type AbpResponseDto, type AuthConfig, AuthManager, type AuthorizationCodeConfig, BcisApiError, type CalculationResponse, type CalculationResultDto, type ClientCredentialsConfig, type CodesResponseDto, CoreApiClient, DurationCalculatorClient, type DurationModelOptionsDto, type DurationModelsDto, type EditionsDto, type Error$1 as Error, type GetBuildUpResponseDto, type GetRateResponseDto, type GetResourceResponseDto, type IndicesResponseDto, ResidentialRebuildClient, ScheduleOfRatesClient, type TokenResponse, type TpsResponseDto, type UsageResponse };
|
package/dist/index.d.ts
CHANGED
|
@@ -330,6 +330,100 @@ declare class CoreApiClient {
|
|
|
330
330
|
codesUpdate(params: CodesUpdateParams): Promise<CodesResponseDto>;
|
|
331
331
|
}
|
|
332
332
|
|
|
333
|
+
interface DurationModelsDto {
|
|
334
|
+
models: Array<{
|
|
335
|
+
modelId: number;
|
|
336
|
+
title: string;
|
|
337
|
+
countryName: string;
|
|
338
|
+
currency: string;
|
|
339
|
+
currencyCode: string;
|
|
340
|
+
editionId: number;
|
|
341
|
+
defaultModel: boolean;
|
|
342
|
+
}>;
|
|
343
|
+
quarters: Array<{
|
|
344
|
+
dateApplicable: string;
|
|
345
|
+
quarter: string;
|
|
346
|
+
defaultQuarter: boolean;
|
|
347
|
+
}>;
|
|
348
|
+
locations: Array<{
|
|
349
|
+
locationId: number;
|
|
350
|
+
location: string;
|
|
351
|
+
defaultLocation: boolean;
|
|
352
|
+
}>;
|
|
353
|
+
}
|
|
354
|
+
interface DurationModelOptionsDto {
|
|
355
|
+
buildingFunctions: Array<{
|
|
356
|
+
id: number;
|
|
357
|
+
description: string;
|
|
358
|
+
defaultOption: boolean;
|
|
359
|
+
}>;
|
|
360
|
+
procurements: Array<{
|
|
361
|
+
id: number;
|
|
362
|
+
description: string;
|
|
363
|
+
defaultOption: boolean;
|
|
364
|
+
}>;
|
|
365
|
+
selectionOfContractors: Array<{
|
|
366
|
+
id: number;
|
|
367
|
+
description: string;
|
|
368
|
+
defaultOption: boolean;
|
|
369
|
+
}>;
|
|
370
|
+
clientOrganisations: Array<{
|
|
371
|
+
id: number;
|
|
372
|
+
description: string;
|
|
373
|
+
defaultOption: boolean;
|
|
374
|
+
}>;
|
|
375
|
+
}
|
|
376
|
+
interface CalculationResultDto {
|
|
377
|
+
estimatedDuration: number;
|
|
378
|
+
confidenceIntervalLower: number;
|
|
379
|
+
confidenceIntervalUpper: number;
|
|
380
|
+
predictionIntervalLower: number;
|
|
381
|
+
predictionIntervalUpper: number;
|
|
382
|
+
message?: string;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
interface GetModelsParams {
|
|
386
|
+
/** The date of the publication in YYYY-MM-DD format. Can be used to reproduce a calculation as it would have been performed at the given date. */
|
|
387
|
+
'publication-date'?: string;
|
|
388
|
+
}
|
|
389
|
+
interface GetOptionsParams {
|
|
390
|
+
/** There are two separate models that underlie the calculator: one for new build projects and one for refurbishment schemes. */
|
|
391
|
+
'model-id': number;
|
|
392
|
+
}
|
|
393
|
+
interface CalculateDurationParams {
|
|
394
|
+
/** The date on which the project details are published. Can be used to reproduce a calculation as it would have been performed at the given date. */
|
|
395
|
+
'publication-date'?: string;
|
|
396
|
+
/** The appropriate sector for the client organisation */
|
|
397
|
+
'organisation-id': number;
|
|
398
|
+
/** The selection of contractor that best describes the way in which the contractor will be selected. */
|
|
399
|
+
'contractor-selection-id': number;
|
|
400
|
+
/** The procurement process that best describes the way in which the project will be procured. */
|
|
401
|
+
'procurement-id': number;
|
|
402
|
+
/** The building function of the project. It is based on groups of building functions rather than the full list of building function codes used elsewhere in BCIS. */
|
|
403
|
+
'function-group-id': number;
|
|
404
|
+
/** The location of the project. Is used to adjust the contract value to UK mean location. */
|
|
405
|
+
'location-id': number;
|
|
406
|
+
/** The quarter at which the contract value has been priced. Is used to adjust the contract value to the base price level used by the models */
|
|
407
|
+
'date-applicable': string;
|
|
408
|
+
/** The anticipated cost of construction expressed as at the anticipated start on site. */
|
|
409
|
+
'contract-value': number;
|
|
410
|
+
/** There are two separate models that underlie the calculator: one for new build projects and one for refurbishment schemes. */
|
|
411
|
+
'model-id': number;
|
|
412
|
+
}
|
|
413
|
+
declare class DurationCalculatorClient {
|
|
414
|
+
private readonly client;
|
|
415
|
+
private readonly baseUrl;
|
|
416
|
+
constructor(auth: AuthManager, options?: {
|
|
417
|
+
baseUrl?: string;
|
|
418
|
+
});
|
|
419
|
+
/** Retrieve the list of models, quarters, and locations available for duration calculations */
|
|
420
|
+
getModels(params: GetModelsParams): Promise<DurationModelsDto>;
|
|
421
|
+
/** Retrieve a list of options for the duration-calculation parameters */
|
|
422
|
+
getOptions(params: GetOptionsParams): Promise<DurationModelOptionsDto>;
|
|
423
|
+
/** Retrieve the calculated construction duration */
|
|
424
|
+
calculateDuration(params: CalculateDurationParams): Promise<CalculationResultDto>;
|
|
425
|
+
}
|
|
426
|
+
|
|
333
427
|
type UsageResponse = Array<{
|
|
334
428
|
/** Month of calculations report */
|
|
335
429
|
calculationMonth?: string;
|
|
@@ -638,4 +732,4 @@ declare class ScheduleOfRatesClient {
|
|
|
638
732
|
getBuildUp(params: GetBuildUpParams): Promise<GetBuildUpResponseDto>;
|
|
639
733
|
}
|
|
640
734
|
|
|
641
|
-
export { type AbpResponseDto, type AuthConfig, AuthManager, type AuthorizationCodeConfig, BcisApiError, type CalculationResponse, type ClientCredentialsConfig, type CodesResponseDto, CoreApiClient, type EditionsDto, type Error$1 as Error, type GetBuildUpResponseDto, type GetRateResponseDto, type GetResourceResponseDto, type IndicesResponseDto, ResidentialRebuildClient, ScheduleOfRatesClient, type TokenResponse, type TpsResponseDto, type UsageResponse };
|
|
735
|
+
export { type AbpResponseDto, type AuthConfig, AuthManager, type AuthorizationCodeConfig, BcisApiError, type CalculationResponse, type CalculationResultDto, type ClientCredentialsConfig, type CodesResponseDto, CoreApiClient, DurationCalculatorClient, type DurationModelOptionsDto, type DurationModelsDto, type EditionsDto, type Error$1 as Error, type GetBuildUpResponseDto, type GetRateResponseDto, type GetResourceResponseDto, type IndicesResponseDto, ResidentialRebuildClient, ScheduleOfRatesClient, type TokenResponse, type TpsResponseDto, type UsageResponse };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var u=class{constructor(){this.token=null;}store(e){let
|
|
2
|
-
exports.AuthManager=d;exports.BcisApiError=p;exports.CoreApiClient=h;exports.
|
|
1
|
+
'use strict';var u=class{constructor(){this.token=null;}store(e){let t=e.expires_in!=null?Date.now()+e.expires_in*1e3:null;this.token={accessToken:e.access_token,expiresAt:t,refreshToken:e.refresh_token??null};}getAccessToken(){return this.token?.accessToken??null}getRefreshToken(){return this.token?.refreshToken??null}isExpired(e=30){return this.token?this.token.expiresAt===null?false:Date.now()>=this.token.expiresAt-e*1e3:true}clear(){this.token=null;}};async function k(n){let e=new URLSearchParams({grant_type:"client_credentials",client_id:n.clientId,client_secret:n.clientSecret});n.scopes&&n.scopes.length>0&&e.set("scope",n.scopes.join(" "));let t=n.tokenUrl;if(!t)throw new Error("tokenUrl is required for client credentials flow");let r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e.toString()});if(!r.ok){let o=await r.text().catch(()=>"");throw new Error(`Token request failed: ${r.status} ${r.statusText}${o?` \u2014 ${o}`:""}`)}return r.json()}function A(){let n=new Uint8Array(32);return crypto.getRandomValues(n),y(n)}async function T(n){let t=new TextEncoder().encode(n),r=await crypto.subtle.digest("SHA-256",t);return y(new Uint8Array(r))}function y(n){let e=String.fromCharCode(...n);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function w(n,e){let t=A(),r=await T(t),o=new URLSearchParams({response_type:"code",client_id:n.clientId,redirect_uri:n.redirectUri,code_challenge:r,code_challenge_method:"S256"});n.scopes&&n.scopes.length>0&&o.set("scope",n.scopes.join(" ")),e&&o.set("state",e);let i=n.authorizationUrl;if(!i)throw new Error("authorizationUrl is required for authorization-code flow");return {url:`${i}?${o.toString()}`,codeVerifier:t}}async function b(n,e,t){let r=new URLSearchParams({grant_type:"authorization_code",client_id:n.clientId,redirect_uri:n.redirectUri,code:e,code_verifier:t}),o=n.tokenUrl;if(!o)throw new Error("tokenUrl is required for authorization-code flow");return U(o,r)}async function R(n,e){let t=new URLSearchParams({grant_type:"refresh_token",client_id:n.clientId,refresh_token:e}),r=n.tokenUrl;if(!r)throw new Error("tokenUrl is required for authorization-code flow");return U(r,t)}async function U(n,e){let t=await fetch(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e.toString()});if(!t.ok){let r=await t.text().catch(()=>"");throw new Error(`Token request failed: ${t.status} ${t.statusText}${r?` \u2014 ${r}`:""}`)}return t.json()}var D="https://id.bcis.co.uk/.well-known/openid-configuration",C=new Map;async function P(n=D){let e=C.get(n);if(e)return e;let t=await fetch(n);if(!t.ok)throw new Error(`OIDC discovery failed: ${t.status} ${t.statusText} (${n})`);let r=await t.json();if(!r.token_endpoint||!r.authorization_endpoint)throw new Error(`OIDC discovery document at ${n} is missing required endpoints`);return C.set(n,r),r}var d=class{constructor(e){this.config=e;this.store=new u;this.inflight=null;this.endpoints=null;}async getAccessToken(){if(!this.store.isExpired())return this.store.getAccessToken();if(this.inflight)return await this.inflight,this.store.getAccessToken();this.inflight=this.refresh();try{await this.inflight;}finally{this.inflight=null;}let e=this.store.getAccessToken();if(!e)throw new Error("Failed to obtain access token");return e}async getAuthorizationUrl(e){if(this.config.flow!=="authorization-code")throw new Error("getAuthorizationUrl is only available for authorization-code flow");let t=await this.resolveEndpoints();return w({...this.config,...t},e)}async handleCallback(e,t){if(this.config.flow!=="authorization-code")throw new Error("handleCallback is only available for authorization-code flow");let r=await this.resolveEndpoints(),o=await b({...this.config,...r},e,t);this.store.store(o);}clearTokens(){this.store.clear();}async resolveEndpoints(){if(this.endpoints)return this.endpoints;let e=this.config;if(!e.tokenUrl||this.config.flow==="authorization-code"&&!e.authorizationUrl){let r=await P(e.discoveryUrl);this.endpoints={tokenUrl:e.tokenUrl??r.token_endpoint,authorizationUrl:e.authorizationUrl??r.authorization_endpoint};}else this.endpoints={tokenUrl:e.tokenUrl,authorizationUrl:e.authorizationUrl??""};return this.endpoints}async refresh(){let e=await this.resolveEndpoints();if(this.config.flow==="client-credentials"){let r=await k({...this.config,tokenUrl:e.tokenUrl});this.store.store(r);return}let t=this.store.getRefreshToken();if(t){let r=await R({...this.config,...e},t);this.store.store(r);return}throw new Error("No valid token available. Call getAuthorizationUrl() and handleCallback() first.")}};var p=class extends Error{constructor(t,r,o){super(`BCIS API error ${t} ${r}`);this.status=t;this.statusText=r;this.body=o;this.name="BcisApiError";}},s=class{constructor(e){this.auth=e;}async get(e,t,r={}){let o=await this.auth.getAccessToken(),i=new URL(e+t);for(let[c,l]of Object.entries(r))if(l!=null)if(Array.isArray(l))for(let x of l)i.searchParams.append(c,String(x));else i.searchParams.set(c,String(l));let a=await fetch(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"}});if(!a.ok){let c;try{c=await a.json();}catch{c=await a.text();}throw new p(a.status,a.statusText,c)}return a.json()}};var h=class{constructor(e,t){this.client=new s(e),this.baseUrl=t?.baseUrl??"https://api.bcis.co.uk/core-apis";}async abpRetrieve(e){return this.client.get(this.baseUrl,"/abp-retrieve",e)}async indicesRetrieve(e){return this.client.get(this.baseUrl,"/indices-retrieve",e)}async tpsRetrieve(e){return this.client.get(this.baseUrl,"/tps-retrieve",e)}async codesUpdate(e){return this.client.get(this.baseUrl,"/codes-update",e)}};var g=class{constructor(e,t){this.client=new s(e),this.baseUrl=t?.baseUrl??"https://api.bcis.co.uk/rebuild-core";}async getModels(e){return this.client.get(this.baseUrl,"/get-models",e)}async getOptions(e){return this.client.get(this.baseUrl,"/get-options",e)}async calculateDuration(e){return this.client.get(this.baseUrl,"/calculate-duration",e)}};var f=class{constructor(e,t){this.client=new s(e),this.baseUrl=t?.baseUrl??"https://api.bcis.co.uk/residential-rebuild-calculator";}async calculate(e){return this.client.get(this.baseUrl,"/rbls-calculate",e)}async reportUsage(e){return this.client.get(this.baseUrl,"/rbls-report-use",e)}};var m=class{constructor(e,t){this.client=new s(e),this.baseUrl=t?.baseUrl??"https://api.bcis.co.uk/schedule-of-rates";}async getBooksEdition(){return this.client.get(this.baseUrl,"/get-books-edition",{})}async getRates(e){return this.client.get(this.baseUrl,"/get-rates",e)}async getResources(e){return this.client.get(this.baseUrl,"/get-resources",e)}async getBuildUp(e){return this.client.get(this.baseUrl,"/get-build-up",e)}};
|
|
2
|
+
exports.AuthManager=d;exports.BcisApiError=p;exports.CoreApiClient=h;exports.DurationCalculatorClient=g;exports.ResidentialRebuildClient=f;exports.ScheduleOfRatesClient=m;//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/auth/token-store.ts","../src/auth/client-credentials.ts","../src/auth/authorization-code.ts","../src/auth/oidc-discovery.ts","../src/auth/auth-manager.ts","../src/http/fetch-client.ts","../src/clients/core-api.ts","../src/clients/residential-rebuild.ts","../src/clients/schedule-of-rates.ts"],"names":["TokenStore","response","expiresAt","bufferSeconds","fetchClientCredentialsToken","config","body","tokenUrl","text","generateCodeVerifier","array","base64UrlEncode","generateCodeChallenge","verifier","data","digest","bytes","str","getAuthorizationUrl","state","codeVerifier","codeChallenge","params","authUrl","exchangeCode","code","tokenRequest","refreshAccessToken","refreshToken","BCIS_DISCOVERY_URL","cache","fetchOidcConfig","discoveryUrl","cached","AuthManager","token","endpoints","tokenResponse","cfg","oidc","BcisApiError","status","statusText","FetchClient","auth","baseUrl","path","url","key","value","item","CoreApiClient","options","ResidentialRebuildClient","ScheduleOfRatesClient"],"mappings":"aAGO,IAAMA,CAAAA,CAAN,KAAiB,CAAjB,WAAA,EAAA,CACL,KAAQ,KAAA,CAA4B,KAAA,CAEpC,KAAA,CAAMC,CAAAA,CAA+B,CACnC,IAAMC,CAAAA,CACJD,CAAAA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S,SAAW,2CACrC,CAGA,MAAM,eAAA,EAAwC,CAC5C,OAAO,IAAA,CAAK,MAAA,CAAO,IAAiB,IAAA,CAAK,OAAA,CAAS,oBAAA,CAAsB,EAAE,CAC5E,CAGA,MAAM,QAAA,CAAS9B,EAAqD,CAClE,OAAO,IAAA,CAAK,MAAA,CAAO,GAAA,CAAwB,IAAA,CAAK,OAAA,CAAS,YAAA,CAAcA,CAA4C,CACrH,CAGA,MAAM,YAAA,CAAaA,EAA6D,CAC9E,OAAO,IAAA,CAAK,MAAA,CAAO,IAA4B,IAAA,CAAK,OAAA,CAAS,gBAAA,CAAkBA,CAA4C,CAC7H,CAGA,MAAM,UAAA,CAAWA,EAA0D,CACzE,OAAO,IAAA,CAAK,MAAA,CAAO,IAA2B,IAAA,CAAK,OAAA,CAAS,eAAA,CAAiBA,CAA4C,CAC3H,CACF","file":"index.js","sourcesContent":["import type { StoredToken, TokenResponse } from './types';\n\n/** In-memory token storage with expiry awareness. */\nexport class TokenStore {\n private token: StoredToken | null = null;\n\n store(response: TokenResponse): void {\n const expiresAt =\n response.expires_in != null\n ? Date.now() + response.expires_in * 1000\n : null;\n\n this.token = {\n accessToken: response.access_token,\n expiresAt,\n refreshToken: response.refresh_token ?? null,\n };\n }\n\n getAccessToken(): string | null {\n return this.token?.accessToken ?? null;\n }\n\n getRefreshToken(): string | null {\n return this.token?.refreshToken ?? null;\n }\n\n /**\n * Returns true if there is no token or the token is within `bufferSeconds`\n * of expiry. Defaults to a 30-second buffer to allow for clock skew.\n */\n isExpired(bufferSeconds = 30): boolean {\n if (!this.token) return true;\n if (this.token.expiresAt === null) return false;\n return Date.now() >= this.token.expiresAt - bufferSeconds * 1000;\n }\n\n clear(): void {\n this.token = null;\n }\n}\n","import type { ClientCredentialsConfig, TokenResponse } from './types';\n\n/**\n * Fetches a new access token using the OAuth2 Client Credentials flow.\n */\nexport async function fetchClientCredentialsToken(\n config: ClientCredentialsConfig\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: config.clientId,\n client_secret: config.clientSecret,\n });\n\n if (config.scopes && config.scopes.length > 0) {\n body.set('scope', config.scopes.join(' '));\n }\n\n const tokenUrl = config.tokenUrl;\n if (!tokenUrl) throw new Error('tokenUrl is required for client credentials flow');\n\n const response = await fetch(tokenUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `Token request failed: ${response.status} ${response.statusText}${text ? ` — ${text}` : ''}`\n );\n }\n\n return response.json() as Promise<TokenResponse>;\n}\n","import type { AuthorizationCodeConfig, TokenResponse } from './types';\n\n// ---------------------------------------------------------------------------\n// PKCE helpers\n// ---------------------------------------------------------------------------\n\n/** Generates a cryptographically random PKCE code verifier (43-128 chars). */\nexport function generateCodeVerifier(): string {\n const array = new Uint8Array(32);\n crypto.getRandomValues(array);\n return base64UrlEncode(array);\n}\n\n/** Derives a PKCE code challenge (S256) from a code verifier. */\nexport async function generateCodeChallenge(verifier: string): Promise<string> {\n const encoder = new TextEncoder();\n const data = encoder.encode(verifier);\n const digest = await crypto.subtle.digest('SHA-256', data);\n return base64UrlEncode(new Uint8Array(digest));\n}\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n const str = String.fromCharCode(...bytes);\n return btoa(str).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\n// ---------------------------------------------------------------------------\n// Authorization Code flows\n// ---------------------------------------------------------------------------\n\n/**\n * Builds the authorization URL to redirect the user to.\n * Returns the URL and the code verifier (must be stored and passed to exchangeCode).\n */\nexport async function getAuthorizationUrl(\n config: AuthorizationCodeConfig,\n state?: string\n): Promise<{ url: string; codeVerifier: string }> {\n const codeVerifier = generateCodeVerifier();\n const codeChallenge = await generateCodeChallenge(codeVerifier);\n\n const params = new URLSearchParams({\n response_type: 'code',\n client_id: config.clientId,\n redirect_uri: config.redirectUri,\n code_challenge: codeChallenge,\n code_challenge_method: 'S256',\n });\n\n if (config.scopes && config.scopes.length > 0) {\n params.set('scope', config.scopes.join(' '));\n }\n\n if (state) {\n params.set('state', state);\n }\n\n const authUrl = config.authorizationUrl;\n if (!authUrl) throw new Error('authorizationUrl is required for authorization-code flow');\n\n return {\n url: `${authUrl}?${params.toString()}`,\n codeVerifier,\n };\n}\n\n/**\n * Exchanges an authorization code for tokens.\n */\nexport async function exchangeCode(\n config: AuthorizationCodeConfig,\n code: string,\n codeVerifier: string\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: config.clientId,\n redirect_uri: config.redirectUri,\n code,\n code_verifier: codeVerifier,\n });\n\n const tokenUrl = config.tokenUrl;\n if (!tokenUrl) throw new Error('tokenUrl is required for authorization-code flow');\n return tokenRequest(tokenUrl, body);\n}\n\n/**\n * Refreshes an access token using a refresh token.\n */\nexport async function refreshAccessToken(\n config: AuthorizationCodeConfig,\n refreshToken: string\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: config.clientId,\n refresh_token: refreshToken,\n });\n\n const tokenUrl = config.tokenUrl;\n if (!tokenUrl) throw new Error('tokenUrl is required for authorization-code flow');\n return tokenRequest(tokenUrl, body);\n}\n\nasync function tokenRequest(\n tokenUrl: string,\n body: URLSearchParams\n): Promise<TokenResponse> {\n const response = await fetch(tokenUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `Token request failed: ${response.status} ${response.statusText}${text ? ` — ${text}` : ''}`\n );\n }\n\n return response.json() as Promise<TokenResponse>;\n}\n","const BCIS_DISCOVERY_URL = 'https://id.bcis.co.uk/.well-known/openid-configuration';\n\nexport interface OidcConfig {\n token_endpoint: string;\n authorization_endpoint: string;\n [key: string]: unknown;\n}\n\n/** Module-level cache keyed by discovery URL */\nconst cache = new Map<string, OidcConfig>();\n\n/**\n * Fetches and caches the OpenID Connect discovery document.\n * Defaults to the BCIS identity provider.\n */\nexport async function fetchOidcConfig(discoveryUrl = BCIS_DISCOVERY_URL): Promise<OidcConfig> {\n const cached = cache.get(discoveryUrl);\n if (cached) return cached;\n\n const response = await fetch(discoveryUrl);\n if (!response.ok) {\n throw new Error(\n `OIDC discovery failed: ${response.status} ${response.statusText} (${discoveryUrl})`\n );\n }\n\n const config = (await response.json()) as OidcConfig;\n\n if (!config.token_endpoint || !config.authorization_endpoint) {\n throw new Error(`OIDC discovery document at ${discoveryUrl} is missing required endpoints`);\n }\n\n cache.set(discoveryUrl, config);\n return config;\n}\n","import type { AuthConfig, AuthorizationCodeConfig, ClientCredentialsConfig } from './types';\nimport { TokenStore } from './token-store';\nimport { fetchClientCredentialsToken } from './client-credentials';\nimport {\n getAuthorizationUrl as buildAuthorizationUrl,\n exchangeCode,\n refreshAccessToken,\n} from './authorization-code';\nimport { fetchOidcConfig } from './oidc-discovery';\n\n/**\n * Centralized OAuth2 authentication manager.\n *\n * Supports:\n * - Client Credentials flow (server-to-server, fully automatic)\n * - Authorization Code + PKCE flow (user-facing applications)\n *\n * Endpoint URLs (`tokenUrl`, `authorizationUrl`) are optional — when omitted they are\n * resolved automatically from the BCIS OpenID Connect discovery document at\n * `https://id.bcis.co.uk/.well-known/openid-configuration`.\n *\n * @example Client Credentials (auto-discovered endpoints)\n * ```ts\n * const auth = new AuthManager({\n * flow: 'client-credentials',\n * clientId: 'my-id',\n * clientSecret: 'my-secret',\n * });\n * const token = await auth.getAccessToken();\n * ```\n *\n * @example Authorization Code (auto-discovered endpoints)\n * ```ts\n * const auth = new AuthManager({\n * flow: 'authorization-code',\n * clientId: 'my-id',\n * redirectUri: 'https://myapp.com/callback',\n * scopes: ['openid', 'profile'],\n * });\n *\n * // Step 1: redirect user\n * const { url, codeVerifier } = await auth.getAuthorizationUrl();\n * // store codeVerifier in session, redirect user to url\n *\n * // Step 2: on callback\n * await auth.handleCallback(code, codeVerifier);\n *\n * // Step 3: use the SDK\n * const token = await auth.getAccessToken();\n * ```\n */\nexport class AuthManager {\n private readonly store = new TokenStore();\n /** Pending token fetch promise to prevent concurrent requests */\n private inflight: Promise<void> | null = null;\n /** Cached resolved endpoints (populated lazily from OIDC discovery) */\n private endpoints: { tokenUrl: string; authorizationUrl: string } | null = null;\n\n constructor(private readonly config: AuthConfig) {}\n\n /**\n * Returns a valid access token, fetching or refreshing as needed.\n * For Client Credentials flow this is fully automatic.\n * For Authorization Code flow, `handleCallback` must have been called first.\n */\n async getAccessToken(): Promise<string> {\n if (!this.store.isExpired()) {\n return this.store.getAccessToken()!;\n }\n\n if (this.inflight) {\n await this.inflight;\n return this.store.getAccessToken()!;\n }\n\n this.inflight = this.refresh();\n try {\n await this.inflight;\n } finally {\n this.inflight = null;\n }\n\n const token = this.store.getAccessToken();\n if (!token) throw new Error('Failed to obtain access token');\n return token;\n }\n\n /**\n * Authorization Code flow only.\n * Builds and returns the authorization URL to redirect the user to.\n * The returned `codeVerifier` must be persisted (e.g. in session storage)\n * and passed to `handleCallback`.\n */\n async getAuthorizationUrl(state?: string): Promise<{ url: string; codeVerifier: string }> {\n if (this.config.flow !== 'authorization-code') {\n throw new Error('getAuthorizationUrl is only available for authorization-code flow');\n }\n const endpoints = await this.resolveEndpoints();\n return buildAuthorizationUrl(\n { ...(this.config as AuthorizationCodeConfig), ...endpoints },\n state\n );\n }\n\n /**\n * Authorization Code flow only.\n * Exchanges the authorization code (from the redirect callback) for tokens\n * and stores them internally.\n */\n async handleCallback(code: string, codeVerifier: string): Promise<void> {\n if (this.config.flow !== 'authorization-code') {\n throw new Error('handleCallback is only available for authorization-code flow');\n }\n const endpoints = await this.resolveEndpoints();\n const tokenResponse = await exchangeCode(\n { ...(this.config as AuthorizationCodeConfig), ...endpoints },\n code,\n codeVerifier\n );\n this.store.store(tokenResponse);\n }\n\n /** Clears all stored tokens. */\n clearTokens(): void {\n this.store.clear();\n }\n\n /**\n * Resolves `tokenUrl` and `authorizationUrl`, fetching the OIDC discovery document\n * if either URL is absent from the config. Result is cached after the first call.\n */\n private async resolveEndpoints(): Promise<{ tokenUrl: string; authorizationUrl: string }> {\n if (this.endpoints) return this.endpoints;\n\n const cfg = this.config as {\n tokenUrl?: string;\n authorizationUrl?: string;\n discoveryUrl?: string;\n };\n\n const needsDiscovery =\n !cfg.tokenUrl ||\n (this.config.flow === 'authorization-code' && !cfg.authorizationUrl);\n\n if (needsDiscovery) {\n const oidc = await fetchOidcConfig(cfg.discoveryUrl);\n this.endpoints = {\n tokenUrl: cfg.tokenUrl ?? oidc.token_endpoint,\n authorizationUrl: cfg.authorizationUrl ?? oidc.authorization_endpoint,\n };\n } else {\n this.endpoints = {\n tokenUrl: cfg.tokenUrl!,\n authorizationUrl: cfg.authorizationUrl ?? '',\n };\n }\n\n return this.endpoints;\n }\n\n private async refresh(): Promise<void> {\n const endpoints = await this.resolveEndpoints();\n\n if (this.config.flow === 'client-credentials') {\n const tokenResponse = await fetchClientCredentialsToken({\n ...(this.config as ClientCredentialsConfig),\n tokenUrl: endpoints.tokenUrl,\n });\n this.store.store(tokenResponse);\n return;\n }\n\n // Authorization Code flow: try refresh token first, else throw\n const refreshToken = this.store.getRefreshToken();\n if (refreshToken) {\n const tokenResponse = await refreshAccessToken(\n { ...(this.config as AuthorizationCodeConfig), ...endpoints },\n refreshToken\n );\n this.store.store(tokenResponse);\n return;\n }\n\n throw new Error(\n 'No valid token available. Call getAuthorizationUrl() and handleCallback() first.'\n );\n }\n}\n","import type { AuthManager } from '../auth/auth-manager';\n\n/** Thrown when an API response is not 2xx. */\nexport class BcisApiError extends Error {\n constructor(\n public readonly status: number,\n public readonly statusText: string,\n public readonly body: unknown\n ) {\n super(`BCIS API error ${status} ${statusText}`);\n this.name = 'BcisApiError';\n }\n}\n\n/**\n * Thin fetch wrapper that:\n * - Injects the Authorization: Bearer header from AuthManager\n * - Serialises query parameters (including arrays as repeated params)\n * - Throws BcisApiError on non-2xx responses\n */\nexport class FetchClient {\n constructor(private readonly auth: AuthManager) {}\n\n async get<T>(\n baseUrl: string,\n path: string,\n params: Record<string, unknown> = {}\n ): Promise<T> {\n const token = await this.auth.getAccessToken();\n const url = new URL(baseUrl + path);\n\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null) continue;\n\n if (Array.isArray(value)) {\n for (const item of value) {\n url.searchParams.append(key, String(item));\n }\n } else {\n url.searchParams.set(key, String(value));\n }\n }\n\n const response = await fetch(url.toString(), {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: 'application/json',\n },\n });\n\n if (!response.ok) {\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n body = await response.text();\n }\n throw new BcisApiError(response.status, response.statusText, body);\n }\n\n return response.json() as Promise<T>;\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { AbpResponseDto, IndicesResponseDto, TpsResponseDto, CodesResponseDto } from '../types/core-api.types';\n\n// --- Parameter interfaces ---\n\nexport interface AbpRetrieveParams {\n /** When true, returns additional data for graph plotting. Default false. */\n 'include-data-for-graph'?: boolean;\n /** When true, includes sub-divided categories (e.g., size bands) in results. Default false. */\n 'include-subclasses'?: boolean;\n /** A comma-separated list of building function codes used to filter study results. [See the Codes Update API](/docs/bcis-grace-svc-core-apis/1a5fdc770c00d-codes-update). */\n 'building-function': string[];\n /** A list of type of work codes to filter the results by, the example contains all valid codes. */\n 'type-of-work': string[];\n /** A six-character code identifying the BCIS study */\n 'abp-study': 'ABPBUI' | 'ABPFUN' | 'ABPGRP' | 'ABPEM2' | 'ABPEUR' | 'ABPEXT';\n}\n\nexport interface IndicesRetrieveParams {\n /** Restricts the index series by year e.g. `1985` or description `1985 mean = 100`. Ignored if a series number is provided. Descriptions must match text exactly, case-insensitive but including spaces. */\n 'base-of-series'?: string;\n /** Restricts index series by `regularity` (`monthly`, `quarterly`, `annual`). Ignored if a series number is used. Defaults to `quarterly`, then `monthly`, then `annual`. */\n regularity?: string[];\n /** Restricts index figures up to a specific month `yyyy-mm`, or leave blank for latest available. */\n 'end-date'?: string;\n /** Restricts index figures to a specific month `yyyy-mm`, or leave blank for earliest available. */\n 'start-date'?: string;\n /** Comma-delimited list of short names (e.g. `BCISTPI:AllIn`) or series numbers. [See the Codes Update API](/docs/bcis-grace-svc-core-apis/1a5fdc770c00d-codes-update). */\n 'series-identification': string[];\n}\n\nexport interface TpsRetrieveParams {\n /** Supports suffixes to filter or refine the study data: - Level Filters: - `:region`, `:county`, `:district` - Example: `location2000:region` (regional indices), `location2000:county,district` (county and district indices) - Postcode Filter: - `:postcode:<POSTCODE>` (no spaces) - Example: `location2000:postcode:SW1P3AD` - Cannot be combined with level filters. - Effective Date Filter: - `:EffectiveDate:<YYYYQn>` - Example: `location2000:EffectiveDate:2015Q2` - Can be combined with postcode or level filters. - Outcode List: - `:outcode` - Example: `location2000:outcode` - Not supported for 1980 boundaries or with EffectiveDate. `short-tps-name` is not case sensitive. For available studies, use the `codesUpdate` web service with `codeType=shortTPSName`. */\n 'short-tps-name': string;\n}\n\nexport interface CodesUpdateParams {\n /** A date in `yyyy-mm-dd` format. Returns only codes added or modified since this date. Not supported for all code types. Leave blank to return all codes. */\n 'if-changed-since'?: string;\n /** A version string to select relevant code tables. */\n version?: string;\n /** A string to select the code list required. The supported values are: - `seriesIdentification`: All regularity names (for `/indices-retrieve`) - `shortTPSName`: Tender Price Studies - short names (for `/tps-retrieve`) - `ABPStudy`: Average building prices study codes (for `/abp-retrieve`) - `BuildingFunction`: List of building function codes (for `/abp-retrieve`, and `/analyses-search`) - `BuildingFunction:Categories`: List of building function categories - `BuildingFunction:[1-9]`: List of building function codes for the category specified after the colon - `BuildingFunction:Duration`: List of building function codes for duration calculator (for `Duration Model Calculate Api`) - `BuildingFunction:Duration:Categories`: List of building function categories for duration calculator (for `Duration Model Calculate Api`) - `BuildingFunction:Duration:[1-9]`: List of building function codes for duration calculator for category specified after the colon (for `Duration Model Calculate Api`) - `BuildingFunction:ABP`: List of building function codes for average building prices study where results are available to the user (for `/abp-retrieve`) - `SimplifiedTypeOfWork`: List of shorter type of work codes (for `/abp-retrieve`) The list of supported code types may be extended in the future. */\n 'code-type': 'shortTPSName' | 'ABPStudy' | 'BuildingFunction' | 'BuildingFunction:Categories' | 'BuildingFunction:[1-9]' | 'BuildingFunction:Duration' | 'BuildingFunction:Duration:Categories' | 'BuildingFunction:Duration:[1-9]' | 'BuildingFunction:ABP' | 'SimplifiedTypeOfWork';\n}\n\n// --- Client ---\n\nexport class CoreApiClient {\n private readonly client: FetchClient;\n private readonly baseUrl: string;\n\n constructor(auth: AuthManager, options?: { baseUrl?: string }) {\n this.client = new FetchClient(auth);\n this.baseUrl = options?.baseUrl ?? 'https://api.bcis.co.uk/core-apis';\n }\n\n /** abp-retrieve */\n async abpRetrieve(params: AbpRetrieveParams): Promise<AbpResponseDto> {\n return this.client.get<AbpResponseDto>(this.baseUrl, '/abp-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** indices-retrieve */\n async indicesRetrieve(params: IndicesRetrieveParams): Promise<IndicesResponseDto> {\n return this.client.get<IndicesResponseDto>(this.baseUrl, '/indices-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** tps-retrieve */\n async tpsRetrieve(params: TpsRetrieveParams): Promise<TpsResponseDto> {\n return this.client.get<TpsResponseDto>(this.baseUrl, '/tps-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** codes-update */\n async codesUpdate(params: CodesUpdateParams): Promise<CodesResponseDto> {\n return this.client.get<CodesResponseDto>(this.baseUrl, '/codes-update', params as unknown as Record<string, unknown>);\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { CalculationResponse, UsageResponse } from '../types/residential-rebuild.types';\n\n// --- Parameter interfaces ---\n\nexport interface CalculateParams {\n /** Postcode of the property */\n postCode: string;\n /** Type of the property */\n type: string;\n /** Number of storeys in the property */\n storeys: string;\n /** Style of the property: detached, terraced, etc */\n style: string;\n /** Type of the walls of the property */\n wallType: string;\n /** Type of the roof of the property */\n roofType?: string;\n /** Year the property was built */\n yearBuilt: number;\n /** Number of flats */\n noOfFlats?: number;\n /** Area of the property in sq.m. */\n area?: number;\n /** Number of rooms in the property */\n noOfRooms?: number;\n /** Number of bedrooms in the property */\n noOfBedrooms?: number;\n /** Number of garage spaces in the property */\n noOfGarageSpaces?: number;\n /** Number of bathrooms in the property */\n noOfBathrooms?: number;\n /** Special features of the property, Must be blank, or a comma delimited list containing one or more of 'cellar' or 'noexternals' */\n specialFeatures?: string;\n}\n\nexport interface ReportUsageParams {\n /** First month of the usage report */\n startMonth?: string;\n /** Last month of the usage report */\n endMonth?: string;\n}\n\n// --- Client ---\n\nexport class ResidentialRebuildClient {\n private readonly client: FetchClient;\n private readonly baseUrl: string;\n\n constructor(auth: AuthManager, options?: { baseUrl?: string }) {\n this.client = new FetchClient(auth);\n this.baseUrl = options?.baseUrl ?? 'https://api.bcis.co.uk/residential-rebuild-calculator';\n }\n\n /** rbls-calculate */\n async calculate(params: CalculateParams): Promise<CalculationResponse> {\n return this.client.get<CalculationResponse>(this.baseUrl, '/rbls-calculate', params as unknown as Record<string, unknown>);\n }\n\n /** rbls-report-use */\n async reportUsage(params: ReportUsageParams): Promise<UsageResponse> {\n return this.client.get<UsageResponse>(this.baseUrl, '/rbls-report-use', params as unknown as Record<string, unknown>);\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { EditionsDto, GetRateResponseDto, GetResourceResponseDto, GetBuildUpResponseDto } from '../types/schedule-of-rates.types';\n\n// --- Parameter interfaces ---\n\nexport interface GetRatesParams {\n /** node id, returned data are for the selected node */\n 'selected-node-id'?: string;\n /** filter term, returned nodes contain the text somewhere in that branch */\n 'filter-text'?: string;\n /** id obtained from get-books-edition */\n 'edition-id': string;\n}\n\nexport interface GetResourcesParams {\n /** node id, returned data are for the selected node */\n 'selected-node-id'?: string;\n /** filter term, returned nodes contain the text somewhere in that branch */\n 'filter-text'?: string;\n /** id obtained from get-books-edition */\n 'edition-id': string;\n}\n\nexport interface GetBuildUpParams {\n /** Id as returned from GetRates or GetResources */\n 'entity-id': string;\n}\n\n// --- Client ---\n\nexport class ScheduleOfRatesClient {\n private readonly client: FetchClient;\n private readonly baseUrl: string;\n\n constructor(auth: AuthManager, options?: { baseUrl?: string }) {\n this.client = new FetchClient(auth);\n this.baseUrl = options?.baseUrl ?? 'https://api.bcis.co.uk/schedule-of-rates';\n }\n\n /** Lists books and editions available to user */\n async getBooksEdition(): Promise<EditionsDto> {\n return this.client.get<EditionsDto>(this.baseUrl, '/get-books-edition', {});\n }\n\n /** Lists matching rates */\n async getRates(params: GetRatesParams): Promise<GetRateResponseDto> {\n return this.client.get<GetRateResponseDto>(this.baseUrl, '/get-rates', params as unknown as Record<string, unknown>);\n }\n\n /** Lists matching resources */\n async getResources(params: GetResourcesParams): Promise<GetResourceResponseDto> {\n return this.client.get<GetResourceResponseDto>(this.baseUrl, '/get-resources', params as unknown as Record<string, unknown>);\n }\n\n /** Lists components of a rate or buildUp */\n async getBuildUp(params: GetBuildUpParams): Promise<GetBuildUpResponseDto> {\n return this.client.get<GetBuildUpResponseDto>(this.baseUrl, '/get-build-up', params as unknown as Record<string, unknown>);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/auth/token-store.ts","../src/auth/client-credentials.ts","../src/auth/authorization-code.ts","../src/auth/oidc-discovery.ts","../src/auth/auth-manager.ts","../src/http/fetch-client.ts","../src/clients/core-api.ts","../src/clients/duration-calculator.ts","../src/clients/residential-rebuild.ts","../src/clients/schedule-of-rates.ts"],"names":["TokenStore","response","expiresAt","bufferSeconds","fetchClientCredentialsToken","config","body","tokenUrl","text","generateCodeVerifier","array","base64UrlEncode","generateCodeChallenge","verifier","data","digest","bytes","str","getAuthorizationUrl","state","codeVerifier","codeChallenge","params","authUrl","exchangeCode","code","tokenRequest","refreshAccessToken","refreshToken","BCIS_DISCOVERY_URL","cache","fetchOidcConfig","discoveryUrl","cached","AuthManager","token","endpoints","tokenResponse","cfg","oidc","BcisApiError","status","statusText","FetchClient","auth","baseUrl","path","url","key","value","item","CoreApiClient","options","DurationCalculatorClient","ResidentialRebuildClient","ScheduleOfRatesClient"],"mappings":"aAGO,IAAMA,CAAAA,CAAN,KAAiB,CAAjB,WAAA,EAAA,CACL,KAAQ,KAAA,CAA4B,KAAA,CAEpC,KAAA,CAAMC,CAAAA,CAA+B,CACnC,IAAMC,CAAAA,CACJD,CAAAA,CAAS,UAAA,EAAc,KACnB,IAAA,CAAK,GAAA,EAAI,CAAIA,CAAAA,CAAS,WAAa,GAAA,CACnC,IAAA,CAEN,IAAA,CAAK,KAAA,CAAQ,CACX,WAAA,CAAaA,CAAAA,CAAS,YAAA,CACtB,SAAA,CAAAC,EACA,YAAA,CAAcD,CAAAA,CAAS,aAAA,EAAiB,IAC1C,EACF,CAEA,cAAA,EAAgC,CAC9B,OAAO,IAAA,CAAK,KAAA,EAAO,WAAA,EAAe,IACpC,CAEA,eAAA,EAAiC,CAC/B,OAAO,IAAA,CAAK,OAAO,YAAA,EAAgB,IACrC,CAMA,SAAA,CAAUE,EAAgB,EAAA,CAAa,CACrC,OAAK,IAAA,CAAK,MACN,IAAA,CAAK,KAAA,CAAM,SAAA,GAAc,IAAA,CAAa,MACnC,IAAA,CAAK,GAAA,EAAI,EAAK,IAAA,CAAK,MAAM,SAAA,CAAYA,CAAAA,CAAgB,GAAA,CAFpC,IAG1B,CAEA,KAAA,EAAc,CACZ,IAAA,CAAK,KAAA,CAAQ,KACf,CACF,CAAA,CCnCA,eAAsBC,EACpBC,CAAAA,CACwB,CACxB,IAAMC,CAAAA,CAAO,IAAI,eA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C,CAC7H,CAGA,MAAM,UAAA,CAAWA,EAA0D,CACzE,OAAO,IAAA,CAAK,MAAA,CAAO,IAA2B,IAAA,CAAK,OAAA,CAAS,eAAA,CAAiBA,CAA4C,CAC3H,CACF","file":"index.js","sourcesContent":["import type { StoredToken, TokenResponse } from './types';\n\n/** In-memory token storage with expiry awareness. */\nexport class TokenStore {\n private token: StoredToken | null = null;\n\n store(response: TokenResponse): void {\n const expiresAt =\n response.expires_in != null\n ? Date.now() + response.expires_in * 1000\n : null;\n\n this.token = {\n accessToken: response.access_token,\n expiresAt,\n refreshToken: response.refresh_token ?? null,\n };\n }\n\n getAccessToken(): string | null {\n return this.token?.accessToken ?? null;\n }\n\n getRefreshToken(): string | null {\n return this.token?.refreshToken ?? null;\n }\n\n /**\n * Returns true if there is no token or the token is within `bufferSeconds`\n * of expiry. Defaults to a 30-second buffer to allow for clock skew.\n */\n isExpired(bufferSeconds = 30): boolean {\n if (!this.token) return true;\n if (this.token.expiresAt === null) return false;\n return Date.now() >= this.token.expiresAt - bufferSeconds * 1000;\n }\n\n clear(): void {\n this.token = null;\n }\n}\n","import type { ClientCredentialsConfig, TokenResponse } from './types';\n\n/**\n * Fetches a new access token using the OAuth2 Client Credentials flow.\n */\nexport async function fetchClientCredentialsToken(\n config: ClientCredentialsConfig\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: config.clientId,\n client_secret: config.clientSecret,\n });\n\n if (config.scopes && config.scopes.length > 0) {\n body.set('scope', config.scopes.join(' '));\n }\n\n const tokenUrl = config.tokenUrl;\n if (!tokenUrl) throw new Error('tokenUrl is required for client credentials flow');\n\n const response = await fetch(tokenUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `Token request failed: ${response.status} ${response.statusText}${text ? ` — ${text}` : ''}`\n );\n }\n\n return response.json() as Promise<TokenResponse>;\n}\n","import type { AuthorizationCodeConfig, TokenResponse } from './types';\n\n// ---------------------------------------------------------------------------\n// PKCE helpers\n// ---------------------------------------------------------------------------\n\n/** Generates a cryptographically random PKCE code verifier (43-128 chars). */\nexport function generateCodeVerifier(): string {\n const array = new Uint8Array(32);\n crypto.getRandomValues(array);\n return base64UrlEncode(array);\n}\n\n/** Derives a PKCE code challenge (S256) from a code verifier. */\nexport async function generateCodeChallenge(verifier: string): Promise<string> {\n const encoder = new TextEncoder();\n const data = encoder.encode(verifier);\n const digest = await crypto.subtle.digest('SHA-256', data);\n return base64UrlEncode(new Uint8Array(digest));\n}\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n const str = String.fromCharCode(...bytes);\n return btoa(str).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\n// ---------------------------------------------------------------------------\n// Authorization Code flows\n// ---------------------------------------------------------------------------\n\n/**\n * Builds the authorization URL to redirect the user to.\n * Returns the URL and the code verifier (must be stored and passed to exchangeCode).\n */\nexport async function getAuthorizationUrl(\n config: AuthorizationCodeConfig,\n state?: string\n): Promise<{ url: string; codeVerifier: string }> {\n const codeVerifier = generateCodeVerifier();\n const codeChallenge = await generateCodeChallenge(codeVerifier);\n\n const params = new URLSearchParams({\n response_type: 'code',\n client_id: config.clientId,\n redirect_uri: config.redirectUri,\n code_challenge: codeChallenge,\n code_challenge_method: 'S256',\n });\n\n if (config.scopes && config.scopes.length > 0) {\n params.set('scope', config.scopes.join(' '));\n }\n\n if (state) {\n params.set('state', state);\n }\n\n const authUrl = config.authorizationUrl;\n if (!authUrl) throw new Error('authorizationUrl is required for authorization-code flow');\n\n return {\n url: `${authUrl}?${params.toString()}`,\n codeVerifier,\n };\n}\n\n/**\n * Exchanges an authorization code for tokens.\n */\nexport async function exchangeCode(\n config: AuthorizationCodeConfig,\n code: string,\n codeVerifier: string\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: config.clientId,\n redirect_uri: config.redirectUri,\n code,\n code_verifier: codeVerifier,\n });\n\n const tokenUrl = config.tokenUrl;\n if (!tokenUrl) throw new Error('tokenUrl is required for authorization-code flow');\n return tokenRequest(tokenUrl, body);\n}\n\n/**\n * Refreshes an access token using a refresh token.\n */\nexport async function refreshAccessToken(\n config: AuthorizationCodeConfig,\n refreshToken: string\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: config.clientId,\n refresh_token: refreshToken,\n });\n\n const tokenUrl = config.tokenUrl;\n if (!tokenUrl) throw new Error('tokenUrl is required for authorization-code flow');\n return tokenRequest(tokenUrl, body);\n}\n\nasync function tokenRequest(\n tokenUrl: string,\n body: URLSearchParams\n): Promise<TokenResponse> {\n const response = await fetch(tokenUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `Token request failed: ${response.status} ${response.statusText}${text ? ` — ${text}` : ''}`\n );\n }\n\n return response.json() as Promise<TokenResponse>;\n}\n","const BCIS_DISCOVERY_URL = 'https://id.bcis.co.uk/.well-known/openid-configuration';\n\nexport interface OidcConfig {\n token_endpoint: string;\n authorization_endpoint: string;\n [key: string]: unknown;\n}\n\n/** Module-level cache keyed by discovery URL */\nconst cache = new Map<string, OidcConfig>();\n\n/**\n * Fetches and caches the OpenID Connect discovery document.\n * Defaults to the BCIS identity provider.\n */\nexport async function fetchOidcConfig(discoveryUrl = BCIS_DISCOVERY_URL): Promise<OidcConfig> {\n const cached = cache.get(discoveryUrl);\n if (cached) return cached;\n\n const response = await fetch(discoveryUrl);\n if (!response.ok) {\n throw new Error(\n `OIDC discovery failed: ${response.status} ${response.statusText} (${discoveryUrl})`\n );\n }\n\n const config = (await response.json()) as OidcConfig;\n\n if (!config.token_endpoint || !config.authorization_endpoint) {\n throw new Error(`OIDC discovery document at ${discoveryUrl} is missing required endpoints`);\n }\n\n cache.set(discoveryUrl, config);\n return config;\n}\n","import type { AuthConfig, AuthorizationCodeConfig, ClientCredentialsConfig } from './types';\nimport { TokenStore } from './token-store';\nimport { fetchClientCredentialsToken } from './client-credentials';\nimport {\n getAuthorizationUrl as buildAuthorizationUrl,\n exchangeCode,\n refreshAccessToken,\n} from './authorization-code';\nimport { fetchOidcConfig } from './oidc-discovery';\n\n/**\n * Centralized OAuth2 authentication manager.\n *\n * Supports:\n * - Client Credentials flow (server-to-server, fully automatic)\n * - Authorization Code + PKCE flow (user-facing applications)\n *\n * Endpoint URLs (`tokenUrl`, `authorizationUrl`) are optional — when omitted they are\n * resolved automatically from the BCIS OpenID Connect discovery document at\n * `https://id.bcis.co.uk/.well-known/openid-configuration`.\n *\n * @example Client Credentials (auto-discovered endpoints)\n * ```ts\n * const auth = new AuthManager({\n * flow: 'client-credentials',\n * clientId: 'my-id',\n * clientSecret: 'my-secret',\n * });\n * const token = await auth.getAccessToken();\n * ```\n *\n * @example Authorization Code (auto-discovered endpoints)\n * ```ts\n * const auth = new AuthManager({\n * flow: 'authorization-code',\n * clientId: 'my-id',\n * redirectUri: 'https://myapp.com/callback',\n * scopes: ['openid', 'profile'],\n * });\n *\n * // Step 1: redirect user\n * const { url, codeVerifier } = await auth.getAuthorizationUrl();\n * // store codeVerifier in session, redirect user to url\n *\n * // Step 2: on callback\n * await auth.handleCallback(code, codeVerifier);\n *\n * // Step 3: use the SDK\n * const token = await auth.getAccessToken();\n * ```\n */\nexport class AuthManager {\n private readonly store = new TokenStore();\n /** Pending token fetch promise to prevent concurrent requests */\n private inflight: Promise<void> | null = null;\n /** Cached resolved endpoints (populated lazily from OIDC discovery) */\n private endpoints: { tokenUrl: string; authorizationUrl: string } | null = null;\n\n constructor(private readonly config: AuthConfig) {}\n\n /**\n * Returns a valid access token, fetching or refreshing as needed.\n * For Client Credentials flow this is fully automatic.\n * For Authorization Code flow, `handleCallback` must have been called first.\n */\n async getAccessToken(): Promise<string> {\n if (!this.store.isExpired()) {\n return this.store.getAccessToken()!;\n }\n\n if (this.inflight) {\n await this.inflight;\n return this.store.getAccessToken()!;\n }\n\n this.inflight = this.refresh();\n try {\n await this.inflight;\n } finally {\n this.inflight = null;\n }\n\n const token = this.store.getAccessToken();\n if (!token) throw new Error('Failed to obtain access token');\n return token;\n }\n\n /**\n * Authorization Code flow only.\n * Builds and returns the authorization URL to redirect the user to.\n * The returned `codeVerifier` must be persisted (e.g. in session storage)\n * and passed to `handleCallback`.\n */\n async getAuthorizationUrl(state?: string): Promise<{ url: string; codeVerifier: string }> {\n if (this.config.flow !== 'authorization-code') {\n throw new Error('getAuthorizationUrl is only available for authorization-code flow');\n }\n const endpoints = await this.resolveEndpoints();\n return buildAuthorizationUrl(\n { ...(this.config as AuthorizationCodeConfig), ...endpoints },\n state\n );\n }\n\n /**\n * Authorization Code flow only.\n * Exchanges the authorization code (from the redirect callback) for tokens\n * and stores them internally.\n */\n async handleCallback(code: string, codeVerifier: string): Promise<void> {\n if (this.config.flow !== 'authorization-code') {\n throw new Error('handleCallback is only available for authorization-code flow');\n }\n const endpoints = await this.resolveEndpoints();\n const tokenResponse = await exchangeCode(\n { ...(this.config as AuthorizationCodeConfig), ...endpoints },\n code,\n codeVerifier\n );\n this.store.store(tokenResponse);\n }\n\n /** Clears all stored tokens. */\n clearTokens(): void {\n this.store.clear();\n }\n\n /**\n * Resolves `tokenUrl` and `authorizationUrl`, fetching the OIDC discovery document\n * if either URL is absent from the config. Result is cached after the first call.\n */\n private async resolveEndpoints(): Promise<{ tokenUrl: string; authorizationUrl: string }> {\n if (this.endpoints) return this.endpoints;\n\n const cfg = this.config as {\n tokenUrl?: string;\n authorizationUrl?: string;\n discoveryUrl?: string;\n };\n\n const needsDiscovery =\n !cfg.tokenUrl ||\n (this.config.flow === 'authorization-code' && !cfg.authorizationUrl);\n\n if (needsDiscovery) {\n const oidc = await fetchOidcConfig(cfg.discoveryUrl);\n this.endpoints = {\n tokenUrl: cfg.tokenUrl ?? oidc.token_endpoint,\n authorizationUrl: cfg.authorizationUrl ?? oidc.authorization_endpoint,\n };\n } else {\n this.endpoints = {\n tokenUrl: cfg.tokenUrl!,\n authorizationUrl: cfg.authorizationUrl ?? '',\n };\n }\n\n return this.endpoints;\n }\n\n private async refresh(): Promise<void> {\n const endpoints = await this.resolveEndpoints();\n\n if (this.config.flow === 'client-credentials') {\n const tokenResponse = await fetchClientCredentialsToken({\n ...(this.config as ClientCredentialsConfig),\n tokenUrl: endpoints.tokenUrl,\n });\n this.store.store(tokenResponse);\n return;\n }\n\n // Authorization Code flow: try refresh token first, else throw\n const refreshToken = this.store.getRefreshToken();\n if (refreshToken) {\n const tokenResponse = await refreshAccessToken(\n { ...(this.config as AuthorizationCodeConfig), ...endpoints },\n refreshToken\n );\n this.store.store(tokenResponse);\n return;\n }\n\n throw new Error(\n 'No valid token available. Call getAuthorizationUrl() and handleCallback() first.'\n );\n }\n}\n","import type { AuthManager } from '../auth/auth-manager';\n\n/** Thrown when an API response is not 2xx. */\nexport class BcisApiError extends Error {\n constructor(\n public readonly status: number,\n public readonly statusText: string,\n public readonly body: unknown\n ) {\n super(`BCIS API error ${status} ${statusText}`);\n this.name = 'BcisApiError';\n }\n}\n\n/**\n * Thin fetch wrapper that:\n * - Injects the Authorization: Bearer header from AuthManager\n * - Serialises query parameters (including arrays as repeated params)\n * - Throws BcisApiError on non-2xx responses\n */\nexport class FetchClient {\n constructor(private readonly auth: AuthManager) {}\n\n async get<T>(\n baseUrl: string,\n path: string,\n params: Record<string, unknown> = {}\n ): Promise<T> {\n const token = await this.auth.getAccessToken();\n const url = new URL(baseUrl + path);\n\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null) continue;\n\n if (Array.isArray(value)) {\n for (const item of value) {\n url.searchParams.append(key, String(item));\n }\n } else {\n url.searchParams.set(key, String(value));\n }\n }\n\n const response = await fetch(url.toString(), {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: 'application/json',\n },\n });\n\n if (!response.ok) {\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n body = await response.text();\n }\n throw new BcisApiError(response.status, response.statusText, body);\n }\n\n return response.json() as Promise<T>;\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { AbpResponseDto, IndicesResponseDto, TpsResponseDto, CodesResponseDto } from '../types/core-api.types';\n\n// --- Parameter interfaces ---\n\nexport interface AbpRetrieveParams {\n /** When true, returns additional data for graph plotting. Default false. */\n 'include-data-for-graph'?: boolean;\n /** When true, includes sub-divided categories (e.g., size bands) in results. Default false. */\n 'include-subclasses'?: boolean;\n /** A comma-separated list of building function codes used to filter study results. [See the Codes Update API](/docs/bcis-grace-svc-core-apis/1a5fdc770c00d-codes-update). */\n 'building-function': string[];\n /** A list of type of work codes to filter the results by, the example contains all valid codes. */\n 'type-of-work': string[];\n /** A six-character code identifying the BCIS study */\n 'abp-study': 'ABPBUI' | 'ABPFUN' | 'ABPGRP' | 'ABPEM2' | 'ABPEUR' | 'ABPEXT';\n}\n\nexport interface IndicesRetrieveParams {\n /** Restricts the index series by year e.g. `1985` or description `1985 mean = 100`. Ignored if a series number is provided. Descriptions must match text exactly, case-insensitive but including spaces. */\n 'base-of-series'?: string;\n /** Restricts index series by `regularity` (`monthly`, `quarterly`, `annual`). Ignored if a series number is used. Defaults to `quarterly`, then `monthly`, then `annual`. */\n regularity?: string[];\n /** Restricts index figures up to a specific month `yyyy-mm`, or leave blank for latest available. */\n 'end-date'?: string;\n /** Restricts index figures to a specific month `yyyy-mm`, or leave blank for earliest available. */\n 'start-date'?: string;\n /** Comma-delimited list of short names (e.g. `BCISTPI:AllIn`) or series numbers. [See the Codes Update API](/docs/bcis-grace-svc-core-apis/1a5fdc770c00d-codes-update). */\n 'series-identification': string[];\n}\n\nexport interface TpsRetrieveParams {\n /** Supports suffixes to filter or refine the study data: - Level Filters: - `:region`, `:county`, `:district` - Example: `location2000:region` (regional indices), `location2000:county,district` (county and district indices) - Postcode Filter: - `:postcode:<POSTCODE>` (no spaces) - Example: `location2000:postcode:SW1P3AD` - Cannot be combined with level filters. - Effective Date Filter: - `:EffectiveDate:<YYYYQn>` - Example: `location2000:EffectiveDate:2015Q2` - Can be combined with postcode or level filters. - Outcode List: - `:outcode` - Example: `location2000:outcode` - Not supported for 1980 boundaries or with EffectiveDate. `short-tps-name` is not case sensitive. For available studies, use the `codesUpdate` web service with `codeType=shortTPSName`. */\n 'short-tps-name': string;\n}\n\nexport interface CodesUpdateParams {\n /** A date in `yyyy-mm-dd` format. Returns only codes added or modified since this date. Not supported for all code types. Leave blank to return all codes. */\n 'if-changed-since'?: string;\n /** A version string to select relevant code tables. */\n version?: string;\n /** A string to select the code list required. The supported values are: - `seriesIdentification`: All regularity names (for `/indices-retrieve`) - `shortTPSName`: Tender Price Studies - short names (for `/tps-retrieve`) - `ABPStudy`: Average building prices study codes (for `/abp-retrieve`) - `BuildingFunction`: List of building function codes (for `/abp-retrieve`, and `/analyses-search`) - `BuildingFunction:Categories`: List of building function categories - `BuildingFunction:[1-9]`: List of building function codes for the category specified after the colon - `BuildingFunction:Duration`: List of building function codes for duration calculator (for `Duration Model Calculate Api`) - `BuildingFunction:Duration:Categories`: List of building function categories for duration calculator (for `Duration Model Calculate Api`) - `BuildingFunction:Duration:[1-9]`: List of building function codes for duration calculator for category specified after the colon (for `Duration Model Calculate Api`) - `BuildingFunction:ABP`: List of building function codes for average building prices study where results are available to the user (for `/abp-retrieve`) - `SimplifiedTypeOfWork`: List of shorter type of work codes (for `/abp-retrieve`) The list of supported code types may be extended in the future. */\n 'code-type': 'shortTPSName' | 'ABPStudy' | 'BuildingFunction' | 'BuildingFunction:Categories' | 'BuildingFunction:[1-9]' | 'BuildingFunction:Duration' | 'BuildingFunction:Duration:Categories' | 'BuildingFunction:Duration:[1-9]' | 'BuildingFunction:ABP' | 'SimplifiedTypeOfWork';\n}\n\n// --- Client ---\n\nexport class CoreApiClient {\n private readonly client: FetchClient;\n private readonly baseUrl: string;\n\n constructor(auth: AuthManager, options?: { baseUrl?: string }) {\n this.client = new FetchClient(auth);\n this.baseUrl = options?.baseUrl ?? 'https://api.bcis.co.uk/core-apis';\n }\n\n /** abp-retrieve */\n async abpRetrieve(params: AbpRetrieveParams): Promise<AbpResponseDto> {\n return this.client.get<AbpResponseDto>(this.baseUrl, '/abp-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** indices-retrieve */\n async indicesRetrieve(params: IndicesRetrieveParams): Promise<IndicesResponseDto> {\n return this.client.get<IndicesResponseDto>(this.baseUrl, '/indices-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** tps-retrieve */\n async tpsRetrieve(params: TpsRetrieveParams): Promise<TpsResponseDto> {\n return this.client.get<TpsResponseDto>(this.baseUrl, '/tps-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** codes-update */\n async codesUpdate(params: CodesUpdateParams): Promise<CodesResponseDto> {\n return this.client.get<CodesResponseDto>(this.baseUrl, '/codes-update', params as unknown as Record<string, unknown>);\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { DurationModelsDto, DurationModelOptionsDto, CalculationResultDto } from '../types/duration-calculator.types';\n\n// --- Parameter interfaces ---\n\nexport interface GetModelsParams {\n /** The date of the publication in YYYY-MM-DD format. Can be used to reproduce a calculation as it would have been performed at the given date. */\n 'publication-date'?: string;\n}\n\nexport interface GetOptionsParams {\n /** There are two separate models that underlie the calculator: one for new build projects and one for refurbishment schemes. */\n 'model-id': number;\n}\n\nexport interface CalculateDurationParams {\n /** The date on which the project details are published. Can be used to reproduce a calculation as it would have been performed at the given date. */\n 'publication-date'?: string;\n /** The appropriate sector for the client organisation */\n 'organisation-id': number;\n /** The selection of contractor that best describes the way in which the contractor will be selected. */\n 'contractor-selection-id': number;\n /** The procurement process that best describes the way in which the project will be procured. */\n 'procurement-id': number;\n /** The building function of the project. It is based on groups of building functions rather than the full list of building function codes used elsewhere in BCIS. */\n 'function-group-id': number;\n /** The location of the project. Is used to adjust the contract value to UK mean location. */\n 'location-id': number;\n /** The quarter at which the contract value has been priced. Is used to adjust the contract value to the base price level used by the models */\n 'date-applicable': string;\n /** The anticipated cost of construction expressed as at the anticipated start on site. */\n 'contract-value': number;\n /** There are two separate models that underlie the calculator: one for new build projects and one for refurbishment schemes. */\n 'model-id': number;\n}\n\n// --- Client ---\n\nexport class DurationCalculatorClient {\n private readonly client: FetchClient;\n private readonly baseUrl: string;\n\n constructor(auth: AuthManager, options?: { baseUrl?: string }) {\n this.client = new FetchClient(auth);\n this.baseUrl = options?.baseUrl ?? 'https://api.bcis.co.uk/rebuild-core';\n }\n\n /** Retrieve the list of models, quarters, and locations available for duration calculations */\n async getModels(params: GetModelsParams): Promise<DurationModelsDto> {\n return this.client.get<DurationModelsDto>(this.baseUrl, '/get-models', params as unknown as Record<string, unknown>);\n }\n\n /** Retrieve a list of options for the duration-calculation parameters */\n async getOptions(params: GetOptionsParams): Promise<DurationModelOptionsDto> {\n return this.client.get<DurationModelOptionsDto>(this.baseUrl, '/get-options', params as unknown as Record<string, unknown>);\n }\n\n /** Retrieve the calculated construction duration */\n async calculateDuration(params: CalculateDurationParams): Promise<CalculationResultDto> {\n return this.client.get<CalculationResultDto>(this.baseUrl, '/calculate-duration', params as unknown as Record<string, unknown>);\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { CalculationResponse, UsageResponse } from '../types/residential-rebuild.types';\n\n// --- Parameter interfaces ---\n\nexport interface CalculateParams {\n /** Postcode of the property */\n postCode: string;\n /** Type of the property */\n type: string;\n /** Number of storeys in the property */\n storeys: string;\n /** Style of the property: detached, terraced, etc */\n style: string;\n /** Type of the walls of the property */\n wallType: string;\n /** Type of the roof of the property */\n roofType?: string;\n /** Year the property was built */\n yearBuilt: number;\n /** Number of flats */\n noOfFlats?: number;\n /** Area of the property in sq.m. */\n area?: number;\n /** Number of rooms in the property */\n noOfRooms?: number;\n /** Number of bedrooms in the property */\n noOfBedrooms?: number;\n /** Number of garage spaces in the property */\n noOfGarageSpaces?: number;\n /** Number of bathrooms in the property */\n noOfBathrooms?: number;\n /** Special features of the property, Must be blank, or a comma delimited list containing one or more of 'cellar' or 'noexternals' */\n specialFeatures?: string;\n}\n\nexport interface ReportUsageParams {\n /** First month of the usage report */\n startMonth?: string;\n /** Last month of the usage report */\n endMonth?: string;\n}\n\n// --- Client ---\n\nexport class ResidentialRebuildClient {\n private readonly client: FetchClient;\n private readonly baseUrl: string;\n\n constructor(auth: AuthManager, options?: { baseUrl?: string }) {\n this.client = new FetchClient(auth);\n this.baseUrl = options?.baseUrl ?? 'https://api.bcis.co.uk/residential-rebuild-calculator';\n }\n\n /** rbls-calculate */\n async calculate(params: CalculateParams): Promise<CalculationResponse> {\n return this.client.get<CalculationResponse>(this.baseUrl, '/rbls-calculate', params as unknown as Record<string, unknown>);\n }\n\n /** rbls-report-use */\n async reportUsage(params: ReportUsageParams): Promise<UsageResponse> {\n return this.client.get<UsageResponse>(this.baseUrl, '/rbls-report-use', params as unknown as Record<string, unknown>);\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { EditionsDto, GetRateResponseDto, GetResourceResponseDto, GetBuildUpResponseDto } from '../types/schedule-of-rates.types';\n\n// --- Parameter interfaces ---\n\nexport interface GetRatesParams {\n /** node id, returned data are for the selected node */\n 'selected-node-id'?: string;\n /** filter term, returned nodes contain the text somewhere in that branch */\n 'filter-text'?: string;\n /** id obtained from get-books-edition */\n 'edition-id': string;\n}\n\nexport interface GetResourcesParams {\n /** node id, returned data are for the selected node */\n 'selected-node-id'?: string;\n /** filter term, returned nodes contain the text somewhere in that branch */\n 'filter-text'?: string;\n /** id obtained from get-books-edition */\n 'edition-id': string;\n}\n\nexport interface GetBuildUpParams {\n /** Id as returned from GetRates or GetResources */\n 'entity-id': string;\n}\n\n// --- Client ---\n\nexport class ScheduleOfRatesClient {\n private readonly client: FetchClient;\n private readonly baseUrl: string;\n\n constructor(auth: AuthManager, options?: { baseUrl?: string }) {\n this.client = new FetchClient(auth);\n this.baseUrl = options?.baseUrl ?? 'https://api.bcis.co.uk/schedule-of-rates';\n }\n\n /** Lists books and editions available to user */\n async getBooksEdition(): Promise<EditionsDto> {\n return this.client.get<EditionsDto>(this.baseUrl, '/get-books-edition', {});\n }\n\n /** Lists matching rates */\n async getRates(params: GetRatesParams): Promise<GetRateResponseDto> {\n return this.client.get<GetRateResponseDto>(this.baseUrl, '/get-rates', params as unknown as Record<string, unknown>);\n }\n\n /** Lists matching resources */\n async getResources(params: GetResourcesParams): Promise<GetResourceResponseDto> {\n return this.client.get<GetResourceResponseDto>(this.baseUrl, '/get-resources', params as unknown as Record<string, unknown>);\n }\n\n /** Lists components of a rate or buildUp */\n async getBuildUp(params: GetBuildUpParams): Promise<GetBuildUpResponseDto> {\n return this.client.get<GetBuildUpResponseDto>(this.baseUrl, '/get-build-up', params as unknown as Record<string, unknown>);\n }\n}\n"]}
|
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var u=class{constructor(){this.token=null;}store(e){let
|
|
2
|
-
export{d as AuthManager,p as BcisApiError,h as CoreApiClient,g as
|
|
1
|
+
var u=class{constructor(){this.token=null;}store(e){let t=e.expires_in!=null?Date.now()+e.expires_in*1e3:null;this.token={accessToken:e.access_token,expiresAt:t,refreshToken:e.refresh_token??null};}getAccessToken(){return this.token?.accessToken??null}getRefreshToken(){return this.token?.refreshToken??null}isExpired(e=30){return this.token?this.token.expiresAt===null?false:Date.now()>=this.token.expiresAt-e*1e3:true}clear(){this.token=null;}};async function k(n){let e=new URLSearchParams({grant_type:"client_credentials",client_id:n.clientId,client_secret:n.clientSecret});n.scopes&&n.scopes.length>0&&e.set("scope",n.scopes.join(" "));let t=n.tokenUrl;if(!t)throw new Error("tokenUrl is required for client credentials flow");let r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e.toString()});if(!r.ok){let o=await r.text().catch(()=>"");throw new Error(`Token request failed: ${r.status} ${r.statusText}${o?` \u2014 ${o}`:""}`)}return r.json()}function A(){let n=new Uint8Array(32);return crypto.getRandomValues(n),y(n)}async function T(n){let t=new TextEncoder().encode(n),r=await crypto.subtle.digest("SHA-256",t);return y(new Uint8Array(r))}function y(n){let e=String.fromCharCode(...n);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function w(n,e){let t=A(),r=await T(t),o=new URLSearchParams({response_type:"code",client_id:n.clientId,redirect_uri:n.redirectUri,code_challenge:r,code_challenge_method:"S256"});n.scopes&&n.scopes.length>0&&o.set("scope",n.scopes.join(" ")),e&&o.set("state",e);let i=n.authorizationUrl;if(!i)throw new Error("authorizationUrl is required for authorization-code flow");return {url:`${i}?${o.toString()}`,codeVerifier:t}}async function b(n,e,t){let r=new URLSearchParams({grant_type:"authorization_code",client_id:n.clientId,redirect_uri:n.redirectUri,code:e,code_verifier:t}),o=n.tokenUrl;if(!o)throw new Error("tokenUrl is required for authorization-code flow");return U(o,r)}async function R(n,e){let t=new URLSearchParams({grant_type:"refresh_token",client_id:n.clientId,refresh_token:e}),r=n.tokenUrl;if(!r)throw new Error("tokenUrl is required for authorization-code flow");return U(r,t)}async function U(n,e){let t=await fetch(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e.toString()});if(!t.ok){let r=await t.text().catch(()=>"");throw new Error(`Token request failed: ${t.status} ${t.statusText}${r?` \u2014 ${r}`:""}`)}return t.json()}var D="https://id.bcis.co.uk/.well-known/openid-configuration",C=new Map;async function P(n=D){let e=C.get(n);if(e)return e;let t=await fetch(n);if(!t.ok)throw new Error(`OIDC discovery failed: ${t.status} ${t.statusText} (${n})`);let r=await t.json();if(!r.token_endpoint||!r.authorization_endpoint)throw new Error(`OIDC discovery document at ${n} is missing required endpoints`);return C.set(n,r),r}var d=class{constructor(e){this.config=e;this.store=new u;this.inflight=null;this.endpoints=null;}async getAccessToken(){if(!this.store.isExpired())return this.store.getAccessToken();if(this.inflight)return await this.inflight,this.store.getAccessToken();this.inflight=this.refresh();try{await this.inflight;}finally{this.inflight=null;}let e=this.store.getAccessToken();if(!e)throw new Error("Failed to obtain access token");return e}async getAuthorizationUrl(e){if(this.config.flow!=="authorization-code")throw new Error("getAuthorizationUrl is only available for authorization-code flow");let t=await this.resolveEndpoints();return w({...this.config,...t},e)}async handleCallback(e,t){if(this.config.flow!=="authorization-code")throw new Error("handleCallback is only available for authorization-code flow");let r=await this.resolveEndpoints(),o=await b({...this.config,...r},e,t);this.store.store(o);}clearTokens(){this.store.clear();}async resolveEndpoints(){if(this.endpoints)return this.endpoints;let e=this.config;if(!e.tokenUrl||this.config.flow==="authorization-code"&&!e.authorizationUrl){let r=await P(e.discoveryUrl);this.endpoints={tokenUrl:e.tokenUrl??r.token_endpoint,authorizationUrl:e.authorizationUrl??r.authorization_endpoint};}else this.endpoints={tokenUrl:e.tokenUrl,authorizationUrl:e.authorizationUrl??""};return this.endpoints}async refresh(){let e=await this.resolveEndpoints();if(this.config.flow==="client-credentials"){let r=await k({...this.config,tokenUrl:e.tokenUrl});this.store.store(r);return}let t=this.store.getRefreshToken();if(t){let r=await R({...this.config,...e},t);this.store.store(r);return}throw new Error("No valid token available. Call getAuthorizationUrl() and handleCallback() first.")}};var p=class extends Error{constructor(t,r,o){super(`BCIS API error ${t} ${r}`);this.status=t;this.statusText=r;this.body=o;this.name="BcisApiError";}},s=class{constructor(e){this.auth=e;}async get(e,t,r={}){let o=await this.auth.getAccessToken(),i=new URL(e+t);for(let[c,l]of Object.entries(r))if(l!=null)if(Array.isArray(l))for(let x of l)i.searchParams.append(c,String(x));else i.searchParams.set(c,String(l));let a=await fetch(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"}});if(!a.ok){let c;try{c=await a.json();}catch{c=await a.text();}throw new p(a.status,a.statusText,c)}return a.json()}};var h=class{constructor(e,t){this.client=new s(e),this.baseUrl=t?.baseUrl??"https://api.bcis.co.uk/core-apis";}async abpRetrieve(e){return this.client.get(this.baseUrl,"/abp-retrieve",e)}async indicesRetrieve(e){return this.client.get(this.baseUrl,"/indices-retrieve",e)}async tpsRetrieve(e){return this.client.get(this.baseUrl,"/tps-retrieve",e)}async codesUpdate(e){return this.client.get(this.baseUrl,"/codes-update",e)}};var g=class{constructor(e,t){this.client=new s(e),this.baseUrl=t?.baseUrl??"https://api.bcis.co.uk/rebuild-core";}async getModels(e){return this.client.get(this.baseUrl,"/get-models",e)}async getOptions(e){return this.client.get(this.baseUrl,"/get-options",e)}async calculateDuration(e){return this.client.get(this.baseUrl,"/calculate-duration",e)}};var f=class{constructor(e,t){this.client=new s(e),this.baseUrl=t?.baseUrl??"https://api.bcis.co.uk/residential-rebuild-calculator";}async calculate(e){return this.client.get(this.baseUrl,"/rbls-calculate",e)}async reportUsage(e){return this.client.get(this.baseUrl,"/rbls-report-use",e)}};var m=class{constructor(e,t){this.client=new s(e),this.baseUrl=t?.baseUrl??"https://api.bcis.co.uk/schedule-of-rates";}async getBooksEdition(){return this.client.get(this.baseUrl,"/get-books-edition",{})}async getRates(e){return this.client.get(this.baseUrl,"/get-rates",e)}async getResources(e){return this.client.get(this.baseUrl,"/get-resources",e)}async getBuildUp(e){return this.client.get(this.baseUrl,"/get-build-up",e)}};
|
|
2
|
+
export{d as AuthManager,p as BcisApiError,h as CoreApiClient,g as DurationCalculatorClient,f as ResidentialRebuildClient,m as ScheduleOfRatesClient};//# sourceMappingURL=index.mjs.map
|
|
3
3
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/auth/token-store.ts","../src/auth/client-credentials.ts","../src/auth/authorization-code.ts","../src/auth/oidc-discovery.ts","../src/auth/auth-manager.ts","../src/http/fetch-client.ts","../src/clients/core-api.ts","../src/clients/residential-rebuild.ts","../src/clients/schedule-of-rates.ts"],"names":["TokenStore","response","expiresAt","bufferSeconds","fetchClientCredentialsToken","config","body","tokenUrl","text","generateCodeVerifier","array","base64UrlEncode","generateCodeChallenge","verifier","data","digest","bytes","str","getAuthorizationUrl","state","codeVerifier","codeChallenge","params","authUrl","exchangeCode","code","tokenRequest","refreshAccessToken","refreshToken","BCIS_DISCOVERY_URL","cache","fetchOidcConfig","discoveryUrl","cached","AuthManager","token","endpoints","tokenResponse","cfg","oidc","BcisApiError","status","statusText","FetchClient","auth","baseUrl","path","url","key","value","item","CoreApiClient","options","ResidentialRebuildClient","ScheduleOfRatesClient"],"mappings":"AAGO,IAAMA,CAAAA,CAAN,KAAiB,CAAjB,WAAA,EAAA,CACL,KAAQ,KAAA,CAA4B,KAAA,CAEpC,KAAA,CAAMC,CAAAA,CAA+B,CACnC,IAAMC,CAAAA,CACJD,CAAAA,CAAS,YAAc,IAAA,CACnB,IAAA,CAAK,GAAA,EAAI,CAAIA,CAAAA,CAAS,UAAA,CAAa,GAAA,CACnC,IAAA,CAEN,KAAK,KAAA,CAAQ,CACX,WAAA,CAAaA,CAAAA,CAAS,aACtB,SAAA,CAAAC,CAAAA,CACA,YAAA,CAAcD,CAAAA,CAAS,eAAiB,IAC1C,EACF,CAEA,cAAA,EAAgC,CAC9B,OAAO,IAAA,CAAK,KAAA,EAAO,aAAe,IACpC,CAEA,eAAA,EAAiC,CAC/B,OAAO,IAAA,CAAK,KAAA,EAAO,YAAA,EAAgB,IACrC,CAMA,SAAA,CAAUE,CAAAA,CAAgB,EAAA,CAAa,CACrC,OAAK,IAAA,CAAK,KAAA,CACN,KAAK,KAAA,CAAM,SAAA,GAAc,IAAA,CAAa,KAAA,CACnC,KAAK,GA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C,CAC3H,CACF","file":"index.mjs","sourcesContent":["import type { StoredToken, TokenResponse } from './types';\n\n/** In-memory token storage with expiry awareness. */\nexport class TokenStore {\n private token: StoredToken | null = null;\n\n store(response: TokenResponse): void {\n const expiresAt =\n response.expires_in != null\n ? Date.now() + response.expires_in * 1000\n : null;\n\n this.token = {\n accessToken: response.access_token,\n expiresAt,\n refreshToken: response.refresh_token ?? null,\n };\n }\n\n getAccessToken(): string | null {\n return this.token?.accessToken ?? null;\n }\n\n getRefreshToken(): string | null {\n return this.token?.refreshToken ?? null;\n }\n\n /**\n * Returns true if there is no token or the token is within `bufferSeconds`\n * of expiry. Defaults to a 30-second buffer to allow for clock skew.\n */\n isExpired(bufferSeconds = 30): boolean {\n if (!this.token) return true;\n if (this.token.expiresAt === null) return false;\n return Date.now() >= this.token.expiresAt - bufferSeconds * 1000;\n }\n\n clear(): void {\n this.token = null;\n }\n}\n","import type { ClientCredentialsConfig, TokenResponse } from './types';\n\n/**\n * Fetches a new access token using the OAuth2 Client Credentials flow.\n */\nexport async function fetchClientCredentialsToken(\n config: ClientCredentialsConfig\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: config.clientId,\n client_secret: config.clientSecret,\n });\n\n if (config.scopes && config.scopes.length > 0) {\n body.set('scope', config.scopes.join(' '));\n }\n\n const tokenUrl = config.tokenUrl;\n if (!tokenUrl) throw new Error('tokenUrl is required for client credentials flow');\n\n const response = await fetch(tokenUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `Token request failed: ${response.status} ${response.statusText}${text ? ` — ${text}` : ''}`\n );\n }\n\n return response.json() as Promise<TokenResponse>;\n}\n","import type { AuthorizationCodeConfig, TokenResponse } from './types';\n\n// ---------------------------------------------------------------------------\n// PKCE helpers\n// ---------------------------------------------------------------------------\n\n/** Generates a cryptographically random PKCE code verifier (43-128 chars). */\nexport function generateCodeVerifier(): string {\n const array = new Uint8Array(32);\n crypto.getRandomValues(array);\n return base64UrlEncode(array);\n}\n\n/** Derives a PKCE code challenge (S256) from a code verifier. */\nexport async function generateCodeChallenge(verifier: string): Promise<string> {\n const encoder = new TextEncoder();\n const data = encoder.encode(verifier);\n const digest = await crypto.subtle.digest('SHA-256', data);\n return base64UrlEncode(new Uint8Array(digest));\n}\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n const str = String.fromCharCode(...bytes);\n return btoa(str).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\n// ---------------------------------------------------------------------------\n// Authorization Code flows\n// ---------------------------------------------------------------------------\n\n/**\n * Builds the authorization URL to redirect the user to.\n * Returns the URL and the code verifier (must be stored and passed to exchangeCode).\n */\nexport async function getAuthorizationUrl(\n config: AuthorizationCodeConfig,\n state?: string\n): Promise<{ url: string; codeVerifier: string }> {\n const codeVerifier = generateCodeVerifier();\n const codeChallenge = await generateCodeChallenge(codeVerifier);\n\n const params = new URLSearchParams({\n response_type: 'code',\n client_id: config.clientId,\n redirect_uri: config.redirectUri,\n code_challenge: codeChallenge,\n code_challenge_method: 'S256',\n });\n\n if (config.scopes && config.scopes.length > 0) {\n params.set('scope', config.scopes.join(' '));\n }\n\n if (state) {\n params.set('state', state);\n }\n\n const authUrl = config.authorizationUrl;\n if (!authUrl) throw new Error('authorizationUrl is required for authorization-code flow');\n\n return {\n url: `${authUrl}?${params.toString()}`,\n codeVerifier,\n };\n}\n\n/**\n * Exchanges an authorization code for tokens.\n */\nexport async function exchangeCode(\n config: AuthorizationCodeConfig,\n code: string,\n codeVerifier: string\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: config.clientId,\n redirect_uri: config.redirectUri,\n code,\n code_verifier: codeVerifier,\n });\n\n const tokenUrl = config.tokenUrl;\n if (!tokenUrl) throw new Error('tokenUrl is required for authorization-code flow');\n return tokenRequest(tokenUrl, body);\n}\n\n/**\n * Refreshes an access token using a refresh token.\n */\nexport async function refreshAccessToken(\n config: AuthorizationCodeConfig,\n refreshToken: string\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: config.clientId,\n refresh_token: refreshToken,\n });\n\n const tokenUrl = config.tokenUrl;\n if (!tokenUrl) throw new Error('tokenUrl is required for authorization-code flow');\n return tokenRequest(tokenUrl, body);\n}\n\nasync function tokenRequest(\n tokenUrl: string,\n body: URLSearchParams\n): Promise<TokenResponse> {\n const response = await fetch(tokenUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `Token request failed: ${response.status} ${response.statusText}${text ? ` — ${text}` : ''}`\n );\n }\n\n return response.json() as Promise<TokenResponse>;\n}\n","const BCIS_DISCOVERY_URL = 'https://id.bcis.co.uk/.well-known/openid-configuration';\n\nexport interface OidcConfig {\n token_endpoint: string;\n authorization_endpoint: string;\n [key: string]: unknown;\n}\n\n/** Module-level cache keyed by discovery URL */\nconst cache = new Map<string, OidcConfig>();\n\n/**\n * Fetches and caches the OpenID Connect discovery document.\n * Defaults to the BCIS identity provider.\n */\nexport async function fetchOidcConfig(discoveryUrl = BCIS_DISCOVERY_URL): Promise<OidcConfig> {\n const cached = cache.get(discoveryUrl);\n if (cached) return cached;\n\n const response = await fetch(discoveryUrl);\n if (!response.ok) {\n throw new Error(\n `OIDC discovery failed: ${response.status} ${response.statusText} (${discoveryUrl})`\n );\n }\n\n const config = (await response.json()) as OidcConfig;\n\n if (!config.token_endpoint || !config.authorization_endpoint) {\n throw new Error(`OIDC discovery document at ${discoveryUrl} is missing required endpoints`);\n }\n\n cache.set(discoveryUrl, config);\n return config;\n}\n","import type { AuthConfig, AuthorizationCodeConfig, ClientCredentialsConfig } from './types';\nimport { TokenStore } from './token-store';\nimport { fetchClientCredentialsToken } from './client-credentials';\nimport {\n getAuthorizationUrl as buildAuthorizationUrl,\n exchangeCode,\n refreshAccessToken,\n} from './authorization-code';\nimport { fetchOidcConfig } from './oidc-discovery';\n\n/**\n * Centralized OAuth2 authentication manager.\n *\n * Supports:\n * - Client Credentials flow (server-to-server, fully automatic)\n * - Authorization Code + PKCE flow (user-facing applications)\n *\n * Endpoint URLs (`tokenUrl`, `authorizationUrl`) are optional — when omitted they are\n * resolved automatically from the BCIS OpenID Connect discovery document at\n * `https://id.bcis.co.uk/.well-known/openid-configuration`.\n *\n * @example Client Credentials (auto-discovered endpoints)\n * ```ts\n * const auth = new AuthManager({\n * flow: 'client-credentials',\n * clientId: 'my-id',\n * clientSecret: 'my-secret',\n * });\n * const token = await auth.getAccessToken();\n * ```\n *\n * @example Authorization Code (auto-discovered endpoints)\n * ```ts\n * const auth = new AuthManager({\n * flow: 'authorization-code',\n * clientId: 'my-id',\n * redirectUri: 'https://myapp.com/callback',\n * scopes: ['openid', 'profile'],\n * });\n *\n * // Step 1: redirect user\n * const { url, codeVerifier } = await auth.getAuthorizationUrl();\n * // store codeVerifier in session, redirect user to url\n *\n * // Step 2: on callback\n * await auth.handleCallback(code, codeVerifier);\n *\n * // Step 3: use the SDK\n * const token = await auth.getAccessToken();\n * ```\n */\nexport class AuthManager {\n private readonly store = new TokenStore();\n /** Pending token fetch promise to prevent concurrent requests */\n private inflight: Promise<void> | null = null;\n /** Cached resolved endpoints (populated lazily from OIDC discovery) */\n private endpoints: { tokenUrl: string; authorizationUrl: string } | null = null;\n\n constructor(private readonly config: AuthConfig) {}\n\n /**\n * Returns a valid access token, fetching or refreshing as needed.\n * For Client Credentials flow this is fully automatic.\n * For Authorization Code flow, `handleCallback` must have been called first.\n */\n async getAccessToken(): Promise<string> {\n if (!this.store.isExpired()) {\n return this.store.getAccessToken()!;\n }\n\n if (this.inflight) {\n await this.inflight;\n return this.store.getAccessToken()!;\n }\n\n this.inflight = this.refresh();\n try {\n await this.inflight;\n } finally {\n this.inflight = null;\n }\n\n const token = this.store.getAccessToken();\n if (!token) throw new Error('Failed to obtain access token');\n return token;\n }\n\n /**\n * Authorization Code flow only.\n * Builds and returns the authorization URL to redirect the user to.\n * The returned `codeVerifier` must be persisted (e.g. in session storage)\n * and passed to `handleCallback`.\n */\n async getAuthorizationUrl(state?: string): Promise<{ url: string; codeVerifier: string }> {\n if (this.config.flow !== 'authorization-code') {\n throw new Error('getAuthorizationUrl is only available for authorization-code flow');\n }\n const endpoints = await this.resolveEndpoints();\n return buildAuthorizationUrl(\n { ...(this.config as AuthorizationCodeConfig), ...endpoints },\n state\n );\n }\n\n /**\n * Authorization Code flow only.\n * Exchanges the authorization code (from the redirect callback) for tokens\n * and stores them internally.\n */\n async handleCallback(code: string, codeVerifier: string): Promise<void> {\n if (this.config.flow !== 'authorization-code') {\n throw new Error('handleCallback is only available for authorization-code flow');\n }\n const endpoints = await this.resolveEndpoints();\n const tokenResponse = await exchangeCode(\n { ...(this.config as AuthorizationCodeConfig), ...endpoints },\n code,\n codeVerifier\n );\n this.store.store(tokenResponse);\n }\n\n /** Clears all stored tokens. */\n clearTokens(): void {\n this.store.clear();\n }\n\n /**\n * Resolves `tokenUrl` and `authorizationUrl`, fetching the OIDC discovery document\n * if either URL is absent from the config. Result is cached after the first call.\n */\n private async resolveEndpoints(): Promise<{ tokenUrl: string; authorizationUrl: string }> {\n if (this.endpoints) return this.endpoints;\n\n const cfg = this.config as {\n tokenUrl?: string;\n authorizationUrl?: string;\n discoveryUrl?: string;\n };\n\n const needsDiscovery =\n !cfg.tokenUrl ||\n (this.config.flow === 'authorization-code' && !cfg.authorizationUrl);\n\n if (needsDiscovery) {\n const oidc = await fetchOidcConfig(cfg.discoveryUrl);\n this.endpoints = {\n tokenUrl: cfg.tokenUrl ?? oidc.token_endpoint,\n authorizationUrl: cfg.authorizationUrl ?? oidc.authorization_endpoint,\n };\n } else {\n this.endpoints = {\n tokenUrl: cfg.tokenUrl!,\n authorizationUrl: cfg.authorizationUrl ?? '',\n };\n }\n\n return this.endpoints;\n }\n\n private async refresh(): Promise<void> {\n const endpoints = await this.resolveEndpoints();\n\n if (this.config.flow === 'client-credentials') {\n const tokenResponse = await fetchClientCredentialsToken({\n ...(this.config as ClientCredentialsConfig),\n tokenUrl: endpoints.tokenUrl,\n });\n this.store.store(tokenResponse);\n return;\n }\n\n // Authorization Code flow: try refresh token first, else throw\n const refreshToken = this.store.getRefreshToken();\n if (refreshToken) {\n const tokenResponse = await refreshAccessToken(\n { ...(this.config as AuthorizationCodeConfig), ...endpoints },\n refreshToken\n );\n this.store.store(tokenResponse);\n return;\n }\n\n throw new Error(\n 'No valid token available. Call getAuthorizationUrl() and handleCallback() first.'\n );\n }\n}\n","import type { AuthManager } from '../auth/auth-manager';\n\n/** Thrown when an API response is not 2xx. */\nexport class BcisApiError extends Error {\n constructor(\n public readonly status: number,\n public readonly statusText: string,\n public readonly body: unknown\n ) {\n super(`BCIS API error ${status} ${statusText}`);\n this.name = 'BcisApiError';\n }\n}\n\n/**\n * Thin fetch wrapper that:\n * - Injects the Authorization: Bearer header from AuthManager\n * - Serialises query parameters (including arrays as repeated params)\n * - Throws BcisApiError on non-2xx responses\n */\nexport class FetchClient {\n constructor(private readonly auth: AuthManager) {}\n\n async get<T>(\n baseUrl: string,\n path: string,\n params: Record<string, unknown> = {}\n ): Promise<T> {\n const token = await this.auth.getAccessToken();\n const url = new URL(baseUrl + path);\n\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null) continue;\n\n if (Array.isArray(value)) {\n for (const item of value) {\n url.searchParams.append(key, String(item));\n }\n } else {\n url.searchParams.set(key, String(value));\n }\n }\n\n const response = await fetch(url.toString(), {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: 'application/json',\n },\n });\n\n if (!response.ok) {\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n body = await response.text();\n }\n throw new BcisApiError(response.status, response.statusText, body);\n }\n\n return response.json() as Promise<T>;\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { AbpResponseDto, IndicesResponseDto, TpsResponseDto, CodesResponseDto } from '../types/core-api.types';\n\n// --- Parameter interfaces ---\n\nexport interface AbpRetrieveParams {\n /** When true, returns additional data for graph plotting. Default false. */\n 'include-data-for-graph'?: boolean;\n /** When true, includes sub-divided categories (e.g., size bands) in results. Default false. */\n 'include-subclasses'?: boolean;\n /** A comma-separated list of building function codes used to filter study results. [See the Codes Update API](/docs/bcis-grace-svc-core-apis/1a5fdc770c00d-codes-update). */\n 'building-function': string[];\n /** A list of type of work codes to filter the results by, the example contains all valid codes. */\n 'type-of-work': string[];\n /** A six-character code identifying the BCIS study */\n 'abp-study': 'ABPBUI' | 'ABPFUN' | 'ABPGRP' | 'ABPEM2' | 'ABPEUR' | 'ABPEXT';\n}\n\nexport interface IndicesRetrieveParams {\n /** Restricts the index series by year e.g. `1985` or description `1985 mean = 100`. Ignored if a series number is provided. Descriptions must match text exactly, case-insensitive but including spaces. */\n 'base-of-series'?: string;\n /** Restricts index series by `regularity` (`monthly`, `quarterly`, `annual`). Ignored if a series number is used. Defaults to `quarterly`, then `monthly`, then `annual`. */\n regularity?: string[];\n /** Restricts index figures up to a specific month `yyyy-mm`, or leave blank for latest available. */\n 'end-date'?: string;\n /** Restricts index figures to a specific month `yyyy-mm`, or leave blank for earliest available. */\n 'start-date'?: string;\n /** Comma-delimited list of short names (e.g. `BCISTPI:AllIn`) or series numbers. [See the Codes Update API](/docs/bcis-grace-svc-core-apis/1a5fdc770c00d-codes-update). */\n 'series-identification': string[];\n}\n\nexport interface TpsRetrieveParams {\n /** Supports suffixes to filter or refine the study data: - Level Filters: - `:region`, `:county`, `:district` - Example: `location2000:region` (regional indices), `location2000:county,district` (county and district indices) - Postcode Filter: - `:postcode:<POSTCODE>` (no spaces) - Example: `location2000:postcode:SW1P3AD` - Cannot be combined with level filters. - Effective Date Filter: - `:EffectiveDate:<YYYYQn>` - Example: `location2000:EffectiveDate:2015Q2` - Can be combined with postcode or level filters. - Outcode List: - `:outcode` - Example: `location2000:outcode` - Not supported for 1980 boundaries or with EffectiveDate. `short-tps-name` is not case sensitive. For available studies, use the `codesUpdate` web service with `codeType=shortTPSName`. */\n 'short-tps-name': string;\n}\n\nexport interface CodesUpdateParams {\n /** A date in `yyyy-mm-dd` format. Returns only codes added or modified since this date. Not supported for all code types. Leave blank to return all codes. */\n 'if-changed-since'?: string;\n /** A version string to select relevant code tables. */\n version?: string;\n /** A string to select the code list required. The supported values are: - `seriesIdentification`: All regularity names (for `/indices-retrieve`) - `shortTPSName`: Tender Price Studies - short names (for `/tps-retrieve`) - `ABPStudy`: Average building prices study codes (for `/abp-retrieve`) - `BuildingFunction`: List of building function codes (for `/abp-retrieve`, and `/analyses-search`) - `BuildingFunction:Categories`: List of building function categories - `BuildingFunction:[1-9]`: List of building function codes for the category specified after the colon - `BuildingFunction:Duration`: List of building function codes for duration calculator (for `Duration Model Calculate Api`) - `BuildingFunction:Duration:Categories`: List of building function categories for duration calculator (for `Duration Model Calculate Api`) - `BuildingFunction:Duration:[1-9]`: List of building function codes for duration calculator for category specified after the colon (for `Duration Model Calculate Api`) - `BuildingFunction:ABP`: List of building function codes for average building prices study where results are available to the user (for `/abp-retrieve`) - `SimplifiedTypeOfWork`: List of shorter type of work codes (for `/abp-retrieve`) The list of supported code types may be extended in the future. */\n 'code-type': 'shortTPSName' | 'ABPStudy' | 'BuildingFunction' | 'BuildingFunction:Categories' | 'BuildingFunction:[1-9]' | 'BuildingFunction:Duration' | 'BuildingFunction:Duration:Categories' | 'BuildingFunction:Duration:[1-9]' | 'BuildingFunction:ABP' | 'SimplifiedTypeOfWork';\n}\n\n// --- Client ---\n\nexport class CoreApiClient {\n private readonly client: FetchClient;\n private readonly baseUrl: string;\n\n constructor(auth: AuthManager, options?: { baseUrl?: string }) {\n this.client = new FetchClient(auth);\n this.baseUrl = options?.baseUrl ?? 'https://api.bcis.co.uk/core-apis';\n }\n\n /** abp-retrieve */\n async abpRetrieve(params: AbpRetrieveParams): Promise<AbpResponseDto> {\n return this.client.get<AbpResponseDto>(this.baseUrl, '/abp-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** indices-retrieve */\n async indicesRetrieve(params: IndicesRetrieveParams): Promise<IndicesResponseDto> {\n return this.client.get<IndicesResponseDto>(this.baseUrl, '/indices-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** tps-retrieve */\n async tpsRetrieve(params: TpsRetrieveParams): Promise<TpsResponseDto> {\n return this.client.get<TpsResponseDto>(this.baseUrl, '/tps-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** codes-update */\n async codesUpdate(params: CodesUpdateParams): Promise<CodesResponseDto> {\n return this.client.get<CodesResponseDto>(this.baseUrl, '/codes-update', params as unknown as Record<string, unknown>);\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { CalculationResponse, UsageResponse } from '../types/residential-rebuild.types';\n\n// --- Parameter interfaces ---\n\nexport interface CalculateParams {\n /** Postcode of the property */\n postCode: string;\n /** Type of the property */\n type: string;\n /** Number of storeys in the property */\n storeys: string;\n /** Style of the property: detached, terraced, etc */\n style: string;\n /** Type of the walls of the property */\n wallType: string;\n /** Type of the roof of the property */\n roofType?: string;\n /** Year the property was built */\n yearBuilt: number;\n /** Number of flats */\n noOfFlats?: number;\n /** Area of the property in sq.m. */\n area?: number;\n /** Number of rooms in the property */\n noOfRooms?: number;\n /** Number of bedrooms in the property */\n noOfBedrooms?: number;\n /** Number of garage spaces in the property */\n noOfGarageSpaces?: number;\n /** Number of bathrooms in the property */\n noOfBathrooms?: number;\n /** Special features of the property, Must be blank, or a comma delimited list containing one or more of 'cellar' or 'noexternals' */\n specialFeatures?: string;\n}\n\nexport interface ReportUsageParams {\n /** First month of the usage report */\n startMonth?: string;\n /** Last month of the usage report */\n endMonth?: string;\n}\n\n// --- Client ---\n\nexport class ResidentialRebuildClient {\n private readonly client: FetchClient;\n private readonly baseUrl: string;\n\n constructor(auth: AuthManager, options?: { baseUrl?: string }) {\n this.client = new FetchClient(auth);\n this.baseUrl = options?.baseUrl ?? 'https://api.bcis.co.uk/residential-rebuild-calculator';\n }\n\n /** rbls-calculate */\n async calculate(params: CalculateParams): Promise<CalculationResponse> {\n return this.client.get<CalculationResponse>(this.baseUrl, '/rbls-calculate', params as unknown as Record<string, unknown>);\n }\n\n /** rbls-report-use */\n async reportUsage(params: ReportUsageParams): Promise<UsageResponse> {\n return this.client.get<UsageResponse>(this.baseUrl, '/rbls-report-use', params as unknown as Record<string, unknown>);\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { EditionsDto, GetRateResponseDto, GetResourceResponseDto, GetBuildUpResponseDto } from '../types/schedule-of-rates.types';\n\n// --- Parameter interfaces ---\n\nexport interface GetRatesParams {\n /** node id, returned data are for the selected node */\n 'selected-node-id'?: string;\n /** filter term, returned nodes contain the text somewhere in that branch */\n 'filter-text'?: string;\n /** id obtained from get-books-edition */\n 'edition-id': string;\n}\n\nexport interface GetResourcesParams {\n /** node id, returned data are for the selected node */\n 'selected-node-id'?: string;\n /** filter term, returned nodes contain the text somewhere in that branch */\n 'filter-text'?: string;\n /** id obtained from get-books-edition */\n 'edition-id': string;\n}\n\nexport interface GetBuildUpParams {\n /** Id as returned from GetRates or GetResources */\n 'entity-id': string;\n}\n\n// --- Client ---\n\nexport class ScheduleOfRatesClient {\n private readonly client: FetchClient;\n private readonly baseUrl: string;\n\n constructor(auth: AuthManager, options?: { baseUrl?: string }) {\n this.client = new FetchClient(auth);\n this.baseUrl = options?.baseUrl ?? 'https://api.bcis.co.uk/schedule-of-rates';\n }\n\n /** Lists books and editions available to user */\n async getBooksEdition(): Promise<EditionsDto> {\n return this.client.get<EditionsDto>(this.baseUrl, '/get-books-edition', {});\n }\n\n /** Lists matching rates */\n async getRates(params: GetRatesParams): Promise<GetRateResponseDto> {\n return this.client.get<GetRateResponseDto>(this.baseUrl, '/get-rates', params as unknown as Record<string, unknown>);\n }\n\n /** Lists matching resources */\n async getResources(params: GetResourcesParams): Promise<GetResourceResponseDto> {\n return this.client.get<GetResourceResponseDto>(this.baseUrl, '/get-resources', params as unknown as Record<string, unknown>);\n }\n\n /** Lists components of a rate or buildUp */\n async getBuildUp(params: GetBuildUpParams): Promise<GetBuildUpResponseDto> {\n return this.client.get<GetBuildUpResponseDto>(this.baseUrl, '/get-build-up', params as unknown as Record<string, unknown>);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/auth/token-store.ts","../src/auth/client-credentials.ts","../src/auth/authorization-code.ts","../src/auth/oidc-discovery.ts","../src/auth/auth-manager.ts","../src/http/fetch-client.ts","../src/clients/core-api.ts","../src/clients/duration-calculator.ts","../src/clients/residential-rebuild.ts","../src/clients/schedule-of-rates.ts"],"names":["TokenStore","response","expiresAt","bufferSeconds","fetchClientCredentialsToken","config","body","tokenUrl","text","generateCodeVerifier","array","base64UrlEncode","generateCodeChallenge","verifier","data","digest","bytes","str","getAuthorizationUrl","state","codeVerifier","codeChallenge","params","authUrl","exchangeCode","code","tokenRequest","refreshAccessToken","refreshToken","BCIS_DISCOVERY_URL","cache","fetchOidcConfig","discoveryUrl","cached","AuthManager","token","endpoints","tokenResponse","cfg","oidc","BcisApiError","status","statusText","FetchClient","auth","baseUrl","path","url","key","value","item","CoreApiClient","options","DurationCalculatorClient","ResidentialRebuildClient","ScheduleOfRatesClient"],"mappings":"AAGO,IAAMA,CAAAA,CAAN,KAAiB,CAAjB,WAAA,EAAA,CACL,KAAQ,KAAA,CAA4B,KAAA,CAEpC,KAAA,CAAMC,CAAAA,CAA+B,CACnC,IAAMC,CAAAA,CACJD,CAAAA,CAAS,UAAA,EAAc,KACn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A4C,CAC3H,CAGA,MAAM,WAAA,CAAYA,CAAAA,CAAmD,CACnE,OAAO,KAAK,MAAA,CAAO,GAAA,CAAmB,IAAA,CAAK,OAAA,CAAS,mBAAoBA,CAA4C,CACtH,CACF,ECjCO,IAAMiC,CAAAA,CAAN,KAA4B,CAIjC,YAAYX,CAAAA,CAAmBQ,CAAAA,CAAgC,CAC7D,IAAA,CAAK,OAAS,IAAIT,CAAAA,CAAYC,CAAI,CAAA,CAClC,KAAK,OAAA,CAAUQ,CAAAA,EAAS,OAAA,EAAW,2CACrC,CAGA,MAAM,eAAA,EAAwC,CAC5C,OAAO,KAAK,MAAA,CAAO,GAAA,CAAiB,IAAA,CAAK,OAAA,CAAS,qBAAsB,EAAE,CAC5E,CAGA,MAAM,QAAA,CAAS9B,CAAAA,CAAqD,CAClE,OAAO,KAAK,MAAA,CAAO,GAAA,CAAwB,IAAA,CAAK,OAAA,CAAS,aAAcA,CAA4C,CACrH,CAGA,MAAM,aAAaA,CAAAA,CAA6D,CAC9E,OAAO,IAAA,CAAK,OAAO,GAAA,CAA4B,IAAA,CAAK,OAAA,CAAS,gBAAA,CAAkBA,CAA4C,CAC7H,CAGA,MAAM,UAAA,CAAWA,EAA0D,CACzE,OAAO,IAAA,CAAK,MAAA,CAAO,IAA2B,IAAA,CAAK,OAAA,CAAS,eAAA,CAAiBA,CAA4C,CAC3H,CACF","file":"index.mjs","sourcesContent":["import type { StoredToken, TokenResponse } from './types';\n\n/** In-memory token storage with expiry awareness. */\nexport class TokenStore {\n private token: StoredToken | null = null;\n\n store(response: TokenResponse): void {\n const expiresAt =\n response.expires_in != null\n ? Date.now() + response.expires_in * 1000\n : null;\n\n this.token = {\n accessToken: response.access_token,\n expiresAt,\n refreshToken: response.refresh_token ?? null,\n };\n }\n\n getAccessToken(): string | null {\n return this.token?.accessToken ?? null;\n }\n\n getRefreshToken(): string | null {\n return this.token?.refreshToken ?? null;\n }\n\n /**\n * Returns true if there is no token or the token is within `bufferSeconds`\n * of expiry. Defaults to a 30-second buffer to allow for clock skew.\n */\n isExpired(bufferSeconds = 30): boolean {\n if (!this.token) return true;\n if (this.token.expiresAt === null) return false;\n return Date.now() >= this.token.expiresAt - bufferSeconds * 1000;\n }\n\n clear(): void {\n this.token = null;\n }\n}\n","import type { ClientCredentialsConfig, TokenResponse } from './types';\n\n/**\n * Fetches a new access token using the OAuth2 Client Credentials flow.\n */\nexport async function fetchClientCredentialsToken(\n config: ClientCredentialsConfig\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: config.clientId,\n client_secret: config.clientSecret,\n });\n\n if (config.scopes && config.scopes.length > 0) {\n body.set('scope', config.scopes.join(' '));\n }\n\n const tokenUrl = config.tokenUrl;\n if (!tokenUrl) throw new Error('tokenUrl is required for client credentials flow');\n\n const response = await fetch(tokenUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `Token request failed: ${response.status} ${response.statusText}${text ? ` — ${text}` : ''}`\n );\n }\n\n return response.json() as Promise<TokenResponse>;\n}\n","import type { AuthorizationCodeConfig, TokenResponse } from './types';\n\n// ---------------------------------------------------------------------------\n// PKCE helpers\n// ---------------------------------------------------------------------------\n\n/** Generates a cryptographically random PKCE code verifier (43-128 chars). */\nexport function generateCodeVerifier(): string {\n const array = new Uint8Array(32);\n crypto.getRandomValues(array);\n return base64UrlEncode(array);\n}\n\n/** Derives a PKCE code challenge (S256) from a code verifier. */\nexport async function generateCodeChallenge(verifier: string): Promise<string> {\n const encoder = new TextEncoder();\n const data = encoder.encode(verifier);\n const digest = await crypto.subtle.digest('SHA-256', data);\n return base64UrlEncode(new Uint8Array(digest));\n}\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n const str = String.fromCharCode(...bytes);\n return btoa(str).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\n// ---------------------------------------------------------------------------\n// Authorization Code flows\n// ---------------------------------------------------------------------------\n\n/**\n * Builds the authorization URL to redirect the user to.\n * Returns the URL and the code verifier (must be stored and passed to exchangeCode).\n */\nexport async function getAuthorizationUrl(\n config: AuthorizationCodeConfig,\n state?: string\n): Promise<{ url: string; codeVerifier: string }> {\n const codeVerifier = generateCodeVerifier();\n const codeChallenge = await generateCodeChallenge(codeVerifier);\n\n const params = new URLSearchParams({\n response_type: 'code',\n client_id: config.clientId,\n redirect_uri: config.redirectUri,\n code_challenge: codeChallenge,\n code_challenge_method: 'S256',\n });\n\n if (config.scopes && config.scopes.length > 0) {\n params.set('scope', config.scopes.join(' '));\n }\n\n if (state) {\n params.set('state', state);\n }\n\n const authUrl = config.authorizationUrl;\n if (!authUrl) throw new Error('authorizationUrl is required for authorization-code flow');\n\n return {\n url: `${authUrl}?${params.toString()}`,\n codeVerifier,\n };\n}\n\n/**\n * Exchanges an authorization code for tokens.\n */\nexport async function exchangeCode(\n config: AuthorizationCodeConfig,\n code: string,\n codeVerifier: string\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: config.clientId,\n redirect_uri: config.redirectUri,\n code,\n code_verifier: codeVerifier,\n });\n\n const tokenUrl = config.tokenUrl;\n if (!tokenUrl) throw new Error('tokenUrl is required for authorization-code flow');\n return tokenRequest(tokenUrl, body);\n}\n\n/**\n * Refreshes an access token using a refresh token.\n */\nexport async function refreshAccessToken(\n config: AuthorizationCodeConfig,\n refreshToken: string\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: config.clientId,\n refresh_token: refreshToken,\n });\n\n const tokenUrl = config.tokenUrl;\n if (!tokenUrl) throw new Error('tokenUrl is required for authorization-code flow');\n return tokenRequest(tokenUrl, body);\n}\n\nasync function tokenRequest(\n tokenUrl: string,\n body: URLSearchParams\n): Promise<TokenResponse> {\n const response = await fetch(tokenUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `Token request failed: ${response.status} ${response.statusText}${text ? ` — ${text}` : ''}`\n );\n }\n\n return response.json() as Promise<TokenResponse>;\n}\n","const BCIS_DISCOVERY_URL = 'https://id.bcis.co.uk/.well-known/openid-configuration';\n\nexport interface OidcConfig {\n token_endpoint: string;\n authorization_endpoint: string;\n [key: string]: unknown;\n}\n\n/** Module-level cache keyed by discovery URL */\nconst cache = new Map<string, OidcConfig>();\n\n/**\n * Fetches and caches the OpenID Connect discovery document.\n * Defaults to the BCIS identity provider.\n */\nexport async function fetchOidcConfig(discoveryUrl = BCIS_DISCOVERY_URL): Promise<OidcConfig> {\n const cached = cache.get(discoveryUrl);\n if (cached) return cached;\n\n const response = await fetch(discoveryUrl);\n if (!response.ok) {\n throw new Error(\n `OIDC discovery failed: ${response.status} ${response.statusText} (${discoveryUrl})`\n );\n }\n\n const config = (await response.json()) as OidcConfig;\n\n if (!config.token_endpoint || !config.authorization_endpoint) {\n throw new Error(`OIDC discovery document at ${discoveryUrl} is missing required endpoints`);\n }\n\n cache.set(discoveryUrl, config);\n return config;\n}\n","import type { AuthConfig, AuthorizationCodeConfig, ClientCredentialsConfig } from './types';\nimport { TokenStore } from './token-store';\nimport { fetchClientCredentialsToken } from './client-credentials';\nimport {\n getAuthorizationUrl as buildAuthorizationUrl,\n exchangeCode,\n refreshAccessToken,\n} from './authorization-code';\nimport { fetchOidcConfig } from './oidc-discovery';\n\n/**\n * Centralized OAuth2 authentication manager.\n *\n * Supports:\n * - Client Credentials flow (server-to-server, fully automatic)\n * - Authorization Code + PKCE flow (user-facing applications)\n *\n * Endpoint URLs (`tokenUrl`, `authorizationUrl`) are optional — when omitted they are\n * resolved automatically from the BCIS OpenID Connect discovery document at\n * `https://id.bcis.co.uk/.well-known/openid-configuration`.\n *\n * @example Client Credentials (auto-discovered endpoints)\n * ```ts\n * const auth = new AuthManager({\n * flow: 'client-credentials',\n * clientId: 'my-id',\n * clientSecret: 'my-secret',\n * });\n * const token = await auth.getAccessToken();\n * ```\n *\n * @example Authorization Code (auto-discovered endpoints)\n * ```ts\n * const auth = new AuthManager({\n * flow: 'authorization-code',\n * clientId: 'my-id',\n * redirectUri: 'https://myapp.com/callback',\n * scopes: ['openid', 'profile'],\n * });\n *\n * // Step 1: redirect user\n * const { url, codeVerifier } = await auth.getAuthorizationUrl();\n * // store codeVerifier in session, redirect user to url\n *\n * // Step 2: on callback\n * await auth.handleCallback(code, codeVerifier);\n *\n * // Step 3: use the SDK\n * const token = await auth.getAccessToken();\n * ```\n */\nexport class AuthManager {\n private readonly store = new TokenStore();\n /** Pending token fetch promise to prevent concurrent requests */\n private inflight: Promise<void> | null = null;\n /** Cached resolved endpoints (populated lazily from OIDC discovery) */\n private endpoints: { tokenUrl: string; authorizationUrl: string } | null = null;\n\n constructor(private readonly config: AuthConfig) {}\n\n /**\n * Returns a valid access token, fetching or refreshing as needed.\n * For Client Credentials flow this is fully automatic.\n * For Authorization Code flow, `handleCallback` must have been called first.\n */\n async getAccessToken(): Promise<string> {\n if (!this.store.isExpired()) {\n return this.store.getAccessToken()!;\n }\n\n if (this.inflight) {\n await this.inflight;\n return this.store.getAccessToken()!;\n }\n\n this.inflight = this.refresh();\n try {\n await this.inflight;\n } finally {\n this.inflight = null;\n }\n\n const token = this.store.getAccessToken();\n if (!token) throw new Error('Failed to obtain access token');\n return token;\n }\n\n /**\n * Authorization Code flow only.\n * Builds and returns the authorization URL to redirect the user to.\n * The returned `codeVerifier` must be persisted (e.g. in session storage)\n * and passed to `handleCallback`.\n */\n async getAuthorizationUrl(state?: string): Promise<{ url: string; codeVerifier: string }> {\n if (this.config.flow !== 'authorization-code') {\n throw new Error('getAuthorizationUrl is only available for authorization-code flow');\n }\n const endpoints = await this.resolveEndpoints();\n return buildAuthorizationUrl(\n { ...(this.config as AuthorizationCodeConfig), ...endpoints },\n state\n );\n }\n\n /**\n * Authorization Code flow only.\n * Exchanges the authorization code (from the redirect callback) for tokens\n * and stores them internally.\n */\n async handleCallback(code: string, codeVerifier: string): Promise<void> {\n if (this.config.flow !== 'authorization-code') {\n throw new Error('handleCallback is only available for authorization-code flow');\n }\n const endpoints = await this.resolveEndpoints();\n const tokenResponse = await exchangeCode(\n { ...(this.config as AuthorizationCodeConfig), ...endpoints },\n code,\n codeVerifier\n );\n this.store.store(tokenResponse);\n }\n\n /** Clears all stored tokens. */\n clearTokens(): void {\n this.store.clear();\n }\n\n /**\n * Resolves `tokenUrl` and `authorizationUrl`, fetching the OIDC discovery document\n * if either URL is absent from the config. Result is cached after the first call.\n */\n private async resolveEndpoints(): Promise<{ tokenUrl: string; authorizationUrl: string }> {\n if (this.endpoints) return this.endpoints;\n\n const cfg = this.config as {\n tokenUrl?: string;\n authorizationUrl?: string;\n discoveryUrl?: string;\n };\n\n const needsDiscovery =\n !cfg.tokenUrl ||\n (this.config.flow === 'authorization-code' && !cfg.authorizationUrl);\n\n if (needsDiscovery) {\n const oidc = await fetchOidcConfig(cfg.discoveryUrl);\n this.endpoints = {\n tokenUrl: cfg.tokenUrl ?? oidc.token_endpoint,\n authorizationUrl: cfg.authorizationUrl ?? oidc.authorization_endpoint,\n };\n } else {\n this.endpoints = {\n tokenUrl: cfg.tokenUrl!,\n authorizationUrl: cfg.authorizationUrl ?? '',\n };\n }\n\n return this.endpoints;\n }\n\n private async refresh(): Promise<void> {\n const endpoints = await this.resolveEndpoints();\n\n if (this.config.flow === 'client-credentials') {\n const tokenResponse = await fetchClientCredentialsToken({\n ...(this.config as ClientCredentialsConfig),\n tokenUrl: endpoints.tokenUrl,\n });\n this.store.store(tokenResponse);\n return;\n }\n\n // Authorization Code flow: try refresh token first, else throw\n const refreshToken = this.store.getRefreshToken();\n if (refreshToken) {\n const tokenResponse = await refreshAccessToken(\n { ...(this.config as AuthorizationCodeConfig), ...endpoints },\n refreshToken\n );\n this.store.store(tokenResponse);\n return;\n }\n\n throw new Error(\n 'No valid token available. Call getAuthorizationUrl() and handleCallback() first.'\n );\n }\n}\n","import type { AuthManager } from '../auth/auth-manager';\n\n/** Thrown when an API response is not 2xx. */\nexport class BcisApiError extends Error {\n constructor(\n public readonly status: number,\n public readonly statusText: string,\n public readonly body: unknown\n ) {\n super(`BCIS API error ${status} ${statusText}`);\n this.name = 'BcisApiError';\n }\n}\n\n/**\n * Thin fetch wrapper that:\n * - Injects the Authorization: Bearer header from AuthManager\n * - Serialises query parameters (including arrays as repeated params)\n * - Throws BcisApiError on non-2xx responses\n */\nexport class FetchClient {\n constructor(private readonly auth: AuthManager) {}\n\n async get<T>(\n baseUrl: string,\n path: string,\n params: Record<string, unknown> = {}\n ): Promise<T> {\n const token = await this.auth.getAccessToken();\n const url = new URL(baseUrl + path);\n\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null) continue;\n\n if (Array.isArray(value)) {\n for (const item of value) {\n url.searchParams.append(key, String(item));\n }\n } else {\n url.searchParams.set(key, String(value));\n }\n }\n\n const response = await fetch(url.toString(), {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: 'application/json',\n },\n });\n\n if (!response.ok) {\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n body = await response.text();\n }\n throw new BcisApiError(response.status, response.statusText, body);\n }\n\n return response.json() as Promise<T>;\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { AbpResponseDto, IndicesResponseDto, TpsResponseDto, CodesResponseDto } from '../types/core-api.types';\n\n// --- Parameter interfaces ---\n\nexport interface AbpRetrieveParams {\n /** When true, returns additional data for graph plotting. Default false. */\n 'include-data-for-graph'?: boolean;\n /** When true, includes sub-divided categories (e.g., size bands) in results. Default false. */\n 'include-subclasses'?: boolean;\n /** A comma-separated list of building function codes used to filter study results. [See the Codes Update API](/docs/bcis-grace-svc-core-apis/1a5fdc770c00d-codes-update). */\n 'building-function': string[];\n /** A list of type of work codes to filter the results by, the example contains all valid codes. */\n 'type-of-work': string[];\n /** A six-character code identifying the BCIS study */\n 'abp-study': 'ABPBUI' | 'ABPFUN' | 'ABPGRP' | 'ABPEM2' | 'ABPEUR' | 'ABPEXT';\n}\n\nexport interface IndicesRetrieveParams {\n /** Restricts the index series by year e.g. `1985` or description `1985 mean = 100`. Ignored if a series number is provided. Descriptions must match text exactly, case-insensitive but including spaces. */\n 'base-of-series'?: string;\n /** Restricts index series by `regularity` (`monthly`, `quarterly`, `annual`). Ignored if a series number is used. Defaults to `quarterly`, then `monthly`, then `annual`. */\n regularity?: string[];\n /** Restricts index figures up to a specific month `yyyy-mm`, or leave blank for latest available. */\n 'end-date'?: string;\n /** Restricts index figures to a specific month `yyyy-mm`, or leave blank for earliest available. */\n 'start-date'?: string;\n /** Comma-delimited list of short names (e.g. `BCISTPI:AllIn`) or series numbers. [See the Codes Update API](/docs/bcis-grace-svc-core-apis/1a5fdc770c00d-codes-update). */\n 'series-identification': string[];\n}\n\nexport interface TpsRetrieveParams {\n /** Supports suffixes to filter or refine the study data: - Level Filters: - `:region`, `:county`, `:district` - Example: `location2000:region` (regional indices), `location2000:county,district` (county and district indices) - Postcode Filter: - `:postcode:<POSTCODE>` (no spaces) - Example: `location2000:postcode:SW1P3AD` - Cannot be combined with level filters. - Effective Date Filter: - `:EffectiveDate:<YYYYQn>` - Example: `location2000:EffectiveDate:2015Q2` - Can be combined with postcode or level filters. - Outcode List: - `:outcode` - Example: `location2000:outcode` - Not supported for 1980 boundaries or with EffectiveDate. `short-tps-name` is not case sensitive. For available studies, use the `codesUpdate` web service with `codeType=shortTPSName`. */\n 'short-tps-name': string;\n}\n\nexport interface CodesUpdateParams {\n /** A date in `yyyy-mm-dd` format. Returns only codes added or modified since this date. Not supported for all code types. Leave blank to return all codes. */\n 'if-changed-since'?: string;\n /** A version string to select relevant code tables. */\n version?: string;\n /** A string to select the code list required. The supported values are: - `seriesIdentification`: All regularity names (for `/indices-retrieve`) - `shortTPSName`: Tender Price Studies - short names (for `/tps-retrieve`) - `ABPStudy`: Average building prices study codes (for `/abp-retrieve`) - `BuildingFunction`: List of building function codes (for `/abp-retrieve`, and `/analyses-search`) - `BuildingFunction:Categories`: List of building function categories - `BuildingFunction:[1-9]`: List of building function codes for the category specified after the colon - `BuildingFunction:Duration`: List of building function codes for duration calculator (for `Duration Model Calculate Api`) - `BuildingFunction:Duration:Categories`: List of building function categories for duration calculator (for `Duration Model Calculate Api`) - `BuildingFunction:Duration:[1-9]`: List of building function codes for duration calculator for category specified after the colon (for `Duration Model Calculate Api`) - `BuildingFunction:ABP`: List of building function codes for average building prices study where results are available to the user (for `/abp-retrieve`) - `SimplifiedTypeOfWork`: List of shorter type of work codes (for `/abp-retrieve`) The list of supported code types may be extended in the future. */\n 'code-type': 'shortTPSName' | 'ABPStudy' | 'BuildingFunction' | 'BuildingFunction:Categories' | 'BuildingFunction:[1-9]' | 'BuildingFunction:Duration' | 'BuildingFunction:Duration:Categories' | 'BuildingFunction:Duration:[1-9]' | 'BuildingFunction:ABP' | 'SimplifiedTypeOfWork';\n}\n\n// --- Client ---\n\nexport class CoreApiClient {\n private readonly client: FetchClient;\n private readonly baseUrl: string;\n\n constructor(auth: AuthManager, options?: { baseUrl?: string }) {\n this.client = new FetchClient(auth);\n this.baseUrl = options?.baseUrl ?? 'https://api.bcis.co.uk/core-apis';\n }\n\n /** abp-retrieve */\n async abpRetrieve(params: AbpRetrieveParams): Promise<AbpResponseDto> {\n return this.client.get<AbpResponseDto>(this.baseUrl, '/abp-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** indices-retrieve */\n async indicesRetrieve(params: IndicesRetrieveParams): Promise<IndicesResponseDto> {\n return this.client.get<IndicesResponseDto>(this.baseUrl, '/indices-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** tps-retrieve */\n async tpsRetrieve(params: TpsRetrieveParams): Promise<TpsResponseDto> {\n return this.client.get<TpsResponseDto>(this.baseUrl, '/tps-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** codes-update */\n async codesUpdate(params: CodesUpdateParams): Promise<CodesResponseDto> {\n return this.client.get<CodesResponseDto>(this.baseUrl, '/codes-update', params as unknown as Record<string, unknown>);\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { DurationModelsDto, DurationModelOptionsDto, CalculationResultDto } from '../types/duration-calculator.types';\n\n// --- Parameter interfaces ---\n\nexport interface GetModelsParams {\n /** The date of the publication in YYYY-MM-DD format. Can be used to reproduce a calculation as it would have been performed at the given date. */\n 'publication-date'?: string;\n}\n\nexport interface GetOptionsParams {\n /** There are two separate models that underlie the calculator: one for new build projects and one for refurbishment schemes. */\n 'model-id': number;\n}\n\nexport interface CalculateDurationParams {\n /** The date on which the project details are published. Can be used to reproduce a calculation as it would have been performed at the given date. */\n 'publication-date'?: string;\n /** The appropriate sector for the client organisation */\n 'organisation-id': number;\n /** The selection of contractor that best describes the way in which the contractor will be selected. */\n 'contractor-selection-id': number;\n /** The procurement process that best describes the way in which the project will be procured. */\n 'procurement-id': number;\n /** The building function of the project. It is based on groups of building functions rather than the full list of building function codes used elsewhere in BCIS. */\n 'function-group-id': number;\n /** The location of the project. Is used to adjust the contract value to UK mean location. */\n 'location-id': number;\n /** The quarter at which the contract value has been priced. Is used to adjust the contract value to the base price level used by the models */\n 'date-applicable': string;\n /** The anticipated cost of construction expressed as at the anticipated start on site. */\n 'contract-value': number;\n /** There are two separate models that underlie the calculator: one for new build projects and one for refurbishment schemes. */\n 'model-id': number;\n}\n\n// --- Client ---\n\nexport class DurationCalculatorClient {\n private readonly client: FetchClient;\n private readonly baseUrl: string;\n\n constructor(auth: AuthManager, options?: { baseUrl?: string }) {\n this.client = new FetchClient(auth);\n this.baseUrl = options?.baseUrl ?? 'https://api.bcis.co.uk/rebuild-core';\n }\n\n /** Retrieve the list of models, quarters, and locations available for duration calculations */\n async getModels(params: GetModelsParams): Promise<DurationModelsDto> {\n return this.client.get<DurationModelsDto>(this.baseUrl, '/get-models', params as unknown as Record<string, unknown>);\n }\n\n /** Retrieve a list of options for the duration-calculation parameters */\n async getOptions(params: GetOptionsParams): Promise<DurationModelOptionsDto> {\n return this.client.get<DurationModelOptionsDto>(this.baseUrl, '/get-options', params as unknown as Record<string, unknown>);\n }\n\n /** Retrieve the calculated construction duration */\n async calculateDuration(params: CalculateDurationParams): Promise<CalculationResultDto> {\n return this.client.get<CalculationResultDto>(this.baseUrl, '/calculate-duration', params as unknown as Record<string, unknown>);\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { CalculationResponse, UsageResponse } from '../types/residential-rebuild.types';\n\n// --- Parameter interfaces ---\n\nexport interface CalculateParams {\n /** Postcode of the property */\n postCode: string;\n /** Type of the property */\n type: string;\n /** Number of storeys in the property */\n storeys: string;\n /** Style of the property: detached, terraced, etc */\n style: string;\n /** Type of the walls of the property */\n wallType: string;\n /** Type of the roof of the property */\n roofType?: string;\n /** Year the property was built */\n yearBuilt: number;\n /** Number of flats */\n noOfFlats?: number;\n /** Area of the property in sq.m. */\n area?: number;\n /** Number of rooms in the property */\n noOfRooms?: number;\n /** Number of bedrooms in the property */\n noOfBedrooms?: number;\n /** Number of garage spaces in the property */\n noOfGarageSpaces?: number;\n /** Number of bathrooms in the property */\n noOfBathrooms?: number;\n /** Special features of the property, Must be blank, or a comma delimited list containing one or more of 'cellar' or 'noexternals' */\n specialFeatures?: string;\n}\n\nexport interface ReportUsageParams {\n /** First month of the usage report */\n startMonth?: string;\n /** Last month of the usage report */\n endMonth?: string;\n}\n\n// --- Client ---\n\nexport class ResidentialRebuildClient {\n private readonly client: FetchClient;\n private readonly baseUrl: string;\n\n constructor(auth: AuthManager, options?: { baseUrl?: string }) {\n this.client = new FetchClient(auth);\n this.baseUrl = options?.baseUrl ?? 'https://api.bcis.co.uk/residential-rebuild-calculator';\n }\n\n /** rbls-calculate */\n async calculate(params: CalculateParams): Promise<CalculationResponse> {\n return this.client.get<CalculationResponse>(this.baseUrl, '/rbls-calculate', params as unknown as Record<string, unknown>);\n }\n\n /** rbls-report-use */\n async reportUsage(params: ReportUsageParams): Promise<UsageResponse> {\n return this.client.get<UsageResponse>(this.baseUrl, '/rbls-report-use', params as unknown as Record<string, unknown>);\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { EditionsDto, GetRateResponseDto, GetResourceResponseDto, GetBuildUpResponseDto } from '../types/schedule-of-rates.types';\n\n// --- Parameter interfaces ---\n\nexport interface GetRatesParams {\n /** node id, returned data are for the selected node */\n 'selected-node-id'?: string;\n /** filter term, returned nodes contain the text somewhere in that branch */\n 'filter-text'?: string;\n /** id obtained from get-books-edition */\n 'edition-id': string;\n}\n\nexport interface GetResourcesParams {\n /** node id, returned data are for the selected node */\n 'selected-node-id'?: string;\n /** filter term, returned nodes contain the text somewhere in that branch */\n 'filter-text'?: string;\n /** id obtained from get-books-edition */\n 'edition-id': string;\n}\n\nexport interface GetBuildUpParams {\n /** Id as returned from GetRates or GetResources */\n 'entity-id': string;\n}\n\n// --- Client ---\n\nexport class ScheduleOfRatesClient {\n private readonly client: FetchClient;\n private readonly baseUrl: string;\n\n constructor(auth: AuthManager, options?: { baseUrl?: string }) {\n this.client = new FetchClient(auth);\n this.baseUrl = options?.baseUrl ?? 'https://api.bcis.co.uk/schedule-of-rates';\n }\n\n /** Lists books and editions available to user */\n async getBooksEdition(): Promise<EditionsDto> {\n return this.client.get<EditionsDto>(this.baseUrl, '/get-books-edition', {});\n }\n\n /** Lists matching rates */\n async getRates(params: GetRatesParams): Promise<GetRateResponseDto> {\n return this.client.get<GetRateResponseDto>(this.baseUrl, '/get-rates', params as unknown as Record<string, unknown>);\n }\n\n /** Lists matching resources */\n async getResources(params: GetResourcesParams): Promise<GetResourceResponseDto> {\n return this.client.get<GetResourceResponseDto>(this.baseUrl, '/get-resources', params as unknown as Record<string, unknown>);\n }\n\n /** Lists components of a rate or buildUp */\n async getBuildUp(params: GetBuildUpParams): Promise<GetBuildUpResponseDto> {\n return this.client.get<GetBuildUpResponseDto>(this.baseUrl, '/get-build-up', params as unknown as Record<string, unknown>);\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bcis/sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Type-safe TypeScript SDK for BCIS APIs",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"module": "./dist/index.mjs",
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
}
|
|
18
18
|
}
|
|
19
19
|
},
|
|
20
|
-
"files": ["dist"],
|
|
20
|
+
"files": ["dist", "LICENSE"],
|
|
21
21
|
"scripts": {
|
|
22
22
|
"build": "tsup",
|
|
23
23
|
"typecheck": "tsc --noEmit",
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
"test:watch": "vitest"
|
|
26
26
|
},
|
|
27
27
|
"keywords": ["bcis", "construction", "cost", "sdk", "typescript"],
|
|
28
|
-
"license": "
|
|
28
|
+
"license": "Apache-2.0",
|
|
29
29
|
"publishConfig": {
|
|
30
30
|
"registry": "https://registry.npmjs.org/",
|
|
31
31
|
"access": "public"
|