buckyos 0.7.193 → 0.7.197
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/cli/README.md +20 -0
- package/cli/core/app.ts +1 -0
- package/cli/core/argv.ts +4 -0
- package/cli/dist/cli.mjs +218 -392
- package/cli/dist/cli.mjs.map +1 -1
- package/cli/modules/aiws.ts +11 -3
- package/cli/modules/obj.ts +70 -3
- package/cli/runtime/host.ts +2 -0
- package/cli/version.ts +1 -1
- package/dist/{aiws_bind-ec6fe2d5.mjs → aiws_bind-a96cb506.mjs} +135 -31
- package/dist/aiws_bind-a96cb506.mjs.map +1 -0
- package/dist/aiws_bind-fb4caf43.js +2 -0
- package/dist/aiws_bind-fb4caf43.js.map +1 -0
- package/dist/aiws_ext.cjs +1 -1
- package/dist/aiws_ext.mjs +1 -1
- package/dist/aiws_rrule.d.ts +3 -2
- package/dist/aiws_rrule.d.ts.map +1 -1
- package/dist/aiws_schedule.d.ts +14 -2
- package/dist/aiws_schedule.d.ts.map +1 -1
- package/dist/{aiws_write-1f179e1c.js → aiws_write-189e4c0e.js} +2 -2
- package/dist/aiws_write-189e4c0e.js.map +1 -0
- package/dist/{aiws_write-07562abc.mjs → aiws_write-7078045b.mjs} +2 -2
- package/dist/aiws_write-7078045b.mjs.map +1 -0
- package/dist/browser.cjs +1 -1
- package/dist/browser.mjs +4 -4
- package/dist/{content_objid-7605d166.mjs → content_objid-20b82f52.mjs} +2 -2
- package/dist/{content_objid-7605d166.mjs.map → content_objid-20b82f52.mjs.map} +1 -1
- package/dist/{content_objid-17daaa69.js → content_objid-d1d089a6.js} +2 -2
- package/dist/{content_objid-17daaa69.js.map → content_objid-d1d089a6.js.map} +1 -1
- package/dist/hybrid_sso.d.ts +37 -2
- package/dist/hybrid_sso.d.ts.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +4 -4
- package/dist/node.cjs +1 -1
- package/dist/node.mjs +3 -3
- package/dist/owner-extensions/object_extensions.toml +160 -0
- package/dist/owner-extensions/profiles/bindings.json +165 -0
- package/dist/owner-extensions/profiles/calendar.json +489 -0
- package/dist/owner-extensions/profiles/contacts.json +89 -0
- package/dist/owner-extensions/profiles/person.json +193 -0
- package/dist/owner-extensions/profiles/sharing.json +65 -0
- package/dist/owner-extensions/profiles/todo.json +493 -0
- package/dist/owner-extensions/scripts/bindings.mjs +9 -0
- package/dist/owner-extensions/scripts/calendar.mjs +3 -0
- package/dist/owner-extensions/scripts/contacts.mjs +9 -0
- package/dist/owner-extensions/scripts/free_busy.mjs +666 -0
- package/dist/owner-extensions/scripts/person.mjs +11 -0
- package/dist/owner-extensions/scripts/schedule.mjs +2618 -0
- package/dist/owner-extensions/scripts/sharing.mjs +8 -0
- package/dist/owner-extensions/scripts/todo.mjs +3 -0
- package/dist/owner_availability.d.ts +15 -0
- package/dist/owner_availability.d.ts.map +1 -0
- package/dist/owner_schedule.d.ts +30 -0
- package/dist/owner_schedule.d.ts.map +1 -0
- package/dist/site_manager-716a2cf5.js +2 -0
- package/dist/site_manager-716a2cf5.js.map +1 -0
- package/dist/{site_manager-8adb478e.mjs → site_manager-91b4d899.mjs} +29 -14
- package/dist/site_manager-91b4d899.mjs.map +1 -0
- package/dist/xllm/core/action_parser.d.ts.map +1 -1
- package/dist/xllm/core/behavior_result.d.ts.map +1 -1
- package/dist/xllm/core/loop.d.ts.map +1 -1
- package/dist/xllm/core/protocol.d.ts.map +1 -1
- package/dist/xllm/core/types.d.ts +2 -0
- package/dist/xllm/core/types.d.ts.map +1 -1
- package/dist/xllm.cjs +1 -1
- package/dist/xllm.mjs +2 -2
- package/dist/xllm_deno.cjs +1 -1
- package/dist/xllm_deno.mjs +1 -1
- package/package.json +2 -2
- package/cli/modules/aiws_schedule.ts +0 -256
- package/dist/aiws_bind-1a26e3e6.js +0 -2
- package/dist/aiws_bind-1a26e3e6.js.map +0 -1
- package/dist/aiws_bind-ec6fe2d5.mjs.map +0 -1
- package/dist/aiws_write-07562abc.mjs.map +0 -1
- package/dist/aiws_write-1f179e1c.js.map +0 -1
- package/dist/site_manager-8adb478e.mjs.map +0 -1
- package/dist/site_manager-c832463b.js +0 -2
- package/dist/site_manager-c832463b.js.map +0 -1
|
@@ -0,0 +1,2618 @@
|
|
|
1
|
+
class NdnError extends Error {
|
|
2
|
+
constructor(kind, message) {
|
|
3
|
+
super(`${kind}: ${message}`);
|
|
4
|
+
this.kind = kind;
|
|
5
|
+
this.name = "NdnError";
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
const OBJ_TYPE_FILE = "cyfile";
|
|
9
|
+
const OBJ_TYPE_DIR = "cydir";
|
|
10
|
+
const OBJ_TYPE_PACK = "cypack";
|
|
11
|
+
const OBJ_TYPE_OBJMAP = "cymap";
|
|
12
|
+
const OBJ_TYPE_LIST = "cylist";
|
|
13
|
+
const OBJ_TYPE_CHUNK_LIST = "clist";
|
|
14
|
+
const HEX_CHARS = "0123456789abcdef";
|
|
15
|
+
function bytesToHex(bytes) {
|
|
16
|
+
let s = "";
|
|
17
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
18
|
+
const b = bytes[i];
|
|
19
|
+
s += HEX_CHARS[b >>> 4 & 15];
|
|
20
|
+
s += HEX_CHARS[b & 15];
|
|
21
|
+
}
|
|
22
|
+
return s;
|
|
23
|
+
}
|
|
24
|
+
function hexToBytes(hex) {
|
|
25
|
+
if (hex.length % 2 !== 0) {
|
|
26
|
+
throw new NdnError("InvalidId", `invalid hex length: ${hex.length}`);
|
|
27
|
+
}
|
|
28
|
+
const out = new Uint8Array(hex.length / 2);
|
|
29
|
+
for (let i = 0; i < out.length; i++) {
|
|
30
|
+
const hi = HEX_CHARS.indexOf(hex[i * 2].toLowerCase());
|
|
31
|
+
const lo = HEX_CHARS.indexOf(hex[i * 2 + 1].toLowerCase());
|
|
32
|
+
if (hi < 0 || lo < 0) {
|
|
33
|
+
throw new NdnError("InvalidId", `invalid hex char at offset ${i * 2}`);
|
|
34
|
+
}
|
|
35
|
+
out[i] = hi << 4 | lo;
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
const BASE32_ALPHABET = "abcdefghijklmnopqrstuvwxyz234567";
|
|
40
|
+
function base32Encode(bytes) {
|
|
41
|
+
let bits = 0;
|
|
42
|
+
let value = 0;
|
|
43
|
+
let out = "";
|
|
44
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
45
|
+
value = value << 8 | bytes[i];
|
|
46
|
+
bits += 8;
|
|
47
|
+
while (bits >= 5) {
|
|
48
|
+
bits -= 5;
|
|
49
|
+
out += BASE32_ALPHABET[value >>> bits & 31];
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
if (bits > 0) {
|
|
53
|
+
out += BASE32_ALPHABET[value << 5 - bits & 31];
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
function base32Decode(str) {
|
|
58
|
+
const lower = str.toLowerCase();
|
|
59
|
+
let bits = 0;
|
|
60
|
+
let value = 0;
|
|
61
|
+
const out = [];
|
|
62
|
+
for (let i = 0; i < lower.length; i++) {
|
|
63
|
+
const ch = lower[i];
|
|
64
|
+
const idx = BASE32_ALPHABET.indexOf(ch);
|
|
65
|
+
if (idx < 0) {
|
|
66
|
+
throw new NdnError("InvalidId", `invalid base32 char '${ch}' at ${i}`);
|
|
67
|
+
}
|
|
68
|
+
value = value << 5 | idx;
|
|
69
|
+
bits += 5;
|
|
70
|
+
if (bits >= 8) {
|
|
71
|
+
bits -= 8;
|
|
72
|
+
out.push(value >>> bits & 255);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return new Uint8Array(out);
|
|
76
|
+
}
|
|
77
|
+
const ChunkType = {
|
|
78
|
+
Sha256: "sha256",
|
|
79
|
+
Mix256: "mix256",
|
|
80
|
+
Sha512: "sha512",
|
|
81
|
+
Mix512: "mix512",
|
|
82
|
+
QCID: "qcid",
|
|
83
|
+
Blake2s256: "blake2s256",
|
|
84
|
+
MixBlake2s256: "mixblake2s256",
|
|
85
|
+
Keccak256: "keccak256",
|
|
86
|
+
MixKeccak256: "mixkeccak256",
|
|
87
|
+
isChunkType(typeStr) {
|
|
88
|
+
switch (typeStr) {
|
|
89
|
+
case "sha256":
|
|
90
|
+
case "mix256":
|
|
91
|
+
case "sha512":
|
|
92
|
+
case "mix512":
|
|
93
|
+
case "qcid":
|
|
94
|
+
case "blake2s256":
|
|
95
|
+
case "mixblake2s256":
|
|
96
|
+
case "keccak256":
|
|
97
|
+
case "mixkeccak256":
|
|
98
|
+
return true;
|
|
99
|
+
default:
|
|
100
|
+
return false;
|
|
101
|
+
}
|
|
102
|
+
},
|
|
103
|
+
isMix(typeStr) {
|
|
104
|
+
switch (typeStr) {
|
|
105
|
+
case "mix256":
|
|
106
|
+
case "mix512":
|
|
107
|
+
case "mixblake2s256":
|
|
108
|
+
case "mixkeccak256":
|
|
109
|
+
case "qcid":
|
|
110
|
+
return true;
|
|
111
|
+
default:
|
|
112
|
+
return false;
|
|
113
|
+
}
|
|
114
|
+
},
|
|
115
|
+
fromHashType(hashType, isMix) {
|
|
116
|
+
switch (hashType) {
|
|
117
|
+
case "sha256":
|
|
118
|
+
return isMix ? "mix256" : "sha256";
|
|
119
|
+
case "sha512":
|
|
120
|
+
return isMix ? "mix512" : "sha512";
|
|
121
|
+
case "qcid":
|
|
122
|
+
if (!isMix) {
|
|
123
|
+
throw new NdnError("InvalidObjType", "QCID must be mix hash");
|
|
124
|
+
}
|
|
125
|
+
return "qcid";
|
|
126
|
+
case "blake2s256":
|
|
127
|
+
return isMix ? "mixblake2s256" : "blake2s256";
|
|
128
|
+
case "keccak256":
|
|
129
|
+
return isMix ? "mixkeccak256" : "keccak256";
|
|
130
|
+
}
|
|
131
|
+
},
|
|
132
|
+
toHashMethod(typeStr) {
|
|
133
|
+
switch (typeStr) {
|
|
134
|
+
case "sha256":
|
|
135
|
+
case "mix256":
|
|
136
|
+
return "sha256";
|
|
137
|
+
case "sha512":
|
|
138
|
+
case "mix512":
|
|
139
|
+
return "sha512";
|
|
140
|
+
case "qcid":
|
|
141
|
+
return "qcid";
|
|
142
|
+
case "blake2s256":
|
|
143
|
+
case "mixblake2s256":
|
|
144
|
+
return "blake2s256";
|
|
145
|
+
case "keccak256":
|
|
146
|
+
case "mixkeccak256":
|
|
147
|
+
return "keccak256";
|
|
148
|
+
default:
|
|
149
|
+
throw new NdnError("InvalidObjType", `invalid chunk type: ${typeStr}`);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
class ObjId {
|
|
154
|
+
constructor(objType, objHash) {
|
|
155
|
+
this.objType = objType;
|
|
156
|
+
this.objHash = objHash;
|
|
157
|
+
}
|
|
158
|
+
/** Parse from base32 (no separator) or `obj_type:hex_hash`. */
|
|
159
|
+
static fromString(s) {
|
|
160
|
+
const parts = s.split(":");
|
|
161
|
+
if (parts.length === 1) {
|
|
162
|
+
const decoded = base32Decode(parts[0]);
|
|
163
|
+
let pos = -1;
|
|
164
|
+
for (let i = 0; i < decoded.length; i++) {
|
|
165
|
+
if (decoded[i] === 58) {
|
|
166
|
+
pos = i;
|
|
167
|
+
break;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (pos < 0) {
|
|
171
|
+
throw new NdnError("InvalidId", "separator ':' not found");
|
|
172
|
+
}
|
|
173
|
+
const objType = utf8Decode(decoded.subarray(0, pos));
|
|
174
|
+
const objHash = decoded.slice(pos + 1);
|
|
175
|
+
return new ObjId(objType, objHash);
|
|
176
|
+
} else if (parts.length === 2) {
|
|
177
|
+
return new ObjId(parts[0], hexToBytes(parts[1]));
|
|
178
|
+
} else {
|
|
179
|
+
throw new NdnError("InvalidId", s);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
static fromBytes(bytes) {
|
|
183
|
+
if (bytes.length < 3) {
|
|
184
|
+
throw new NdnError("InvalidId", "objid bytes too short");
|
|
185
|
+
}
|
|
186
|
+
let pos = -1;
|
|
187
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
188
|
+
if (bytes[i] === 58) {
|
|
189
|
+
pos = i;
|
|
190
|
+
break;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
if (pos < 0) {
|
|
194
|
+
throw new NdnError("InvalidId", "separator ':' not found");
|
|
195
|
+
}
|
|
196
|
+
const objType = utf8Decode(bytes.subarray(0, pos));
|
|
197
|
+
const objHash = bytes.slice(pos + 1);
|
|
198
|
+
return new ObjId(objType, objHash);
|
|
199
|
+
}
|
|
200
|
+
static fromValue(v) {
|
|
201
|
+
if (typeof v === "string") {
|
|
202
|
+
return ObjId.fromString(v);
|
|
203
|
+
}
|
|
204
|
+
throw new NdnError("InvalidData", "ObjId MUST be string");
|
|
205
|
+
}
|
|
206
|
+
static fromHostname(hostname) {
|
|
207
|
+
const first = hostname.split(".")[0];
|
|
208
|
+
return ObjId.fromString(first);
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Try to extract an ObjId from an NDN-style path. Returns the ObjId and
|
|
212
|
+
* the optional remaining sub-path (with leading '/'), or null if no part
|
|
213
|
+
* of the path parses as an ObjId.
|
|
214
|
+
*/
|
|
215
|
+
static fromPath(path) {
|
|
216
|
+
const parts = path.split("/");
|
|
217
|
+
for (let i = 0; i < parts.length; i++) {
|
|
218
|
+
const part = parts[i];
|
|
219
|
+
if (part.length === 0)
|
|
220
|
+
continue;
|
|
221
|
+
try {
|
|
222
|
+
const objId = ObjId.fromString(part);
|
|
223
|
+
if (i < parts.length - 1) {
|
|
224
|
+
return { objId, subPath: "/" + parts.slice(i + 1).join("/") };
|
|
225
|
+
}
|
|
226
|
+
return { objId, subPath: null };
|
|
227
|
+
} catch {
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
throw new NdnError("InvalidId", `no objid found in path: ${path}`);
|
|
231
|
+
}
|
|
232
|
+
/** Construct an ObjId from a precomputed hash. */
|
|
233
|
+
static fromRaw(objType, hashValue) {
|
|
234
|
+
return new ObjId(objType, hashValue);
|
|
235
|
+
}
|
|
236
|
+
isChunk() {
|
|
237
|
+
return ChunkType.isChunkType(this.objType);
|
|
238
|
+
}
|
|
239
|
+
isChunkList() {
|
|
240
|
+
return this.objType === OBJ_TYPE_CHUNK_LIST;
|
|
241
|
+
}
|
|
242
|
+
isJson() {
|
|
243
|
+
if (this.isChunk() || this.isContainer())
|
|
244
|
+
return false;
|
|
245
|
+
return this.objType !== OBJ_TYPE_PACK;
|
|
246
|
+
}
|
|
247
|
+
isDirObject() {
|
|
248
|
+
return this.objType === OBJ_TYPE_DIR;
|
|
249
|
+
}
|
|
250
|
+
isFileObject() {
|
|
251
|
+
return this.objType === OBJ_TYPE_FILE;
|
|
252
|
+
}
|
|
253
|
+
isContainer() {
|
|
254
|
+
switch (this.objType) {
|
|
255
|
+
case OBJ_TYPE_DIR:
|
|
256
|
+
case OBJ_TYPE_OBJMAP:
|
|
257
|
+
case OBJ_TYPE_LIST:
|
|
258
|
+
case OBJ_TYPE_CHUNK_LIST:
|
|
259
|
+
return true;
|
|
260
|
+
default:
|
|
261
|
+
return false;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
isBigContainer() {
|
|
265
|
+
switch (this.objType) {
|
|
266
|
+
case OBJ_TYPE_OBJMAP:
|
|
267
|
+
case OBJ_TYPE_LIST:
|
|
268
|
+
case OBJ_TYPE_CHUNK_LIST:
|
|
269
|
+
return true;
|
|
270
|
+
default:
|
|
271
|
+
return false;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
/** `${obj_type}:${hex(obj_hash)}` form. */
|
|
275
|
+
toString() {
|
|
276
|
+
return `${this.objType}:${bytesToHex(this.objHash)}`;
|
|
277
|
+
}
|
|
278
|
+
toFilename() {
|
|
279
|
+
return `${bytesToHex(this.objHash)}.${this.objType}`;
|
|
280
|
+
}
|
|
281
|
+
toBase32() {
|
|
282
|
+
return base32Encode(this.toBytes());
|
|
283
|
+
}
|
|
284
|
+
toBytes() {
|
|
285
|
+
const typeBytes = utf8Encode(this.objType);
|
|
286
|
+
const out = new Uint8Array(typeBytes.length + 1 + this.objHash.length);
|
|
287
|
+
out.set(typeBytes, 0);
|
|
288
|
+
out[typeBytes.length] = 58;
|
|
289
|
+
out.set(this.objHash, typeBytes.length + 1);
|
|
290
|
+
return out;
|
|
291
|
+
}
|
|
292
|
+
/** Used for JSON.stringify -> serialized as the `${type}:${hex}` string. */
|
|
293
|
+
toJSON() {
|
|
294
|
+
return this.toString();
|
|
295
|
+
}
|
|
296
|
+
equals(other) {
|
|
297
|
+
if (this.objType !== other.objType)
|
|
298
|
+
return false;
|
|
299
|
+
if (this.objHash.length !== other.objHash.length)
|
|
300
|
+
return false;
|
|
301
|
+
for (let i = 0; i < this.objHash.length; i++) {
|
|
302
|
+
if (this.objHash[i] !== other.objHash[i])
|
|
303
|
+
return false;
|
|
304
|
+
}
|
|
305
|
+
return true;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
const MSG_OBJECT_RESERVED_KEYS = [
|
|
309
|
+
"from",
|
|
310
|
+
"to",
|
|
311
|
+
"kind",
|
|
312
|
+
"to_session",
|
|
313
|
+
"thread",
|
|
314
|
+
"relates_to",
|
|
315
|
+
"mentions",
|
|
316
|
+
"workspace",
|
|
317
|
+
"created_at_ms",
|
|
318
|
+
"expires_at_ms",
|
|
319
|
+
"nonce",
|
|
320
|
+
"content",
|
|
321
|
+
"proof"
|
|
322
|
+
];
|
|
323
|
+
new Set(MSG_OBJECT_RESERVED_KEYS.filter((key) => key !== "proof"));
|
|
324
|
+
const _textEncoder = typeof TextEncoder !== "undefined" ? new TextEncoder() : null;
|
|
325
|
+
const _textDecoder = typeof TextDecoder !== "undefined" ? new TextDecoder("utf-8") : null;
|
|
326
|
+
function utf8Encode(s) {
|
|
327
|
+
if (_textEncoder)
|
|
328
|
+
return _textEncoder.encode(s);
|
|
329
|
+
const out = [];
|
|
330
|
+
for (let i = 0; i < s.length; i++) {
|
|
331
|
+
let c = s.charCodeAt(i);
|
|
332
|
+
if (c < 128) {
|
|
333
|
+
out.push(c);
|
|
334
|
+
} else if (c < 2048) {
|
|
335
|
+
out.push(192 | c >> 6, 128 | c & 63);
|
|
336
|
+
} else if (c >= 55296 && c <= 56319 && i + 1 < s.length) {
|
|
337
|
+
const c2 = s.charCodeAt(++i);
|
|
338
|
+
const cp = 65536 + ((c & 1023) << 10 | c2 & 1023);
|
|
339
|
+
out.push(
|
|
340
|
+
240 | cp >> 18,
|
|
341
|
+
128 | cp >> 12 & 63,
|
|
342
|
+
128 | cp >> 6 & 63,
|
|
343
|
+
128 | cp & 63
|
|
344
|
+
);
|
|
345
|
+
} else {
|
|
346
|
+
out.push(224 | c >> 12, 128 | c >> 6 & 63, 128 | c & 63);
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
return new Uint8Array(out);
|
|
350
|
+
}
|
|
351
|
+
function utf8Decode(bytes) {
|
|
352
|
+
if (_textDecoder)
|
|
353
|
+
return _textDecoder.decode(bytes);
|
|
354
|
+
let s = "";
|
|
355
|
+
let i = 0;
|
|
356
|
+
while (i < bytes.length) {
|
|
357
|
+
const b = bytes[i++];
|
|
358
|
+
if (b < 128) {
|
|
359
|
+
s += String.fromCharCode(b);
|
|
360
|
+
} else if (b < 224) {
|
|
361
|
+
s += String.fromCharCode((b & 31) << 6 | bytes[i++] & 63);
|
|
362
|
+
} else if (b < 240) {
|
|
363
|
+
s += String.fromCharCode(
|
|
364
|
+
(b & 15) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63
|
|
365
|
+
);
|
|
366
|
+
} else {
|
|
367
|
+
const cp = (b & 7) << 18 | (bytes[i++] & 63) << 12 | (bytes[i++] & 63) << 6 | bytes[i++] & 63;
|
|
368
|
+
const u = cp - 65536;
|
|
369
|
+
s += String.fromCharCode(55296 + (u >> 10), 56320 + (u & 1023));
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
return s;
|
|
373
|
+
}
|
|
374
|
+
const OBJ_SERVICE_NAMES = [
|
|
375
|
+
"config",
|
|
376
|
+
"dfs",
|
|
377
|
+
"taskmgr",
|
|
378
|
+
"kmsg",
|
|
379
|
+
"bucket",
|
|
380
|
+
"ndm",
|
|
381
|
+
"msg-center",
|
|
382
|
+
"aiworkspace",
|
|
383
|
+
"homestation",
|
|
384
|
+
"opendan",
|
|
385
|
+
"aicc"
|
|
386
|
+
];
|
|
387
|
+
class ObjectUrlError extends Error {
|
|
388
|
+
}
|
|
389
|
+
function isObjServiceName(name) {
|
|
390
|
+
return OBJ_SERVICE_NAMES.includes(name);
|
|
391
|
+
}
|
|
392
|
+
function parseObjectUrl(input) {
|
|
393
|
+
input = input.trim();
|
|
394
|
+
const sep = input.indexOf("://");
|
|
395
|
+
if (sep < 0)
|
|
396
|
+
throw new ObjectUrlError(`'${input}' has no scheme`);
|
|
397
|
+
const scheme = input.slice(0, sep).toLowerCase();
|
|
398
|
+
const rest = input.slice(sep + 3);
|
|
399
|
+
switch (scheme) {
|
|
400
|
+
case "https":
|
|
401
|
+
case "http": {
|
|
402
|
+
try {
|
|
403
|
+
return { kind: "web", url: new URL(input).toString() };
|
|
404
|
+
} catch (e) {
|
|
405
|
+
throw new ObjectUrlError(`invalid web url '${input}': ${e}`);
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
case "buckyos":
|
|
409
|
+
return { kind: "buckyos", url: input };
|
|
410
|
+
case "file": {
|
|
411
|
+
const { authority, path, query } = splitAuthority(rest);
|
|
412
|
+
if (query !== null)
|
|
413
|
+
throw new ObjectUrlError("file url does not take query or fragment");
|
|
414
|
+
const host = authority.toLowerCase();
|
|
415
|
+
let deviceId;
|
|
416
|
+
if (host === "" || host === "localhost")
|
|
417
|
+
deviceId = null;
|
|
418
|
+
else if (isHostname(host))
|
|
419
|
+
deviceId = host;
|
|
420
|
+
else
|
|
421
|
+
throw new ObjectUrlError(`invalid device id '${host}' in file url`);
|
|
422
|
+
if (path === "")
|
|
423
|
+
throw new ObjectUrlError("file url requires an absolute path");
|
|
424
|
+
return { kind: "file", deviceId, path: normalizePath(path, false) };
|
|
425
|
+
}
|
|
426
|
+
case "cyfs": {
|
|
427
|
+
const { authority: rawAuthority, path, query } = splitAuthority(rest);
|
|
428
|
+
if (query !== null)
|
|
429
|
+
throw new ObjectUrlError("cyfs url does not take query or fragment");
|
|
430
|
+
const authority = rawAuthority.toLowerCase();
|
|
431
|
+
if (authority === "" || authority === "_") {
|
|
432
|
+
if (path === "")
|
|
433
|
+
throw new ObjectUrlError("cyfs path url requires a path");
|
|
434
|
+
return { kind: "cyfs_path", zone: null, path: normalizePath(path, false) };
|
|
435
|
+
}
|
|
436
|
+
const dot = authority.indexOf(".");
|
|
437
|
+
const firstLabel = dot < 0 ? authority : authority.slice(0, dot);
|
|
438
|
+
const restLabels = dot < 0 ? null : authority.slice(dot + 1);
|
|
439
|
+
const objId = strictObjIdLabel(firstLabel);
|
|
440
|
+
if (objId) {
|
|
441
|
+
if (restLabels !== null && !isHostname(restLabels)) {
|
|
442
|
+
throw new ObjectUrlError(`invalid source zone '${restLabels}'`);
|
|
443
|
+
}
|
|
444
|
+
return {
|
|
445
|
+
kind: "cyfs_object",
|
|
446
|
+
objId,
|
|
447
|
+
sourceZone: restLabels,
|
|
448
|
+
innerPath: path === "" || path === "/" ? "" : normalizePath(path, false)
|
|
449
|
+
};
|
|
450
|
+
}
|
|
451
|
+
if (!isHostname(authority) || !authority.includes(".")) {
|
|
452
|
+
throw new ObjectUrlError(`'${authority}' is neither a zone host nor an ObjId`);
|
|
453
|
+
}
|
|
454
|
+
if (path === "")
|
|
455
|
+
throw new ObjectUrlError("cyfs path url requires a path");
|
|
456
|
+
return { kind: "cyfs_path", zone: authority, path: normalizePath(path, false) };
|
|
457
|
+
}
|
|
458
|
+
case "obj": {
|
|
459
|
+
const { authority, path, query } = splitAuthority(rest);
|
|
460
|
+
const host = parseObjHost(authority.toLowerCase());
|
|
461
|
+
return {
|
|
462
|
+
kind: "obj",
|
|
463
|
+
host,
|
|
464
|
+
path: path === "" || path === "/" ? "" : normalizePath(path, true),
|
|
465
|
+
query: query === null ? {} : parseQuery(query)
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
default:
|
|
469
|
+
throw new ObjectUrlError(`unsupported scheme '${scheme}'`);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
function parseObjHost(host) {
|
|
473
|
+
if (host === "")
|
|
474
|
+
throw new ObjectUrlError("obj url requires a host");
|
|
475
|
+
if (isObjServiceName(host))
|
|
476
|
+
return { kind: "service", name: host };
|
|
477
|
+
if (!host.includes(".")) {
|
|
478
|
+
throw new ObjectUrlError(
|
|
479
|
+
`'${host}' is not a registered obj:// service name; type shorthands are not supported`
|
|
480
|
+
);
|
|
481
|
+
}
|
|
482
|
+
if (!isHostname(host))
|
|
483
|
+
throw new ObjectUrlError(`'${host}' is not a valid entity hostname`);
|
|
484
|
+
const firstLabel = host.split(".")[0];
|
|
485
|
+
if (isObjServiceName(firstLabel)) {
|
|
486
|
+
throw new ObjectUrlError(
|
|
487
|
+
`'${host}' expands a service name; write obj://${firstLabel}/ for the current zone or use https across zones`
|
|
488
|
+
);
|
|
489
|
+
}
|
|
490
|
+
if (strictObjIdLabel(firstLabel)) {
|
|
491
|
+
throw new ObjectUrlError("NamedObject ids do not go into obj:// host; use cyfs://<objid>/");
|
|
492
|
+
}
|
|
493
|
+
return { kind: "entity", name: host };
|
|
494
|
+
}
|
|
495
|
+
function formatObjectUrl(url) {
|
|
496
|
+
switch (url.kind) {
|
|
497
|
+
case "file":
|
|
498
|
+
return `file://${url.deviceId ?? ""}${url.path}`;
|
|
499
|
+
case "cyfs_path":
|
|
500
|
+
return `cyfs://${url.zone ?? ""}${url.path}`;
|
|
501
|
+
case "cyfs_object":
|
|
502
|
+
return `cyfs://${url.objId.toBase32()}${url.sourceZone ? `.${url.sourceZone}` : ""}${url.innerPath || "/"}`;
|
|
503
|
+
case "obj": {
|
|
504
|
+
const keys = Object.keys(url.query).sort();
|
|
505
|
+
const query = keys.map((k) => `${encodeObjQueryComponent(k)}=${encodeObjQueryComponent(url.query[k])}`).join("&");
|
|
506
|
+
return `obj://${url.host.name}${url.path}${query ? `?${query}` : ""}`;
|
|
507
|
+
}
|
|
508
|
+
case "web":
|
|
509
|
+
case "buckyos":
|
|
510
|
+
return url.url;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
function normalizeObjectUrl(input) {
|
|
514
|
+
return formatObjectUrl(parseObjectUrl(input));
|
|
515
|
+
}
|
|
516
|
+
function objectSegments(url) {
|
|
517
|
+
return url.kind === "obj" ? decodedSegments(url.path) : [];
|
|
518
|
+
}
|
|
519
|
+
function objServiceUrl(service, segments) {
|
|
520
|
+
return `obj://${service}${segments.map((s) => `/${encodeObjSegment(s)}`).join("")}`;
|
|
521
|
+
}
|
|
522
|
+
function canonicalJson(value) {
|
|
523
|
+
if (Array.isArray(value))
|
|
524
|
+
return `[${value.map(canonicalJson).join(",")}]`;
|
|
525
|
+
if (value !== null && typeof value === "object") {
|
|
526
|
+
const entries = Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`);
|
|
527
|
+
return `{${entries.join(",")}}`;
|
|
528
|
+
}
|
|
529
|
+
return JSON.stringify(value);
|
|
530
|
+
}
|
|
531
|
+
function encodeObjSegment(segment) {
|
|
532
|
+
return encodeWith(segment, (b) => isUnreserved(b) || "!$&'()*+,;=:@".includes(String.fromCharCode(b)));
|
|
533
|
+
}
|
|
534
|
+
function encodeObjQueryComponent(component) {
|
|
535
|
+
return encodeWith(component, (b) => isUnreserved(b) || "!$'()*,;:@/".includes(String.fromCharCode(b)));
|
|
536
|
+
}
|
|
537
|
+
function encodeWith(input, keep) {
|
|
538
|
+
let out = "";
|
|
539
|
+
for (const byte of new TextEncoder().encode(input)) {
|
|
540
|
+
out += keep(byte) ? String.fromCharCode(byte) : `%${byte.toString(16).toUpperCase().padStart(2, "0")}`;
|
|
541
|
+
}
|
|
542
|
+
return out;
|
|
543
|
+
}
|
|
544
|
+
function isUnreserved(byte) {
|
|
545
|
+
const ch = String.fromCharCode(byte);
|
|
546
|
+
return /[A-Za-z0-9]/.test(ch) || "-._~".includes(ch);
|
|
547
|
+
}
|
|
548
|
+
function splitAuthority(rest) {
|
|
549
|
+
const qpos = rest.search(/[?#]/);
|
|
550
|
+
const beforeQuery = qpos < 0 ? rest : rest.slice(0, qpos);
|
|
551
|
+
let query = null;
|
|
552
|
+
if (qpos >= 0) {
|
|
553
|
+
const q = rest.slice(qpos).split("#")[0];
|
|
554
|
+
query = q.startsWith("?") ? q.slice(1) : q;
|
|
555
|
+
if (query === "")
|
|
556
|
+
query = null;
|
|
557
|
+
}
|
|
558
|
+
const slash = beforeQuery.indexOf("/");
|
|
559
|
+
return slash < 0 ? { authority: beforeQuery, path: "", query } : { authority: beforeQuery.slice(0, slash), path: beforeQuery.slice(slash), query };
|
|
560
|
+
}
|
|
561
|
+
function normalizePath(path, trimTrailingSlash) {
|
|
562
|
+
if (!path.startsWith("/"))
|
|
563
|
+
throw new ObjectUrlError(`path '${path}' must be absolute`);
|
|
564
|
+
let body = path.slice(1);
|
|
565
|
+
if (trimTrailingSlash && body.endsWith("/"))
|
|
566
|
+
body = body.slice(0, -1);
|
|
567
|
+
const raw = body.split("/");
|
|
568
|
+
let out = "";
|
|
569
|
+
raw.forEach((segment, index) => {
|
|
570
|
+
if (segment === "" && index === raw.length - 1 && !trimTrailingSlash) {
|
|
571
|
+
out += "/";
|
|
572
|
+
return;
|
|
573
|
+
}
|
|
574
|
+
const decoded = percentDecode(segment);
|
|
575
|
+
if (decoded === "" || decoded === "." || decoded === "..") {
|
|
576
|
+
throw new ObjectUrlError(`ambiguous path segment in '${path}'`);
|
|
577
|
+
}
|
|
578
|
+
out += `/${encodeObjSegment(decoded)}`;
|
|
579
|
+
});
|
|
580
|
+
return out;
|
|
581
|
+
}
|
|
582
|
+
function decodedSegments(path) {
|
|
583
|
+
return path.split("/").filter((s) => s !== "").map((s) => {
|
|
584
|
+
try {
|
|
585
|
+
return percentDecode(s);
|
|
586
|
+
} catch {
|
|
587
|
+
return s;
|
|
588
|
+
}
|
|
589
|
+
});
|
|
590
|
+
}
|
|
591
|
+
function parseQuery(query) {
|
|
592
|
+
const out = {};
|
|
593
|
+
for (const pair of query.split("&")) {
|
|
594
|
+
if (pair === "")
|
|
595
|
+
continue;
|
|
596
|
+
const eq = pair.indexOf("=");
|
|
597
|
+
const key = percentDecode((eq < 0 ? pair : pair.slice(0, eq)).replace(/\+/g, " "));
|
|
598
|
+
let value = percentDecode((eq < 0 ? "" : pair.slice(eq + 1)).replace(/\+/g, " "));
|
|
599
|
+
if (key === "selector") {
|
|
600
|
+
try {
|
|
601
|
+
value = canonicalJson(JSON.parse(value));
|
|
602
|
+
} catch (e) {
|
|
603
|
+
throw new ObjectUrlError(`selector must be JSON: ${e}`);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
if (Object.prototype.hasOwnProperty.call(out, key)) {
|
|
607
|
+
throw new ObjectUrlError(`query key '${key}' repeats`);
|
|
608
|
+
}
|
|
609
|
+
out[key] = value;
|
|
610
|
+
}
|
|
611
|
+
return out;
|
|
612
|
+
}
|
|
613
|
+
function percentDecode(input) {
|
|
614
|
+
const raw = new TextEncoder().encode(input);
|
|
615
|
+
const bytes = [];
|
|
616
|
+
for (let i = 0; i < raw.length; ) {
|
|
617
|
+
if (raw[i] === 37) {
|
|
618
|
+
const hex = String.fromCharCode(raw[i + 1] ?? 0, raw[i + 2] ?? 0);
|
|
619
|
+
if (!/^[0-9A-Fa-f]{2}$/.test(hex))
|
|
620
|
+
throw new ObjectUrlError(`invalid escape in '${input}'`);
|
|
621
|
+
bytes.push(parseInt(hex, 16));
|
|
622
|
+
i += 3;
|
|
623
|
+
} else {
|
|
624
|
+
bytes.push(raw[i]);
|
|
625
|
+
i += 1;
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
try {
|
|
629
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(new Uint8Array(bytes));
|
|
630
|
+
} catch {
|
|
631
|
+
throw new ObjectUrlError(`'${input}' is not UTF-8`);
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
function isHostname(host) {
|
|
635
|
+
return host !== "" && host.length <= 253 && host.split(".").every((label) => label !== "" && label.length <= 63 && /^[a-z0-9-]+$/.test(label) && !label.startsWith("-") && !label.endsWith("-"));
|
|
636
|
+
}
|
|
637
|
+
function strictObjIdLabel(label) {
|
|
638
|
+
if (label.length < 26)
|
|
639
|
+
return null;
|
|
640
|
+
try {
|
|
641
|
+
const objId = ObjId.fromString(label);
|
|
642
|
+
const typeOk = /^[a-z0-9_-]+$/.test(objId.objType);
|
|
643
|
+
return typeOk && objId.objHash.length >= 16 && objId.toBase32() === label ? objId : null;
|
|
644
|
+
} catch {
|
|
645
|
+
return null;
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
class AiwsFailure extends Error {
|
|
649
|
+
constructor(error) {
|
|
650
|
+
super(`${error.code}${error.sub_code ? `/${error.sub_code}` : ""}: ${error.detail}`);
|
|
651
|
+
this.name = "AiwsFailure";
|
|
652
|
+
this.code = error.code;
|
|
653
|
+
this.subCode = error.sub_code;
|
|
654
|
+
this.data = error.data;
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
function aiwsReferenceUrl(reference, workspaceId) {
|
|
658
|
+
const ws = reference.workspace_id ?? workspaceId;
|
|
659
|
+
if (!ws)
|
|
660
|
+
throw new Error("reference names no workspace");
|
|
661
|
+
const query = [];
|
|
662
|
+
if (reference.mode === "fixed")
|
|
663
|
+
query.push("mode=fixed");
|
|
664
|
+
if (reference.selector != null)
|
|
665
|
+
query.push(`selector=${encodeObjQueryComponent(canonicalJson(reference.selector))}`);
|
|
666
|
+
if (reference.version != null)
|
|
667
|
+
query.push(`version=${encodeObjQueryComponent(canonicalJson(reference.version))}`);
|
|
668
|
+
const base = objServiceUrl("aiworkspace", [ws, "entities", reference.entity_id]);
|
|
669
|
+
return normalizeObjectUrl(query.length ? `${base}?${query.join("&")}` : base);
|
|
670
|
+
}
|
|
671
|
+
function parseAiwsReferenceUrl(url) {
|
|
672
|
+
const parsed = parseObjectUrl(url);
|
|
673
|
+
const segments = objectSegments(parsed);
|
|
674
|
+
if (parsed.kind !== "obj" || parsed.host.name !== "aiworkspace" || segments.length !== 3 || segments[1] !== "entities") {
|
|
675
|
+
throw new Error(`${url} is not an AI Workspace entity url`);
|
|
676
|
+
}
|
|
677
|
+
const reference = {
|
|
678
|
+
workspace_id: segments[0],
|
|
679
|
+
entity_id: segments[2],
|
|
680
|
+
mode: parsed.query.mode === "fixed" ? "fixed" : "live"
|
|
681
|
+
};
|
|
682
|
+
if (parsed.query.selector !== void 0)
|
|
683
|
+
reference.selector = JSON.parse(parsed.query.selector);
|
|
684
|
+
if (parsed.query.version !== void 0)
|
|
685
|
+
reference.version = JSON.parse(parsed.query.version);
|
|
686
|
+
return reference;
|
|
687
|
+
}
|
|
688
|
+
new TextEncoder();
|
|
689
|
+
const WEEKDAYS = ["MO", "TU", "WE", "TH", "FR", "SA", "SU"];
|
|
690
|
+
class RRuleError extends Error {
|
|
691
|
+
constructor(message) {
|
|
692
|
+
super(message);
|
|
693
|
+
this.name = "RRuleError";
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
const FREQS = ["DAILY", "WEEKLY", "MONTHLY", "YEARLY"];
|
|
697
|
+
const MAX_COUNT = 1e3;
|
|
698
|
+
const MAX_INTERVAL = 999;
|
|
699
|
+
function intIn(part, value, lo, hi, zero = false) {
|
|
700
|
+
if (!/^[+-]?\d{1,3}$/.test(value))
|
|
701
|
+
throw new RRuleError(`${part}: ${value} is not a number`);
|
|
702
|
+
const n = Number(value);
|
|
703
|
+
if (n < lo || n > hi || !zero && n === 0)
|
|
704
|
+
throw new RRuleError(`${part}: ${value} is out of range`);
|
|
705
|
+
return n;
|
|
706
|
+
}
|
|
707
|
+
function list(part, value, max) {
|
|
708
|
+
const items = value.split(",");
|
|
709
|
+
if (items.length === 0 || items.length > max || items.some((x) => x === ""))
|
|
710
|
+
throw new RRuleError(`${part}: at most ${max} comma-separated values`);
|
|
711
|
+
return items;
|
|
712
|
+
}
|
|
713
|
+
function untilOf(value) {
|
|
714
|
+
let m = /^(\d{4})(\d{2})(\d{2})$/.exec(value);
|
|
715
|
+
if (m) {
|
|
716
|
+
const date = `${m[1]}-${m[2]}-${m[3]}`;
|
|
717
|
+
if (!isDate(date))
|
|
718
|
+
throw new RRuleError(`UNTIL: ${value} is not a date`);
|
|
719
|
+
return date;
|
|
720
|
+
}
|
|
721
|
+
m = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/.exec(value);
|
|
722
|
+
if (m) {
|
|
723
|
+
const ms = Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6]);
|
|
724
|
+
if (!isDate(`${m[1]}-${m[2]}-${m[3]}`) || +m[4] > 23 || +m[5] > 59 || +m[6] > 59)
|
|
725
|
+
throw new RRuleError(`UNTIL: ${value} is not a UTC time`);
|
|
726
|
+
return new Date(ms).toISOString();
|
|
727
|
+
}
|
|
728
|
+
throw new RRuleError(`UNTIL: ${value} must be YYYYMMDD or YYYYMMDDTHHMMSSZ`);
|
|
729
|
+
}
|
|
730
|
+
function parseRRule(text) {
|
|
731
|
+
const body = text.startsWith("RRULE:") ? text.slice(6) : text;
|
|
732
|
+
if (body.trim() === "")
|
|
733
|
+
throw new RRuleError("empty rule");
|
|
734
|
+
const seen = /* @__PURE__ */ new Set();
|
|
735
|
+
const raw = {};
|
|
736
|
+
for (const part of body.split(";")) {
|
|
737
|
+
const eq = part.indexOf("=");
|
|
738
|
+
if (eq <= 0)
|
|
739
|
+
throw new RRuleError(`${part || "(empty)"}: expected NAME=VALUE`);
|
|
740
|
+
const name = part.slice(0, eq);
|
|
741
|
+
const value = part.slice(eq + 1);
|
|
742
|
+
if (name !== name.toUpperCase() || value !== value.toUpperCase())
|
|
743
|
+
throw new RRuleError(`${part}: write the rule in upper case`);
|
|
744
|
+
if (seen.has(name))
|
|
745
|
+
throw new RRuleError(`${name}: given twice`);
|
|
746
|
+
seen.add(name);
|
|
747
|
+
if (!["FREQ", "INTERVAL", "COUNT", "UNTIL", "BYDAY", "BYMONTHDAY", "BYMONTH", "BYSETPOS", "WKST"].includes(name)) {
|
|
748
|
+
throw new RRuleError(`${name}: not supported (supported: FREQ, INTERVAL, COUNT, UNTIL, BYDAY, BYMONTHDAY, BYMONTH, BYSETPOS, WKST)`);
|
|
749
|
+
}
|
|
750
|
+
if (value === "")
|
|
751
|
+
throw new RRuleError(`${name}: empty value`);
|
|
752
|
+
raw[name] = value;
|
|
753
|
+
}
|
|
754
|
+
if (!raw.FREQ)
|
|
755
|
+
throw new RRuleError("FREQ is required");
|
|
756
|
+
if (!FREQS.includes(raw.FREQ))
|
|
757
|
+
throw new RRuleError(`FREQ: ${raw.FREQ} is not supported (DAILY, WEEKLY, MONTHLY, YEARLY)`);
|
|
758
|
+
const freq = raw.FREQ;
|
|
759
|
+
const rule = { freq, interval: 1, wkst: 0 };
|
|
760
|
+
if (raw.INTERVAL !== void 0)
|
|
761
|
+
rule.interval = intIn("INTERVAL", raw.INTERVAL, 1, MAX_INTERVAL);
|
|
762
|
+
if (raw.COUNT !== void 0 && raw.UNTIL !== void 0)
|
|
763
|
+
throw new RRuleError("COUNT and UNTIL cannot both be given");
|
|
764
|
+
if (raw.COUNT !== void 0)
|
|
765
|
+
rule.count = intIn("COUNT", raw.COUNT, 1, MAX_COUNT);
|
|
766
|
+
if (raw.UNTIL !== void 0)
|
|
767
|
+
rule.until = untilOf(raw.UNTIL);
|
|
768
|
+
if (raw.BYDAY !== void 0) {
|
|
769
|
+
rule.byDay = list("BYDAY", raw.BYDAY, 7).map((item) => {
|
|
770
|
+
const m = /^([+-]?\d)?(MO|TU|WE|TH|FR|SA|SU)$/.exec(item);
|
|
771
|
+
if (!m)
|
|
772
|
+
throw new RRuleError(`BYDAY: ${item} is not a weekday`);
|
|
773
|
+
const weekday = WEEKDAYS.indexOf(m[2]);
|
|
774
|
+
if (m[1] === void 0)
|
|
775
|
+
return { weekday };
|
|
776
|
+
if (freq !== "MONTHLY" && freq !== "YEARLY")
|
|
777
|
+
throw new RRuleError(`BYDAY: ${item}: an ordinal needs FREQ=MONTHLY or YEARLY`);
|
|
778
|
+
return { weekday, ordinal: intIn("BYDAY", m[1], -5, 5) };
|
|
779
|
+
});
|
|
780
|
+
const keys = rule.byDay.map((d) => `${d.ordinal ?? ""}${d.weekday}`);
|
|
781
|
+
if (new Set(keys).size !== keys.length)
|
|
782
|
+
throw new RRuleError("BYDAY: repeated day");
|
|
783
|
+
}
|
|
784
|
+
if (raw.BYMONTHDAY !== void 0) {
|
|
785
|
+
if (freq !== "MONTHLY" && freq !== "YEARLY")
|
|
786
|
+
throw new RRuleError("BYMONTHDAY needs FREQ=MONTHLY or YEARLY");
|
|
787
|
+
rule.byMonthDay = list("BYMONTHDAY", raw.BYMONTHDAY, 31).map((v) => {
|
|
788
|
+
const n = intIn("BYMONTHDAY", v, -1, 31);
|
|
789
|
+
return n;
|
|
790
|
+
});
|
|
791
|
+
if (new Set(rule.byMonthDay).size !== rule.byMonthDay.length)
|
|
792
|
+
throw new RRuleError("BYMONTHDAY: repeated day");
|
|
793
|
+
}
|
|
794
|
+
if (raw.BYMONTH !== void 0) {
|
|
795
|
+
if (freq !== "YEARLY")
|
|
796
|
+
throw new RRuleError("BYMONTH needs FREQ=YEARLY");
|
|
797
|
+
rule.byMonth = list("BYMONTH", raw.BYMONTH, 12).map((v) => intIn("BYMONTH", v, 1, 12));
|
|
798
|
+
if (new Set(rule.byMonth).size !== rule.byMonth.length)
|
|
799
|
+
throw new RRuleError("BYMONTH: repeated month");
|
|
800
|
+
}
|
|
801
|
+
if (raw.BYSETPOS !== void 0) {
|
|
802
|
+
if (freq !== "MONTHLY" || !rule.byDay)
|
|
803
|
+
throw new RRuleError("BYSETPOS needs FREQ=MONTHLY and BYDAY");
|
|
804
|
+
rule.bySetPos = intIn("BYSETPOS", raw.BYSETPOS, -5, 5);
|
|
805
|
+
}
|
|
806
|
+
if (raw.WKST !== void 0) {
|
|
807
|
+
const w = WEEKDAYS.indexOf(raw.WKST);
|
|
808
|
+
if (w < 0)
|
|
809
|
+
throw new RRuleError(`WKST: ${raw.WKST} is not a weekday`);
|
|
810
|
+
rule.wkst = w;
|
|
811
|
+
}
|
|
812
|
+
return rule;
|
|
813
|
+
}
|
|
814
|
+
function formatRRule(rule) {
|
|
815
|
+
const parts = [`FREQ=${rule.freq}`];
|
|
816
|
+
if (rule.interval > 1)
|
|
817
|
+
parts.push(`INTERVAL=${rule.interval}`);
|
|
818
|
+
if (rule.byMonth?.length)
|
|
819
|
+
parts.push(`BYMONTH=${rule.byMonth.join(",")}`);
|
|
820
|
+
if (rule.byMonthDay?.length)
|
|
821
|
+
parts.push(`BYMONTHDAY=${rule.byMonthDay.join(",")}`);
|
|
822
|
+
if (rule.byDay?.length)
|
|
823
|
+
parts.push(`BYDAY=${rule.byDay.map((d) => `${d.ordinal ?? ""}${WEEKDAYS[d.weekday]}`).join(",")}`);
|
|
824
|
+
if (rule.bySetPos !== void 0)
|
|
825
|
+
parts.push(`BYSETPOS=${rule.bySetPos}`);
|
|
826
|
+
if (rule.count !== void 0)
|
|
827
|
+
parts.push(`COUNT=${rule.count}`);
|
|
828
|
+
if (rule.until !== void 0)
|
|
829
|
+
parts.push(`UNTIL=${rule.until.length === 10 ? rule.until.replace(/-/g, "") : rule.until.replace(/[-:]/g, "").replace(/\.\d{3}/, "")}`);
|
|
830
|
+
if (rule.wkst !== 0)
|
|
831
|
+
parts.push(`WKST=${WEEKDAYS[rule.wkst]}`);
|
|
832
|
+
return parts.join(";");
|
|
833
|
+
}
|
|
834
|
+
function isDate(s) {
|
|
835
|
+
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(s);
|
|
836
|
+
if (!m)
|
|
837
|
+
return false;
|
|
838
|
+
const y = +m[1], mo = +m[2], d = +m[3];
|
|
839
|
+
return y >= 1 && mo >= 1 && mo <= 12 && d >= 1 && d <= daysInMonth(y, mo);
|
|
840
|
+
}
|
|
841
|
+
const isLeap = (y) => y % 4 === 0 && y % 100 !== 0 || y % 400 === 0;
|
|
842
|
+
function daysInMonth(y, m) {
|
|
843
|
+
return [31, isLeap(y) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][m - 1];
|
|
844
|
+
}
|
|
845
|
+
const dayNumber = (y, m, d) => Math.floor(Date.UTC(y, m - 1, d) / 864e5);
|
|
846
|
+
function dayOf(date) {
|
|
847
|
+
return dayNumber(+date.slice(0, 4), +date.slice(5, 7), +date.slice(8, 10));
|
|
848
|
+
}
|
|
849
|
+
function dateOf(day) {
|
|
850
|
+
return new Date(day * 864e5).toISOString().slice(0, 10);
|
|
851
|
+
}
|
|
852
|
+
function ymdOf(day) {
|
|
853
|
+
const t = new Date(day * 864e5);
|
|
854
|
+
return { y: t.getUTCFullYear(), m: t.getUTCMonth() + 1, d: t.getUTCDate() };
|
|
855
|
+
}
|
|
856
|
+
const weekdayOf = (day) => ((day + 3) % 7 + 7) % 7;
|
|
857
|
+
const formatters = /* @__PURE__ */ new Map();
|
|
858
|
+
function formatter(tz) {
|
|
859
|
+
let f = formatters.get(tz);
|
|
860
|
+
if (!f) {
|
|
861
|
+
f = new Intl.DateTimeFormat("en-US", { timeZone: tz, hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" });
|
|
862
|
+
formatters.set(tz, f);
|
|
863
|
+
}
|
|
864
|
+
return f;
|
|
865
|
+
}
|
|
866
|
+
function isTimeZone(tz) {
|
|
867
|
+
try {
|
|
868
|
+
formatter(tz);
|
|
869
|
+
return true;
|
|
870
|
+
} catch {
|
|
871
|
+
return false;
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
function zonedParts(ms, tz) {
|
|
875
|
+
const parts = {};
|
|
876
|
+
for (const p of formatter(tz).formatToParts(new Date(ms)))
|
|
877
|
+
if (p.type !== "literal")
|
|
878
|
+
parts[p.type] = Number(p.value);
|
|
879
|
+
return { y: parts.year, m: parts.month, d: parts.day, h: parts.hour === 24 ? 0 : parts.hour, mi: parts.minute, s: parts.second };
|
|
880
|
+
}
|
|
881
|
+
function offsetMs(ms, tz) {
|
|
882
|
+
const p = zonedParts(ms, tz);
|
|
883
|
+
return Date.UTC(p.y, p.m - 1, p.d, p.h, p.mi, p.s) - Math.floor(ms / 1e3) * 1e3;
|
|
884
|
+
}
|
|
885
|
+
function zonedToUtc(day, minuteOfDay, secondOfMinute, tz) {
|
|
886
|
+
const local = day * 864e5 + minuteOfDay * 6e4 + secondOfMinute * 1e3;
|
|
887
|
+
const first = local - offsetMs(local, tz);
|
|
888
|
+
const second = local - offsetMs(first, tz);
|
|
889
|
+
return second !== first && local - offsetMs(second, tz) !== second ? Math.max(first, second) : second;
|
|
890
|
+
}
|
|
891
|
+
function localDay(ms, tz) {
|
|
892
|
+
const p = zonedParts(ms, tz);
|
|
893
|
+
return dayNumber(p.y, p.m, p.d);
|
|
894
|
+
}
|
|
895
|
+
const MAX_PERIODS = 2e5;
|
|
896
|
+
function candidates(rule, period, startDay) {
|
|
897
|
+
const s = ymdOf(startDay);
|
|
898
|
+
const out = [];
|
|
899
|
+
const byDayAll = (day0, len, wanted) => {
|
|
900
|
+
for (let i = 0; i < len; i++)
|
|
901
|
+
if (wanted.some((w) => w.ordinal === void 0 && w.weekday === weekdayOf(day0 + i)))
|
|
902
|
+
out.push(day0 + i);
|
|
903
|
+
};
|
|
904
|
+
const nth = (day0, len, w) => {
|
|
905
|
+
const days = [];
|
|
906
|
+
for (let i = 0; i < len; i++)
|
|
907
|
+
if (weekdayOf(day0 + i) === w.weekday)
|
|
908
|
+
days.push(day0 + i);
|
|
909
|
+
const k = w.ordinal > 0 ? w.ordinal - 1 : days.length + w.ordinal;
|
|
910
|
+
if (k >= 0 && k < days.length)
|
|
911
|
+
out.push(days[k]);
|
|
912
|
+
};
|
|
913
|
+
const monthDays = (y, m, list2) => {
|
|
914
|
+
const n = daysInMonth(y, m);
|
|
915
|
+
for (const d of list2) {
|
|
916
|
+
const day = d > 0 ? d : n + d + 1;
|
|
917
|
+
if (day >= 1 && day <= n)
|
|
918
|
+
out.push(dayNumber(y, m, day));
|
|
919
|
+
}
|
|
920
|
+
};
|
|
921
|
+
switch (rule.freq) {
|
|
922
|
+
case "DAILY": {
|
|
923
|
+
const day = startDay + period * rule.interval;
|
|
924
|
+
const { m, d } = ymdOf(day);
|
|
925
|
+
if (rule.byMonth && !rule.byMonth.includes(m))
|
|
926
|
+
break;
|
|
927
|
+
if (rule.byMonthDay && !rule.byMonthDay.some((x) => x > 0 ? x === d : daysInMonth(ymdOf(day).y, m) + x + 1 === d))
|
|
928
|
+
break;
|
|
929
|
+
if (rule.byDay && !rule.byDay.some((w) => w.weekday === weekdayOf(day)))
|
|
930
|
+
break;
|
|
931
|
+
out.push(day);
|
|
932
|
+
break;
|
|
933
|
+
}
|
|
934
|
+
case "WEEKLY": {
|
|
935
|
+
const weekStart = startDay - (weekdayOf(startDay) - rule.wkst + 7) % 7 + period * rule.interval * 7;
|
|
936
|
+
const wanted = rule.byDay ?? [{ weekday: weekdayOf(startDay) }];
|
|
937
|
+
byDayAll(weekStart, 7, wanted);
|
|
938
|
+
if (rule.byMonth)
|
|
939
|
+
return out.filter((d) => rule.byMonth.includes(ymdOf(d).m)).sort((a, b) => a - b);
|
|
940
|
+
break;
|
|
941
|
+
}
|
|
942
|
+
case "MONTHLY": {
|
|
943
|
+
const index = s.y * 12 + (s.m - 1) + period * rule.interval;
|
|
944
|
+
const y = Math.floor(index / 12), m = index % 12 + 1;
|
|
945
|
+
const day0 = dayNumber(y, m, 1), len = daysInMonth(y, m);
|
|
946
|
+
if (rule.byMonthDay) {
|
|
947
|
+
monthDays(y, m, rule.byMonthDay);
|
|
948
|
+
if (rule.byDay) {
|
|
949
|
+
const keep = out.filter((d) => rule.byDay.some((w) => w.weekday === weekdayOf(d)));
|
|
950
|
+
out.length = 0;
|
|
951
|
+
out.push(...keep);
|
|
952
|
+
}
|
|
953
|
+
} else if (rule.byDay) {
|
|
954
|
+
byDayAll(day0, len, rule.byDay);
|
|
955
|
+
for (const w of rule.byDay)
|
|
956
|
+
if (w.ordinal !== void 0)
|
|
957
|
+
nth(day0, len, w);
|
|
958
|
+
} else if (s.d <= len)
|
|
959
|
+
out.push(dayNumber(y, m, s.d));
|
|
960
|
+
break;
|
|
961
|
+
}
|
|
962
|
+
case "YEARLY": {
|
|
963
|
+
const y = s.y + period * rule.interval;
|
|
964
|
+
if (rule.byDay && !rule.byMonth && !rule.byMonthDay) {
|
|
965
|
+
const day0 = dayNumber(y, 1, 1), len = isLeap(y) ? 366 : 365;
|
|
966
|
+
byDayAll(day0, len, rule.byDay);
|
|
967
|
+
for (const w of rule.byDay)
|
|
968
|
+
if (w.ordinal !== void 0)
|
|
969
|
+
nth(day0, len, w);
|
|
970
|
+
break;
|
|
971
|
+
}
|
|
972
|
+
const months = rule.byMonth ?? [s.m];
|
|
973
|
+
for (const m of months) {
|
|
974
|
+
if (rule.byMonthDay)
|
|
975
|
+
monthDays(y, m, rule.byMonthDay);
|
|
976
|
+
else if (rule.byDay) {
|
|
977
|
+
const day0 = dayNumber(y, m, 1), len = daysInMonth(y, m);
|
|
978
|
+
byDayAll(day0, len, rule.byDay);
|
|
979
|
+
for (const w of rule.byDay)
|
|
980
|
+
if (w.ordinal !== void 0)
|
|
981
|
+
nth(day0, len, w);
|
|
982
|
+
} else if (s.d <= daysInMonth(y, m))
|
|
983
|
+
out.push(dayNumber(y, m, s.d));
|
|
984
|
+
}
|
|
985
|
+
if (rule.byMonthDay && rule.byDay) {
|
|
986
|
+
const keep = out.filter((d) => rule.byDay.some((w) => w.weekday === weekdayOf(d)));
|
|
987
|
+
out.length = 0;
|
|
988
|
+
out.push(...keep);
|
|
989
|
+
}
|
|
990
|
+
break;
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
const sorted = [...new Set(out)].sort((a, b) => a - b);
|
|
994
|
+
if (rule.bySetPos !== void 0) {
|
|
995
|
+
const k = rule.bySetPos > 0 ? rule.bySetPos - 1 : sorted.length + rule.bySetPos;
|
|
996
|
+
return k >= 0 && k < sorted.length ? [sorted[k]] : [];
|
|
997
|
+
}
|
|
998
|
+
return sorted;
|
|
999
|
+
}
|
|
1000
|
+
function periodStart(rule, p, startDay) {
|
|
1001
|
+
const s = ymdOf(startDay);
|
|
1002
|
+
switch (rule.freq) {
|
|
1003
|
+
case "DAILY":
|
|
1004
|
+
return startDay + p * rule.interval;
|
|
1005
|
+
case "WEEKLY":
|
|
1006
|
+
return startDay - (weekdayOf(startDay) - rule.wkst + 7) % 7 + p * rule.interval * 7;
|
|
1007
|
+
case "MONTHLY": {
|
|
1008
|
+
const index = s.y * 12 + (s.m - 1) + p * rule.interval;
|
|
1009
|
+
return dayNumber(Math.floor(index / 12), index % 12 + 1, 1);
|
|
1010
|
+
}
|
|
1011
|
+
case "YEARLY":
|
|
1012
|
+
return dayNumber(s.y + p * rule.interval, 1, 1);
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
function periodsBefore(rule, startDay, day) {
|
|
1016
|
+
const s = ymdOf(startDay);
|
|
1017
|
+
const t = ymdOf(day);
|
|
1018
|
+
let p;
|
|
1019
|
+
switch (rule.freq) {
|
|
1020
|
+
case "DAILY":
|
|
1021
|
+
p = Math.floor((day - startDay) / rule.interval);
|
|
1022
|
+
break;
|
|
1023
|
+
case "WEEKLY":
|
|
1024
|
+
p = Math.floor((day - periodStart(rule, 0, startDay)) / (7 * rule.interval));
|
|
1025
|
+
break;
|
|
1026
|
+
case "MONTHLY":
|
|
1027
|
+
p = Math.floor((t.y * 12 + t.m - (s.y * 12 + s.m)) / rule.interval);
|
|
1028
|
+
break;
|
|
1029
|
+
case "YEARLY":
|
|
1030
|
+
p = Math.floor((t.y - s.y) / rule.interval);
|
|
1031
|
+
break;
|
|
1032
|
+
}
|
|
1033
|
+
return Math.max(-1, p - 1);
|
|
1034
|
+
}
|
|
1035
|
+
function expandSeries(rule, start, window, opts = {}) {
|
|
1036
|
+
const limit = opts.limit ?? 2e3;
|
|
1037
|
+
const excluded = new Set(opts.exdate ?? []);
|
|
1038
|
+
const out = [];
|
|
1039
|
+
let startDay;
|
|
1040
|
+
let minute = 0, second = 0;
|
|
1041
|
+
let tz = "UTC";
|
|
1042
|
+
let fromDay, toDay;
|
|
1043
|
+
const viewerTz = opts.viewerTz ?? "UTC";
|
|
1044
|
+
if (start.kind === "date") {
|
|
1045
|
+
startDay = dayOf(start.date);
|
|
1046
|
+
fromDay = localDay(window.fromMs, viewerTz) - (opts.durationDays ?? 0);
|
|
1047
|
+
toDay = localDay(window.toMs - 1, viewerTz);
|
|
1048
|
+
} else {
|
|
1049
|
+
tz = start.tz;
|
|
1050
|
+
const ms = Date.parse(start.utc);
|
|
1051
|
+
const p = zonedParts(ms, tz);
|
|
1052
|
+
startDay = dayNumber(p.y, p.m, p.d);
|
|
1053
|
+
minute = p.h * 60 + p.mi;
|
|
1054
|
+
second = p.s;
|
|
1055
|
+
fromDay = localDay(window.fromMs - (opts.durationMs ?? 0), tz) - 1;
|
|
1056
|
+
toDay = localDay(window.toMs, tz) + 1;
|
|
1057
|
+
}
|
|
1058
|
+
const untilDay = rule.until?.length === 10 ? dayOf(rule.until) : void 0;
|
|
1059
|
+
const untilMs = rule.until && rule.until.length > 10 ? Date.parse(rule.until) : void 0;
|
|
1060
|
+
let count = 0;
|
|
1061
|
+
const emit = (day) => {
|
|
1062
|
+
if (rule.count !== void 0 && count >= rule.count)
|
|
1063
|
+
return false;
|
|
1064
|
+
if (untilDay !== void 0 && day > untilDay)
|
|
1065
|
+
return false;
|
|
1066
|
+
let occ;
|
|
1067
|
+
if (start.kind === "date") {
|
|
1068
|
+
if (untilMs !== void 0 && day * 864e5 > untilMs)
|
|
1069
|
+
return false;
|
|
1070
|
+
const date = dateOf(day);
|
|
1071
|
+
occ = { original: date, date };
|
|
1072
|
+
} else {
|
|
1073
|
+
const firstMs = Date.parse(start.utc);
|
|
1074
|
+
const ms = day === startDay ? firstMs : zonedToUtc(day, minute, second, tz) + new Date(firstMs).getUTCMilliseconds();
|
|
1075
|
+
if (untilMs !== void 0 && ms > untilMs)
|
|
1076
|
+
return false;
|
|
1077
|
+
occ = { original: new Date(ms).toISOString(), startMs: ms };
|
|
1078
|
+
}
|
|
1079
|
+
count += 1;
|
|
1080
|
+
if (excluded.has(occ.original))
|
|
1081
|
+
return true;
|
|
1082
|
+
if (start.kind === "date") {
|
|
1083
|
+
if (day >= fromDay && day <= toDay)
|
|
1084
|
+
out.push(occ);
|
|
1085
|
+
} else if (occ.startMs + (opts.durationMs ?? 0) > window.fromMs && occ.startMs < window.toMs)
|
|
1086
|
+
out.push(occ);
|
|
1087
|
+
return true;
|
|
1088
|
+
};
|
|
1089
|
+
if (startDay > toDay || !emit(startDay))
|
|
1090
|
+
return out;
|
|
1091
|
+
let period = rule.count === void 0 ? periodsBefore(rule, startDay, fromDay) + 1 : 0;
|
|
1092
|
+
for (let guard = 0; guard < MAX_PERIODS && out.length < limit; guard++, period++) {
|
|
1093
|
+
if (periodStart(rule, period, startDay) > toDay)
|
|
1094
|
+
return out;
|
|
1095
|
+
for (const day of candidates(rule, period, startDay)) {
|
|
1096
|
+
if (day <= startDay)
|
|
1097
|
+
continue;
|
|
1098
|
+
if (day > toDay)
|
|
1099
|
+
return out;
|
|
1100
|
+
if (!emit(day))
|
|
1101
|
+
return out;
|
|
1102
|
+
if (out.length >= limit) {
|
|
1103
|
+
opts.onTruncated?.();
|
|
1104
|
+
return out;
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
if (periodStart(rule, period, startDay) <= toDay)
|
|
1109
|
+
opts.onTruncated?.();
|
|
1110
|
+
return out;
|
|
1111
|
+
}
|
|
1112
|
+
function seriesStartOf(values, tz, fallbackTz = "UTC") {
|
|
1113
|
+
if (values.all_day === true)
|
|
1114
|
+
return typeof values.start_date === "string" ? { kind: "date", date: values.start_date } : null;
|
|
1115
|
+
return typeof values.start === "string" ? { kind: "datetime", utc: values.start, tz: tz && isTimeZone(tz) ? tz : fallbackTz } : null;
|
|
1116
|
+
}
|
|
1117
|
+
function occurrenceId(recordId, original) {
|
|
1118
|
+
return `${recordId}@${original}`;
|
|
1119
|
+
}
|
|
1120
|
+
const TODO_SCHEMA_ID = "buckyos.todo@1";
|
|
1121
|
+
const CALENDAR_SCHEMA_ID = "buckyos.calendar@1";
|
|
1122
|
+
const SCHEDULE_WORKSPACE_NAME = "schedule";
|
|
1123
|
+
const SCHEDULE_TODO_ID = "todo";
|
|
1124
|
+
const SCHEDULE_CALENDAR_ID = "calendar";
|
|
1125
|
+
const SCHEDULE_SURFACE_ID = "schedule-board";
|
|
1126
|
+
const TODO_DONE = "done";
|
|
1127
|
+
const AIWS_PROTOCOL_VERSION = "1.2";
|
|
1128
|
+
const LABELS = {
|
|
1129
|
+
zh: {
|
|
1130
|
+
title: "标题",
|
|
1131
|
+
status: "状态",
|
|
1132
|
+
due: "截止",
|
|
1133
|
+
order: "顺序",
|
|
1134
|
+
done_at: "完成时间",
|
|
1135
|
+
ext: "扩展",
|
|
1136
|
+
todo: "待办",
|
|
1137
|
+
doing: "进行中",
|
|
1138
|
+
done: "已完成",
|
|
1139
|
+
all_day: "全天",
|
|
1140
|
+
start: "开始",
|
|
1141
|
+
end: "结束",
|
|
1142
|
+
start_date: "开始日期",
|
|
1143
|
+
end_date: "结束日期",
|
|
1144
|
+
confirmed: "已确认",
|
|
1145
|
+
tentative: "暂定",
|
|
1146
|
+
cancelled: "已取消",
|
|
1147
|
+
todo_table: "待办",
|
|
1148
|
+
calendar_table: "日程",
|
|
1149
|
+
workspace: "我的日程",
|
|
1150
|
+
board: "日程"
|
|
1151
|
+
},
|
|
1152
|
+
en: {
|
|
1153
|
+
title: "Title",
|
|
1154
|
+
status: "Status",
|
|
1155
|
+
due: "Due",
|
|
1156
|
+
order: "Order",
|
|
1157
|
+
done_at: "Completed",
|
|
1158
|
+
ext: "Extension",
|
|
1159
|
+
todo: "To do",
|
|
1160
|
+
doing: "In progress",
|
|
1161
|
+
done: "Done",
|
|
1162
|
+
all_day: "All day",
|
|
1163
|
+
start: "Start",
|
|
1164
|
+
end: "End",
|
|
1165
|
+
start_date: "Start date",
|
|
1166
|
+
end_date: "End date",
|
|
1167
|
+
confirmed: "Confirmed",
|
|
1168
|
+
tentative: "Tentative",
|
|
1169
|
+
cancelled: "Cancelled",
|
|
1170
|
+
todo_table: "To-do",
|
|
1171
|
+
calendar_table: "Calendar",
|
|
1172
|
+
workspace: "My schedule",
|
|
1173
|
+
board: "Schedule"
|
|
1174
|
+
},
|
|
1175
|
+
"zh-TW": {
|
|
1176
|
+
title: "標題",
|
|
1177
|
+
status: "狀態",
|
|
1178
|
+
due: "截止",
|
|
1179
|
+
order: "順序",
|
|
1180
|
+
done_at: "完成時間",
|
|
1181
|
+
ext: "擴充",
|
|
1182
|
+
todo: "待辦",
|
|
1183
|
+
doing: "進行中",
|
|
1184
|
+
done: "已完成",
|
|
1185
|
+
all_day: "全天",
|
|
1186
|
+
start: "開始",
|
|
1187
|
+
end: "結束",
|
|
1188
|
+
start_date: "開始日期",
|
|
1189
|
+
end_date: "結束日期",
|
|
1190
|
+
confirmed: "已確認",
|
|
1191
|
+
tentative: "暫定",
|
|
1192
|
+
cancelled: "已取消",
|
|
1193
|
+
todo_table: "待辦事項",
|
|
1194
|
+
calendar_table: "行程",
|
|
1195
|
+
workspace: "我的行程",
|
|
1196
|
+
board: "行程"
|
|
1197
|
+
},
|
|
1198
|
+
ja: {
|
|
1199
|
+
title: "タイトル",
|
|
1200
|
+
status: "ステータス",
|
|
1201
|
+
due: "期限",
|
|
1202
|
+
order: "順序",
|
|
1203
|
+
done_at: "完了日時",
|
|
1204
|
+
ext: "拡張",
|
|
1205
|
+
todo: "未着手",
|
|
1206
|
+
doing: "進行中",
|
|
1207
|
+
done: "完了",
|
|
1208
|
+
all_day: "終日",
|
|
1209
|
+
start: "開始",
|
|
1210
|
+
end: "終了",
|
|
1211
|
+
start_date: "開始日",
|
|
1212
|
+
end_date: "終了日",
|
|
1213
|
+
confirmed: "確定",
|
|
1214
|
+
tentative: "仮",
|
|
1215
|
+
cancelled: "キャンセル",
|
|
1216
|
+
todo_table: "ToDo",
|
|
1217
|
+
calendar_table: "予定",
|
|
1218
|
+
workspace: "マイスケジュール",
|
|
1219
|
+
board: "スケジュール"
|
|
1220
|
+
},
|
|
1221
|
+
ko: {
|
|
1222
|
+
title: "제목",
|
|
1223
|
+
status: "상태",
|
|
1224
|
+
due: "마감",
|
|
1225
|
+
order: "순서",
|
|
1226
|
+
done_at: "완료 시각",
|
|
1227
|
+
ext: "확장",
|
|
1228
|
+
todo: "할 일",
|
|
1229
|
+
doing: "진행 중",
|
|
1230
|
+
done: "완료",
|
|
1231
|
+
all_day: "종일",
|
|
1232
|
+
start: "시작",
|
|
1233
|
+
end: "종료",
|
|
1234
|
+
start_date: "시작일",
|
|
1235
|
+
end_date: "종료일",
|
|
1236
|
+
confirmed: "확정",
|
|
1237
|
+
tentative: "미정",
|
|
1238
|
+
cancelled: "취소됨",
|
|
1239
|
+
todo_table: "할 일",
|
|
1240
|
+
calendar_table: "일정",
|
|
1241
|
+
workspace: "내 일정",
|
|
1242
|
+
board: "일정"
|
|
1243
|
+
},
|
|
1244
|
+
fr: {
|
|
1245
|
+
title: "Titre",
|
|
1246
|
+
status: "Statut",
|
|
1247
|
+
due: "Échéance",
|
|
1248
|
+
order: "Ordre",
|
|
1249
|
+
done_at: "Terminé le",
|
|
1250
|
+
ext: "Extension",
|
|
1251
|
+
todo: "À faire",
|
|
1252
|
+
doing: "En cours",
|
|
1253
|
+
done: "Terminé",
|
|
1254
|
+
all_day: "Toute la journée",
|
|
1255
|
+
start: "Début",
|
|
1256
|
+
end: "Fin",
|
|
1257
|
+
start_date: "Date de début",
|
|
1258
|
+
end_date: "Date de fin",
|
|
1259
|
+
confirmed: "Confirmé",
|
|
1260
|
+
tentative: "Provisoire",
|
|
1261
|
+
cancelled: "Annulé",
|
|
1262
|
+
todo_table: "Tâches",
|
|
1263
|
+
calendar_table: "Calendrier",
|
|
1264
|
+
workspace: "Mon agenda",
|
|
1265
|
+
board: "Agenda"
|
|
1266
|
+
},
|
|
1267
|
+
de: {
|
|
1268
|
+
title: "Titel",
|
|
1269
|
+
status: "Status",
|
|
1270
|
+
due: "Fällig",
|
|
1271
|
+
order: "Reihenfolge",
|
|
1272
|
+
done_at: "Erledigt am",
|
|
1273
|
+
ext: "Erweiterung",
|
|
1274
|
+
todo: "Offen",
|
|
1275
|
+
doing: "In Arbeit",
|
|
1276
|
+
done: "Erledigt",
|
|
1277
|
+
all_day: "Ganztägig",
|
|
1278
|
+
start: "Beginn",
|
|
1279
|
+
end: "Ende",
|
|
1280
|
+
start_date: "Startdatum",
|
|
1281
|
+
end_date: "Enddatum",
|
|
1282
|
+
confirmed: "Bestätigt",
|
|
1283
|
+
tentative: "Vorläufig",
|
|
1284
|
+
cancelled: "Abgesagt",
|
|
1285
|
+
todo_table: "Aufgaben",
|
|
1286
|
+
calendar_table: "Kalender",
|
|
1287
|
+
workspace: "Mein Terminplan",
|
|
1288
|
+
board: "Terminplan"
|
|
1289
|
+
},
|
|
1290
|
+
es: {
|
|
1291
|
+
title: "Título",
|
|
1292
|
+
status: "Estado",
|
|
1293
|
+
due: "Vencimiento",
|
|
1294
|
+
order: "Orden",
|
|
1295
|
+
done_at: "Completado el",
|
|
1296
|
+
ext: "Extensión",
|
|
1297
|
+
todo: "Pendiente",
|
|
1298
|
+
doing: "En curso",
|
|
1299
|
+
done: "Hecho",
|
|
1300
|
+
all_day: "Todo el día",
|
|
1301
|
+
start: "Inicio",
|
|
1302
|
+
end: "Fin",
|
|
1303
|
+
start_date: "Fecha de inicio",
|
|
1304
|
+
end_date: "Fecha de fin",
|
|
1305
|
+
confirmed: "Confirmado",
|
|
1306
|
+
tentative: "Provisional",
|
|
1307
|
+
cancelled: "Cancelado",
|
|
1308
|
+
todo_table: "Tareas",
|
|
1309
|
+
calendar_table: "Calendario",
|
|
1310
|
+
workspace: "Mi agenda",
|
|
1311
|
+
board: "Agenda"
|
|
1312
|
+
},
|
|
1313
|
+
ar: {
|
|
1314
|
+
title: "العنوان",
|
|
1315
|
+
status: "الحالة",
|
|
1316
|
+
due: "تاريخ الاستحقاق",
|
|
1317
|
+
order: "الترتيب",
|
|
1318
|
+
done_at: "وقت الإكمال",
|
|
1319
|
+
ext: "بيانات إضافية",
|
|
1320
|
+
todo: "قيد الانتظار",
|
|
1321
|
+
doing: "قيد التنفيذ",
|
|
1322
|
+
done: "مكتملة",
|
|
1323
|
+
all_day: "طوال اليوم",
|
|
1324
|
+
start: "البداية",
|
|
1325
|
+
end: "النهاية",
|
|
1326
|
+
start_date: "تاريخ البدء",
|
|
1327
|
+
end_date: "تاريخ الانتهاء",
|
|
1328
|
+
confirmed: "مؤكد",
|
|
1329
|
+
tentative: "مبدئي",
|
|
1330
|
+
cancelled: "ملغى",
|
|
1331
|
+
todo_table: "المهام",
|
|
1332
|
+
calendar_table: "التقويم",
|
|
1333
|
+
workspace: "جدولي",
|
|
1334
|
+
board: "الجدول"
|
|
1335
|
+
},
|
|
1336
|
+
ru: {
|
|
1337
|
+
title: "Название",
|
|
1338
|
+
status: "Статус",
|
|
1339
|
+
due: "Срок",
|
|
1340
|
+
order: "Порядок",
|
|
1341
|
+
done_at: "Выполнено",
|
|
1342
|
+
ext: "Расширение",
|
|
1343
|
+
todo: "К выполнению",
|
|
1344
|
+
doing: "В работе",
|
|
1345
|
+
done: "Готово",
|
|
1346
|
+
all_day: "Весь день",
|
|
1347
|
+
start: "Начало",
|
|
1348
|
+
end: "Конец",
|
|
1349
|
+
start_date: "Дата начала",
|
|
1350
|
+
end_date: "Дата окончания",
|
|
1351
|
+
confirmed: "Подтверждено",
|
|
1352
|
+
tentative: "Предварительно",
|
|
1353
|
+
cancelled: "Отменено",
|
|
1354
|
+
todo_table: "Задачи",
|
|
1355
|
+
calendar_table: "Календарь",
|
|
1356
|
+
workspace: "Моё расписание",
|
|
1357
|
+
board: "Расписание"
|
|
1358
|
+
}
|
|
1359
|
+
};
|
|
1360
|
+
function scheduleLabel(locale, key) {
|
|
1361
|
+
return LABELS[locale]?.[key] ?? LABELS.en[key] ?? key;
|
|
1362
|
+
}
|
|
1363
|
+
function todoFields(locale = "zh") {
|
|
1364
|
+
const l = (k) => scheduleLabel(locale, k);
|
|
1365
|
+
return [
|
|
1366
|
+
{ field_id: "title", name: l("title"), type: "text", required: true },
|
|
1367
|
+
{ field_id: "status", name: l("status"), type: "select", required: true, options: ["todo", "doing", "done"].map((id) => ({ option_id: id, label: l(id) })) },
|
|
1368
|
+
{ field_id: "due", name: l("due"), type: "date", nullable: true },
|
|
1369
|
+
{ field_id: "order", name: l("order"), type: "text", nullable: true },
|
|
1370
|
+
{ field_id: "done_at", name: l("done_at"), type: "datetime", nullable: true },
|
|
1371
|
+
{ field_id: "ext", name: l("ext"), type: "json", nullable: true }
|
|
1372
|
+
];
|
|
1373
|
+
}
|
|
1374
|
+
function calendarFields(locale = "zh") {
|
|
1375
|
+
const l = (k) => scheduleLabel(locale, k);
|
|
1376
|
+
return [
|
|
1377
|
+
{ field_id: "title", name: l("title"), type: "text", required: true },
|
|
1378
|
+
{ field_id: "all_day", name: l("all_day"), type: "boolean", nullable: true },
|
|
1379
|
+
{ field_id: "start", name: l("start"), type: "datetime", nullable: true },
|
|
1380
|
+
{ field_id: "end", name: l("end"), type: "datetime", nullable: true },
|
|
1381
|
+
{ field_id: "start_date", name: l("start_date"), type: "date", nullable: true },
|
|
1382
|
+
{ field_id: "end_date", name: l("end_date"), type: "date", nullable: true },
|
|
1383
|
+
{ field_id: "status", name: l("status"), type: "select", nullable: true, options: ["confirmed", "tentative", "cancelled"].map((id) => ({ option_id: id, label: l(id) })) },
|
|
1384
|
+
{ field_id: "ext", name: l("ext"), type: "json", nullable: true }
|
|
1385
|
+
];
|
|
1386
|
+
}
|
|
1387
|
+
function standardTableOp(kind, args) {
|
|
1388
|
+
const locale = args.locale ?? "zh";
|
|
1389
|
+
return {
|
|
1390
|
+
op: "entity.create",
|
|
1391
|
+
entity_id: args.entity_id,
|
|
1392
|
+
type_id: "buckyos.table-source",
|
|
1393
|
+
parent_id: args.parent_id,
|
|
1394
|
+
order_key: args.order_key,
|
|
1395
|
+
schema_id: kind === "todo" ? TODO_SCHEMA_ID : CALENDAR_SCHEMA_ID,
|
|
1396
|
+
name: args.name ?? scheduleLabel(locale, kind === "todo" ? "todo_table" : "calendar_table"),
|
|
1397
|
+
payload: { title_field_id: "title", fields: kind === "todo" ? todoFields(locale) : calendarFields(locale) }
|
|
1398
|
+
};
|
|
1399
|
+
}
|
|
1400
|
+
const DIGITS = "0123456789abcdefghijklmnopqrstuvwxyz";
|
|
1401
|
+
const MAX_KEY_LEN = 64;
|
|
1402
|
+
const APPEND_WIDTH = 8;
|
|
1403
|
+
function isOrderKey(k) {
|
|
1404
|
+
return typeof k === "string" && k.length > 0 && k.length <= MAX_KEY_LEN && /^[0-9a-z]+$/.test(k) && !k.endsWith("0");
|
|
1405
|
+
}
|
|
1406
|
+
function midpoint(a, b) {
|
|
1407
|
+
if (b !== null) {
|
|
1408
|
+
let n = 0;
|
|
1409
|
+
while (n < b.length && (a[n] ?? "0") === b[n])
|
|
1410
|
+
n++;
|
|
1411
|
+
if (n > 0)
|
|
1412
|
+
return b.slice(0, n) + midpoint(a.length > n ? a.slice(n) : "", b.slice(n));
|
|
1413
|
+
}
|
|
1414
|
+
const da = a.length ? DIGITS.indexOf(a[0]) : 0;
|
|
1415
|
+
const db = b !== null ? DIGITS.indexOf(b[0]) : DIGITS.length;
|
|
1416
|
+
if (db - da > 1)
|
|
1417
|
+
return DIGITS[Math.floor((da + db + 1) / 2)];
|
|
1418
|
+
if (b !== null && b.length > 1)
|
|
1419
|
+
return b[0];
|
|
1420
|
+
return DIGITS[da] + midpoint(a.length > 1 ? a.slice(1) : "", null);
|
|
1421
|
+
}
|
|
1422
|
+
function after(a) {
|
|
1423
|
+
const out = a.padEnd(Math.max(a.length, APPEND_WIDTH), "0").split("");
|
|
1424
|
+
let i = out.length - 1;
|
|
1425
|
+
while (i >= 0 && out[i] === "z")
|
|
1426
|
+
i--;
|
|
1427
|
+
if (i >= 0) {
|
|
1428
|
+
out[i] = DIGITS[DIGITS.indexOf(out[i]) + 1];
|
|
1429
|
+
for (let j = i + 1; j < out.length; j++)
|
|
1430
|
+
out[j] = "0";
|
|
1431
|
+
if (out[out.length - 1] === "0")
|
|
1432
|
+
out[out.length - 1] = "1";
|
|
1433
|
+
return out.join("");
|
|
1434
|
+
}
|
|
1435
|
+
if (out.length >= MAX_KEY_LEN)
|
|
1436
|
+
throw new Error("order key space exhausted; rebalance");
|
|
1437
|
+
const longer = out.join("").padEnd(Math.min(out.length + APPEND_WIDTH, MAX_KEY_LEN), "0");
|
|
1438
|
+
return longer.slice(0, -1) + "1";
|
|
1439
|
+
}
|
|
1440
|
+
function orderKeyBetween(a, b) {
|
|
1441
|
+
const lo = a ?? null, hi = b ?? null;
|
|
1442
|
+
if (lo !== null && hi !== null && lo >= hi)
|
|
1443
|
+
throw new Error("orderKeyBetween requires a < b");
|
|
1444
|
+
const key = lo !== null && hi === null ? after(lo) : midpoint(lo ?? "", hi);
|
|
1445
|
+
if (!isOrderKey(key))
|
|
1446
|
+
throw new Error("order key space exhausted; rebalance");
|
|
1447
|
+
return key;
|
|
1448
|
+
}
|
|
1449
|
+
let counter = 0;
|
|
1450
|
+
function newRecordId(prefix = "r") {
|
|
1451
|
+
counter = (counter + 1) % 1296;
|
|
1452
|
+
const rand = Math.floor(Math.random() * 36 ** 6).toString(36).padStart(6, "0");
|
|
1453
|
+
return `${prefix}${Date.now().toString(36)}${counter.toString(36).padStart(2, "0")}${rand}`;
|
|
1454
|
+
}
|
|
1455
|
+
function setValuesOps(sourceId, row, changes) {
|
|
1456
|
+
const set = [];
|
|
1457
|
+
const unset = [];
|
|
1458
|
+
for (const [field, value] of Object.entries(changes)) {
|
|
1459
|
+
const cell = { record_id: row.record_id, field_id: field, expect: { rev: row.revs?.[field] ?? 0 } };
|
|
1460
|
+
if (value === null || value === void 0) {
|
|
1461
|
+
if (row.values[field] !== void 0 && row.values[field] !== null)
|
|
1462
|
+
unset.push(cell);
|
|
1463
|
+
} else {
|
|
1464
|
+
set.push({ ...cell, value });
|
|
1465
|
+
}
|
|
1466
|
+
}
|
|
1467
|
+
const out = [];
|
|
1468
|
+
if (set.length)
|
|
1469
|
+
out.push({ op: "table.set_values", source_id: sourceId, values: set });
|
|
1470
|
+
if (unset.length)
|
|
1471
|
+
out.push({ op: "table.unset_values", source_id: sourceId, values: unset });
|
|
1472
|
+
return out;
|
|
1473
|
+
}
|
|
1474
|
+
function insertRecordOp(sourceId, records) {
|
|
1475
|
+
return {
|
|
1476
|
+
op: "table.insert_records",
|
|
1477
|
+
source_id: sourceId,
|
|
1478
|
+
records: records.map((r) => ({ record_id: r.record_id, values: Object.fromEntries(Object.entries(r.values).filter(([, v]) => v !== void 0 && v !== null)) }))
|
|
1479
|
+
};
|
|
1480
|
+
}
|
|
1481
|
+
function deleteRecordsOp(sourceId, rows) {
|
|
1482
|
+
return { op: "table.delete_records", source_id: sourceId, records: rows.map((r) => ({ record_id: r.record_id, expect: { rev: r.rev ?? 0 } })) };
|
|
1483
|
+
}
|
|
1484
|
+
function canonicalOriginal(x) {
|
|
1485
|
+
if (isDate(x))
|
|
1486
|
+
return x;
|
|
1487
|
+
const t = Date.parse(x);
|
|
1488
|
+
return Number.isFinite(t) ? new Date(t).toISOString() : x;
|
|
1489
|
+
}
|
|
1490
|
+
const originals = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string").map(canonicalOriginal) : [];
|
|
1491
|
+
const extOf = (row) => {
|
|
1492
|
+
const e = row?.values.ext;
|
|
1493
|
+
return e && typeof e === "object" && !Array.isArray(e) ? { ...e } : {};
|
|
1494
|
+
};
|
|
1495
|
+
function todoItem(row) {
|
|
1496
|
+
const v = row.values;
|
|
1497
|
+
const status = typeof v.status === "string" ? v.status : "todo";
|
|
1498
|
+
return {
|
|
1499
|
+
record_id: row.record_id,
|
|
1500
|
+
rev: row.rev,
|
|
1501
|
+
revs: row.revs,
|
|
1502
|
+
values: row.values,
|
|
1503
|
+
title: typeof v.title === "string" ? v.title : "",
|
|
1504
|
+
status,
|
|
1505
|
+
due: typeof v.due === "string" ? v.due : null,
|
|
1506
|
+
order: isOrderKey(v.order) ? v.order : null,
|
|
1507
|
+
done: status === TODO_DONE,
|
|
1508
|
+
done_at: typeof v.done_at === "string" ? v.done_at : null,
|
|
1509
|
+
ext: extOf(row)
|
|
1510
|
+
};
|
|
1511
|
+
}
|
|
1512
|
+
function sortTodos(items) {
|
|
1513
|
+
return [...items].sort((a, b) => a.order === b.order ? a.record_id.localeCompare(b.record_id) : a.order === null ? 1 : b.order === null ? -1 : a.order < b.order ? -1 : 1);
|
|
1514
|
+
}
|
|
1515
|
+
function todoAddOps(sourceId, input, place = {}) {
|
|
1516
|
+
const record_id = input.record_id ?? newRecordId("t");
|
|
1517
|
+
let order = input.order ?? null;
|
|
1518
|
+
if (!order) {
|
|
1519
|
+
if (place.after !== void 0 || place.before !== void 0)
|
|
1520
|
+
order = orderKeyBetween(place.after ?? null, place.before ?? null);
|
|
1521
|
+
else {
|
|
1522
|
+
const last = (place.items ?? []).map((i) => i.order).filter(isOrderKey).sort().pop() ?? null;
|
|
1523
|
+
order = orderKeyBetween(last, null);
|
|
1524
|
+
}
|
|
1525
|
+
}
|
|
1526
|
+
const status = input.status ?? "todo";
|
|
1527
|
+
const values = {
|
|
1528
|
+
title: input.title,
|
|
1529
|
+
status,
|
|
1530
|
+
order,
|
|
1531
|
+
due: input.due ?? void 0,
|
|
1532
|
+
ext: input.ext && Object.keys(input.ext).length ? input.ext : void 0,
|
|
1533
|
+
done_at: status === TODO_DONE ? input.done_at ?? (/* @__PURE__ */ new Date()).toISOString() : void 0
|
|
1534
|
+
};
|
|
1535
|
+
return { record_id, order, ops: [insertRecordOp(sourceId, [{ record_id, values }])] };
|
|
1536
|
+
}
|
|
1537
|
+
function todoCompleteOps(sourceId, row, done, opts = {}) {
|
|
1538
|
+
if (done)
|
|
1539
|
+
return setValuesOps(sourceId, row, { status: TODO_DONE, done_at: opts.now ?? (/* @__PURE__ */ new Date()).toISOString() });
|
|
1540
|
+
return setValuesOps(sourceId, row, { status: opts.reopenStatus ?? "todo", done_at: null });
|
|
1541
|
+
}
|
|
1542
|
+
function todoMoveOps(sourceId, row, to, opts = {}) {
|
|
1543
|
+
const changes = {};
|
|
1544
|
+
const was = typeof row.values.status === "string" ? row.values.status : void 0;
|
|
1545
|
+
if (to.status !== void 0 && to.status !== was) {
|
|
1546
|
+
changes.status = to.status;
|
|
1547
|
+
if (to.status === TODO_DONE)
|
|
1548
|
+
changes.done_at = opts.now ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
1549
|
+
else if (was === TODO_DONE)
|
|
1550
|
+
changes.done_at = null;
|
|
1551
|
+
}
|
|
1552
|
+
if (to.order !== void 0 && to.order !== row.values.order)
|
|
1553
|
+
changes.order = to.order;
|
|
1554
|
+
return Object.keys(changes).length ? setValuesOps(sourceId, row, changes) : [];
|
|
1555
|
+
}
|
|
1556
|
+
function todoUpdateOps(sourceId, row, changes) {
|
|
1557
|
+
const out = {};
|
|
1558
|
+
for (const k of ["title", "status", "due", "order", "done_at"])
|
|
1559
|
+
if (changes[k] !== void 0)
|
|
1560
|
+
out[k] = changes[k];
|
|
1561
|
+
if (changes.ext !== void 0)
|
|
1562
|
+
out.ext = changes.ext && Object.keys(changes.ext).length ? changes.ext : null;
|
|
1563
|
+
if (changes.ext_merge) {
|
|
1564
|
+
const ext = extOf(row);
|
|
1565
|
+
for (const [k, v] of Object.entries(changes.ext_merge))
|
|
1566
|
+
if (v === null)
|
|
1567
|
+
delete ext[k];
|
|
1568
|
+
else
|
|
1569
|
+
ext[k] = v;
|
|
1570
|
+
out.ext = Object.keys(ext).length ? ext : null;
|
|
1571
|
+
}
|
|
1572
|
+
if (out.status !== void 0 && out.status !== row.values.status && out.done_at === void 0) {
|
|
1573
|
+
if (out.status === TODO_DONE)
|
|
1574
|
+
out.done_at = (/* @__PURE__ */ new Date()).toISOString();
|
|
1575
|
+
else if (row.values.status === TODO_DONE)
|
|
1576
|
+
out.done_at = null;
|
|
1577
|
+
}
|
|
1578
|
+
return setValuesOps(sourceId, row, out);
|
|
1579
|
+
}
|
|
1580
|
+
function orderAt(items, index) {
|
|
1581
|
+
const keys = items.map((i) => i.order);
|
|
1582
|
+
const before = index > 0 ? keys[index - 1] : null;
|
|
1583
|
+
const afterKey = index < keys.length ? keys[index] : null;
|
|
1584
|
+
if (before !== null && !isOrderKey(before))
|
|
1585
|
+
return orderKeyBetween(null, null);
|
|
1586
|
+
if (afterKey !== null && isOrderKey(afterKey) && (before === null || before < afterKey))
|
|
1587
|
+
return orderKeyBetween(before, afterKey);
|
|
1588
|
+
return orderKeyBetween(before, null);
|
|
1589
|
+
}
|
|
1590
|
+
const DEFAULT_EVENT_MS = 36e5;
|
|
1591
|
+
function rowTimes(row) {
|
|
1592
|
+
const v = row.values;
|
|
1593
|
+
if (v.all_day === true) {
|
|
1594
|
+
if (typeof v.start_date !== "string" || !isDate(v.start_date))
|
|
1595
|
+
return null;
|
|
1596
|
+
const endDate = typeof v.end_date === "string" && isDate(v.end_date) && v.end_date >= v.start_date ? v.end_date : v.start_date;
|
|
1597
|
+
return { allDay: true, startDate: v.start_date, endDate };
|
|
1598
|
+
}
|
|
1599
|
+
if (typeof v.start !== "string")
|
|
1600
|
+
return null;
|
|
1601
|
+
const startMs = Date.parse(v.start);
|
|
1602
|
+
if (!Number.isFinite(startMs))
|
|
1603
|
+
return null;
|
|
1604
|
+
const end = typeof v.end === "string" ? Date.parse(v.end) : NaN;
|
|
1605
|
+
return { allDay: false, startMs, endMs: Number.isFinite(end) && end >= startMs ? end : startMs + DEFAULT_EVENT_MS };
|
|
1606
|
+
}
|
|
1607
|
+
function addDays(date, n) {
|
|
1608
|
+
return dateOf(dayOf(date) + n);
|
|
1609
|
+
}
|
|
1610
|
+
const daysBetween = (a, b) => dayOf(b) - dayOf(a);
|
|
1611
|
+
function occurrenceOf(row, times2, extra) {
|
|
1612
|
+
const ext = extOf(row);
|
|
1613
|
+
return {
|
|
1614
|
+
id: row.record_id,
|
|
1615
|
+
row,
|
|
1616
|
+
title: typeof row.values.title === "string" ? row.values.title : "",
|
|
1617
|
+
allDay: times2.allDay,
|
|
1618
|
+
startMs: times2.startMs,
|
|
1619
|
+
endMs: times2.endMs,
|
|
1620
|
+
startDate: times2.startDate,
|
|
1621
|
+
endDate: times2.endDate,
|
|
1622
|
+
status: typeof row.values.status === "string" ? row.values.status : null,
|
|
1623
|
+
ext,
|
|
1624
|
+
recurring: false,
|
|
1625
|
+
override: false,
|
|
1626
|
+
agentWritten: false,
|
|
1627
|
+
...extra
|
|
1628
|
+
};
|
|
1629
|
+
}
|
|
1630
|
+
function overlaps(o, window, viewerTz) {
|
|
1631
|
+
if (!o.allDay)
|
|
1632
|
+
return o.startMs < window.toMs && Math.max(o.endMs, o.startMs + 1) > window.fromMs;
|
|
1633
|
+
const from = localDate(window.fromMs, viewerTz), to = localDate(window.toMs - 1, viewerTz);
|
|
1634
|
+
return o.startDate <= to && o.endDate >= from;
|
|
1635
|
+
}
|
|
1636
|
+
function localDate(ms, tz) {
|
|
1637
|
+
const f = new Intl.DateTimeFormat("en-CA", { timeZone: tz, year: "numeric", month: "2-digit", day: "2-digit" });
|
|
1638
|
+
return f.format(new Date(ms));
|
|
1639
|
+
}
|
|
1640
|
+
function viewerTimeZone() {
|
|
1641
|
+
try {
|
|
1642
|
+
return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
|
|
1643
|
+
} catch {
|
|
1644
|
+
return "UTC";
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
function calendarOccurrences(rows, window, opts = {}) {
|
|
1648
|
+
const viewerTz = opts.viewerTz ?? viewerTimeZone();
|
|
1649
|
+
const out = [];
|
|
1650
|
+
const overrides = /* @__PURE__ */ new Map();
|
|
1651
|
+
for (const row of rows) {
|
|
1652
|
+
const rid = extOf(row).recurrence_id;
|
|
1653
|
+
if (rid && typeof rid === "object" && !Array.isArray(rid) && typeof rid.master === "string" && typeof rid.original === "string")
|
|
1654
|
+
overrides.set(`${rid.master}@${canonicalOriginal(rid.original)}`, row);
|
|
1655
|
+
}
|
|
1656
|
+
const byId = new Map(rows.map((r) => [r.record_id, r]));
|
|
1657
|
+
for (const row of rows) {
|
|
1658
|
+
const times2 = rowTimes(row);
|
|
1659
|
+
if (!times2)
|
|
1660
|
+
continue;
|
|
1661
|
+
const ext = extOf(row);
|
|
1662
|
+
const rid = ext.recurrence_id;
|
|
1663
|
+
if (rid && typeof rid === "object") {
|
|
1664
|
+
const master = typeof rid.master === "string" ? byId.get(rid.master) : void 0;
|
|
1665
|
+
const original = typeof rid.original === "string" ? canonicalOriginal(rid.original) : void 0;
|
|
1666
|
+
const occ2 = occurrenceOf(row, times2, { id: master && original ? occurrenceId(master.record_id, original) : row.record_id, master, original, recurring: Boolean(master), override: true });
|
|
1667
|
+
if (overlaps(occ2, window, viewerTz))
|
|
1668
|
+
out.push(occ2);
|
|
1669
|
+
continue;
|
|
1670
|
+
}
|
|
1671
|
+
const duration = times2.allDay ? daysBetween(times2.startDate, times2.endDate) : times2.endMs - times2.startMs;
|
|
1672
|
+
const shift = (o) => {
|
|
1673
|
+
const key = `${row.record_id}@${o.original}`;
|
|
1674
|
+
if (overrides.has(key))
|
|
1675
|
+
return null;
|
|
1676
|
+
if (times2.allDay)
|
|
1677
|
+
return occurrenceOf(row, { allDay: true, startDate: o.date, endDate: addDays(o.date, duration) }, { id: key, master: row, original: o.original, recurring: true });
|
|
1678
|
+
return occurrenceOf(row, { allDay: false, startMs: o.startMs, endMs: o.startMs + duration }, { id: key, master: row, original: o.original, recurring: true });
|
|
1679
|
+
};
|
|
1680
|
+
let rule = null;
|
|
1681
|
+
if (typeof ext.rrule === "string") {
|
|
1682
|
+
try {
|
|
1683
|
+
rule = parseRRule(ext.rrule);
|
|
1684
|
+
} catch {
|
|
1685
|
+
rule = null;
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
if (rule) {
|
|
1689
|
+
const start = seriesStartOf(row.values, typeof ext.tz === "string" ? ext.tz : void 0, viewerTz);
|
|
1690
|
+
if (!start)
|
|
1691
|
+
continue;
|
|
1692
|
+
const exdate = originals(ext.exdate);
|
|
1693
|
+
const occs = expandSeries(rule, start, window, { exdate, viewerTz, durationMs: times2.allDay ? void 0 : duration, durationDays: times2.allDay ? duration : void 0, limit: opts.limit, onTruncated: opts.onTruncated });
|
|
1694
|
+
for (const o of occs) {
|
|
1695
|
+
const s = shift(o);
|
|
1696
|
+
if (s)
|
|
1697
|
+
out.push(s);
|
|
1698
|
+
}
|
|
1699
|
+
continue;
|
|
1700
|
+
}
|
|
1701
|
+
if (Array.isArray(ext.occurrences) && ext.occurrences.length > 0) {
|
|
1702
|
+
const exdate = new Set(originals(ext.exdate));
|
|
1703
|
+
for (const raw of ext.occurrences) {
|
|
1704
|
+
if (typeof raw !== "string")
|
|
1705
|
+
continue;
|
|
1706
|
+
const x = canonicalOriginal(raw);
|
|
1707
|
+
if (exdate.has(x))
|
|
1708
|
+
continue;
|
|
1709
|
+
const o = times2.allDay ? { original: x, date: x } : { original: x, startMs: Date.parse(x) };
|
|
1710
|
+
if (!times2.allDay && !Number.isFinite(o.startMs))
|
|
1711
|
+
continue;
|
|
1712
|
+
if (times2.allDay && !isDate(x))
|
|
1713
|
+
continue;
|
|
1714
|
+
const s = shift(o);
|
|
1715
|
+
if (s && overlaps(s, window, viewerTz))
|
|
1716
|
+
out.push({ ...s, agentWritten: true });
|
|
1717
|
+
}
|
|
1718
|
+
continue;
|
|
1719
|
+
}
|
|
1720
|
+
const occ = occurrenceOf(row, times2, {});
|
|
1721
|
+
if (overlaps(occ, window, viewerTz))
|
|
1722
|
+
out.push(occ);
|
|
1723
|
+
}
|
|
1724
|
+
return out.sort((a, b) => sortKey(a) - sortKey(b) || a.id.localeCompare(b.id));
|
|
1725
|
+
}
|
|
1726
|
+
const sortKey = (o) => o.allDay ? Date.parse(`${o.startDate}T00:00:00Z`) : o.startMs;
|
|
1727
|
+
function eventAddOps(sourceId, input) {
|
|
1728
|
+
const record_id = input.record_id ?? newRecordId("e");
|
|
1729
|
+
const values = { title: input.title, status: input.status ?? void 0, ext: input.ext && Object.keys(input.ext).length ? input.ext : void 0 };
|
|
1730
|
+
if (input.all_day) {
|
|
1731
|
+
values.all_day = true;
|
|
1732
|
+
values.start_date = input.start_date ?? void 0;
|
|
1733
|
+
values.end_date = input.end_date && input.end_date !== input.start_date ? input.end_date : void 0;
|
|
1734
|
+
} else {
|
|
1735
|
+
values.start = input.start ?? void 0;
|
|
1736
|
+
values.end = input.end ?? void 0;
|
|
1737
|
+
}
|
|
1738
|
+
return { record_id, ops: [insertRecordOp(sourceId, [{ record_id, values }])] };
|
|
1739
|
+
}
|
|
1740
|
+
function timesChanges(times2) {
|
|
1741
|
+
return times2.allDay ? { all_day: true, start_date: times2.startDate, end_date: times2.endDate !== times2.startDate ? times2.endDate : null, start: null, end: null } : { all_day: null, start: times2.start, end: times2.end, start_date: null, end_date: null };
|
|
1742
|
+
}
|
|
1743
|
+
function overridesOf(rows, masterId) {
|
|
1744
|
+
return rows.filter((r) => {
|
|
1745
|
+
const rid = extOf(r).recurrence_id;
|
|
1746
|
+
return rid && typeof rid === "object" && rid.master === masterId;
|
|
1747
|
+
});
|
|
1748
|
+
}
|
|
1749
|
+
const isoShift = (iso, deltaMs) => new Date(Date.parse(iso) + deltaMs).toISOString();
|
|
1750
|
+
function shiftOriginal(original, allDay, deltaMs, deltaDays) {
|
|
1751
|
+
return allDay ? addDays(original, deltaDays) : isoShift(original, deltaMs);
|
|
1752
|
+
}
|
|
1753
|
+
function shiftRule(rule, deltaDays) {
|
|
1754
|
+
if (!deltaDays)
|
|
1755
|
+
return rule;
|
|
1756
|
+
const next = { ...rule };
|
|
1757
|
+
if (rule.byDay && rule.byDay.every((d) => d.ordinal === void 0) && (rule.freq === "WEEKLY" || rule.freq === "DAILY")) {
|
|
1758
|
+
next.byDay = rule.byDay.map((d) => ({ weekday: ((d.weekday + deltaDays) % 7 + 7) % 7 }));
|
|
1759
|
+
} else if (rule.byDay && rule.freq === "MONTHLY" && rule.byDay.length === 1 && rule.bySetPos === void 0 && Math.abs(deltaDays) < 7) {
|
|
1760
|
+
next.byDay = [{ ...rule.byDay[0], weekday: ((rule.byDay[0].weekday + deltaDays) % 7 + 7) % 7 }];
|
|
1761
|
+
} else if (rule.byMonthDay && rule.byMonthDay.length === 1 && rule.byMonthDay[0] > 0) {
|
|
1762
|
+
const d = rule.byMonthDay[0] + deltaDays;
|
|
1763
|
+
if (d >= 1 && d <= 28)
|
|
1764
|
+
next.byMonthDay = [d];
|
|
1765
|
+
}
|
|
1766
|
+
return next;
|
|
1767
|
+
}
|
|
1768
|
+
function eventEditOps(sourceId, occ, change, scope, ctx) {
|
|
1769
|
+
const newId = ctx.newRecordId ?? (() => newRecordId("e"));
|
|
1770
|
+
const fieldChanges = (row) => {
|
|
1771
|
+
const out = { ...change.values };
|
|
1772
|
+
if (change.ext_merge) {
|
|
1773
|
+
const ext = extOf(row);
|
|
1774
|
+
for (const [k, v] of Object.entries(change.ext_merge))
|
|
1775
|
+
if (v === null)
|
|
1776
|
+
delete ext[k];
|
|
1777
|
+
else
|
|
1778
|
+
ext[k] = v;
|
|
1779
|
+
out.ext = Object.keys(ext).length ? ext : null;
|
|
1780
|
+
}
|
|
1781
|
+
return out;
|
|
1782
|
+
};
|
|
1783
|
+
const master = occ.master;
|
|
1784
|
+
if (!master || occ.row !== master && scope === "one") {
|
|
1785
|
+
const row = occ.row;
|
|
1786
|
+
const changes = { ...fieldChanges(row), ...change.times ? timesChanges(change.times) : {} };
|
|
1787
|
+
if (change.rrule !== void 0 && !master) {
|
|
1788
|
+
const ext = changes.ext ?? extOf(row);
|
|
1789
|
+
const next = { ...ext ?? {} };
|
|
1790
|
+
if (change.rrule === null)
|
|
1791
|
+
delete next.rrule;
|
|
1792
|
+
else
|
|
1793
|
+
next.rrule = formatRRule(parseRRule(change.rrule));
|
|
1794
|
+
if (change.rrule === null)
|
|
1795
|
+
delete next.exdate;
|
|
1796
|
+
changes.ext = Object.keys(next).length ? next : null;
|
|
1797
|
+
}
|
|
1798
|
+
return { ops: setValuesOps(sourceId, row, changes), record_id: row.record_id };
|
|
1799
|
+
}
|
|
1800
|
+
const original = occ.original;
|
|
1801
|
+
const masterTimes = rowTimes(master);
|
|
1802
|
+
const masterExt = extOf(master);
|
|
1803
|
+
if (scope === "one") {
|
|
1804
|
+
const id2 = newId();
|
|
1805
|
+
const ext = { ...masterExt, recurrence_id: { master: master.record_id, original } };
|
|
1806
|
+
delete ext.rrule;
|
|
1807
|
+
delete ext.exdate;
|
|
1808
|
+
delete ext.occurrences;
|
|
1809
|
+
delete ext.rule_text;
|
|
1810
|
+
delete ext.covered_until;
|
|
1811
|
+
delete ext.maintenance;
|
|
1812
|
+
const base = { title: master.values.title, status: master.values.status, ext };
|
|
1813
|
+
const times22 = change.times ?? (occ.allDay ? { allDay: true, startDate: occ.startDate, endDate: addDays(occ.startDate, daysBetween(masterTimes.startDate, masterTimes.endDate)) } : { allDay: false, start: new Date(occ.startMs).toISOString(), end: new Date(occ.startMs + (masterTimes.endMs - masterTimes.startMs)).toISOString() });
|
|
1814
|
+
const values2 = { ...base, ...fieldChanges({ record_id: id2, values: { ext } }), ...timesChanges(times22) };
|
|
1815
|
+
if (!values2.ext)
|
|
1816
|
+
values2.ext = ext;
|
|
1817
|
+
return { ops: [insertRecordOp(sourceId, [{ record_id: id2, values: values2 }])], record_id: id2 };
|
|
1818
|
+
}
|
|
1819
|
+
let deltaMs = 0, deltaDays = 0;
|
|
1820
|
+
let durationMs = masterTimes.allDay ? 0 : masterTimes.endMs - masterTimes.startMs;
|
|
1821
|
+
let durationDays = masterTimes.allDay ? daysBetween(masterTimes.startDate, masterTimes.endDate) : 0;
|
|
1822
|
+
if (change.times) {
|
|
1823
|
+
if (change.times.allDay !== masterTimes.allDay)
|
|
1824
|
+
throw new Error("changing a series between all-day and timed: edit the series itself (scope all) with new times");
|
|
1825
|
+
if (change.times.allDay) {
|
|
1826
|
+
deltaDays = daysBetween(original, change.times.startDate);
|
|
1827
|
+
durationDays = daysBetween(change.times.startDate, change.times.endDate);
|
|
1828
|
+
} else {
|
|
1829
|
+
deltaMs = Date.parse(change.times.start) - Date.parse(original);
|
|
1830
|
+
deltaDays = Math.round(deltaMs / 864e5);
|
|
1831
|
+
durationMs = Date.parse(change.times.end) - Date.parse(change.times.start);
|
|
1832
|
+
}
|
|
1833
|
+
}
|
|
1834
|
+
const rule = typeof masterExt.rrule === "string" ? parseRRule(masterExt.rrule) : null;
|
|
1835
|
+
const overrides = overridesOf(ctx.rows, master.record_id);
|
|
1836
|
+
const exdate = originals(masterExt.exdate);
|
|
1837
|
+
const isFirst = masterTimes.allDay ? original === masterTimes.startDate : original === new Date(masterTimes.startMs).toISOString();
|
|
1838
|
+
const seriesTimes = (startMs, startDate) => masterTimes.allDay ? { allDay: true, startDate: addDays(startDate, deltaDays), endDate: addDays(addDays(startDate, deltaDays), durationDays) } : { allDay: false, start: new Date(startMs + deltaMs).toISOString(), end: new Date(startMs + deltaMs + durationMs).toISOString() };
|
|
1839
|
+
const nextRule = (r) => {
|
|
1840
|
+
if (change.rrule !== void 0)
|
|
1841
|
+
return change.rrule === null ? null : formatRRule(parseRRule(change.rrule));
|
|
1842
|
+
return r ? formatRRule(shiftRule(r, deltaDays)) : null;
|
|
1843
|
+
};
|
|
1844
|
+
const ops = [];
|
|
1845
|
+
if (scope === "all" || isFirst) {
|
|
1846
|
+
const times22 = seriesTimes(masterTimes.startMs, masterTimes.startDate);
|
|
1847
|
+
const ext = { ...masterExt };
|
|
1848
|
+
const r = nextRule(rule);
|
|
1849
|
+
if (r)
|
|
1850
|
+
ext.rrule = r;
|
|
1851
|
+
else {
|
|
1852
|
+
delete ext.rrule;
|
|
1853
|
+
delete ext.exdate;
|
|
1854
|
+
}
|
|
1855
|
+
if (r && exdate.length)
|
|
1856
|
+
ext.exdate = exdate.map((x) => shiftOriginal(x, masterTimes.allDay, deltaMs, deltaDays));
|
|
1857
|
+
const fc2 = fieldChanges({ record_id: master.record_id, values: { ext } });
|
|
1858
|
+
const extOut = fc2.ext !== void 0 ? fc2.ext : ext;
|
|
1859
|
+
ops.push(...setValuesOps(sourceId, master, { ...fc2, ...timesChanges(times22), ext: extOut && Object.keys(extOut).length ? extOut : null }));
|
|
1860
|
+
for (const o of overrides) {
|
|
1861
|
+
const oext = extOf(o);
|
|
1862
|
+
const rid = oext.recurrence_id;
|
|
1863
|
+
if (!r) {
|
|
1864
|
+
ops.push(deleteRecordsOp(sourceId, [o]));
|
|
1865
|
+
continue;
|
|
1866
|
+
}
|
|
1867
|
+
if (deltaMs || deltaDays)
|
|
1868
|
+
ops.push(...setValuesOps(sourceId, o, { ext: { ...oext, recurrence_id: { ...rid, original: shiftOriginal(String(rid.original), masterTimes.allDay, deltaMs, deltaDays) } } }));
|
|
1869
|
+
}
|
|
1870
|
+
return { ops, record_id: master.record_id };
|
|
1871
|
+
}
|
|
1872
|
+
if (!rule)
|
|
1873
|
+
throw new Error("not a repeating event");
|
|
1874
|
+
const id = newId();
|
|
1875
|
+
const before = (x) => masterTimes.allDay ? x < original : Date.parse(x) < Date.parse(original);
|
|
1876
|
+
let headRule = { ...rule };
|
|
1877
|
+
let tailRule = { ...rule };
|
|
1878
|
+
if (rule.count !== void 0) {
|
|
1879
|
+
const start = seriesStartOf(master.values, typeof masterExt.tz === "string" ? masterExt.tz : void 0);
|
|
1880
|
+
const fromMs = masterTimes.allDay ? Date.parse(`${masterTimes.startDate}T00:00:00Z`) - 864e5 * 2 : masterTimes.startMs;
|
|
1881
|
+
const toMs = masterTimes.allDay ? Date.parse(`${original}T00:00:00Z`) : Date.parse(original);
|
|
1882
|
+
const done = expandSeries(rule, start, { fromMs, toMs }, { viewerTz: "UTC" }).filter((o) => before(o.original)).length;
|
|
1883
|
+
headRule = { ...rule, count: Math.max(1, done) };
|
|
1884
|
+
tailRule = { ...rule, count: Math.max(1, rule.count - done) };
|
|
1885
|
+
} else {
|
|
1886
|
+
headRule = { ...rule, until: masterTimes.allDay ? addDays(original, -1) : new Date(Date.parse(original) - 1e3).toISOString().replace(/\.\d{3}Z$/, ".000Z") };
|
|
1887
|
+
}
|
|
1888
|
+
const headExt = { ...masterExt, rrule: formatRRule(headRule) };
|
|
1889
|
+
const headEx = exdate.filter(before);
|
|
1890
|
+
if (headEx.length)
|
|
1891
|
+
headExt.exdate = headEx;
|
|
1892
|
+
else
|
|
1893
|
+
delete headExt.exdate;
|
|
1894
|
+
ops.push(...setValuesOps(sourceId, master, { ext: headExt }));
|
|
1895
|
+
const tailExt = { ...masterExt };
|
|
1896
|
+
const tr = nextRule(tailRule);
|
|
1897
|
+
if (tr)
|
|
1898
|
+
tailExt.rrule = tr;
|
|
1899
|
+
else
|
|
1900
|
+
delete tailExt.rrule;
|
|
1901
|
+
const tailEx = exdate.filter((x) => !before(x)).map((x) => shiftOriginal(x, masterTimes.allDay, deltaMs, deltaDays));
|
|
1902
|
+
if (tailEx.length && tr)
|
|
1903
|
+
tailExt.exdate = tailEx;
|
|
1904
|
+
else
|
|
1905
|
+
delete tailExt.exdate;
|
|
1906
|
+
const times2 = seriesTimes(masterTimes.allDay ? void 0 : Date.parse(original), masterTimes.allDay ? original : void 0);
|
|
1907
|
+
const fc = fieldChanges({ record_id: id, values: { ext: tailExt } });
|
|
1908
|
+
const values = { title: master.values.title, status: master.values.status, ...fc, ...timesChanges(times2) };
|
|
1909
|
+
values.ext = (fc.ext !== void 0 ? fc.ext : tailExt) ?? void 0;
|
|
1910
|
+
ops.push(insertRecordOp(sourceId, [{ record_id: id, values }]));
|
|
1911
|
+
for (const o of overrides) {
|
|
1912
|
+
const oext = extOf(o);
|
|
1913
|
+
const rid = oext.recurrence_id;
|
|
1914
|
+
if (before(String(rid.original)))
|
|
1915
|
+
continue;
|
|
1916
|
+
if (!tr) {
|
|
1917
|
+
ops.push(deleteRecordsOp(sourceId, [o]));
|
|
1918
|
+
continue;
|
|
1919
|
+
}
|
|
1920
|
+
ops.push(...setValuesOps(sourceId, o, { ext: { ...oext, recurrence_id: { master: id, original: shiftOriginal(String(rid.original), masterTimes.allDay, deltaMs, deltaDays) } } }));
|
|
1921
|
+
}
|
|
1922
|
+
return { ops, record_id: id };
|
|
1923
|
+
}
|
|
1924
|
+
function eventDeleteOps(sourceId, occ, scope, ctx) {
|
|
1925
|
+
const master = occ.master;
|
|
1926
|
+
if (!master)
|
|
1927
|
+
return [deleteRecordsOp(sourceId, [occ.row])];
|
|
1928
|
+
const original = occ.original;
|
|
1929
|
+
const masterExt = extOf(master);
|
|
1930
|
+
const masterTimes = rowTimes(master);
|
|
1931
|
+
const overrides = overridesOf(ctx.rows, master.record_id);
|
|
1932
|
+
const isFirst = masterTimes.allDay ? original === masterTimes.startDate : original === new Date(masterTimes.startMs).toISOString();
|
|
1933
|
+
if (scope === "all" || scope === "following" && isFirst)
|
|
1934
|
+
return [deleteRecordsOp(sourceId, [master, ...overrides])];
|
|
1935
|
+
const ops = [];
|
|
1936
|
+
if (scope === "one") {
|
|
1937
|
+
const exdate = originals(masterExt.exdate);
|
|
1938
|
+
if (!exdate.includes(original))
|
|
1939
|
+
ops.push(...setValuesOps(sourceId, master, { ext: { ...masterExt, exdate: [...exdate, original].sort() } }));
|
|
1940
|
+
const own = overrides.filter((o) => canonicalOriginal(String(extOf(o).recurrence_id.original)) === original);
|
|
1941
|
+
if (own.length)
|
|
1942
|
+
ops.push(deleteRecordsOp(sourceId, own));
|
|
1943
|
+
return ops;
|
|
1944
|
+
}
|
|
1945
|
+
const rule = typeof masterExt.rrule === "string" ? parseRRule(masterExt.rrule) : null;
|
|
1946
|
+
if (!rule)
|
|
1947
|
+
return [deleteRecordsOp(sourceId, [occ.row])];
|
|
1948
|
+
const before = (x) => masterTimes.allDay ? x < original : Date.parse(x) < Date.parse(original);
|
|
1949
|
+
const head = { ...rule, count: void 0, until: masterTimes.allDay ? addDays(original, -1) : new Date(Date.parse(original) - 1e3).toISOString() };
|
|
1950
|
+
const ext = { ...masterExt, rrule: formatRRule(head) };
|
|
1951
|
+
if (Array.isArray(masterExt.exdate)) {
|
|
1952
|
+
const keep = originals(masterExt.exdate).filter(before);
|
|
1953
|
+
if (keep.length)
|
|
1954
|
+
ext.exdate = keep;
|
|
1955
|
+
else
|
|
1956
|
+
delete ext.exdate;
|
|
1957
|
+
}
|
|
1958
|
+
ops.push(...setValuesOps(sourceId, master, { ext }));
|
|
1959
|
+
const gone = overrides.filter((o) => !before(String(extOf(o).recurrence_id.original)));
|
|
1960
|
+
if (gone.length)
|
|
1961
|
+
ops.push(deleteRecordsOp(sourceId, gone));
|
|
1962
|
+
return ops;
|
|
1963
|
+
}
|
|
1964
|
+
function eventPostponeOps(sourceId, occ, minutes, ctx) {
|
|
1965
|
+
const times2 = occ.allDay ? { allDay: true, startDate: addDays(occ.startDate, Math.max(1, Math.round(minutes / 1440))), endDate: addDays(occ.endDate, Math.max(1, Math.round(minutes / 1440))) } : { allDay: false, start: new Date(occ.startMs + minutes * 6e4).toISOString(), end: new Date(occ.endMs + minutes * 6e4).toISOString() };
|
|
1966
|
+
return eventEditOps(sourceId, occ, { times: times2 }, "one", ctx);
|
|
1967
|
+
}
|
|
1968
|
+
const ROWS_PAGE = 1e3;
|
|
1969
|
+
class ScheduleClient {
|
|
1970
|
+
constructor(aiws, opts = {}) {
|
|
1971
|
+
this.aiws = aiws;
|
|
1972
|
+
this.opts = opts;
|
|
1973
|
+
this.handle = null;
|
|
1974
|
+
this.locale = opts.locale ?? "zh";
|
|
1975
|
+
}
|
|
1976
|
+
/** The schedule Workspace with its two tables (created when missing; concurrent first uses converge). */
|
|
1977
|
+
async ensure() {
|
|
1978
|
+
if (this.handle)
|
|
1979
|
+
return this.handle;
|
|
1980
|
+
const ws = await this.aiws.call("ws.ensure", { name: SCHEDULE_WORKSPACE_NAME, title: scheduleLabel(this.locale, "workspace") });
|
|
1981
|
+
return this.open(ws, true);
|
|
1982
|
+
}
|
|
1983
|
+
async open(ws, initialize = false) {
|
|
1984
|
+
const handle = { workspace_id: ws.workspace_id, epoch: ws.epoch, created: ws.created ?? false, todo: SCHEDULE_TODO_ID, calendar: SCHEDULE_CALENDAR_ID };
|
|
1985
|
+
if (!initialize) {
|
|
1986
|
+
this.handle = handle;
|
|
1987
|
+
return handle;
|
|
1988
|
+
}
|
|
1989
|
+
const have = /* @__PURE__ */ new Set();
|
|
1990
|
+
for (const id of [SCHEDULE_TODO_ID, SCHEDULE_CALENDAR_ID, SCHEDULE_SURFACE_ID]) {
|
|
1991
|
+
try {
|
|
1992
|
+
const read = await this.aiws.call("doc.read", { workspace_id: ws.workspace_id, entity_id: id, as: "meta" });
|
|
1993
|
+
const schema = id === SCHEDULE_TODO_ID ? TODO_SCHEMA_ID : id === SCHEDULE_CALENDAR_ID ? CALENDAR_SCHEMA_ID : void 0;
|
|
1994
|
+
if (schema && read.schema_id !== schema)
|
|
1995
|
+
throw new AiwsFailure({ code: "RESOURCE_TYPE_MISMATCH", detail: id + " is not the expected schedule table", retryable: false });
|
|
1996
|
+
if (!read.deleted)
|
|
1997
|
+
have.add(id);
|
|
1998
|
+
} catch (error) {
|
|
1999
|
+
const code = error?.code;
|
|
2000
|
+
if (code !== "NOT_FOUND" && code !== "TARGET_DELETED")
|
|
2001
|
+
throw error;
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
2004
|
+
const ops = [];
|
|
2005
|
+
if (!have.has(SCHEDULE_TODO_ID))
|
|
2006
|
+
ops.push(standardTableOp("todo", { entity_id: SCHEDULE_TODO_ID, parent_id: "data", order_key: "u", locale: this.locale }));
|
|
2007
|
+
if (!have.has(SCHEDULE_CALENDAR_ID))
|
|
2008
|
+
ops.push(standardTableOp("calendar", { entity_id: SCHEDULE_CALENDAR_ID, parent_id: "data", order_key: "v", locale: this.locale }));
|
|
2009
|
+
if (!have.has(SCHEDULE_SURFACE_ID))
|
|
2010
|
+
ops.push(...scheduleBoardOps(this.locale));
|
|
2011
|
+
if (ops.length) {
|
|
2012
|
+
const initKey = `init-${this.opts.idempotencyKey ?? newRecordId("k")}`;
|
|
2013
|
+
const result = await this.commitTo(handle, ops, "create the schedule", "system", initKey);
|
|
2014
|
+
const idConflict = (result.sub_code ?? result.errors?.[0]?.sub_code ?? result.error?.sub_code) === "ID_CONFLICT";
|
|
2015
|
+
if (result.status !== "accepted") {
|
|
2016
|
+
if (!(result.status === "rejected" && idConflict))
|
|
2017
|
+
throw failureOf(result);
|
|
2018
|
+
for (const id of [SCHEDULE_TODO_ID, SCHEDULE_CALENDAR_ID, SCHEDULE_SURFACE_ID]) {
|
|
2019
|
+
const meta = await this.aiws.call("doc.read", { workspace_id: ws.workspace_id, entity_id: id, as: "meta" });
|
|
2020
|
+
if (id !== SCHEDULE_SURFACE_ID && meta.schema_id !== (id === SCHEDULE_TODO_ID ? TODO_SCHEMA_ID : CALENDAR_SCHEMA_ID))
|
|
2021
|
+
throw failureOf(result);
|
|
2022
|
+
}
|
|
2023
|
+
}
|
|
2024
|
+
}
|
|
2025
|
+
this.handle = handle;
|
|
2026
|
+
return handle;
|
|
2027
|
+
}
|
|
2028
|
+
async commitTo(handle, operations, message, origin = "agent", key = this.opts.idempotencyKey ?? `sched-${newRecordId("k")}`) {
|
|
2029
|
+
const request = (epoch) => ({ protocol_version: AIWS_PROTOCOL_VERSION, workspace_id: handle.workspace_id, epoch, idempotency_key: key, origin, message, operations });
|
|
2030
|
+
let result = await this.aiws.call("doc.commit", request(handle.epoch));
|
|
2031
|
+
if (result.status === "rejected" && (result.code ?? result.error?.code) === "EPOCH_MISMATCH") {
|
|
2032
|
+
if (this.opts.idempotencyKey)
|
|
2033
|
+
throw new AiwsFailure({ code: "WRITE_OUTCOME_UNKNOWN", retryable: false, detail: "original workspace epoch changed", data: { workspace_id: handle.workspace_id, idempotency_key: key } });
|
|
2034
|
+
const info = await this.aiws.call("ws.get_info", { workspace_id: handle.workspace_id });
|
|
2035
|
+
handle.epoch = info.epoch;
|
|
2036
|
+
result = await this.aiws.call("doc.commit", request(handle.epoch));
|
|
2037
|
+
}
|
|
2038
|
+
return result;
|
|
2039
|
+
}
|
|
2040
|
+
/** Commit operations into the schedule; a refusal or conflict throws with the service's reason. */
|
|
2041
|
+
async commit(operations, message) {
|
|
2042
|
+
const handle = await this.ensure();
|
|
2043
|
+
const result = await this.commitTo(handle, operations, message);
|
|
2044
|
+
if (result.status !== "accepted")
|
|
2045
|
+
throw failureOf(result);
|
|
2046
|
+
return result;
|
|
2047
|
+
}
|
|
2048
|
+
/** Every live record of a table, as `doc.read` answers one (the SQL `_record` column), by record id. */
|
|
2049
|
+
async rows(sourceId) {
|
|
2050
|
+
const handle = await this.ensure();
|
|
2051
|
+
const rows = [];
|
|
2052
|
+
for (let i = 0; ; i++) {
|
|
2053
|
+
const page = await this.aiws.call("doc.query", {
|
|
2054
|
+
workspace_id: handle.workspace_id,
|
|
2055
|
+
sql: 'SELECT "_record" FROM t ORDER BY "_id" LIMIT ? OFFSET ?',
|
|
2056
|
+
params: [ROWS_PAGE, i * ROWS_PAGE],
|
|
2057
|
+
tables: { t: sourceId },
|
|
2058
|
+
max_rows: ROWS_PAGE
|
|
2059
|
+
});
|
|
2060
|
+
for (const [record] of page.rows)
|
|
2061
|
+
rows.push(typeof record === "string" ? JSON.parse(record) : record);
|
|
2062
|
+
if (page.rows.length < ROWS_PAGE)
|
|
2063
|
+
break;
|
|
2064
|
+
}
|
|
2065
|
+
return rows;
|
|
2066
|
+
}
|
|
2067
|
+
async row(sourceId, recordId) {
|
|
2068
|
+
const handle = await this.ensure();
|
|
2069
|
+
const r = await this.aiws.call("doc.read", { workspace_id: handle.workspace_id, entity_id: sourceId, selector: { kind: "table_record", record_id: recordId } });
|
|
2070
|
+
const row = r.content;
|
|
2071
|
+
if (!row?.record_id)
|
|
2072
|
+
throw new AiwsFailure({ code: "NOT_FOUND", retryable: false, detail: `record ${recordId} not found` });
|
|
2073
|
+
return row;
|
|
2074
|
+
}
|
|
2075
|
+
// ---- to-do
|
|
2076
|
+
async todos(opts = {}) {
|
|
2077
|
+
const items = sortTodos((await this.rows(SCHEDULE_TODO_ID)).map(todoItem));
|
|
2078
|
+
return opts.includeDone ? items : items.filter((i) => !i.done);
|
|
2079
|
+
}
|
|
2080
|
+
async addTodo(input, place = {}) {
|
|
2081
|
+
const items = sortTodos((await this.rows(SCHEDULE_TODO_ID)).map(todoItem));
|
|
2082
|
+
const at = (id) => items.find((i) => i.record_id === id);
|
|
2083
|
+
if (place.after && !at(place.after) || place.before && !at(place.before))
|
|
2084
|
+
throw new AiwsFailure({ code: "NOT_FOUND", retryable: false, detail: "placement anchor does not exist" });
|
|
2085
|
+
let pos = { items };
|
|
2086
|
+
if (place.after) {
|
|
2087
|
+
const i = items.findIndex((x) => x.record_id === place.after);
|
|
2088
|
+
pos = { after: at(place.after)?.order ?? null, before: items[i + 1]?.order ?? null };
|
|
2089
|
+
} else if (place.before) {
|
|
2090
|
+
const i = items.findIndex((x) => x.record_id === place.before);
|
|
2091
|
+
pos = { after: items[i - 1]?.order ?? null, before: at(place.before)?.order ?? null };
|
|
2092
|
+
}
|
|
2093
|
+
const { record_id, ops } = todoAddOps(SCHEDULE_TODO_ID, input, pos);
|
|
2094
|
+
await this.commit(ops, `add to-do: ${input.title}`);
|
|
2095
|
+
return todoItem(await this.row(SCHEDULE_TODO_ID, record_id));
|
|
2096
|
+
}
|
|
2097
|
+
async commitRowChange(source, row, ops, message, field = "title") {
|
|
2098
|
+
if (!ops.length && this.opts.idempotencyKey) {
|
|
2099
|
+
ops = setValuesOps(source, row, { [field]: row.values[field] ?? (field === "status" ? "todo" : row.values.title) });
|
|
2100
|
+
}
|
|
2101
|
+
if (ops.length)
|
|
2102
|
+
await this.commit(ops, message);
|
|
2103
|
+
}
|
|
2104
|
+
async completeTodo(recordId, done = true) {
|
|
2105
|
+
const row = await this.row(SCHEDULE_TODO_ID, recordId);
|
|
2106
|
+
const ops = todoCompleteOps(SCHEDULE_TODO_ID, row, done);
|
|
2107
|
+
await this.commitRowChange(SCHEDULE_TODO_ID, row, ops, `${done ? "complete" : "reopen"} to-do ${recordId}`, "status");
|
|
2108
|
+
}
|
|
2109
|
+
async updateTodo(recordId, changes) {
|
|
2110
|
+
const row = await this.row(SCHEDULE_TODO_ID, recordId);
|
|
2111
|
+
const ops = todoUpdateOps(SCHEDULE_TODO_ID, row, changes);
|
|
2112
|
+
await this.commitRowChange(SCHEDULE_TODO_ID, row, ops, `update to-do ${recordId}`);
|
|
2113
|
+
}
|
|
2114
|
+
/** Move a to-do before / after another one, and / or into another status. */
|
|
2115
|
+
async moveTodo(recordId, to) {
|
|
2116
|
+
const items = sortTodos((await this.rows(SCHEDULE_TODO_ID)).map(todoItem));
|
|
2117
|
+
const row = items.find((i) => i.record_id === recordId);
|
|
2118
|
+
if (!row)
|
|
2119
|
+
throw new AiwsFailure({ code: "NOT_FOUND", retryable: false, detail: `to-do ${recordId} not found` });
|
|
2120
|
+
const others = items.filter((i) => i.record_id !== recordId);
|
|
2121
|
+
let order;
|
|
2122
|
+
if (to.before || to.after) {
|
|
2123
|
+
const anchor = others.findIndex((i) => i.record_id === (to.before ?? to.after));
|
|
2124
|
+
if (anchor < 0)
|
|
2125
|
+
throw new AiwsFailure({ code: "NOT_FOUND", retryable: false, detail: `to-do ${to.before ?? to.after} not found` });
|
|
2126
|
+
order = orderAt(others, to.before ? anchor : anchor + 1);
|
|
2127
|
+
}
|
|
2128
|
+
const ops = todoMoveOps(SCHEDULE_TODO_ID, row, { status: to.status, order });
|
|
2129
|
+
await this.commitRowChange(SCHEDULE_TODO_ID, row, ops, `move to-do ${recordId}`, "status");
|
|
2130
|
+
}
|
|
2131
|
+
async removeTodos(recordIds) {
|
|
2132
|
+
const rows = await Promise.all(recordIds.map((id) => this.row(SCHEDULE_TODO_ID, id)));
|
|
2133
|
+
await this.commit([deleteRecordsOp(SCHEDULE_TODO_ID, rows)], `delete to-do ${recordIds.join(", ")}`);
|
|
2134
|
+
}
|
|
2135
|
+
// ---- calendar
|
|
2136
|
+
async events(window, opts = {}) {
|
|
2137
|
+
return calendarOccurrences(await this.rows(SCHEDULE_CALENDAR_ID), window, opts);
|
|
2138
|
+
}
|
|
2139
|
+
async addEvent(input) {
|
|
2140
|
+
if (input.ext?.rrule !== void 0 && typeof input.ext.rrule === "string")
|
|
2141
|
+
input = { ...input, ext: { ...input.ext, rrule: formatRRule(parseRRule(input.ext.rrule)) } };
|
|
2142
|
+
const { record_id, ops } = eventAddOps(SCHEDULE_CALENDAR_ID, input);
|
|
2143
|
+
await this.commit(ops, `add event: ${input.title}`);
|
|
2144
|
+
return record_id;
|
|
2145
|
+
}
|
|
2146
|
+
/** The occurrence an id names (`record_id` or `<master>@<original>`), from all rows. */
|
|
2147
|
+
async occurrence(id) {
|
|
2148
|
+
const rows = await this.rows(SCHEDULE_CALENDAR_ID);
|
|
2149
|
+
return { occ: findOccurrence(rows, id), rows };
|
|
2150
|
+
}
|
|
2151
|
+
async editEvent(id, change, scope = "one") {
|
|
2152
|
+
const { occ, rows } = await this.occurrence(id);
|
|
2153
|
+
const { ops, record_id } = eventEditOps(SCHEDULE_CALENDAR_ID, occ, change, scope, { rows, newRecordId: this.opts.newRecordId });
|
|
2154
|
+
await this.commitRowChange(SCHEDULE_CALENDAR_ID, occ.row, ops, `edit event ${id} (${scope})`);
|
|
2155
|
+
return record_id;
|
|
2156
|
+
}
|
|
2157
|
+
async deleteEvent(id, scope = "one") {
|
|
2158
|
+
const { occ, rows } = await this.occurrence(id);
|
|
2159
|
+
await this.commit(eventDeleteOps(SCHEDULE_CALENDAR_ID, occ, scope, { rows }), `delete event ${id} (${scope})`);
|
|
2160
|
+
}
|
|
2161
|
+
}
|
|
2162
|
+
function failureOf(result) {
|
|
2163
|
+
const first = result.errors?.[0];
|
|
2164
|
+
if (result.status === "conflict") {
|
|
2165
|
+
const c = result.conflicts?.[0];
|
|
2166
|
+
return new AiwsFailure({ code: result.code ?? "REVISION_CONFLICT", retryable: true, detail: `changed meanwhile, read it again${c ? `: ${JSON.stringify(c.selector ?? c)}` : ""}` });
|
|
2167
|
+
}
|
|
2168
|
+
return new AiwsFailure({ code: result.code ?? result.error?.code ?? "REJECTED", sub_code: result.sub_code ?? first?.sub_code, retryable: false, detail: first?.detail ?? result.detail ?? result.error?.detail ?? "refused" });
|
|
2169
|
+
}
|
|
2170
|
+
function findOccurrence(rows, id) {
|
|
2171
|
+
const at = id.indexOf("@");
|
|
2172
|
+
const recordId = at < 0 ? id : id.slice(0, at);
|
|
2173
|
+
const original = at < 0 ? null : canonicalOriginal(id.slice(at + 1));
|
|
2174
|
+
const row = rows.find((r) => r.record_id === recordId);
|
|
2175
|
+
if (!row)
|
|
2176
|
+
throw new AiwsFailure({ code: "NOT_FOUND", retryable: false, detail: `event ${recordId} not found` });
|
|
2177
|
+
if (original === null) {
|
|
2178
|
+
const times22 = rowTimes(row);
|
|
2179
|
+
if (!times22)
|
|
2180
|
+
throw new AiwsFailure({ code: "INVALID_OPERATION", retryable: false, detail: `event ${recordId} has no time` });
|
|
2181
|
+
const ext = extOf(row);
|
|
2182
|
+
const rid = ext.recurrence_id;
|
|
2183
|
+
const master = rid && typeof rid.master === "string" ? rows.find((r) => r.record_id === rid.master) : void 0;
|
|
2184
|
+
return occurrenceOf(row, times22, master ? { master, original: String(rid.original), recurring: true, override: true } : { recurring: typeof ext.rrule === "string", master: typeof ext.rrule === "string" ? row : void 0, original: typeof ext.rrule === "string" ? times22.allDay ? times22.startDate : new Date(times22.startMs).toISOString() : void 0 });
|
|
2185
|
+
}
|
|
2186
|
+
const override = rows.find((r) => {
|
|
2187
|
+
const rid = extOf(r).recurrence_id;
|
|
2188
|
+
return rid && rid.master === recordId && typeof rid.original === "string" && canonicalOriginal(rid.original) === canonicalOriginal(original);
|
|
2189
|
+
});
|
|
2190
|
+
const times2 = rowTimes(row);
|
|
2191
|
+
if (!times2)
|
|
2192
|
+
throw new AiwsFailure({ code: "INVALID_OPERATION", retryable: false, detail: `event ${recordId} has no time` });
|
|
2193
|
+
if (override)
|
|
2194
|
+
return occurrenceOf(override, rowTimes(override), { id, master: row, original, recurring: true, override: true });
|
|
2195
|
+
const fromMs = Date.parse(times2.allDay ? original + "T00:00:00Z" : original);
|
|
2196
|
+
const instance = Number.isFinite(fromMs) && calendarOccurrences([row], { fromMs, toMs: fromMs + 1 }, { viewerTz: "UTC" }).find((o) => o.original === original);
|
|
2197
|
+
if (!instance)
|
|
2198
|
+
throw new AiwsFailure({ code: "NOT_FOUND", retryable: false, detail: "occurrence is outside the series or was removed" });
|
|
2199
|
+
return instance;
|
|
2200
|
+
}
|
|
2201
|
+
function scheduleBoardOps(locale = "zh") {
|
|
2202
|
+
const folder = `${SCHEDULE_SURFACE_ID}-content`;
|
|
2203
|
+
const title = scheduleLabel(locale, "board");
|
|
2204
|
+
return [
|
|
2205
|
+
{ op: "entity.create", entity_id: folder, type_id: "buckyos.container", parent_id: "canvas-content", order_key: "u", name: title, payload: { kind: "folder", title, system: "surface_content", surface_id: SCHEDULE_SURFACE_ID } },
|
|
2206
|
+
{ op: "entity.create", entity_id: SCHEDULE_SURFACE_ID, type_id: "buckyos.container", parent_id: "surfaces", order_key: "a", name: title, payload: { kind: "surface", layout: { mode: "free" }, title, content_folder_id: folder } },
|
|
2207
|
+
{
|
|
2208
|
+
op: "entity.create",
|
|
2209
|
+
entity_id: `${SCHEDULE_SURFACE_ID}-calendar`,
|
|
2210
|
+
type_id: "buckyos.container",
|
|
2211
|
+
parent_id: SCHEDULE_SURFACE_ID,
|
|
2212
|
+
order_key: "a",
|
|
2213
|
+
placement: { x: 40, y: 40, w: 880, h: 640 },
|
|
2214
|
+
payload: { kind: "calendar", layout: { mode: "data" }, title: scheduleLabel(locale, "calendar_table"), bindings: { events: [{ entity_id: SCHEDULE_CALENDAR_ID }], todo: [{ entity_id: SCHEDULE_TODO_ID }] }, config: { view: "week" } }
|
|
2215
|
+
},
|
|
2216
|
+
{
|
|
2217
|
+
op: "entity.create",
|
|
2218
|
+
entity_id: `${SCHEDULE_SURFACE_ID}-todo`,
|
|
2219
|
+
type_id: "buckyos.container",
|
|
2220
|
+
parent_id: SCHEDULE_SURFACE_ID,
|
|
2221
|
+
order_key: "b",
|
|
2222
|
+
placement: { x: 960, y: 40, w: 420, h: 640 },
|
|
2223
|
+
payload: { kind: "todo", layout: { mode: "data" }, title: scheduleLabel(locale, "todo_table"), bindings: { items: { entity_id: SCHEDULE_TODO_ID } }, config: { mode: "list" } }
|
|
2224
|
+
}
|
|
2225
|
+
];
|
|
2226
|
+
}
|
|
2227
|
+
function invalid(message) {
|
|
2228
|
+
throw new AiwsFailure({ code: "INVALID_ARGUMENT", detail: message, retryable: false });
|
|
2229
|
+
}
|
|
2230
|
+
function object(value) {
|
|
2231
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
2232
|
+
invalid("expected an object");
|
|
2233
|
+
return value;
|
|
2234
|
+
}
|
|
2235
|
+
function required(value, field) {
|
|
2236
|
+
if (typeof value !== "string" || !value.trim())
|
|
2237
|
+
invalid(`${field} is required`);
|
|
2238
|
+
return value;
|
|
2239
|
+
}
|
|
2240
|
+
function instant(value, field) {
|
|
2241
|
+
if (typeof value !== "string" || !/^\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/i.test(value) || !isDate(value.slice(0, 10)) || !Number.isFinite(Date.parse(value)))
|
|
2242
|
+
invalid(`${field} requires an RFC 3339 instant with offset`);
|
|
2243
|
+
return Date.parse(value);
|
|
2244
|
+
}
|
|
2245
|
+
function times(input) {
|
|
2246
|
+
const { start, end, start_date, end_date } = input;
|
|
2247
|
+
if (start_date !== void 0 || end_date !== void 0) {
|
|
2248
|
+
if (start !== void 0 || end !== void 0)
|
|
2249
|
+
invalid("choose either dates or instants");
|
|
2250
|
+
if (typeof start_date !== "string" || !isDate(start_date) || typeof end_date !== "string" || !isDate(end_date) || end_date < start_date)
|
|
2251
|
+
invalid("expected start_date and inclusive end_date");
|
|
2252
|
+
return { allDay: true, startDate: start_date, endDate: end_date };
|
|
2253
|
+
}
|
|
2254
|
+
if (start === void 0 && end === void 0)
|
|
2255
|
+
return;
|
|
2256
|
+
const from = instant(start, "start"), to = instant(end, "end");
|
|
2257
|
+
if (to <= from)
|
|
2258
|
+
invalid("end must follow start");
|
|
2259
|
+
return { allDay: false, start: new Date(from).toISOString(), end: new Date(to).toISOString() };
|
|
2260
|
+
}
|
|
2261
|
+
function location(raw, slot, zone, owner) {
|
|
2262
|
+
const url = required(raw, "record_ref");
|
|
2263
|
+
try {
|
|
2264
|
+
const parsed = parseAiwsReferenceUrl(url);
|
|
2265
|
+
const address = new URL(url);
|
|
2266
|
+
const query = address.searchParams;
|
|
2267
|
+
const keys = [...query.keys()];
|
|
2268
|
+
if (address.username || address.password || address.port || address.hash || new Set(keys).size !== keys.length || keys.some((k) => !["zone", "owner", "epoch", "binding_revision", "selector", "occurrence"].includes(k)))
|
|
2269
|
+
invalid("invalid record reference");
|
|
2270
|
+
const epoch = required(query.get("epoch"), "epoch");
|
|
2271
|
+
const id = parsed.selector?.record_id;
|
|
2272
|
+
if (!parsed.workspace_id || parsed.entity_id !== slot || parsed.mode !== "live" || parsed.selector?.kind !== "table_record" || typeof id !== "string" || !id || query.get("zone") !== zone || query.get("owner") !== owner)
|
|
2273
|
+
invalid("record_ref does not belong to this Zone and resource type");
|
|
2274
|
+
const occ = query.get("occurrence");
|
|
2275
|
+
if (occ && (slot !== "calendar" || !isDate(occ) && !Number.isFinite(instant(occ, "occurrence"))))
|
|
2276
|
+
invalid("invalid occurrence");
|
|
2277
|
+
return { workspace_id: parsed.workspace_id, epoch, id, occurrence: occ ?? void 0 };
|
|
2278
|
+
} catch (error) {
|
|
2279
|
+
invalid(error instanceof Error ? error.message : "invalid record_ref");
|
|
2280
|
+
}
|
|
2281
|
+
}
|
|
2282
|
+
function references(input, action, slot, zone, owner) {
|
|
2283
|
+
if (action === "list" || action === "add")
|
|
2284
|
+
return [];
|
|
2285
|
+
if (slot === "todo" && action === "rm" && input.record_refs !== void 0) {
|
|
2286
|
+
if (input.record_ref || !Array.isArray(input.record_refs) || !input.record_refs.length)
|
|
2287
|
+
invalid("use record_ref or a nonempty record_refs array");
|
|
2288
|
+
const refs = input.record_refs.map((value) => location(value, slot, zone, owner));
|
|
2289
|
+
if (refs.some((r) => r.workspace_id !== refs[0].workspace_id) || new Set(refs.map((r) => r.id)).size !== refs.length)
|
|
2290
|
+
invalid("record_refs must name distinct rows in one table");
|
|
2291
|
+
return refs;
|
|
2292
|
+
}
|
|
2293
|
+
return [location(input.record_ref, slot, zone, owner)];
|
|
2294
|
+
}
|
|
2295
|
+
function links(ws, slot, zone, owner, revision, id, occurrence) {
|
|
2296
|
+
const url = new URL(aiwsReferenceUrl({ workspace_id: ws.workspace_id, entity_id: slot, selector: { kind: "table_record", record_id: id }, mode: "live" }));
|
|
2297
|
+
url.searchParams.set("zone", zone);
|
|
2298
|
+
url.searchParams.set("owner", owner);
|
|
2299
|
+
url.searchParams.set("epoch", ws.epoch);
|
|
2300
|
+
url.searchParams.set("binding_revision", String(revision));
|
|
2301
|
+
if (occurrence)
|
|
2302
|
+
url.searchParams.set("occurrence", occurrence);
|
|
2303
|
+
const query = new URLSearchParams({ id: SCHEDULE_SURFACE_ID, block: SCHEDULE_SURFACE_ID + "-" + slot, record: id });
|
|
2304
|
+
if (occurrence)
|
|
2305
|
+
query.set("occ", occurrence);
|
|
2306
|
+
return {
|
|
2307
|
+
record_ref: url.toString(),
|
|
2308
|
+
...ws.public_base ? { open_url: new URL("/workspace/surface?" + query, ws.public_base).toString() } : {}
|
|
2309
|
+
};
|
|
2310
|
+
}
|
|
2311
|
+
function todoView(item) {
|
|
2312
|
+
const { title, status, due, order, done, done_at, ext } = item;
|
|
2313
|
+
return { title, status, due, order, done, done_at, ext };
|
|
2314
|
+
}
|
|
2315
|
+
function eventView(o) {
|
|
2316
|
+
return {
|
|
2317
|
+
title: o.title,
|
|
2318
|
+
all_day: o.allDay,
|
|
2319
|
+
status: o.status,
|
|
2320
|
+
ext: o.ext,
|
|
2321
|
+
...o.allDay ? { start_date: o.startDate, end_date: o.endDate } : { start: new Date(o.startMs).toISOString(), end: new Date(o.endMs).toISOString() },
|
|
2322
|
+
...o.recurring ? { recurring: true, original: o.original } : {},
|
|
2323
|
+
...o.override ? { changed_once: true } : {},
|
|
2324
|
+
...o.agentWritten ? { agent_written: true } : {}
|
|
2325
|
+
};
|
|
2326
|
+
}
|
|
2327
|
+
function windowOf(input, tz) {
|
|
2328
|
+
const fromMs = instant(input.from, "from"), toMs = instant(input.to, "to");
|
|
2329
|
+
if (toMs <= fromMs || toMs - fromMs > 366 * 864e5)
|
|
2330
|
+
invalid("use a positive window of at most 366 days");
|
|
2331
|
+
const offset = String(input.from).slice(-6);
|
|
2332
|
+
const zone = input.tz ?? tz ?? (/^[+-]/.test(offset) ? offset : "UTC");
|
|
2333
|
+
if (typeof zone !== "string" || !isTimeZone(zone))
|
|
2334
|
+
invalid("unknown calendar time zone");
|
|
2335
|
+
return { fromMs, toMs, viewerTz: zone };
|
|
2336
|
+
}
|
|
2337
|
+
function pageOf(input) {
|
|
2338
|
+
const offset = input.cursor === void 0 ? 0 : Number(input.cursor);
|
|
2339
|
+
const limit = input.limit ?? 100;
|
|
2340
|
+
if (input.cursor !== void 0 && String(offset) !== input.cursor || !Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(limit) || typeof limit !== "number" || limit < 1 || limit > 1e3)
|
|
2341
|
+
invalid("invalid pagination");
|
|
2342
|
+
return { offset, limit };
|
|
2343
|
+
}
|
|
2344
|
+
function calendarChange(p, tz) {
|
|
2345
|
+
const time = times(p);
|
|
2346
|
+
const ext = { ...p.ext === void 0 ? {} : object(p.ext) };
|
|
2347
|
+
if (p.location !== void 0)
|
|
2348
|
+
ext.location = p.location;
|
|
2349
|
+
if (p.reminders !== void 0) {
|
|
2350
|
+
if (!Array.isArray(p.reminders) || !p.reminders.every((n) => typeof n === "number" && Number.isSafeInteger(n) && n >= 0))
|
|
2351
|
+
invalid("invalid reminders");
|
|
2352
|
+
ext.reminders = p.reminders.map((before_min) => ({ before_min }));
|
|
2353
|
+
}
|
|
2354
|
+
const repeat = p.rrule ?? ext.rrule;
|
|
2355
|
+
if (repeat) {
|
|
2356
|
+
if (typeof repeat !== "string")
|
|
2357
|
+
invalid("rrule requires a string");
|
|
2358
|
+
try {
|
|
2359
|
+
parseRRule(repeat);
|
|
2360
|
+
} catch (e) {
|
|
2361
|
+
invalid(String(e));
|
|
2362
|
+
}
|
|
2363
|
+
}
|
|
2364
|
+
const zone = p.tz ?? ext.tz ?? (repeat && time && !time.allDay ? tz : void 0);
|
|
2365
|
+
if (zone !== void 0) {
|
|
2366
|
+
if (typeof zone !== "string" || !isTimeZone(zone))
|
|
2367
|
+
invalid("unknown repeat time zone");
|
|
2368
|
+
ext.tz = zone;
|
|
2369
|
+
} else if (repeat && time && !time.allDay) {
|
|
2370
|
+
if (!String(p.start).endsWith("Z"))
|
|
2371
|
+
invalid("provide tz for a repeating timed event");
|
|
2372
|
+
ext.tz = "UTC";
|
|
2373
|
+
}
|
|
2374
|
+
const values = { ...p.title !== void 0 ? { title: required(p.title, "title") } : {}, ...p.status !== void 0 ? { status: required(p.status, "status") } : {} };
|
|
2375
|
+
return { times: time, values, ext_merge: ext, rrule: p.rrule };
|
|
2376
|
+
}
|
|
2377
|
+
function todoChange(p) {
|
|
2378
|
+
if (p.due !== void 0 && p.due !== null && (typeof p.due !== "string" || !isDate(p.due)))
|
|
2379
|
+
invalid("due requires a date or null");
|
|
2380
|
+
const ext = { ...p.ext === void 0 ? {} : object(p.ext) };
|
|
2381
|
+
if (p.priority !== void 0)
|
|
2382
|
+
ext.priority = p.priority === "none" ? null : p.priority;
|
|
2383
|
+
return {
|
|
2384
|
+
...p.title !== void 0 ? { title: required(p.title, "title") } : {},
|
|
2385
|
+
...p.status !== void 0 ? { status: required(p.status, "status") } : {},
|
|
2386
|
+
due: p.due,
|
|
2387
|
+
ext_merge: ext
|
|
2388
|
+
};
|
|
2389
|
+
}
|
|
2390
|
+
async function invoke(slot, request, host) {
|
|
2391
|
+
const { method, params: p } = request;
|
|
2392
|
+
const zone = host.context.zone_did;
|
|
2393
|
+
const identity = { owner_did: host.context.owner_did };
|
|
2394
|
+
const read = method === "list";
|
|
2395
|
+
const pagination = read ? pageOf(p) : void 0;
|
|
2396
|
+
const window = slot === "calendar" && read ? windowOf(p, host.context.tz) : void 0;
|
|
2397
|
+
const input = method === "update" ? object(p.patch) : p;
|
|
2398
|
+
const change = !read && slot === "calendar" ? calendarChange(input, host.context.tz) : void 0;
|
|
2399
|
+
const todo = !read && slot === "todo" ? todoChange(input) : void 0;
|
|
2400
|
+
if (method === "add") {
|
|
2401
|
+
required(p.title, "title");
|
|
2402
|
+
if (slot === "calendar" && !change?.times)
|
|
2403
|
+
invalid("add requires a time or all-day date range");
|
|
2404
|
+
}
|
|
2405
|
+
if (p.before !== void 0 && p.after !== void 0)
|
|
2406
|
+
invalid("choose only one placement anchor");
|
|
2407
|
+
const prepared = await host.call("owner.prepare", { slot });
|
|
2408
|
+
if ("result" in prepared)
|
|
2409
|
+
return prepared.result;
|
|
2410
|
+
const base = { ...identity, binding_revision: prepared.binding_revision };
|
|
2411
|
+
const owner = host.context.owner_did;
|
|
2412
|
+
const refs = references(p, method, slot, zone, owner);
|
|
2413
|
+
const before = p.before === void 0 ? void 0 : location(p.before, slot, zone, owner);
|
|
2414
|
+
const after2 = p.after === void 0 ? void 0 : location(p.after, slot, zone, owner);
|
|
2415
|
+
const locations = [...refs, ...[before, after2].filter((a) => Boolean(a))];
|
|
2416
|
+
const transport = { call: async (m, params) => {
|
|
2417
|
+
let response;
|
|
2418
|
+
try {
|
|
2419
|
+
response = await host.call("aiws." + m, params);
|
|
2420
|
+
const code = response.error?.code ?? response.code;
|
|
2421
|
+
if (m === "doc.commit" && ["STORAGE_IO_ERROR", "WRITE_OUTCOME_UNKNOWN", "IDEMPOTENCY_MISMATCH"].includes(code ?? ""))
|
|
2422
|
+
throw new Error(code);
|
|
2423
|
+
} catch (error) {
|
|
2424
|
+
if (m !== "doc.commit")
|
|
2425
|
+
throw error;
|
|
2426
|
+
const cause = error;
|
|
2427
|
+
if (cause.code && !["WRITE_OUTCOME_UNKNOWN", "PROVIDER_UNAVAILABLE", "TRANSPORT_ERROR", "STORAGE_IO_ERROR", "TIMEOUT"].includes(cause.code))
|
|
2428
|
+
throw error;
|
|
2429
|
+
const { workspace_id, epoch, idempotency_key } = params;
|
|
2430
|
+
try {
|
|
2431
|
+
const tableWrite = Array.isArray(params.operations) && params.operations.every((op) => String(op.op).startsWith("table."));
|
|
2432
|
+
const found = await host.call("aiws.doc.get_submission", {
|
|
2433
|
+
workspace_id,
|
|
2434
|
+
epoch,
|
|
2435
|
+
idempotency_key,
|
|
2436
|
+
...tableWrite ? { source_id: slot } : {}
|
|
2437
|
+
});
|
|
2438
|
+
if (found.status === "accepted")
|
|
2439
|
+
return found.result ?? { status: "accepted" };
|
|
2440
|
+
} catch (checkError) {
|
|
2441
|
+
if (["PERMISSION_DENIED", "AUTH_REQUIRED", "UNAUTHORIZED"].includes(String(checkError.code)))
|
|
2442
|
+
throw checkError;
|
|
2443
|
+
}
|
|
2444
|
+
throw new AiwsFailure({ code: "WRITE_OUTCOME_UNKNOWN", detail: "the service could not confirm the submission", retryable: false, data: { idempotency_key, workspace_id } });
|
|
2445
|
+
}
|
|
2446
|
+
if (response.ok === false && response.error)
|
|
2447
|
+
throw new AiwsFailure(response.error);
|
|
2448
|
+
return response;
|
|
2449
|
+
} };
|
|
2450
|
+
let workspaceId = prepared.workspace_id ?? refs[0]?.workspace_id;
|
|
2451
|
+
if (!workspaceId) {
|
|
2452
|
+
if (read || before || after2) {
|
|
2453
|
+
const ws2 = await transport.call("ws.lookup", { name: "schedule" });
|
|
2454
|
+
if (ws2.found === false && !read)
|
|
2455
|
+
invalid("placement anchor requires an existing personal schedule");
|
|
2456
|
+
if (ws2.found === false)
|
|
2457
|
+
return { ...base, initialized: false, [slot === "calendar" ? "events" : "items"]: [], next_cursor: null };
|
|
2458
|
+
if (ws2.found !== true || !ws2.workspace_id)
|
|
2459
|
+
throw new AiwsFailure({ code: "INVALID_SERVICE_RESPONSE", retryable: false, detail: "invalid workspace lookup result" });
|
|
2460
|
+
workspaceId = ws2.workspace_id;
|
|
2461
|
+
} else {
|
|
2462
|
+
const ws2 = await transport.call("ws.ensure", { name: "schedule", title: "我的日程" });
|
|
2463
|
+
workspaceId = ws2.workspace_id;
|
|
2464
|
+
}
|
|
2465
|
+
}
|
|
2466
|
+
const businessKey = request.idempotency_key ?? prepared.idempotency_key;
|
|
2467
|
+
const inputKey = "xcall:" + slot + ":" + method + ":" + businessKey;
|
|
2468
|
+
const key = read ? "" : /^[\x21-\x7e]{1,110}$/.test(inputKey) ? inputKey : "xcall:" + Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(inputKey))), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
2469
|
+
const allocated = prepared.record_id;
|
|
2470
|
+
const client = new ScheduleClient(transport, { idempotencyKey: key, newRecordId: () => allocated });
|
|
2471
|
+
async function workspace(id2) {
|
|
2472
|
+
const ws2 = await transport.call("ws.get_info", { workspace_id: id2 });
|
|
2473
|
+
if (ws2.workspace_id !== id2 || !ws2.owned_by_caller_user || ws2.name !== "schedule" && ws2.former_name !== "schedule") {
|
|
2474
|
+
throw new AiwsFailure({ code: "PERMISSION_DENIED", detail: "workspace is outside the owner’s personal schedule", retryable: false });
|
|
2475
|
+
}
|
|
2476
|
+
for (const loc of locations) {
|
|
2477
|
+
if (loc.workspace_id !== ws2.workspace_id)
|
|
2478
|
+
invalid("record reference belongs to another workspace");
|
|
2479
|
+
if (loc.epoch !== ws2.epoch)
|
|
2480
|
+
throw new AiwsFailure({ code: "EPOCH_MISMATCH", detail: "record reference belongs to an earlier workspace history", retryable: false });
|
|
2481
|
+
}
|
|
2482
|
+
return ws2;
|
|
2483
|
+
}
|
|
2484
|
+
let ws = await workspace(workspaceId);
|
|
2485
|
+
if (!read) {
|
|
2486
|
+
const pinned = await host.call("owner.pin", { slot, workspace_id: ws.workspace_id, epoch: ws.epoch });
|
|
2487
|
+
if (pinned.workspace_id !== ws.workspace_id)
|
|
2488
|
+
ws = await workspace(pinned.workspace_id);
|
|
2489
|
+
if (pinned.epoch !== ws.epoch)
|
|
2490
|
+
throw new AiwsFailure({ code: "WRITE_OUTCOME_UNKNOWN", detail: "original workspace epoch has changed", retryable: false, data: { idempotency_key: key } });
|
|
2491
|
+
}
|
|
2492
|
+
const link = (id2, occ) => links(ws, slot, zone, owner, prepared.binding_revision, id2, occ);
|
|
2493
|
+
const ref = refs[0];
|
|
2494
|
+
const id = ref?.occurrence ? ref.id + "@" + ref.occurrence : ref?.id;
|
|
2495
|
+
const receipt = (resultId, occurrence) => ({
|
|
2496
|
+
...base,
|
|
2497
|
+
idempotency_key: businessKey,
|
|
2498
|
+
status: method === "add" ? "created" : method === "rm" ? "removed" : "updated",
|
|
2499
|
+
...resultId ? link(resultId, occurrence) : {},
|
|
2500
|
+
...method === "rm" && slot === "todo" ? { removed: refs.length } : {}
|
|
2501
|
+
});
|
|
2502
|
+
let initialize = method === "add";
|
|
2503
|
+
if (initialize && prepared.replay) {
|
|
2504
|
+
const prior = await transport.call("doc.get_submission", {
|
|
2505
|
+
workspace_id: ws.workspace_id,
|
|
2506
|
+
epoch: ws.epoch,
|
|
2507
|
+
idempotency_key: key
|
|
2508
|
+
});
|
|
2509
|
+
if (!["accepted", "not_found"].includes(prior.status))
|
|
2510
|
+
throw new AiwsFailure({ code: "WRITE_OUTCOME_UNKNOWN", detail: "cannot confirm the original write", retryable: false, data: { idempotency_key: key } });
|
|
2511
|
+
initialize = prior.status === "not_found";
|
|
2512
|
+
}
|
|
2513
|
+
await client.open(ws, initialize);
|
|
2514
|
+
try {
|
|
2515
|
+
const meta = await transport.call("doc.read", { workspace_id: ws.workspace_id, entity_id: slot, as: "meta" });
|
|
2516
|
+
if (meta.schema_id !== "buckyos." + slot + "@1")
|
|
2517
|
+
throw new AiwsFailure({ code: "RESOURCE_TYPE_MISMATCH", detail: "unexpected table schema", retryable: false });
|
|
2518
|
+
if (slot === "todo" && ["done", "undone", "update", "move"].includes(method) && !meta.capabilities.includes("update")) {
|
|
2519
|
+
throw new AiwsFailure({ code: "PERMISSION_DENIED", detail: "table update permission required", retryable: false });
|
|
2520
|
+
}
|
|
2521
|
+
} catch (error) {
|
|
2522
|
+
if (read && (ws.owner === true || ws.head_seq === 0) && ["NOT_FOUND", "TARGET_DELETED"].includes(String(error.code))) {
|
|
2523
|
+
return { ...base, initialized: false, [slot === "todo" ? "items" : "events"]: [], next_cursor: null };
|
|
2524
|
+
}
|
|
2525
|
+
throw error;
|
|
2526
|
+
}
|
|
2527
|
+
if (prepared.replay && !read) {
|
|
2528
|
+
const sub = await transport.call("doc.get_submission", {
|
|
2529
|
+
workspace_id: ws.workspace_id,
|
|
2530
|
+
epoch: ws.epoch,
|
|
2531
|
+
idempotency_key: key,
|
|
2532
|
+
source_id: slot
|
|
2533
|
+
});
|
|
2534
|
+
if (sub.status === "accepted") {
|
|
2535
|
+
if (method === "add")
|
|
2536
|
+
return receipt(allocated);
|
|
2537
|
+
if (["update", "postpone"].includes(method) && slot === "calendar")
|
|
2538
|
+
return receipt(sub.inserted?.[0] ?? sub.changed?.[0] ?? ref.id);
|
|
2539
|
+
return receipt(ref.id, ref.occurrence);
|
|
2540
|
+
}
|
|
2541
|
+
if (sub.status !== "not_found")
|
|
2542
|
+
throw new AiwsFailure({ code: "WRITE_OUTCOME_UNKNOWN", detail: "provider could not confirm submission", retryable: false, data: { idempotency_key: key } });
|
|
2543
|
+
}
|
|
2544
|
+
if (read) {
|
|
2545
|
+
const all = slot === "todo" ? (await client.todos({ includeDone: p.include_done === true })).map((item) => ({ ...todoView(item), ...link(item.record_id) })) : (await client.events(window, window)).map((o) => ({ ...eventView(o), ...link(o.master?.record_id ?? o.row.record_id, o.original) }));
|
|
2546
|
+
const { offset, limit } = pagination;
|
|
2547
|
+
return { ...base, initialized: true, [slot === "todo" ? "items" : "events"]: all.slice(offset, offset + limit), next_cursor: offset + limit < all.length ? String(offset + limit) : null };
|
|
2548
|
+
}
|
|
2549
|
+
if (slot === "todo") {
|
|
2550
|
+
const place = { before: before?.id, after: after2?.id };
|
|
2551
|
+
switch (method) {
|
|
2552
|
+
case "add": {
|
|
2553
|
+
const item = await client.addTodo({ ...todo, title: required(p.title, "title"), record_id: allocated, ext: todo.ext_merge }, place);
|
|
2554
|
+
return receipt(item.record_id);
|
|
2555
|
+
}
|
|
2556
|
+
case "done":
|
|
2557
|
+
case "undone":
|
|
2558
|
+
await client.completeTodo(id, method === "done");
|
|
2559
|
+
break;
|
|
2560
|
+
case "update":
|
|
2561
|
+
await client.updateTodo(id, todo);
|
|
2562
|
+
break;
|
|
2563
|
+
case "move":
|
|
2564
|
+
await client.moveTodo(id, { status: todo.status, ...place });
|
|
2565
|
+
break;
|
|
2566
|
+
case "rm":
|
|
2567
|
+
await client.removeTodos(refs.map((r) => r.id));
|
|
2568
|
+
break;
|
|
2569
|
+
default:
|
|
2570
|
+
invalid("unknown to-do action");
|
|
2571
|
+
}
|
|
2572
|
+
return receipt(id);
|
|
2573
|
+
}
|
|
2574
|
+
const scope = p.scope ?? "one";
|
|
2575
|
+
switch (method) {
|
|
2576
|
+
case "add": {
|
|
2577
|
+
const t = change.times;
|
|
2578
|
+
const ext = { ...change.ext_merge, ...change.rrule ? { rrule: change.rrule } : {} };
|
|
2579
|
+
const event = await client.addEvent({
|
|
2580
|
+
...change.values,
|
|
2581
|
+
title: required(p.title, "title"),
|
|
2582
|
+
record_id: allocated,
|
|
2583
|
+
ext,
|
|
2584
|
+
...t.allDay ? { all_day: true, start_date: t.startDate, end_date: t.endDate } : { start: t.start, end: t.end }
|
|
2585
|
+
});
|
|
2586
|
+
return receipt(event);
|
|
2587
|
+
}
|
|
2588
|
+
case "update":
|
|
2589
|
+
return receipt(await client.editEvent(id, change, scope));
|
|
2590
|
+
case "rm":
|
|
2591
|
+
case "skip":
|
|
2592
|
+
await client.deleteEvent(id, method === "skip" ? "one" : scope);
|
|
2593
|
+
return receipt(ref.id, ref.occurrence);
|
|
2594
|
+
case "postpone": {
|
|
2595
|
+
if (typeof p.minutes !== "number" || !Number.isSafeInteger(p.minutes) || p.minutes <= 0)
|
|
2596
|
+
invalid("minutes must be positive");
|
|
2597
|
+
const { occ, rows } = await client.occurrence(id);
|
|
2598
|
+
const { ops, record_id } = eventPostponeOps(slot, occ, p.minutes, { rows, newRecordId: () => allocated });
|
|
2599
|
+
if (ops.length)
|
|
2600
|
+
await client.commit(ops, "postpone occurrence");
|
|
2601
|
+
return receipt(record_id);
|
|
2602
|
+
}
|
|
2603
|
+
default:
|
|
2604
|
+
invalid("unknown calendar action");
|
|
2605
|
+
}
|
|
2606
|
+
}
|
|
2607
|
+
async function scheduleAction(slot, request, host) {
|
|
2608
|
+
try {
|
|
2609
|
+
return { result: await invoke(slot, request, host) };
|
|
2610
|
+
} catch (error) {
|
|
2611
|
+
const e = error;
|
|
2612
|
+
return { error: { code: e.code ?? "PROVIDER_UNAVAILABLE", message: e.message ?? String(error), details: e.details ?? e.data ?? null } };
|
|
2613
|
+
}
|
|
2614
|
+
}
|
|
2615
|
+
export {
|
|
2616
|
+
instant,
|
|
2617
|
+
scheduleAction
|
|
2618
|
+
};
|