@cogover/sdk 0.17.0 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -0
- package/dist/compare.d.ts +4 -0
- package/dist/compare.js +67 -0
- package/dist/format.d.ts +22 -0
- package/dist/format.js +135 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +2 -0
- package/dist/router.d.ts +5 -0
- package/dist/router.js +129 -12
- package/docs/en/api-reference/actions.md +1 -1
- package/docs/en/api-reference/fetch-and-secrets.md +3 -1
- package/docs/en/api-reference/formatting.md +88 -0
- package/docs/en/api-reference/overview.md +60 -7
- package/docs/en/api-reference/scripts-and-routes.md +44 -0
- package/docs/en/api-reference/state-and-locks.md +10 -2
- package/docs/en/usage-guide.md +191 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -52,6 +52,8 @@ authentication credentials are not exposed to project code, and Cogover enforces
|
|
|
52
52
|
the configured permissions and the per-execution limits on capability calls and
|
|
53
53
|
records. `limits.usage()` (also `context.limits`) reports how much of each budget
|
|
54
54
|
the execution has used, without a capability call.
|
|
55
|
+
Calls started together, for example with `Promise.all`, run in parallel up to a
|
|
56
|
+
platform limit; every call still counts towards the budgets.
|
|
55
57
|
|
|
56
58
|
## Current identity and workspace
|
|
57
59
|
|
|
@@ -116,6 +118,16 @@ HTTP 200. `response.json`, `text`, `bytes`, `empty`, and `redirect` provide expl
|
|
|
116
118
|
status, safe response headers, and text/binary bodies. Missing routes, including a
|
|
117
119
|
path registered only for other methods, return 404; methods other than these five
|
|
118
120
|
return 405. Existing `defineScript()` projects continue at `/`.
|
|
121
|
+
|
|
122
|
+
To keep a group of routes in its own file, export a router created with
|
|
123
|
+
`createRouter()` from that file and mount it with `router.route(prefix, childRouter)`:
|
|
124
|
+
|
|
125
|
+
```typescript
|
|
126
|
+
import { ordersRouter } from "./orders-router.js";
|
|
127
|
+
|
|
128
|
+
router.route("/orders", ordersRouter); // the routes of ordersRouter, under /orders
|
|
129
|
+
```
|
|
130
|
+
|
|
119
131
|
The complete router contract is included in `docs/en/api-reference/scripts-and-routes.md`.
|
|
120
132
|
|
|
121
133
|
## Record triggers
|
|
@@ -699,6 +711,25 @@ Available calls: `org.me`, `org.personnel.get/getMany/managerChain`,
|
|
|
699
711
|
`org.positions.list/get/members`, `org.isInDepartment`, and `org.isManagerOf`.
|
|
700
712
|
Membership `level` is `0` for staff and `1`, `2`, ... for managers, highest first.
|
|
701
713
|
|
|
714
|
+
## Formatting and sorting without `Intl`
|
|
715
|
+
|
|
716
|
+
Runtime V2 has no `Intl`, and `toLocaleString`, `toLocaleDateString`,
|
|
717
|
+
`toLocaleTimeString`, and `localeCompare` ignore their locale there. Use these
|
|
718
|
+
functions instead (0.19.0 and later):
|
|
719
|
+
|
|
720
|
+
```typescript
|
|
721
|
+
import { compareVietnamese, formatDate, formatNumber, formatUsd, formatVnd, sortVietnamese } from "@cogover/sdk";
|
|
722
|
+
|
|
723
|
+
formatNumber(1234567.891); // "1.234.567,891"
|
|
724
|
+
formatUsd(1234.5); // "$1,234.50"
|
|
725
|
+
formatVnd(1234567); // "1.234.567 ₫"
|
|
726
|
+
formatDate(Date.now(), "dd/MM/yyyy HH:mm"); // GMT+7
|
|
727
|
+
names.sort(compareVietnamese);
|
|
728
|
+
```
|
|
729
|
+
|
|
730
|
+
Publishing code that imports them needs a Workspace where Cogover supports SDK
|
|
731
|
+
0.19.0. See `docs/en/api-reference/formatting.md`.
|
|
732
|
+
|
|
702
733
|
## Workspace types
|
|
703
734
|
|
|
704
735
|
`WorkspaceObjects` is an open interface augmented by a generated declaration for
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
/** Negative, zero or positive: the order a.localeCompare(b, "vi") gave on the previous runtime, for Vietnamese and English text. */
|
|
2
|
+
export declare function compareVietnamese(a: string, b: string): number;
|
|
3
|
+
/** A sorted copy: sortVietnamese(["Bình", "An", "Ân", "Đức", "Dũng"]) returns ["An", "Ân", "Bình", "Dũng", "Đức"]. */
|
|
4
|
+
export declare function sortVietnamese<T>(items: readonly T[], key?: (item: T) => string): T[];
|
package/dist/compare.js
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// Vietnamese-aware comparison without Intl or localeCompare: letters in Vietnamese alphabet order
|
|
2
|
+
// (a ă â b c d đ e ê ... o ô ơ ... u ư ...), then tone marks, then lower case before upper case.
|
|
3
|
+
const ALPHABET = "a\u0103\u00e2bcd\u0111e\u00eafghijklmno\u00f4\u01a1pqrstu\u01b0vwxyz";
|
|
4
|
+
// A letter followed by one of these marks is another letter of the alphabet (ă, â, ê, ô, ơ, ư).
|
|
5
|
+
const MARKED_LETTERS = {
|
|
6
|
+
"a\u0306": "\u0103", "a\u0302": "\u00e2", "e\u0302": "\u00ea",
|
|
7
|
+
"o\u0302": "\u00f4", "o\u031b": "\u01a1", "u\u031b": "\u01b0",
|
|
8
|
+
};
|
|
9
|
+
// Tone marks, in order: huyền, hỏi, ngã, sắc, nặng.
|
|
10
|
+
const TONES = ["\u0300", "\u0309", "\u0303", "\u0301", "\u0323"];
|
|
11
|
+
// Letters that look like a Vietnamese or English one sort with it (Ð U+00D0 is often typed for Đ but sorts as D).
|
|
12
|
+
const LOOK_ALIKE = { "\u00f0": "d", "\u00f8": "o", "\u0131": "i", "\u0142": "l" };
|
|
13
|
+
function units(text) {
|
|
14
|
+
const result = [];
|
|
15
|
+
const chars = Array.from(text.normalize("NFD"));
|
|
16
|
+
for (let index = 0; index < chars.length; index += 1) {
|
|
17
|
+
const char = chars[index] ?? "";
|
|
18
|
+
const lower = char.toLowerCase();
|
|
19
|
+
let letter = LOOK_ALIKE[lower] ?? lower;
|
|
20
|
+
let tone = letter === lower ? 0 : TONES.length + 1;
|
|
21
|
+
while (index + 1 < chars.length && /\p{M}/u.test(chars[index + 1] ?? "")) {
|
|
22
|
+
const mark = chars[index + 1] ?? "";
|
|
23
|
+
const toneIndex = TONES.indexOf(mark);
|
|
24
|
+
if (toneIndex >= 0)
|
|
25
|
+
tone = toneIndex + 1;
|
|
26
|
+
else
|
|
27
|
+
letter = MARKED_LETTERS[letter + mark] ?? letter;
|
|
28
|
+
index += 1;
|
|
29
|
+
}
|
|
30
|
+
const code = letter.codePointAt(0) ?? 0;
|
|
31
|
+
const position = ALPHABET.indexOf(letter);
|
|
32
|
+
let primary;
|
|
33
|
+
if (position >= 0)
|
|
34
|
+
primary = 3_000_000 + position;
|
|
35
|
+
else if (/\d/.test(letter))
|
|
36
|
+
primary = 2_000_000 + code;
|
|
37
|
+
else if (/\s/u.test(letter))
|
|
38
|
+
primary = code;
|
|
39
|
+
else if (/[\p{P}\p{S}]/u.test(letter))
|
|
40
|
+
primary = 1_000_000 + code;
|
|
41
|
+
else
|
|
42
|
+
primary = 4_000_000 + code;
|
|
43
|
+
result.push({ primary, tone, upper: char !== lower ? 1 : 0 });
|
|
44
|
+
}
|
|
45
|
+
return result;
|
|
46
|
+
}
|
|
47
|
+
function compareLevel(left, right, key) {
|
|
48
|
+
const length = Math.min(left.length, right.length);
|
|
49
|
+
for (let index = 0; index < length; index += 1) {
|
|
50
|
+
const a = left[index]?.[key] ?? 0;
|
|
51
|
+
const b = right[index]?.[key] ?? 0;
|
|
52
|
+
if (a !== b)
|
|
53
|
+
return a < b ? -1 : 1;
|
|
54
|
+
}
|
|
55
|
+
return left.length === right.length ? 0 : left.length < right.length ? -1 : 1;
|
|
56
|
+
}
|
|
57
|
+
/** Negative, zero or positive: the order a.localeCompare(b, "vi") gave on the previous runtime, for Vietnamese and English text. */
|
|
58
|
+
export function compareVietnamese(a, b) {
|
|
59
|
+
const left = units(a);
|
|
60
|
+
const right = units(b);
|
|
61
|
+
return compareLevel(left, right, "primary") || compareLevel(left, right, "tone")
|
|
62
|
+
|| compareLevel(left, right, "upper");
|
|
63
|
+
}
|
|
64
|
+
/** A sorted copy: sortVietnamese(["Bình", "An", "Ân", "Đức", "Dũng"]) returns ["An", "Ân", "Bình", "Dũng", "Đức"]. */
|
|
65
|
+
export function sortVietnamese(items, key = String) {
|
|
66
|
+
return [...items].sort((left, right) => compareVietnamese(key(left), key(right)));
|
|
67
|
+
}
|
package/dist/format.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export type NumberLocale = "vi" | "en";
|
|
2
|
+
/**
|
|
3
|
+
* Formats a number like `toLocaleString` did: grouping every 3 digits, at most `maxDecimals` decimals
|
|
4
|
+
* (trailing zeros removed down to `minDecimals`), rounding half away from zero.
|
|
5
|
+
* formatNumber(1234567.891, "vi") === "1.234.567,891"; formatNumber(1234567.891, "en", 2) === "1,234,567.89"
|
|
6
|
+
* Throws a TypeError when `value` is not a number (a string, null, undefined, a bigint) and a RangeError for another
|
|
7
|
+
* locale than "vi" or "en" or decimals that are not integers from 0 to 20.
|
|
8
|
+
*/
|
|
9
|
+
export declare function formatNumber(value: number, locale?: NumberLocale, maxDecimals?: number, minDecimals?: number): string;
|
|
10
|
+
/** Vietnamese dong, no decimals: formatVnd(1234567) === "1.234.567 \u20ab" (no-break space before the sign). */
|
|
11
|
+
export declare function formatVnd(value: number): string;
|
|
12
|
+
/** US dollars, 2 decimals: formatUsd(1234.5) === "$1,234.50", formatUsd(-3) === "-$3.00". */
|
|
13
|
+
export declare function formatUsd(value: number): string;
|
|
14
|
+
/** Vietnam time (GMT+7, no daylight saving). */
|
|
15
|
+
export declare const VIETNAM_OFFSET_MINUTES: number;
|
|
16
|
+
/**
|
|
17
|
+
* Formats a date in a fixed time zone (default GMT+7). Tokens: yyyy, MM, M, dd, d, HH, H, hh, h, mm, ss, a (AM/PM).
|
|
18
|
+
* Text in single quotes is copied as is. formatDate(Date.UTC(2026, 4, 29, 7, 5, 9), "dd/MM/yyyy HH:mm") === "29/05/2026 14:05"
|
|
19
|
+
* An invalid date gives "Invalid Date". Throws a TypeError when `value` is neither a Date nor a number, and a RangeError
|
|
20
|
+
* for an offset that is not an integer from -1440 to 1440 or a date outside the years 1 to 9999 in that offset.
|
|
21
|
+
*/
|
|
22
|
+
export declare function formatDate(value: Date | number, pattern?: string, offsetMinutes?: number): string;
|
package/dist/format.js
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// Number, currency, date and time formatting without Intl or toLocale* methods.
|
|
2
|
+
const SEPARATORS = {
|
|
3
|
+
vi: { group: ".", decimal: "," },
|
|
4
|
+
en: { group: ",", decimal: "." },
|
|
5
|
+
};
|
|
6
|
+
/** Plain decimal digits of a finite, non-negative number ("1e+21" becomes "1000000000000000000000"). */
|
|
7
|
+
function plainDigits(value) {
|
|
8
|
+
const text = String(value);
|
|
9
|
+
const match = /^(\d+)(?:\.(\d+))?e([+-]\d+)$/.exec(text);
|
|
10
|
+
if (match === null)
|
|
11
|
+
return text;
|
|
12
|
+
const whole = match[1] ?? "";
|
|
13
|
+
const digits = whole + (match[2] ?? "");
|
|
14
|
+
const point = whole.length + Number(match[3]);
|
|
15
|
+
if (point <= 0)
|
|
16
|
+
return "0." + "0".repeat(-point) + digits;
|
|
17
|
+
if (point >= digits.length)
|
|
18
|
+
return digits + "0".repeat(point - digits.length);
|
|
19
|
+
return digits.slice(0, point) + "." + digits.slice(point);
|
|
20
|
+
}
|
|
21
|
+
/** Rounds a plain decimal string to `decimals` digits, half away from zero. Returns [integer, fraction]. */
|
|
22
|
+
function roundDigits(text, decimals) {
|
|
23
|
+
const [integer = "", fraction = ""] = text.split(".");
|
|
24
|
+
if (fraction.length <= decimals)
|
|
25
|
+
return [integer, fraction.padEnd(decimals, "0")];
|
|
26
|
+
const kept = (integer + fraction.slice(0, decimals)).split("").map(Number);
|
|
27
|
+
if (Number(fraction[decimals]) >= 5) {
|
|
28
|
+
let index = kept.length - 1;
|
|
29
|
+
while (index >= 0 && kept[index] === 9) {
|
|
30
|
+
kept[index] = 0;
|
|
31
|
+
index -= 1;
|
|
32
|
+
}
|
|
33
|
+
if (index < 0)
|
|
34
|
+
kept.unshift(1);
|
|
35
|
+
else
|
|
36
|
+
kept[index] = (kept[index] ?? 0) + 1;
|
|
37
|
+
}
|
|
38
|
+
const all = kept.join("");
|
|
39
|
+
const cut = all.length - decimals;
|
|
40
|
+
return [all.slice(0, cut), all.slice(cut)];
|
|
41
|
+
}
|
|
42
|
+
/** The value as a number, or a TypeError: money is never formatted from a string, null or undefined by mistake. */
|
|
43
|
+
function checkNumber(value, name) {
|
|
44
|
+
if (typeof value !== "number") {
|
|
45
|
+
throw new TypeError(name + " expects a number, got " + (value === null ? "null" : typeof value));
|
|
46
|
+
}
|
|
47
|
+
return value;
|
|
48
|
+
}
|
|
49
|
+
/** A number of decimals: an integer from 0 to 20, or a RangeError. */
|
|
50
|
+
function checkDecimals(value, name) {
|
|
51
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > 20) {
|
|
52
|
+
throw new RangeError(name + " must be an integer from 0 to 20");
|
|
53
|
+
}
|
|
54
|
+
return value;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Formats a number like `toLocaleString` did: grouping every 3 digits, at most `maxDecimals` decimals
|
|
58
|
+
* (trailing zeros removed down to `minDecimals`), rounding half away from zero.
|
|
59
|
+
* formatNumber(1234567.891, "vi") === "1.234.567,891"; formatNumber(1234567.891, "en", 2) === "1,234,567.89"
|
|
60
|
+
* Throws a TypeError when `value` is not a number (a string, null, undefined, a bigint) and a RangeError for another
|
|
61
|
+
* locale than "vi" or "en" or decimals that are not integers from 0 to 20.
|
|
62
|
+
*/
|
|
63
|
+
export function formatNumber(value, locale = "vi", maxDecimals = 3, minDecimals = 0) {
|
|
64
|
+
checkNumber(value, "formatNumber");
|
|
65
|
+
if (typeof locale !== "string" || !Object.prototype.hasOwnProperty.call(SEPARATORS, locale)) {
|
|
66
|
+
throw new RangeError("formatNumber supports the locales \"vi\" and \"en\", not " + String(locale));
|
|
67
|
+
}
|
|
68
|
+
checkDecimals(maxDecimals, "maxDecimals");
|
|
69
|
+
checkDecimals(minDecimals, "minDecimals");
|
|
70
|
+
if (minDecimals > maxDecimals)
|
|
71
|
+
throw new RangeError("minDecimals must not be greater than maxDecimals");
|
|
72
|
+
if (Number.isNaN(value))
|
|
73
|
+
return "NaN";
|
|
74
|
+
if (!Number.isFinite(value))
|
|
75
|
+
return value > 0 ? "\u221e" : "-\u221e";
|
|
76
|
+
const { group, decimal } = SEPARATORS[locale];
|
|
77
|
+
let [integer, fraction] = roundDigits(plainDigits(Math.abs(value)), maxDecimals);
|
|
78
|
+
while (fraction.length > minDecimals && fraction.endsWith("0"))
|
|
79
|
+
fraction = fraction.slice(0, -1);
|
|
80
|
+
integer = integer.replace(/^0+(?=\d)/, "");
|
|
81
|
+
const grouped = integer.replace(/\B(?=(\d{3})+(?!\d))/g, group);
|
|
82
|
+
const sign = value < 0 || Object.is(value, -0) ? "-" : "";
|
|
83
|
+
return sign + grouped + (fraction.length > 0 ? decimal + fraction : "");
|
|
84
|
+
}
|
|
85
|
+
/** Vietnamese dong, no decimals: formatVnd(1234567) === "1.234.567 \u20ab" (no-break space before the sign). */
|
|
86
|
+
export function formatVnd(value) {
|
|
87
|
+
return formatNumber(checkNumber(value, "formatVnd"), "vi", 0, 0) + "\u00a0\u20ab";
|
|
88
|
+
}
|
|
89
|
+
/** US dollars, 2 decimals: formatUsd(1234.5) === "$1,234.50", formatUsd(-3) === "-$3.00". */
|
|
90
|
+
export function formatUsd(value) {
|
|
91
|
+
const text = formatNumber(Math.abs(checkNumber(value, "formatUsd")), "en", 2, 2);
|
|
92
|
+
return (value < 0 || Object.is(value, -0) ? "-$" : "$") + text;
|
|
93
|
+
}
|
|
94
|
+
/** Vietnam time (GMT+7, no daylight saving). */
|
|
95
|
+
export const VIETNAM_OFFSET_MINUTES = 7 * 60;
|
|
96
|
+
const pad = (value, length = 2) => String(value).padStart(length, "0");
|
|
97
|
+
/**
|
|
98
|
+
* Formats a date in a fixed time zone (default GMT+7). Tokens: yyyy, MM, M, dd, d, HH, H, hh, h, mm, ss, a (AM/PM).
|
|
99
|
+
* Text in single quotes is copied as is. formatDate(Date.UTC(2026, 4, 29, 7, 5, 9), "dd/MM/yyyy HH:mm") === "29/05/2026 14:05"
|
|
100
|
+
* An invalid date gives "Invalid Date". Throws a TypeError when `value` is neither a Date nor a number, and a RangeError
|
|
101
|
+
* for an offset that is not an integer from -1440 to 1440 or a date outside the years 1 to 9999 in that offset.
|
|
102
|
+
*/
|
|
103
|
+
export function formatDate(value, pattern = "dd/MM/yyyy", offsetMinutes = VIETNAM_OFFSET_MINUTES) {
|
|
104
|
+
if (typeof value !== "number" && !(value instanceof Date)) {
|
|
105
|
+
throw new TypeError("formatDate expects a Date or a number of milliseconds");
|
|
106
|
+
}
|
|
107
|
+
if (typeof pattern !== "string")
|
|
108
|
+
throw new TypeError("formatDate expects the pattern as a string");
|
|
109
|
+
if (typeof offsetMinutes !== "number" || !Number.isInteger(offsetMinutes) || Math.abs(offsetMinutes) > 1440) {
|
|
110
|
+
throw new RangeError("offsetMinutes must be an integer from -1440 to 1440");
|
|
111
|
+
}
|
|
112
|
+
const time = typeof value === "number" ? value : value.getTime();
|
|
113
|
+
if (!Number.isFinite(time))
|
|
114
|
+
return "Invalid Date";
|
|
115
|
+
const shifted = new Date(time + offsetMinutes * 60_000);
|
|
116
|
+
const year = shifted.getUTCFullYear();
|
|
117
|
+
if (!(year >= 1 && year <= 9999))
|
|
118
|
+
throw new RangeError("formatDate supports the years 1 to 9999");
|
|
119
|
+
const hours = shifted.getUTCHours();
|
|
120
|
+
const parts = {
|
|
121
|
+
yyyy: pad(year, 4),
|
|
122
|
+
MM: pad(shifted.getUTCMonth() + 1),
|
|
123
|
+
M: String(shifted.getUTCMonth() + 1),
|
|
124
|
+
dd: pad(shifted.getUTCDate()),
|
|
125
|
+
d: String(shifted.getUTCDate()),
|
|
126
|
+
HH: pad(hours),
|
|
127
|
+
H: String(hours),
|
|
128
|
+
hh: pad(hours % 12 === 0 ? 12 : hours % 12),
|
|
129
|
+
h: String(hours % 12 === 0 ? 12 : hours % 12),
|
|
130
|
+
mm: pad(shifted.getUTCMinutes()),
|
|
131
|
+
ss: pad(shifted.getUTCSeconds()),
|
|
132
|
+
a: hours < 12 ? "AM" : "PM",
|
|
133
|
+
};
|
|
134
|
+
return pattern.replace(/'([^']*)'|yyyy|MM|M|dd|d|HH|H|hh|h|mm|ss|a/g, (token, quoted) => quoted ?? parts[token] ?? token);
|
|
135
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -22,6 +22,9 @@ export type { SecretsApi } from "./secrets.js";
|
|
|
22
22
|
export type { OrgApi, OrgPersonnelApi, OrgDepartmentsApi, OrgPositionsApi, OrgReadOptions, OrgPageOptions, OrgDepartmentMembersOptions, OrgPositionMembersOptions, OrgManagerOptions, OrgPersonnelChainOptions, OrgTreeOptions, OrgIsInDepartmentOptions, OrgIsManagerOfOptions, OrgPersonnelDisplay, OrgNameDisplay, OrgMembership, OrgMember, OrgPersonnel, OrgDepartment, OrgDepartmentNode, OrgPosition, OrgManagerTier, OrgManagerChain, OrgPage, OrgGetManyResult, } from "./org.js";
|
|
23
23
|
export { limits } from "./limits.js";
|
|
24
24
|
export type { LimitsApi, LimitUsage, LimitCounter } from "./limits.js";
|
|
25
|
+
export { formatNumber, formatVnd, formatUsd, formatDate, VIETNAM_OFFSET_MINUTES } from "./format.js";
|
|
26
|
+
export type { NumberLocale } from "./format.js";
|
|
27
|
+
export { compareVietnamese, sortVietnamese } from "./compare.js";
|
|
25
28
|
export { crypto } from "./crypto.js";
|
|
26
29
|
export type { CryptoApi, BinaryEncoding, DecryptOutput, SecretKeyReference, AesKey, AsymmetricKey, AesMode, AesEncryptOptions, AesEncryptResult, AesDecryptOptions, RsaPadding, RsaEncryptOptions, RsaDecryptOptions, SignatureAlgorithm, SignatureOptions, } from "./crypto.js";
|
|
27
30
|
export type { CurrentWorkspace, CurrentWorkspaceMembership, CurrentWorkspaceRole, CurrentUser, UserInvocationContext, SystemInvocationContext, InboundInvocationContext, InvocationContext, } from "./invocation.js";
|
package/dist/index.js
CHANGED
|
@@ -6,6 +6,8 @@ export { defineJob } from "./jobs.js";
|
|
|
6
6
|
export { defineAction } from "./actions.js";
|
|
7
7
|
export { s } from "./action-schema.js";
|
|
8
8
|
export { limits } from "./limits.js";
|
|
9
|
+
export { formatNumber, formatVnd, formatUsd, formatDate, VIETNAM_OFFSET_MINUTES } from "./format.js";
|
|
10
|
+
export { compareVietnamese, sortVietnamese } from "./compare.js";
|
|
9
11
|
export { crypto } from "./crypto.js";
|
|
10
12
|
export { createRouter } from "./router.js";
|
|
11
13
|
export { fetch } from "./fetch.js";
|
package/dist/router.d.ts
CHANGED
|
@@ -8,6 +8,11 @@ export interface ScriptRouter<TSchema extends object = EffectiveWorkspaceObjects
|
|
|
8
8
|
put<TInput = unknown, TOutput = unknown>(path: string, handler: ScriptHandler<TInput, TOutput, TSchema>): ScriptRouter<TSchema>;
|
|
9
9
|
patch<TInput = unknown, TOutput = unknown>(path: string, handler: ScriptHandler<TInput, TOutput, TSchema>): ScriptRouter<TSchema>;
|
|
10
10
|
delete<TInput = unknown, TOutput = unknown>(path: string, handler: ScriptHandler<TInput, TOutput, TSchema>): ScriptRouter<TSchema>;
|
|
11
|
+
/**
|
|
12
|
+
* Mounts every route of `router` under `prefix` (`"/"` mounts them unchanged) and returns this router. The routes
|
|
13
|
+
* of `router` are read when `toHandler()` is called, so routes added to it after this call are included.
|
|
14
|
+
*/
|
|
15
|
+
route(prefix: string, router: ScriptRouter<TSchema>): ScriptRouter<TSchema>;
|
|
11
16
|
toHandler(): SandboxHandler;
|
|
12
17
|
}
|
|
13
18
|
export declare function createRouter<TSchema extends object = EffectiveWorkspaceObjects>(): ScriptRouter<TSchema>;
|
package/dist/router.js
CHANGED
|
@@ -1,8 +1,15 @@
|
|
|
1
1
|
import { NotFoundError, ValidationError } from "./errors.js";
|
|
2
2
|
import { validateRoutePath, withRouteParams } from "./internal/request.js";
|
|
3
3
|
import { createSandboxHandler } from "./script.js";
|
|
4
|
+
// Routers created by createRouter(); route() accepts only these.
|
|
5
|
+
const ROUTER_ITEMS = new WeakMap();
|
|
6
|
+
const MAX_MOUNTS_PER_ROUTER = 64;
|
|
7
|
+
const MAX_MOUNT_DEPTH = 8;
|
|
8
|
+
const MAX_FLATTENED_ROUTES = 2048;
|
|
4
9
|
export function createRouter() {
|
|
5
10
|
const routes = [];
|
|
11
|
+
const items = [];
|
|
12
|
+
let mounts = 0;
|
|
6
13
|
const router = {
|
|
7
14
|
addRoute(method, path, handler) {
|
|
8
15
|
if (!isRequestMethod(method))
|
|
@@ -16,8 +23,10 @@ export function createRouter() {
|
|
|
16
23
|
}
|
|
17
24
|
if (routes.length >= 256)
|
|
18
25
|
throw new ValidationError("A router supports at most 256 routes");
|
|
19
|
-
|
|
20
|
-
handler: handler })
|
|
26
|
+
const route = Object.freeze({ method, path, signature,
|
|
27
|
+
handler: handler });
|
|
28
|
+
routes.push(route);
|
|
29
|
+
items.push(Object.freeze({ route }));
|
|
21
30
|
return router;
|
|
22
31
|
},
|
|
23
32
|
post(path, handler) {
|
|
@@ -35,19 +44,40 @@ export function createRouter() {
|
|
|
35
44
|
delete(path, handler) {
|
|
36
45
|
return router.addRoute("DELETE", path, handler);
|
|
37
46
|
},
|
|
47
|
+
route(prefix, child) {
|
|
48
|
+
validateRoutePath(prefix);
|
|
49
|
+
if (typeof child !== "object" || child === null || !ROUTER_ITEMS.has(child)) {
|
|
50
|
+
throw new ValidationError("route() requires a router created by createRouter()");
|
|
51
|
+
}
|
|
52
|
+
if (child === router)
|
|
53
|
+
throw new ValidationError("A router cannot be mounted on itself");
|
|
54
|
+
if (mounts >= MAX_MOUNTS_PER_ROUTER) {
|
|
55
|
+
throw new ValidationError(`A router supports at most ${MAX_MOUNTS_PER_ROUTER} mounted routers`);
|
|
56
|
+
}
|
|
57
|
+
items.push(Object.freeze({ prefix, child, mount: mounts++ }));
|
|
58
|
+
return router;
|
|
59
|
+
},
|
|
38
60
|
toHandler() {
|
|
39
61
|
// Each exported handler gets a stable route table, never a global registry.
|
|
40
|
-
const
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
62
|
+
const flat = flattenRouter(router, 0, new Set(), new Map()).routes;
|
|
63
|
+
const signatures = new Set();
|
|
64
|
+
const registered = [];
|
|
65
|
+
for (const { route } of flat) {
|
|
66
|
+
validateRoutePath(route.path);
|
|
67
|
+
const signature = routeSignature(route.path);
|
|
68
|
+
const key = `${route.method} ${signature}`;
|
|
69
|
+
if (signatures.has(key)) {
|
|
70
|
+
throw new ValidationError(`Duplicate or ambiguous route: ${route.method} ${route.path}`);
|
|
71
|
+
}
|
|
72
|
+
signatures.add(key);
|
|
73
|
+
registered.push(route.signature === signature ? route : Object.freeze({ ...route, signature }));
|
|
74
|
+
}
|
|
75
|
+
Object.freeze(registered);
|
|
76
|
+
const handler = createSandboxHandler(context => {
|
|
77
|
+
const matched = selectRoute(registered, context.request.method, context.request.path);
|
|
78
|
+
if (matched === null)
|
|
49
79
|
throw new NotFoundError("route", context.request.path);
|
|
50
|
-
return matched.
|
|
80
|
+
return registered[matched.index].handler({
|
|
51
81
|
input: context.input,
|
|
52
82
|
request: withRouteParams(context.request, matched.params),
|
|
53
83
|
get invocation() {
|
|
@@ -71,10 +101,97 @@ export function createRouter() {
|
|
|
71
101
|
agents: context.agents,
|
|
72
102
|
});
|
|
73
103
|
});
|
|
104
|
+
// Hidden, read-only description of the flattened table; matching is the handler's own selection.
|
|
105
|
+
Object.defineProperty(handler, "__cogoverRoutes", {
|
|
106
|
+
value: Object.freeze({
|
|
107
|
+
version: 1,
|
|
108
|
+
routes: Object.freeze(flat.map(entry => Object.freeze({
|
|
109
|
+
method: entry.route.method,
|
|
110
|
+
path: entry.route.path,
|
|
111
|
+
owner: entry.owner,
|
|
112
|
+
mount: entry.mount,
|
|
113
|
+
prefix: entry.prefix,
|
|
114
|
+
}))),
|
|
115
|
+
match(method, path) {
|
|
116
|
+
if (typeof method !== "string" || typeof path !== "string")
|
|
117
|
+
return -1;
|
|
118
|
+
return selectRoute(registered, method, path)?.index ?? -1;
|
|
119
|
+
},
|
|
120
|
+
}),
|
|
121
|
+
enumerable: false,
|
|
122
|
+
writable: false,
|
|
123
|
+
configurable: false,
|
|
124
|
+
});
|
|
125
|
+
return handler;
|
|
74
126
|
},
|
|
75
127
|
};
|
|
128
|
+
ROUTER_ITEMS.set(router, items);
|
|
76
129
|
return Object.freeze(router);
|
|
77
130
|
}
|
|
131
|
+
// Flattens own routes and mounted routers in registration order. A router mounted more than once is flattened once
|
|
132
|
+
// per call; `height` bounds nesting from any depth it is reached at.
|
|
133
|
+
function flattenRouter(router, depth, ancestors, done) {
|
|
134
|
+
const cached = done.get(router);
|
|
135
|
+
if (cached !== undefined) {
|
|
136
|
+
if (depth + cached.height > MAX_MOUNT_DEPTH)
|
|
137
|
+
throw new ValidationError("Router mounts are nested too deeply");
|
|
138
|
+
return cached;
|
|
139
|
+
}
|
|
140
|
+
if (ancestors.has(router))
|
|
141
|
+
throw new ValidationError("Router mounts form a cycle");
|
|
142
|
+
if (depth > MAX_MOUNT_DEPTH)
|
|
143
|
+
throw new ValidationError("Router mounts are nested too deeply");
|
|
144
|
+
ancestors.add(router);
|
|
145
|
+
const items = ROUTER_ITEMS.get(router);
|
|
146
|
+
const routes = [];
|
|
147
|
+
let height = 0;
|
|
148
|
+
const append = (entry) => {
|
|
149
|
+
if (routes.length >= MAX_FLATTENED_ROUTES) {
|
|
150
|
+
throw new ValidationError(`A router supports at most ${MAX_FLATTENED_ROUTES} routes including mounted routers`);
|
|
151
|
+
}
|
|
152
|
+
routes.push(entry);
|
|
153
|
+
};
|
|
154
|
+
for (const item of items) {
|
|
155
|
+
if ("route" in item) {
|
|
156
|
+
append({ route: item.route, owner: null, mount: -1, prefix: null });
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
const child = flattenRouter(item.child, depth + 1, ancestors, done);
|
|
160
|
+
height = Math.max(height, child.height + 1);
|
|
161
|
+
for (const { route } of child.routes) {
|
|
162
|
+
const path = joinRoutePath(item.prefix, route.path);
|
|
163
|
+
append({ route: path === route.path ? route : Object.freeze({ ...route, path }),
|
|
164
|
+
owner: item.child, mount: item.mount, prefix: item.prefix });
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
ancestors.delete(router);
|
|
168
|
+
const result = Object.freeze({ routes: Object.freeze(routes), height });
|
|
169
|
+
done.set(router, result);
|
|
170
|
+
return result;
|
|
171
|
+
}
|
|
172
|
+
function joinRoutePath(prefix, path) {
|
|
173
|
+
if (prefix === "/")
|
|
174
|
+
return path;
|
|
175
|
+
return path === "/" ? prefix : prefix + path;
|
|
176
|
+
}
|
|
177
|
+
// Static routes that equal the path win; otherwise the first registered route that matches.
|
|
178
|
+
function selectRoute(registered, method, path) {
|
|
179
|
+
for (let index = 0; index < registered.length; index++) {
|
|
180
|
+
const route = registered[index];
|
|
181
|
+
if (route.method === method && !route.path.includes(":") && route.path === path) {
|
|
182
|
+
return { index, params: {} };
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
for (let index = 0; index < registered.length; index++) {
|
|
186
|
+
const route = registered[index];
|
|
187
|
+
if (route.method !== method)
|
|
188
|
+
continue;
|
|
189
|
+
const params = matchRoute(route.path, path);
|
|
190
|
+
if (params !== null)
|
|
191
|
+
return { index, params };
|
|
192
|
+
}
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
78
195
|
function isRequestMethod(method) {
|
|
79
196
|
return method === "GET" || method === "POST" || method === "PUT"
|
|
80
197
|
|| method === "PATCH" || method === "DELETE";
|
|
@@ -391,7 +391,7 @@ codes:
|
|
|
391
391
|
| `SCRIPT_ERROR` | The handler threw an SDK error. `details.scriptErrorCode` is its code, such as `VALIDATION_ERROR` or `NOT_FOUND`, with the same safe message an HTTP route returns for that code. Any other error is reported with the message `The action handler failed`. |
|
|
392
392
|
| `TIMEOUT` | The call exceeded `timeoutMs`; `details.timeoutMs` is the limit applied. |
|
|
393
393
|
| `RATE_LIMITED` | The call went over a budget of the execution; `details.budget` describes it. |
|
|
394
|
-
| `SCRIPT_ERROR` with `details.reason` `"RESOURCE_LIMIT_EXCEEDED"` | The handler used up a sandbox resource limit:
|
|
394
|
+
| `SCRIPT_ERROR` with `details.reason` `"RESOURCE_LIMIT_EXCEEDED"` | The handler used up a sandbox resource limit: memory or stack, and on the previous runtime also statements. Runtime V2 has no statement limit: a loop that does not end runs until `TIMEOUT`, and recursion that is too deep throws a `RangeError` the handler can catch. |
|
|
395
395
|
| `PERMISSION_DENIED` | The handler let a `PermissionDeniedError` escape, for example a write in a `"read"` action. While a new version is being activated, a call may briefly fail with `details.reason` `"PROJECT_POLICY_NOT_APPROVED"` before it runs; the caller's retry runs it. |
|
|
396
396
|
| `INTERNAL_ERROR` | Another failure. |
|
|
397
397
|
|
|
@@ -78,7 +78,9 @@ headers, time, calls, destinations, and concurrency are bounded by platform quot
|
|
|
78
78
|
U+FFFD, so binary content cannot be read exactly.
|
|
79
79
|
- A host name that resolves to an address that is not public fails with
|
|
80
80
|
`FETCH_FAILED`.
|
|
81
|
-
- Calls started together, for example with `Promise.all`,
|
|
81
|
+
- Calls started together, for example with `Promise.all`, run in parallel up to a
|
|
82
|
+
number of simultaneous `fetch` calls set by the platform; further calls wait for a
|
|
83
|
+
free slot instead of failing.
|
|
82
84
|
- A before-change trigger cannot call `fetch`: it throws `PermissionDeniedError` with
|
|
83
85
|
`details.reason` `"TRIGGER_READ_ONLY"`. A read-only version preview allows only `GET`
|
|
84
86
|
and `HEAD` without `credential` and refuses other calls with `PermissionDeniedError`.
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# `@cogover/sdk` API reference: Formatting and sorting
|
|
2
|
+
|
|
3
|
+
This page is part of the [`@cogover/sdk` API reference](overview.md).
|
|
4
|
+
|
|
5
|
+
## Formatting and sorting
|
|
6
|
+
|
|
7
|
+
Runtime V2 has no `Intl` object, and `toLocaleString`, `toLocaleDateString`,
|
|
8
|
+
`toLocaleTimeString`, and `localeCompare` ignore their locale and options there.
|
|
9
|
+
These functions format numbers, money, and dates and compare Vietnamese text
|
|
10
|
+
without them, and give the same text on Runtime V2, on the previous runtime,
|
|
11
|
+
and in Node.js. They are plain functions: they call no Cogover service, count
|
|
12
|
+
against no budget, and can be used anywhere, also while a module loads.
|
|
13
|
+
|
|
14
|
+
The functions were added in 0.19.0. Code that imports them can be published
|
|
15
|
+
once Cogover supports `@cogover/sdk` 0.19.0 for your Workspace; before that,
|
|
16
|
+
the publish fails with a compile error that names the function. The Runtime V2 compatibility guide shows the same functions as files
|
|
17
|
+
you can copy into a Project instead.
|
|
18
|
+
|
|
19
|
+
```typescript
|
|
20
|
+
type NumberLocale = "vi" | "en";
|
|
21
|
+
const VIETNAM_OFFSET_MINUTES: number; // 420 (GMT+7)
|
|
22
|
+
|
|
23
|
+
function formatNumber(value: number, locale?: NumberLocale, maxDecimals?: number, minDecimals?: number): string;
|
|
24
|
+
function formatVnd(value: number): string;
|
|
25
|
+
function formatUsd(value: number): string;
|
|
26
|
+
function formatDate(value: Date | number, pattern?: string, offsetMinutes?: number): string;
|
|
27
|
+
function compareVietnamese(a: string, b: string): number;
|
|
28
|
+
function sortVietnamese<T>(items: readonly T[], key?: (item: T) => string): T[];
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
### `formatNumber(value, locale?, maxDecimals?, minDecimals?)`
|
|
32
|
+
|
|
33
|
+
Formats `value` as `toLocaleString` did on the previous runtime: digits grouped
|
|
34
|
+
by three, at most `maxDecimals` decimals (default `3`), trailing zeros removed
|
|
35
|
+
down to `minDecimals` (default `0`), rounding half away from zero on the
|
|
36
|
+
shortest decimal form of the number. `locale` is `"vi"` (default: `.` groups,
|
|
37
|
+
`,` decimals) or `"en"` (`,` groups, `.` decimals). Large values are written in
|
|
38
|
+
full, never in scientific notation; `NaN`, `Infinity`, and `-Infinity` give
|
|
39
|
+
`NaN`, `∞`, and `-∞`.
|
|
40
|
+
|
|
41
|
+
Throws `TypeError` when `value` is not a number (a string, `null`, `undefined`,
|
|
42
|
+
a `bigint`), and `RangeError` for another locale, decimals that are not
|
|
43
|
+
integers from 0 to 20, or `minDecimals` greater than `maxDecimals`.
|
|
44
|
+
|
|
45
|
+
### `formatVnd(value)` and `formatUsd(value)`
|
|
46
|
+
|
|
47
|
+
`formatVnd` gives Vietnamese dong without decimals and with a no-break space
|
|
48
|
+
(`\u00a0`) before `₫`, as the previous runtime did. `formatUsd` gives US
|
|
49
|
+
dollars with two decimals and the sign before `$`. Both throw `TypeError` when
|
|
50
|
+
`value` is not a number.
|
|
51
|
+
|
|
52
|
+
### `formatDate(value, pattern?, offsetMinutes?)`
|
|
53
|
+
|
|
54
|
+
Formats a `Date` or a number of milliseconds in a fixed time zone,
|
|
55
|
+
`offsetMinutes` from UTC (default `VIETNAM_OFFSET_MINUTES`, GMT+7, no daylight
|
|
56
|
+
saving). `pattern` (default `"dd/MM/yyyy"`) accepts the tokens `yyyy`, `MM`,
|
|
57
|
+
`M`, `dd`, `d`, `HH`, `H`, `hh`, `h`, `mm`, `ss`, and `a` (`AM`/`PM`); text in
|
|
58
|
+
single quotes is copied as is. An invalid date gives `Invalid Date`. Throws
|
|
59
|
+
`TypeError` when `value` is neither a `Date` nor a number or `pattern` is not a
|
|
60
|
+
string, and `RangeError` for an offset that is not an integer from -1440 to
|
|
61
|
+
1440 or a date outside the years 1 to 9999 in that offset. The previous runtime
|
|
62
|
+
used the historical offsets of Vietnam, which differ before 1976.
|
|
63
|
+
|
|
64
|
+
### `compareVietnamese(a, b)` and `sortVietnamese(items, key?)`
|
|
65
|
+
|
|
66
|
+
`compareVietnamese` returns a negative number, zero, or a positive number in
|
|
67
|
+
the order `a.localeCompare(b, "vi")` gave on the previous runtime for
|
|
68
|
+
Vietnamese and English letters and digits: the Vietnamese alphabet
|
|
69
|
+
(`a ă â b c d đ e ê ... o ô ơ ... u ư ...`), then tone marks (none, huyền, hỏi,
|
|
70
|
+
ngã, sắc, nặng), then lower case before upper case. Text with combining marks
|
|
71
|
+
and the same text with precomposed letters compare equal. `sortVietnamese`
|
|
72
|
+
returns a sorted copy of `items`, compared by `key(item)` (default `String`).
|
|
73
|
+
|
|
74
|
+
Digits compare one by one (`"10"` before `"9"`); spaces, punctuation, and
|
|
75
|
+
symbols sort before digits and letters; other letters (`ß`, `Æ`, Greek,
|
|
76
|
+
Cyrillic...) sort after `z`, except `Ð`, `Ø`, `ı`, and `ł`, which sort as `D`,
|
|
77
|
+
`O`, `I`, and `L`. There is no numeric option.
|
|
78
|
+
|
|
79
|
+
```typescript
|
|
80
|
+
import { compareVietnamese, formatDate, formatNumber, formatVnd, sortVietnamese } from "@cogover/sdk";
|
|
81
|
+
|
|
82
|
+
formatNumber(1234567.891); // "1.234.567,891"
|
|
83
|
+
formatNumber(1234.5, "en", 2, 2); // "1,234.50"
|
|
84
|
+
formatVnd(1234567); // "1.234.567 ₫"
|
|
85
|
+
formatDate(Date.UTC(2026, 4, 29, 7, 5, 9), "dd/MM/yyyy HH:mm"); // "29/05/2026 14:05"
|
|
86
|
+
sortVietnamese(["Bình", "An", "Ân", "Đức", "Dũng"]); // ["An", "Ân", "Bình", "Dũng", "Đức"]
|
|
87
|
+
names.sort(compareVietnamese);
|
|
88
|
+
```
|
|
@@ -24,8 +24,9 @@ The reference is split into the following pages. Each page covers one area of th
|
|
|
24
24
|
| [Organization structure](organization-structure.md) | Organization structure |
|
|
25
25
|
| [Custom Module Actions](actions.md) | Custom Module Actions; Schema builder |
|
|
26
26
|
| [Processes and AI Agents](processes-and-agents.md) | Processes and AI Agents |
|
|
27
|
+
| [Formatting and sorting](formatting.md) | Numbers, money, dates, and Vietnamese sorting without `Intl` |
|
|
27
28
|
|
|
28
|
-
The sections below apply to every area: the errors every API can throw, the limits of one execution, reading those limits in code, and the compatibility helper.
|
|
29
|
+
The sections below apply to every area: the errors every API can throw, the limits of one execution, calls that run in parallel, reading those limits in code, and the compatibility helper.
|
|
29
30
|
|
|
30
31
|
## Errors
|
|
31
32
|
|
|
@@ -226,9 +227,9 @@ set by the platform and may differ between environments.
|
|
|
226
227
|
server. A record trigger has its own `timeoutMs`, and a background job its
|
|
227
228
|
`timeoutMs`. A Custom Module Action has the budgets of an HTTP route and its own
|
|
228
229
|
`timeoutMs`, at most 8 seconds. Exceeding the time ends the whole execution: the script cannot catch it,
|
|
229
|
-
and an HTTP route returns the generic HTTP 422 response.
|
|
230
|
-
|
|
231
|
-
|
|
230
|
+
and an HTTP route returns the generic HTTP 422 response. Calls started together run
|
|
231
|
+
in parallel (see [Parallel calls](#parallel-calls)), which shortens the time spent
|
|
232
|
+
waiting.
|
|
232
233
|
- A single capability request, JSON-encoded with its arguments, must not exceed
|
|
233
234
|
262,144 bytes. A larger request is refused before it is sent with `ValidationError`,
|
|
234
235
|
or with `CogoverApiError` `code: "FETCH_REQUEST_TOO_LARGE"` for `fetch`; `details.limit`
|
|
@@ -236,14 +237,66 @@ set by the platform and may differ between environments.
|
|
|
236
237
|
way (`FETCH_RESPONSE_TOO_LARGE` for `fetch`): ask for fewer records, or name the
|
|
237
238
|
fields instead of `"*"`. The
|
|
238
239
|
operation itself did run, so a write may have completed.
|
|
239
|
-
- When the Workspace already has
|
|
240
|
-
|
|
241
|
-
This refusal has no `details.budget
|
|
240
|
+
- When the Workspace already has so many executions waiting that a new HTTP call could
|
|
241
|
+
not start in time, the call is refused at once with HTTP 429 and
|
|
242
|
+
`code: "RATE_LIMITED"` before anything runs. This refusal has no `details.budget`; it
|
|
243
|
+
carries a `Retry-After` header (seconds) and `retryAfterMillis` in the body when
|
|
244
|
+
Cogover can estimate when to send the request again. The caller should wait at least
|
|
245
|
+
that long, and send an `Idempotency-Key` with calls that write so that a retry is
|
|
246
|
+
safe.
|
|
242
247
|
|
|
243
248
|
Some APIs also keep their own quota per execution, such as 20 `fetch` calls, 20
|
|
244
249
|
secret reads, 20 `processes.start` calls, or 5 `agents.start` calls. Going over one is
|
|
245
250
|
reported as `RateLimitError` too.
|
|
246
251
|
|
|
252
|
+
## Parallel calls
|
|
253
|
+
|
|
254
|
+
Capability calls that a handler starts together run in parallel, up to a number of
|
|
255
|
+
simultaneous calls set by the platform; further calls wait for a free slot. A handler
|
|
256
|
+
that awaits each call before it starts the next one runs them one after another.
|
|
257
|
+
Independent reads and writes can therefore be grouped with `Promise.all`:
|
|
258
|
+
|
|
259
|
+
```typescript
|
|
260
|
+
import { defineScript } from "@cogover/sdk";
|
|
261
|
+
|
|
262
|
+
export default defineScript(async ({ data, input }) => {
|
|
263
|
+
const { orderId, customerId } = input as { orderId: string; customerId: string };
|
|
264
|
+
const [order, customer] = await Promise.all([
|
|
265
|
+
data.object("order").records.get(orderId, { fields: ["amount", "status"] }),
|
|
266
|
+
data.object("customer").records.get(customerId, { fields: ["credit_limit"] }),
|
|
267
|
+
]);
|
|
268
|
+
return { order, customer };
|
|
269
|
+
});
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
- Every call counts towards the budgets of the execution as usual, whether it runs
|
|
273
|
+
alone or in parallel. Prefer one `records.getMany` or `records.batchInsert` to many
|
|
274
|
+
parallel `get` or `create` calls: it is one capability call instead of many.
|
|
275
|
+
- A call started without `await` still runs to completion before the execution ends,
|
|
276
|
+
within its time limit.
|
|
277
|
+
- The order of parallel calls is not fixed. Push messages and notifications sent
|
|
278
|
+
together can arrive in any order, and a `push.refreshRecords` started in the same
|
|
279
|
+
`Promise.all` as the update it announces can reach users before the update is saved:
|
|
280
|
+
await the write first, then refresh.
|
|
281
|
+
- Two `state.set` calls for the same key without `expectedVersion` leave either value.
|
|
282
|
+
Use `expectedVersion` or a lock when the result matters.
|
|
283
|
+
- Do not give two calls in the same `Promise.all` the same `idempotencyKey`: the second
|
|
284
|
+
one fails with `DUPLICATE_IN_PROGRESS` or `RETRYABLE` instead of returning the first
|
|
285
|
+
result with `duplicate: true`.
|
|
286
|
+
- When one call of a `Promise.all` fails, the others still run; writes that they made
|
|
287
|
+
are not undone.
|
|
288
|
+
- When code runs locally with Cogover Dev CLI, calls run one after another: the
|
|
289
|
+
results are the same, only slower.
|
|
290
|
+
|
|
291
|
+
Separate executions can also run at the same time. Several invocations of the same
|
|
292
|
+
Workspace, for example two requests, or a request together with an after-change record
|
|
293
|
+
trigger or a background job, can run interleaved, up to a limit set by the platform for
|
|
294
|
+
each Workspace. Code that reads a record or a state key, changes it, and writes it back
|
|
295
|
+
must hold a lock from `locks` around that sequence, or write state with `state.set` and
|
|
296
|
+
`expectedVersion` (see [Project state and locks](state-and-locks.md)). A project can
|
|
297
|
+
also be limited to fewer simultaneous invocations, down to one at a time, with its
|
|
298
|
+
`maxConcurrentRuns` setting. Cogover Dev CLI runs local executions one after another.
|
|
299
|
+
|
|
247
300
|
## Reading limits in code
|
|
248
301
|
|
|
249
302
|
```typescript
|
|
@@ -259,6 +259,50 @@ The same handler may be registered at more than one path.
|
|
|
259
259
|
Method-specific shorthand for `addRoute()`, with identical validation, return value,
|
|
260
260
|
and errors.
|
|
261
261
|
|
|
262
|
+
### `router.route(prefix: string, router: ScriptRouter<TSchema>): ScriptRouter<TSchema>`
|
|
263
|
+
|
|
264
|
+
Mounts every route of another router under `prefix` and returns this router for
|
|
265
|
+
chaining. Use it to keep a group of related routes in its own file:
|
|
266
|
+
|
|
267
|
+
```typescript
|
|
268
|
+
// src/orders-router.ts
|
|
269
|
+
import { createRouter } from "@cogover/sdk";
|
|
270
|
+
|
|
271
|
+
export const ordersRouter = createRouter();
|
|
272
|
+
ordersRouter.get("/", () => ({ orders: [] }));
|
|
273
|
+
ordersRouter.get("/:orderId", ({ request }) => ({ orderId: request.params.orderId }));
|
|
274
|
+
|
|
275
|
+
// src/main.ts
|
|
276
|
+
import { createRouter } from "@cogover/sdk";
|
|
277
|
+
import { ordersRouter } from "./orders-router.js";
|
|
278
|
+
|
|
279
|
+
const router = createRouter();
|
|
280
|
+
router.get("/health", () => ({ ok: true }));
|
|
281
|
+
router.route("/orders", ordersRouter); // GET /orders, GET /orders/:orderId
|
|
282
|
+
export default router.toHandler();
|
|
283
|
+
```
|
|
284
|
+
|
|
285
|
+
`prefix` follows the same rules as a route path and may contain parameters, such as
|
|
286
|
+
`/customers/:customerId`; their values appear in `request.params` together with the
|
|
287
|
+
route's own parameters. `"/"` mounts the routes unchanged. A route `/` of the mounted
|
|
288
|
+
router answers at `prefix` itself. The mounted router must come from `createRouter()`
|
|
289
|
+
and cannot be the router itself; one router accepts at most 64 mounts. These errors
|
|
290
|
+
throw `ValidationError` immediately.
|
|
291
|
+
|
|
292
|
+
Mounted routes are read when `toHandler()` is called, so routes added to the mounted
|
|
293
|
+
router after `route()` are included. Routers can be mounted inside mounted routers, up
|
|
294
|
+
to 8 levels, and the same router can be mounted under several prefixes. When
|
|
295
|
+
`toHandler()` builds the table, a cycle of mounts, deeper nesting, a full path that
|
|
296
|
+
breaks the path rules (for example a parameter name repeated in the prefix and the
|
|
297
|
+
route), a duplicate or structurally ambiguous route across routers, or more than 2,048
|
|
298
|
+
routes in total throw `ValidationError`. The limit of 256 routes registered on one
|
|
299
|
+
router still applies.
|
|
300
|
+
|
|
301
|
+
Routes are matched exactly as if they had been registered on one router in
|
|
302
|
+
registration order, a mount inserting its routes where `route()` was called: static
|
|
303
|
+
routes that equal the path win, otherwise the first matching route handles the
|
|
304
|
+
request. Mounting is optional; a router without mounts behaves as before.
|
|
305
|
+
|
|
262
306
|
### `router.toHandler(): SandboxHandler`
|
|
263
307
|
|
|
264
308
|
Returns a default-exportable handler that captures a snapshot of the current routes.
|
|
@@ -90,8 +90,16 @@ large data.
|
|
|
90
90
|
## Distributed locks
|
|
91
91
|
|
|
92
92
|
Locks are distributed leases scoped by workspace, project, namespace, and key. They
|
|
93
|
-
prevent concurrent executions from entering the same protected section.
|
|
94
|
-
|
|
93
|
+
prevent concurrent executions from entering the same protected section.
|
|
94
|
+
|
|
95
|
+
Several executions of the same Workspace can run at the same time: two requests, or a
|
|
96
|
+
request together with an after-change record trigger or a background job, can
|
|
97
|
+
interleave. When code reads a record or a state key, changes it, and writes it back,
|
|
98
|
+
hold a lock on that record or key for the whole sequence, or use `expectedVersion` on
|
|
99
|
+
`state.set`; otherwise one execution can overwrite the change of another. Clients that
|
|
100
|
+
resend a write should also send an `Idempotency-Key`.
|
|
101
|
+
|
|
102
|
+
Prefer `withLock` for automatic release:
|
|
95
103
|
|
|
96
104
|
```typescript
|
|
97
105
|
interface LockOptions {
|
package/docs/en/usage-guide.md
CHANGED
|
@@ -405,6 +405,29 @@ With a key from a secret, these operations follow the rules of secrets and are
|
|
|
405
405
|
not available in before-change triggers. The API reference describes every option
|
|
406
406
|
and the JWT algorithm names.
|
|
407
407
|
|
|
408
|
+
## Format numbers, money, and dates
|
|
409
|
+
|
|
410
|
+
Runtime V2 has no `Intl`, and the locale methods (`toLocaleString`,
|
|
411
|
+
`toLocaleDateString`, `toLocaleTimeString`, `localeCompare`) ignore their
|
|
412
|
+
locale and options there. From 0.19.0 the SDK has functions that give the same
|
|
413
|
+
text everywhere:
|
|
414
|
+
|
|
415
|
+
```typescript
|
|
416
|
+
import { formatDate, formatNumber, formatUsd, formatVnd, sortVietnamese } from "@cogover/sdk";
|
|
417
|
+
|
|
418
|
+
formatNumber(1234567.891); // "1.234.567,891"
|
|
419
|
+
formatNumber(1234567.891, "en", 2); // "1,234,567.89"
|
|
420
|
+
formatVnd(1234567); // "1.234.567 ₫"
|
|
421
|
+
formatUsd(-1234.5); // "-$1,234.50"
|
|
422
|
+
formatDate(record.createdAt, "dd/MM/yyyy HH:mm"); // in GMT+7
|
|
423
|
+
sortVietnamese(customers, (customer) => customer.name);
|
|
424
|
+
```
|
|
425
|
+
|
|
426
|
+
They throw `TypeError` for a value that is not a number or a date, so a field
|
|
427
|
+
that is `null` is not formatted by mistake. Publishing code that imports them
|
|
428
|
+
needs a Workspace where Cogover supports SDK 0.19.0. See
|
|
429
|
+
[Formatting and sorting](api-reference/formatting.md).
|
|
430
|
+
|
|
408
431
|
## Permissions and limits
|
|
409
432
|
|
|
410
433
|
- Cogover authentication credentials are never exposed to module code. Access is
|
|
@@ -422,6 +445,44 @@ and the JWT algorithm names.
|
|
|
422
445
|
call whatever the number of records.
|
|
423
446
|
- Do not automatically retry writes after a timeout because the commit outcome may
|
|
424
447
|
be unknown.
|
|
448
|
+
- When a Workspace has too many executions waiting, a new HTTP call is refused at once
|
|
449
|
+
with HTTP 429, `code: "RATE_LIMITED"`, and a `Retry-After` header. Callers should wait
|
|
450
|
+
that long before sending the request again, with an `Idempotency-Key` for writes.
|
|
451
|
+
|
|
452
|
+
## Run independent calls together
|
|
453
|
+
|
|
454
|
+
Calls started together, for example with `Promise.all`, run in parallel, while a call
|
|
455
|
+
that is awaited before the next one starts runs alone. Group the reads that do not
|
|
456
|
+
depend on each other, write many records of one Object with one `records.batchInsert`
|
|
457
|
+
or `records.batchUpdate`, and then send the independent writes together:
|
|
458
|
+
|
|
459
|
+
```typescript
|
|
460
|
+
router.post("/orders/:orderId/confirm", async ({ data, request }) => {
|
|
461
|
+
const orderId = request.params.orderId ?? "";
|
|
462
|
+
const orders = data.object("order");
|
|
463
|
+
const lines = data.object("order_line");
|
|
464
|
+
const [order, products] = await Promise.all([
|
|
465
|
+
orders.records.get(orderId, { fields: ["customer", "status"] }),
|
|
466
|
+
data.object("product").records.list({ fields: ["price"], limit: 50 }),
|
|
467
|
+
]);
|
|
468
|
+
if (order === null) return { confirmed: false };
|
|
469
|
+
const [, inserted] = await Promise.all([
|
|
470
|
+
orders.records.update(order.id, { status: "confirmed" }),
|
|
471
|
+
lines.records.batchInsert(products.items.map(product => ({
|
|
472
|
+
order: order.id,
|
|
473
|
+
product: product.id,
|
|
474
|
+
price: product.fields.price,
|
|
475
|
+
}))),
|
|
476
|
+
]);
|
|
477
|
+
return { confirmed: inserted.success };
|
|
478
|
+
});
|
|
479
|
+
```
|
|
480
|
+
|
|
481
|
+
Each call still counts towards the budgets. Parallel calls have no fixed order: await a
|
|
482
|
+
write before a `push.refreshRecords` that announces it, and do not give two calls of the
|
|
483
|
+
same `Promise.all` the same `idempotencyKey`. Cogover Dev CLI runs the calls one after
|
|
484
|
+
another locally, with the same results. See
|
|
485
|
+
[Parallel calls](api-reference/overview.md#parallel-calls).
|
|
425
486
|
|
|
426
487
|
## Store small progress with state
|
|
427
488
|
|
|
@@ -1218,6 +1279,136 @@ path registered only for other methods, return 404; methods other than these fiv
|
|
|
1218
1279
|
return 405. Existing `defineScript()` projects continue at `/`.
|
|
1219
1280
|
Validate all business input. See the [router API reference](api-reference/scripts-and-routes.md#http-routers-and-request-context).
|
|
1220
1281
|
|
|
1282
|
+
### Organize routes in groups
|
|
1283
|
+
|
|
1284
|
+
As a module grows, you can keep each group of related routes in its own file: create
|
|
1285
|
+
a router with `createRouter()` in that file, export it, and mount it on the main
|
|
1286
|
+
router with `router.route(prefix, childRouter)`. This is optional; routes registered
|
|
1287
|
+
directly on the main router keep working.
|
|
1288
|
+
|
|
1289
|
+
```typescript
|
|
1290
|
+
// src/orders-router.ts
|
|
1291
|
+
import { createRouter } from "@cogover/sdk";
|
|
1292
|
+
|
|
1293
|
+
export const ordersRouter = createRouter();
|
|
1294
|
+
ordersRouter.get("/", () => ({ orders: [] }));
|
|
1295
|
+
ordersRouter.get("/:orderId", ({ request }) => ({ orderId: request.params.orderId }));
|
|
1296
|
+
|
|
1297
|
+
// src/main.ts
|
|
1298
|
+
import { createRouter } from "@cogover/sdk";
|
|
1299
|
+
import { ordersRouter } from "./orders-router.js";
|
|
1300
|
+
|
|
1301
|
+
const router = createRouter();
|
|
1302
|
+
router.get("/health", () => ({ ok: true }));
|
|
1303
|
+
router.route("/orders", ordersRouter);
|
|
1304
|
+
export default router.toHandler();
|
|
1305
|
+
```
|
|
1306
|
+
|
|
1307
|
+
Mounted routes are matched as if they were registered on the main router where
|
|
1308
|
+
`route()` is called. Two groups may share a prefix, such as `/me`, as long as their
|
|
1309
|
+
routes do not overlap. See [`router.route()`](api-reference/scripts-and-routes.md#routerrouteprefix-string-router-scriptroutertschema-scriptroutertschema).
|
|
1310
|
+
|
|
1311
|
+
### Keep the module fast to load
|
|
1312
|
+
|
|
1313
|
+
On the previous runtime every invocation loads the module code it runs; on
|
|
1314
|
+
Runtime V2 the module is loaded once when the version is prepared, and code that
|
|
1315
|
+
runs while it loads runs only once (see the Runtime V2 compatibility guide).
|
|
1316
|
+
When a module is published, Cogover can load only the code one trigger, job,
|
|
1317
|
+
action, or group of routes needs instead of the whole module, which makes the
|
|
1318
|
+
first invocation after a publish or an idle period much faster. The
|
|
1319
|
+
`cogover-dev publish` load profile shows what each entry point gets. To benefit from it:
|
|
1320
|
+
|
|
1321
|
+
- Define each trigger, job, or action (`defineTrigger`, `defineJob`,
|
|
1322
|
+
`defineAction`) in a file other than `src/main.ts` and export it from there,
|
|
1323
|
+
directly or in an exported array. `src/main.ts` only imports and collects.
|
|
1324
|
+
- Put each group of routes in a router file that contains only
|
|
1325
|
+
`createRouter()` and its route registrations, import that file only from
|
|
1326
|
+
`src/main.ts`, and mount it with `router.route()`. Keep handlers and shared
|
|
1327
|
+
logic in other files, so that a job or another route importing a handler
|
|
1328
|
+
does not also load the whole group. Routes registered directly on the main
|
|
1329
|
+
router always load the whole module.
|
|
1330
|
+
- Code that runs while a file loads may compute values and build objects of
|
|
1331
|
+
its own: calling your own functions and static methods (also from other
|
|
1332
|
+
files) whose code follows these rules too, `.map()`, `.filter()`, loops,
|
|
1333
|
+
`if`, `try`, `throw`, an immediately called function,
|
|
1334
|
+
registering routes on a router the file created, filling an array, an
|
|
1335
|
+
object, or a `Map` the same file created (also from the file's own
|
|
1336
|
+
functions). It must not change anything outside: a variable or an object of
|
|
1337
|
+
another file (an imported registry, a configuration object, a list a
|
|
1338
|
+
function returns), a global or a prototype, a parameter of a function, a
|
|
1339
|
+
variable of another file from one of that file's functions.
|
|
1340
|
+
- It must also give the same result each time it loads: no `Date.now()`,
|
|
1341
|
+
`new Date()` without arguments, `Math.random()`, `Intl` (which Runtime V2
|
|
1342
|
+
does not have), `performance`, `globalThis`, globals the runtime
|
|
1343
|
+
defines, or SDK services such as `fetch`, `crypto`, or `limits` while files
|
|
1344
|
+
load.
|
|
1345
|
+
- A call of a method of one of your objects or classes (`Config.select()`,
|
|
1346
|
+
`registry.get()`) counts only when nothing in the project hands that object
|
|
1347
|
+
or class around or changes it, anywhere, including in handlers: passing it to
|
|
1348
|
+
a function, assigning it to another variable, spreading it, storing it in
|
|
1349
|
+
another object or array, returning it, writing one of its members
|
|
1350
|
+
(`registry.get = ...`), creating instances of a class (`new Config()`) or
|
|
1351
|
+
reading its `prototype`. Otherwise Cogover cannot know which code the method
|
|
1352
|
+
runs, and the call counts as changing something outside. The same applies to
|
|
1353
|
+
converting such an object to a string or JSON.
|
|
1354
|
+
- What Cogover cannot check at publish time counts as changing something
|
|
1355
|
+
outside: calling a parameter, a function assigned more than once, a method
|
|
1356
|
+
of a value it cannot trace back to your code or to a built-in type (on such
|
|
1357
|
+
a value only common read-only methods such as `map`, `filter`, `includes`,
|
|
1358
|
+
`join`, `slice`, `split`, `trim`, or `toString` are accepted), an `async`
|
|
1359
|
+
function or a generator, `console.log()`; `Object.defineProperty()`,
|
|
1360
|
+
`Object.setPrototypeOf()`, `Object.create(prototype)`, `new Object(value)`,
|
|
1361
|
+
a built-in called with spread arguments (`Math.max(...values)` is fine),
|
|
1362
|
+
methods or conversions of data imported from a JSON file, and getters,
|
|
1363
|
+
setters, or `toString`/`toJSON`/`Symbol` methods that change something
|
|
1364
|
+
outside, in objects or classes created while loading.
|
|
1365
|
+
- A file that breaks these rules is loaded, with what it imports, with every
|
|
1366
|
+
entry point; the load profile lists it under `REQUIRED_MODULES` with the
|
|
1367
|
+
statement and the chain of calls that leads to it. Move such code into
|
|
1368
|
+
handlers, or into a file that only the entry points needing it import.
|
|
1369
|
+
- When `src/main.ts` breaks these rules, every entry point loads the whole
|
|
1370
|
+
module (`MAIN_TOP_LEVEL_EFFECT`). Do configuration in a file the entry points
|
|
1371
|
+
import.
|
|
1372
|
+
- When code anywhere in the project writes globals or built-in objects (a
|
|
1373
|
+
polyfill such as `URL` or `TextEncoder`, a patched prototype, a value put on
|
|
1374
|
+
`globalThis`), or the whole module changes them while it loads, every entry
|
|
1375
|
+
point loads the whole module (`PART_GLOBALS_MODIFIED`).
|
|
1376
|
+
|
|
1377
|
+
Entry points run from their smaller modules only when you declare that the
|
|
1378
|
+
project follows these rules: set `"entryPointParts": true` in `cogover.json`
|
|
1379
|
+
(or publish with `cogover-dev publish --parts`). Without it the platform
|
|
1380
|
+
default applies, which is the whole module unless the platform says otherwise;
|
|
1381
|
+
`false` (or `--no-parts`) always keeps the whole module. The load profile
|
|
1382
|
+
printed by `cogover-dev publish` says what the version runs on.
|
|
1383
|
+
|
|
1384
|
+
Declaring `true` means you confirm that code running while files load changes
|
|
1385
|
+
nothing outside its file, and you answer for any difference if it does: an
|
|
1386
|
+
entry point may then run without a configuration another file sets while
|
|
1387
|
+
loading, including an authorization check your project writes itself. Cogover
|
|
1388
|
+
reads the code to check what it can: a file found to break the rules is loaded
|
|
1389
|
+
with every entry point, and the cases above load the whole module. It does not
|
|
1390
|
+
guarantee to catch every violation. Known limits:
|
|
1391
|
+
|
|
1392
|
+
- the `.name` of a class or function (also `constructor.name`, `error.name`)
|
|
1393
|
+
can differ between the whole module and a smaller one when two files define
|
|
1394
|
+
a top-level class or function of the same name: do not rely on it, set
|
|
1395
|
+
`name` explicitly where it matters;
|
|
1396
|
+
- a value Cogover cannot trace (a function parameter, the result of a call)
|
|
1397
|
+
whose method has the name of an accepted read-only built-in method (`map`,
|
|
1398
|
+
`filter`, `includes`, `join`...), or whose getter, setter, `Proxy`, iterator,
|
|
1399
|
+
`toString`, `valueOf`, `toJSON`, or `Symbol` method runs when loading code
|
|
1400
|
+
reads or converts it, is not checked;
|
|
1401
|
+
- a built-in object changed through another name
|
|
1402
|
+
(`const p = Array.prototype; p.x = ...`) and restored while loading is not
|
|
1403
|
+
seen;
|
|
1404
|
+
- code that depends on the date or time while loading behaves as it did on the
|
|
1405
|
+
day of publishing.
|
|
1406
|
+
|
|
1407
|
+
Keep such code inside handlers. Check the `REQUIRED_MODULES` list of the load
|
|
1408
|
+
profile: if a file there changes an object of another file, or a call Cogover
|
|
1409
|
+
cannot resolve, and you are not sure it is harmless, do not declare `true`.
|
|
1410
|
+
When in doubt, do not declare it.
|
|
1411
|
+
|
|
1221
1412
|
## Receive webhooks
|
|
1222
1413
|
|
|
1223
1414
|
An external system can call a route without a Cogover user session through an
|