@krizaka/app-config 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,16 @@
1
- # Temporary Holding Version
1
+ # @krizaka/app-config
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ App version compatibility between Krizaka apps (React Native, the Mac app, the web) and their backends. One contract,
4
+ two implementations: this package (Next.js backends and clients) and the Java building block
5
+ [`krizaka-app-config`](https://github.com/krizaka/krizaka-platform-kit/tree/main/krizaka-app-config), both passing the
6
+ same fixture (`test/cases.json`) and sharing one JSON schema (`contract/app-config.schema.json`). Zero dependency.
7
+
8
+ | Entry | For |
9
+ |:---|:---|
10
+ | `@krizaka/app-config` | the contract, pure: versions, the payload, `evaluateGuard`, `validateRecord` |
11
+ | `@krizaka/app-config/server` | Next.js backends: `createAppConfigHandler`, `checkClientVersion`, `withClientVersionGuard`, `cachedStore`, `memoryStore`, `schemaSql` (the tables) |
12
+ | `@krizaka/app-config/client` | apps: `createAppConfigClient` (launch + resume checks, soft dismissal, the global 426 interceptor `client.fetch`), `decide` |
13
+ | `@krizaka/app-config/react` | `useAppConfig`, `appStateResume(AppState)`, `visibilityResume(document)` |
14
+
15
+ The screens are in `@krizaka/ui`: `UpdatePrompt`, `ForceUpdateScreen`, `MaintenanceScreen` (web and `/native`).
16
+ Documentation: <https://ui.krizaka.com/packages/app-config>.
@@ -0,0 +1,56 @@
1
+ {
2
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
3
+ "$id": "https://krizaka.com/contracts/app-config.schema.json",
4
+ "title": "Krizaka app-config payload",
5
+ "description": "The body of GET /api/v1/app-config and the appConfig member of a 426 Upgrade Required problem. Shared by the Java building block krizaka-app-config and the TypeScript package @krizaka/app-config.",
6
+ "type": "object",
7
+ "additionalProperties": false,
8
+ "required": [
9
+ "platform",
10
+ "minSupportedVersion",
11
+ "latestVersion",
12
+ "updateMode",
13
+ "storeUrl",
14
+ "maintenance",
15
+ "contract",
16
+ "flags",
17
+ "message",
18
+ "locale"
19
+ ],
20
+ "properties": {
21
+ "platform": { "enum": ["ios", "android", "macos", "windows", "linux", "web"] },
22
+ "minSupportedVersion": { "$ref": "#/$defs/version" },
23
+ "latestVersion": { "$ref": "#/$defs/version" },
24
+ "updateMode": { "enum": ["none", "soft", "force"] },
25
+ "storeUrl": { "type": ["string", "null"], "pattern": "^https://" },
26
+ "maintenance": {
27
+ "type": "object",
28
+ "additionalProperties": false,
29
+ "required": ["on", "message"],
30
+ "properties": {
31
+ "on": { "type": "boolean" },
32
+ "message": { "type": ["string", "null"], "maxLength": 500 }
33
+ }
34
+ },
35
+ "contract": {
36
+ "type": "object",
37
+ "additionalProperties": false,
38
+ "required": ["min", "max", "sunset"],
39
+ "properties": {
40
+ "min": { "type": "integer", "minimum": 1 },
41
+ "max": { "type": "integer", "minimum": 1 },
42
+ "sunset": { "type": ["string", "null"], "format": "date" }
43
+ }
44
+ },
45
+ "flags": {
46
+ "type": "object",
47
+ "propertyNames": { "pattern": "^[A-Za-z][A-Za-z0-9._-]{0,63}$" },
48
+ "additionalProperties": { "type": ["boolean", "number", "string"] }
49
+ },
50
+ "message": { "type": ["string", "null"], "maxLength": 500 },
51
+ "locale": { "type": "string", "pattern": "^[a-z]{2}$" }
52
+ },
53
+ "$defs": {
54
+ "version": { "type": "string", "pattern": "^\\d+\\.\\d+\\.\\d+$" }
55
+ }
56
+ }
@@ -0,0 +1,57 @@
1
+ -- krizaka-app-config: the parameters of the app-version contract, one row per platform.
2
+ -- Version 1 is seeded here (permissive: no minimum, no maintenance, one contract); a product's own
3
+ -- migration publishes its real values through the admin API, never by editing the row by hand.
4
+ CREATE TABLE IF NOT EXISTS app_config (
5
+ platform VARCHAR(16) PRIMARY KEY,
6
+ min_supported_version VARCHAR(32) NOT NULL DEFAULT '0.0.0',
7
+ latest_version VARCHAR(32) NOT NULL DEFAULT '0.0.0',
8
+ update_override VARCHAR(8),
9
+ store_url TEXT,
10
+ maintenance_on BOOLEAN NOT NULL DEFAULT FALSE,
11
+ maintenance_message JSONB NOT NULL DEFAULT '{}'::jsonb,
12
+ message JSONB NOT NULL DEFAULT '{}'::jsonb,
13
+ contract_min INTEGER NOT NULL DEFAULT 1,
14
+ contract_max INTEGER NOT NULL DEFAULT 1,
15
+ contract_sunset DATE,
16
+ flags JSONB NOT NULL DEFAULT '{}'::jsonb,
17
+ revision INTEGER NOT NULL DEFAULT 1,
18
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
19
+ updated_by VARCHAR(255) NOT NULL DEFAULT 'seed',
20
+ CONSTRAINT app_config_platform_known CHECK (platform IN ('ios', 'android', 'macos', 'windows', 'linux', 'web')),
21
+ CONSTRAINT app_config_contract_range CHECK (contract_min >= 1 AND contract_max >= contract_min)
22
+ );
23
+
24
+ -- Every published revision, append-only: the audit trail and the source of a rollback.
25
+ CREATE TABLE IF NOT EXISTS app_config_history (
26
+ id BIGSERIAL PRIMARY KEY,
27
+ platform VARCHAR(16) NOT NULL,
28
+ revision INTEGER NOT NULL,
29
+ min_supported_version VARCHAR(32) NOT NULL,
30
+ latest_version VARCHAR(32) NOT NULL,
31
+ update_override VARCHAR(8),
32
+ store_url TEXT,
33
+ maintenance_on BOOLEAN NOT NULL,
34
+ maintenance_message JSONB NOT NULL,
35
+ message JSONB NOT NULL,
36
+ contract_min INTEGER NOT NULL,
37
+ contract_max INTEGER NOT NULL,
38
+ contract_sunset DATE,
39
+ flags JSONB NOT NULL,
40
+ reason TEXT NOT NULL,
41
+ changed_by VARCHAR(255) NOT NULL,
42
+ changed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
43
+ CONSTRAINT app_config_history_revision UNIQUE (platform, revision)
44
+ );
45
+
46
+ INSERT INTO app_config (platform)
47
+ VALUES ('ios'), ('android'), ('macos'), ('windows'), ('linux'), ('web')
48
+ ON CONFLICT (platform) DO NOTHING;
49
+
50
+ INSERT INTO app_config_history (platform, revision, min_supported_version, latest_version, update_override,
51
+ store_url, maintenance_on, maintenance_message, message, contract_min,
52
+ contract_max, contract_sunset, flags, reason, changed_by, changed_at)
53
+ SELECT platform, revision, min_supported_version, latest_version, update_override, store_url, maintenance_on,
54
+ maintenance_message, message, contract_min, contract_max, contract_sunset, flags, 'seed', updated_by,
55
+ updated_at
56
+ FROM app_config
57
+ ON CONFLICT (platform, revision) DO NOTHING;
@@ -0,0 +1,152 @@
1
+ // src/core.ts
2
+ var PLATFORMS = ["ios", "android", "macos", "windows", "linux", "web"];
3
+ var UPDATE_MODES = ["none", "soft", "force"];
4
+ var CLIENT_HEADERS = {
5
+ version: "X-Client-Version",
6
+ platform: "X-Client-Platform",
7
+ contract: "X-Contract-Version",
8
+ build: "X-Client-Build",
9
+ deprecation: "Deprecation",
10
+ sunset: "Sunset"
11
+ };
12
+ var APP_CONFIG_PATH = "/api/v1/app-config";
13
+ var VERSION = /^v?(\d{1,6})(?:\.(\d{1,6}))?(?:\.(\d{1,6}))?(?:[-+].*)?$/;
14
+ function parseVersion(text) {
15
+ const match = VERSION.exec((text ?? "").trim());
16
+ return match ? [Number(match[1]), Number(match[2] ?? 0), Number(match[3] ?? 0)] : null;
17
+ }
18
+ function compareVersions(a, b) {
19
+ return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
20
+ }
21
+ function formatVersion(version) {
22
+ return version.join(".");
23
+ }
24
+ var ZERO = [0, 0, 0];
25
+ function isPlatform(value) {
26
+ return typeof value === "string" && PLATFORMS.includes(value.trim().toLowerCase());
27
+ }
28
+ function toPlatform(value) {
29
+ const wanted = (value ?? "").trim().toLowerCase();
30
+ return isPlatform(wanted) ? wanted : null;
31
+ }
32
+ function defaultRecord(platform) {
33
+ return {
34
+ platform,
35
+ minSupportedVersion: "0.0.0",
36
+ latestVersion: "0.0.0",
37
+ updateOverride: null,
38
+ storeUrl: null,
39
+ maintenanceOn: false,
40
+ maintenanceMessage: {},
41
+ message: {},
42
+ contractMin: 1,
43
+ contractMax: 1,
44
+ contractSunset: null,
45
+ flags: {},
46
+ revision: 1,
47
+ updatedAt: (/* @__PURE__ */ new Date(0)).toISOString(),
48
+ updatedBy: "seed"
49
+ };
50
+ }
51
+ var LANGUAGE = /^[a-z]{2}$/;
52
+ var FLAG_KEY = /^[A-Za-z][A-Za-z0-9._-]{0,63}$/;
53
+ var MAX_TEXT = 500;
54
+ function checkTexts(field, texts) {
55
+ return Object.entries(texts).flatMap(([language, text]) => {
56
+ if (!LANGUAGE.test(language)) return [`${field} language must be two letters: ${language}`];
57
+ return text.length > MAX_TEXT ? [`${field}.${language} is too long`] : [];
58
+ });
59
+ }
60
+ function validateRecord(record) {
61
+ const problems = [];
62
+ const min = parseVersion(record.minSupportedVersion);
63
+ const latest = parseVersion(record.latestVersion);
64
+ if (!min || !latest) problems.push("versions must look like 1.4.0");
65
+ else if (compareVersions(latest, min) < 0) problems.push("latestVersion is older than minSupportedVersion");
66
+ if (!Number.isInteger(record.contractMin) || record.contractMin < 1 || record.contractMax < record.contractMin) {
67
+ problems.push("contract range must satisfy 1 <= min <= max");
68
+ }
69
+ if (record.storeUrl !== null && !/^https:\/\/[^\s/]+/.test(record.storeUrl)) problems.push("storeUrl must be an absolute https URL");
70
+ problems.push(...checkTexts("message", record.message), ...checkTexts("maintenanceMessage", record.maintenanceMessage));
71
+ for (const [key, value] of Object.entries(record.flags)) {
72
+ if (!FLAG_KEY.test(key)) problems.push(`flag key not allowed: ${key}`);
73
+ if (!["boolean", "number", "string"].includes(typeof value)) problems.push(`flag ${key} must be a boolean, number or string`);
74
+ }
75
+ return problems;
76
+ }
77
+ function updateModeFor(record, client) {
78
+ if (record.updateOverride) return record.updateOverride;
79
+ if (!client) return "none";
80
+ if (compareVersions(client, parseVersion(record.minSupportedVersion) ?? ZERO) < 0) return "force";
81
+ return compareVersions(client, parseVersion(record.latestVersion) ?? ZERO) < 0 ? "soft" : "none";
82
+ }
83
+ function pickLanguage(wanted, ...texts) {
84
+ const language = (wanted ?? "en").toLowerCase();
85
+ return texts.some((t) => language in t) ? language : "en";
86
+ }
87
+ function buildPayload(record, client, language) {
88
+ const chosen = pickLanguage(language, record.message, record.maintenanceMessage);
89
+ const text = (texts) => texts[chosen] ?? texts.en ?? null;
90
+ return {
91
+ platform: record.platform,
92
+ minSupportedVersion: formatVersion(parseVersion(record.minSupportedVersion) ?? ZERO),
93
+ latestVersion: formatVersion(parseVersion(record.latestVersion) ?? ZERO),
94
+ updateMode: updateModeFor(record, client),
95
+ storeUrl: record.storeUrl,
96
+ maintenance: { on: record.maintenanceOn, message: text(record.maintenanceMessage) },
97
+ contract: { min: record.contractMin, max: record.contractMax, sunset: record.contractSunset },
98
+ flags: record.flags,
99
+ message: text(record.message),
100
+ locale: chosen
101
+ };
102
+ }
103
+ function contractOf(value) {
104
+ const n = typeof value === "number" ? value : Number.parseInt(String(value ?? "").trim(), 10);
105
+ return Number.isInteger(n) && n >= 1 ? n : null;
106
+ }
107
+ function sunsetDate(day) {
108
+ const [y, m, d] = day.split("-").map(Number);
109
+ return new Date(Date.UTC(y, m - 1, d + 1)).toUTCString();
110
+ }
111
+ function evaluateGuard(record, client) {
112
+ const version = parseVersion(client.version);
113
+ const contract = contractOf(client.contract);
114
+ const base = { deprecation: false, contract: record.contractMax };
115
+ const tooOld = version !== null && compareVersions(version, parseVersion(record.minSupportedVersion) ?? ZERO) < 0;
116
+ const contractGone = contract !== null && contract < record.contractMin;
117
+ if (tooOld || contractGone) {
118
+ const payload = { ...buildPayload(record, version, client.language), updateMode: "force" };
119
+ return { ...base, status: 426, code: tooOld ? "upgrade-required" : "contract-unsupported", payload };
120
+ }
121
+ if (contract !== null && contract < record.contractMax) {
122
+ return { ...base, status: 200, deprecation: true, ...record.contractSunset ? { sunset: sunsetDate(record.contractSunset) } : {} };
123
+ }
124
+ return { ...base, status: 200 };
125
+ }
126
+ var SEMVER = /^\d+\.\d+\.\d+$/;
127
+ function isAppConfigPayload(value) {
128
+ if (typeof value !== "object" || value === null) return false;
129
+ const v = value;
130
+ const maintenance = v.maintenance;
131
+ const contract = v.contract;
132
+ return isPlatform(v.platform) && typeof v.minSupportedVersion === "string" && SEMVER.test(v.minSupportedVersion) && typeof v.latestVersion === "string" && SEMVER.test(v.latestVersion) && UPDATE_MODES.includes(v.updateMode) && typeof maintenance === "object" && typeof maintenance?.on === "boolean" && typeof contract === "object" && typeof contract?.min === "number" && typeof contract?.max === "number";
133
+ }
134
+
135
+ export {
136
+ PLATFORMS,
137
+ UPDATE_MODES,
138
+ CLIENT_HEADERS,
139
+ APP_CONFIG_PATH,
140
+ parseVersion,
141
+ compareVersions,
142
+ formatVersion,
143
+ isPlatform,
144
+ toPlatform,
145
+ defaultRecord,
146
+ validateRecord,
147
+ updateModeFor,
148
+ buildPayload,
149
+ evaluateGuard,
150
+ isAppConfigPayload
151
+ };
152
+ //# sourceMappingURL=chunk-D3DIU5IW.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core.ts"],"sourcesContent":["/**\n * The contract, pure: versions, the payload, and the rules that decide what happens to a client.\n * Twin of the Java building block `krizaka-app-config`; `test/cases.json` is the fixture both obey.\n */\n\nexport const PLATFORMS = [\"ios\", \"android\", \"macos\", \"windows\", \"linux\", \"web\"] as const;\nexport type Platform = (typeof PLATFORMS)[number];\n\nexport const UPDATE_MODES = [\"none\", \"soft\", \"force\"] as const;\nexport type UpdateMode = (typeof UPDATE_MODES)[number];\n\n/** The headers an app sends and the backend answers with. */\nexport const CLIENT_HEADERS = {\n version: \"X-Client-Version\",\n platform: \"X-Client-Platform\",\n contract: \"X-Contract-Version\",\n build: \"X-Client-Build\",\n deprecation: \"Deprecation\",\n sunset: \"Sunset\",\n} as const;\n\n/** The public endpoint's path. */\nexport const APP_CONFIG_PATH = \"/api/v1/app-config\";\n\nexport type FlagValue = boolean | number | string;\n\n/** What `GET /api/v1/app-config` returns and what a `426` carries as `appConfig`. */\nexport interface AppConfigPayload {\n platform: Platform;\n minSupportedVersion: string;\n latestVersion: string;\n updateMode: UpdateMode;\n storeUrl: string | null;\n maintenance: { on: boolean; message: string | null };\n contract: { min: number; max: number; sunset: string | null };\n flags: Record<string, FlagValue>;\n message: string | null;\n locale: string;\n}\n\n/** The parameters of one platform, as the database holds them (the admin edits this shape). */\nexport interface AppConfigRecord {\n platform: Platform;\n minSupportedVersion: string;\n latestVersion: string;\n updateOverride: UpdateMode | null;\n storeUrl: string | null;\n maintenanceOn: boolean;\n maintenanceMessage: Record<string, string>;\n message: Record<string, string>;\n contractMin: number;\n contractMax: number;\n contractSunset: string | null;\n flags: Record<string, FlagValue>;\n revision: number;\n updatedAt: string;\n updatedBy: string;\n}\n\n/** What a client says about itself (headers or query). */\nexport interface ClientInfo {\n platform?: string | null;\n version?: string | null;\n contract?: string | number | null;\n language?: string | null;\n}\n\nexport type Version = readonly [major: number, minor: number, patch: number];\n\nconst VERSION = /^v?(\\d{1,6})(?:\\.(\\d{1,6}))?(?:\\.(\\d{1,6}))?(?:[-+].*)?$/;\n\n/** `1.4`, `v1.4.0`, `1.4.0-beta.2` and `1.4.0+42` all read as `[1, 4, 0]`; anything else is `null`. */\nexport function parseVersion(text: string | null | undefined): Version | null {\n const match = VERSION.exec((text ?? \"\").trim());\n return match ? [Number(match[1]), Number(match[2] ?? 0), Number(match[3] ?? 0)] : null;\n}\n\nexport function compareVersions(a: Version, b: Version): number {\n return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];\n}\n\nexport function formatVersion(version: Version): string {\n return version.join(\".\");\n}\n\nconst ZERO: Version = [0, 0, 0];\n\nexport function isPlatform(value: unknown): value is Platform {\n return typeof value === \"string\" && (PLATFORMS as readonly string[]).includes(value.trim().toLowerCase());\n}\n\nexport function toPlatform(value: string | null | undefined): Platform | null {\n const wanted = (value ?? \"\").trim().toLowerCase();\n return isPlatform(wanted) ? wanted : null;\n}\n\n/** The permissive parameters a platform starts with: nobody is locked out. */\nexport function defaultRecord(platform: Platform): AppConfigRecord {\n return {\n platform,\n minSupportedVersion: \"0.0.0\",\n latestVersion: \"0.0.0\",\n updateOverride: null,\n storeUrl: null,\n maintenanceOn: false,\n maintenanceMessage: {},\n message: {},\n contractMin: 1,\n contractMax: 1,\n contractSunset: null,\n flags: {},\n revision: 1,\n updatedAt: new Date(0).toISOString(),\n updatedBy: \"seed\",\n };\n}\n\nconst LANGUAGE = /^[a-z]{2}$/;\nconst FLAG_KEY = /^[A-Za-z][A-Za-z0-9._-]{0,63}$/;\nconst MAX_TEXT = 500;\n\nfunction checkTexts(field: string, texts: Record<string, string>): string[] {\n return Object.entries(texts).flatMap(([language, text]) => {\n if (!LANGUAGE.test(language)) return [`${field} language must be two letters: ${language}`];\n return text.length > MAX_TEXT ? [`${field}.${language} is too long`] : [];\n });\n}\n\n/** The safety bounds of an edit; an empty list means the record can be published. */\nexport function validateRecord(record: AppConfigRecord): string[] {\n const problems: string[] = [];\n const min = parseVersion(record.minSupportedVersion);\n const latest = parseVersion(record.latestVersion);\n if (!min || !latest) problems.push(\"versions must look like 1.4.0\");\n else if (compareVersions(latest, min) < 0) problems.push(\"latestVersion is older than minSupportedVersion\");\n if (!Number.isInteger(record.contractMin) || record.contractMin < 1 || record.contractMax < record.contractMin) {\n problems.push(\"contract range must satisfy 1 <= min <= max\");\n }\n if (record.storeUrl !== null && !/^https:\\/\\/[^\\s/]+/.test(record.storeUrl)) problems.push(\"storeUrl must be an absolute https URL\");\n problems.push(...checkTexts(\"message\", record.message), ...checkTexts(\"maintenanceMessage\", record.maintenanceMessage));\n for (const [key, value] of Object.entries(record.flags)) {\n if (!FLAG_KEY.test(key)) problems.push(`flag key not allowed: ${key}`);\n if (![\"boolean\", \"number\", \"string\"].includes(typeof value)) problems.push(`flag ${key} must be a boolean, number or string`);\n }\n return problems;\n}\n\n/** `none`, `soft` or `force` for the version the client runs. The operator's override wins. */\nexport function updateModeFor(record: AppConfigRecord, client: Version | null): UpdateMode {\n if (record.updateOverride) return record.updateOverride;\n if (!client) return \"none\";\n if (compareVersions(client, parseVersion(record.minSupportedVersion) ?? ZERO) < 0) return \"force\";\n return compareVersions(client, parseVersion(record.latestVersion) ?? ZERO) < 0 ? \"soft\" : \"none\";\n}\n\nfunction pickLanguage(wanted: string | null | undefined, ...texts: Record<string, string>[]): string {\n const language = (wanted ?? \"en\").toLowerCase();\n return texts.some((t) => language in t) ? language : \"en\";\n}\n\n/** The public payload for a client, its texts in the best language available. */\nexport function buildPayload(record: AppConfigRecord, client: Version | null, language?: string | null): AppConfigPayload {\n const chosen = pickLanguage(language, record.message, record.maintenanceMessage);\n const text = (texts: Record<string, string>) => texts[chosen] ?? texts.en ?? null;\n return {\n platform: record.platform,\n minSupportedVersion: formatVersion(parseVersion(record.minSupportedVersion) ?? ZERO),\n latestVersion: formatVersion(parseVersion(record.latestVersion) ?? ZERO),\n updateMode: updateModeFor(record, client),\n storeUrl: record.storeUrl,\n maintenance: { on: record.maintenanceOn, message: text(record.maintenanceMessage) },\n contract: { min: record.contractMin, max: record.contractMax, sunset: record.contractSunset },\n flags: record.flags,\n message: text(record.message),\n locale: chosen,\n };\n}\n\nexport type GuardCode = \"upgrade-required\" | \"contract-unsupported\";\n\n/** What the 426 filter does with a request. */\nexport type GuardResult = {\n /** `Deprecation: true` — the contract the client speaks is served but on its way out. */\n deprecation: boolean;\n /** The newest contract the backend speaks (`X-Contract-Version` of the answer). */\n contract: number;\n} & (\n | {\n status: 200;\n /** The `Sunset` HTTP date, when announced. */\n sunset?: string;\n }\n | {\n status: 426;\n code: GuardCode;\n /** The `appConfig` of a 426: the payload with `updateMode: \"force\"`. */\n payload: AppConfigPayload;\n }\n);\n\nfunction contractOf(value: string | number | null | undefined): number | null {\n const n = typeof value === \"number\" ? value : Number.parseInt(String(value ?? \"\").trim(), 10);\n return Number.isInteger(n) && n >= 1 ? n : null;\n}\n\nfunction sunsetDate(day: string): string {\n const [y, m, d] = day.split(\"-\").map(Number) as [number, number, number];\n return new Date(Date.UTC(y, m - 1, d + 1)).toUTCString();\n}\n\n/** The 426 filter's decision: below the minimum or an unserved contract is refused; N-1 is deprecated. */\nexport function evaluateGuard(record: AppConfigRecord, client: ClientInfo): GuardResult {\n const version = parseVersion(client.version);\n const contract = contractOf(client.contract);\n const base = { deprecation: false, contract: record.contractMax };\n const tooOld = version !== null && compareVersions(version, parseVersion(record.minSupportedVersion) ?? ZERO) < 0;\n const contractGone = contract !== null && contract < record.contractMin;\n if (tooOld || contractGone) {\n const payload: AppConfigPayload = { ...buildPayload(record, version, client.language), updateMode: \"force\" };\n return { ...base, status: 426, code: tooOld ? \"upgrade-required\" : \"contract-unsupported\", payload };\n }\n if (contract !== null && contract < record.contractMax) {\n return { ...base, status: 200, deprecation: true, ...(record.contractSunset ? { sunset: sunsetDate(record.contractSunset) } : {}) };\n }\n return { ...base, status: 200 };\n}\n\nconst SEMVER = /^\\d+\\.\\d+\\.\\d+$/;\n\n/** A structural check of a payload read from the network: anything else is ignored (fail open). */\nexport function isAppConfigPayload(value: unknown): value is AppConfigPayload {\n if (typeof value !== \"object\" || value === null) return false;\n const v = value as Record<string, unknown>;\n const maintenance = v.maintenance as Record<string, unknown> | undefined;\n const contract = v.contract as Record<string, unknown> | undefined;\n return (\n isPlatform(v.platform) &&\n typeof v.minSupportedVersion === \"string\" &&\n SEMVER.test(v.minSupportedVersion) &&\n typeof v.latestVersion === \"string\" &&\n SEMVER.test(v.latestVersion) &&\n (UPDATE_MODES as readonly unknown[]).includes(v.updateMode) &&\n typeof maintenance === \"object\" &&\n typeof maintenance?.on === \"boolean\" &&\n typeof contract === \"object\" &&\n typeof contract?.min === \"number\" &&\n typeof contract?.max === \"number\"\n );\n}\n"],"mappings":";AAKO,IAAM,YAAY,CAAC,OAAO,WAAW,SAAS,WAAW,SAAS,KAAK;AAGvE,IAAM,eAAe,CAAC,QAAQ,QAAQ,OAAO;AAI7C,IAAM,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B,OAAO,aAAa,OAAO,aAC3B,OAAO,aAAa,YACpB,OAAO,UAAU,QAAQ,YACzB,OAAO,UAAU,QAAQ;AAE7B;","names":[]}
@@ -0,0 +1,83 @@
1
+ import { AppConfigPayload, Platform } from './index.js';
2
+
3
+ /** What the app must show, decided from the payload. Maintenance outranks an update. */
4
+ type Decision = {
5
+ kind: "ok";
6
+ } | {
7
+ kind: "soft";
8
+ config: AppConfigPayload;
9
+ } | {
10
+ kind: "force";
11
+ config: AppConfigPayload;
12
+ } | {
13
+ kind: "maintenance";
14
+ config: AppConfigPayload;
15
+ };
16
+ type AppConfigStatus = "idle" | "loading" | "ready" | "failed";
17
+ interface AppConfigState {
18
+ status: AppConfigStatus;
19
+ config: AppConfigPayload | null;
20
+ decision: Decision;
21
+ /** The 426 payload that forced the screen, if a request got one. */
22
+ upgradeRequired: AppConfigPayload | null;
23
+ }
24
+ /** A place to remember which version's soft prompt the person already dismissed. */
25
+ interface DismissStorage {
26
+ getItem(key: string): string | null | Promise<string | null>;
27
+ setItem(key: string, value: string): void | Promise<void>;
28
+ }
29
+ interface AppConfigClientOptions {
30
+ /** The backend's origin, e.g. `https://dev.orazaka.com`. */
31
+ baseUrl: string;
32
+ platform: Platform;
33
+ /** The version the app runs (`1.4.0`), from the build, never typed twice. */
34
+ version: string;
35
+ /** The API contract the app speaks. Defaults to 1. */
36
+ contract?: number;
37
+ build?: string;
38
+ fetch?: typeof fetch;
39
+ /** The language to ask texts in (`fr`); defaults to the backend's `Accept-Language` reading. */
40
+ language?: () => string | undefined;
41
+ storage?: DismissStorage;
42
+ now?: () => number;
43
+ /** A check requested sooner than this after the last one is skipped (resume storms). Default 300 s. */
44
+ minIntervalMs?: number;
45
+ }
46
+ /** Maintenance first, then a forced update, then a soft one. */
47
+ declare function decide(config: AppConfigPayload | null, softDismissedFor?: string | null): Decision;
48
+ /** The headers every request of the app carries. */
49
+ declare function clientHeaders(info: {
50
+ platform: Platform;
51
+ version: string;
52
+ contract?: number;
53
+ build?: string;
54
+ }): Record<string, string>;
55
+ /** Whether a response is the backend telling the app to update. */
56
+ declare function isUpgradeRequired(response: {
57
+ status: number;
58
+ }): boolean;
59
+ /** The `appConfig` member of an already parsed `426` body, or `null` (for a transport that is not `fetch`, e.g. XHR). */
60
+ declare function upgradePayloadOf(body: unknown): AppConfigPayload | null;
61
+ /** The `appConfig` of a `426` response, or `null` when the body is not one (the app still must update). */
62
+ declare function readUpgradeRequired(response: Response): Promise<AppConfigPayload | null>;
63
+ interface AppConfigClient {
64
+ /** The headers every request carries — for a transport that is not `fetch` (XHR, a native module). */
65
+ readonly headers: Readonly<Record<string, string>>;
66
+ getState(): AppConfigState;
67
+ subscribe(listener: () => void): () => void;
68
+ /** Checks the backend. Skipped when a check ran less than `minIntervalMs` ago, unless `force`. Never throws. */
69
+ check(options?: {
70
+ force?: boolean;
71
+ }): Promise<void>;
72
+ /** The person dismissed the soft prompt: not shown again for this `latestVersion`. */
73
+ dismissSoft(): Promise<void>;
74
+ /** A request got a 426 (the global interceptor calls this). */
75
+ reportUpgradeRequired(payload: AppConfigPayload | null): void;
76
+ /** `fetch` that sends the client headers and reports every 426 to this client. */
77
+ fetch: typeof fetch;
78
+ /** Checks again each time `resume` fires (app foreground, tab visible). Returns the unsubscribe. */
79
+ attach(resume: (callback: () => void) => () => void): () => void;
80
+ }
81
+ declare function createAppConfigClient(options: AppConfigClientOptions): AppConfigClient;
82
+
83
+ export { type AppConfigClient, type AppConfigClientOptions, type AppConfigState, type AppConfigStatus, type Decision, type DismissStorage, clientHeaders, createAppConfigClient, decide, isUpgradeRequired, readUpgradeRequired, upgradePayloadOf };